如何在python中调用本地大模型:经验分享

文摘   2024-10-19 21:47   广东  

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 requestsimport 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 还有一点点想说的

现在的开源大模型很多很多,我挑了一个适合自己的电脑性能的大模型进行安装,做这个中英翻译其实也是为了满足自己的小需求。



往期文章回顾

避免 Python 中 GDAL/OGR 绑定导致的崩溃

从原图中提取GPS信息并创建Shapefile(第5版)| 把文件名字写入shp、txt

这么多年下来,我确实是没处理过modis影像 | hdf格式转为tif格式

为什么我经常使用python,原因在于Python 是地理信息系统(GIS)和遥感领域的热门编程语言。

在Ubuntu 24.04系统上安装Rust编程语言环境

从原图中提取GPS信息并创建Shapefile(第四版)允许文件夹里同时存在原图、非原图





remote sensing
一个专注于测绘、地信、遥感的公众号
 最新文章