1 简介
之前我在自己的电脑上安装了ollama软件,并且在ollama上安装了千问大模型。
如何在配备RTX 2060 Super的电脑上安装深度学习大模型:经验分享
今天记录一下,如何在python中调用本地大模型
2 前置步骤
首先确保安装好了ollama,及在ollama安装好大模型。本次我以qwen2.5大模型为例子。不懂怎么安装的话,请参考这篇文章:
《如何在配备RTX 2060 Super的电脑上安装深度学习大模型:经验分享》
1.在终端运行
ollama run qwen2.5
2.在浏览器打开http://127.0.0.1:11434/
确保大模型的本地api接口可以正常被打开。如下:
自此,前置步骤已做完!
3 代码
我们将使用以下代码,在python环境中调用本地大模型。
import requests
import json
def translate_text(content):
url = "http://localhost:11434/api/chat"
data = {
"model": "qwen2.5",
"messages": [
{
"role": "user",
"content": f"请将以下中文翻译成英文:{content}"
},
],
"stream": True
}
response = requests.post(url, json=data, stream=True)
print(response.status_code)
if response.status_code == 200:
full_response = ''
for line in response.iter_lines():
if line:
try:
json_object = json.loads(line)
if 'message' in json_object and 'content' in json_object['message']:
chunk = json_object['message']['content']
full_response += chunk
print(chunk, end='', flush=True)
except json.JSONDecodeError:
pass
print()
return full_response
else:
print(f"Error: {response.status_code}")
return response.text
if __name__ == "__main__":
user_input = '你好,帮我翻译,测试翻译功能'
result = translate_text(user_input)
我们使用requests库,来访问大模型的api接口,这里我预设大模型的任务是:
你可以根据你的需求进行修改。
本次测试的大模型中英翻译功能,中文是:
本次代码的运行结果如下:
4 还有一点点想说的
现在的开源大模型很多很多,我挑了一个适合自己的电脑性能的大模型进行安装,做这个中英翻译其实也是为了满足自己的小需求。
往期文章回顾