本地部署可以直接下载模型文件和源代码,打开安装包之后直接运行,也可以使用框架部署。
本次使用的是第二种,使用ollama部署大语言模型。
根据自己用的操作系统选择对应的ollama安装包,直接选择windows下载即可。
下载地址:
官网下载链接:https://ollama.com/download/OllamaSetup.exe
Github链接:https://github.com/ollama/ollama/releases
如果下载太慢可以使用代理网址https://github.akams.cn/
如果还是太慢可以选择迅雷下载,刚好一个G加速流量。
Ctrl + Shift + Esc打开任务管理器。8.0 GB)。去官网查看想要部署的模型:
https://ollama.com/library
根据自己的显存大小选择适合的模型:
查看模型列表命令:ollama list
运行命令如下:
运行模型命令:ollama run qwen2.5:0.5b ,其中qwen2.5:0.5b为要运行的大语言模型,如果本地没有则先拉取该模型。
拉取模型命令:ollama pull qwen2.5:0.5b
删除模型命令:ollama rm qwen2.5:0.5b
安装好模型后就可以进行提问了,提问如下图所示:
除了本地运行,ollama还支持接口调用,端口为11434。
API参考文档:https://ollama.cadn.net.cn/api.html
以下为示例:
importrequestsimportjsonclassOllamaChat:def__init__(self, model="qwen:7b", base_url="http://localhost:11434"):self.model = modelself.base_url = base_urlself.session = requests.Session()self.session.headers.update({"Content-Type":"application/json"})defgenerate(self, prompt, stream=False, system_prompt=None):"""发送请求到Ollama API"""data = {"model": self.model,"prompt": prompt,"stream": stream,"options": {"temperature":0.7}}ifsystem_prompt:data["system"] = system_prompttry:response = self.session.post(f"{self.base_url}/api/generate",data=json.dumps(data, ensure_ascii=False).encode('utf-8'))response.raise_for_status()returnresponse.json()exceptrequests.exceptions.RequestExceptionase:print(f"请求出错:{e}")returnNonedefchat(self):"""交互式聊天"""print(f"正在使用{self.model}模型(输入'退出'结束对话)")# 系统提示(强制中文回复)system_msg ="你是一个AI助手,必须使用简体中文回答所有问题,回答应当详细专业"whileTrue:user_input =input("\n你: ")ifuser_input.lower()in['退出','exit','quit']:breakresult = self.generate(prompt=user_input,system_prompt=system_msg)ifresultand'response'inresult:print(f"\nAI:{result['response']}")else:print("获取回复失败,请检查模型服务")if__name__ =="__main__":# 可替换为其他模型如 "llama3-chinese"、"qwen2.5:0.5b" 等chat = OllamaChat(model="qwen2.5:0.5b")# 测试单次请求test_response = chat.generate("用中文介绍你自己")iftest_response:print("\n测试回复:", test_response.get('response','无回复'))# 启动交互聊天chat.chat()
可以简单部署小型模型进行AI应用的开发,同时网上也有免费的API可调用,如glm-4-flash等,具体的操作还需自行学习,不懂的多问AI多查资料。
| 欢迎光临 链载Ai (https://www.lianzai.com/) | Powered by Discuz! X3.5 |