Python调用Ollama本地API实战指南
本文介绍如何使用Python调用Ollama本地API,实现自动化问答与批量处理。在开始前,需确保已完成Ollama的安装与模型拉取,并保持`ollama serve`服务在后台运行。Ollama自带RESTful API服务,默认运行在11434端口,无需额外配置网关,支持流式输出与参数自定义。
01核心API规则与环境准备
Ollama提供两个核心接口:`/api/generate`用于单轮问答,`/api/chat`用于多轮记忆对话(推荐)。全程本地调用,无外网依赖与流量费。Python环境只需3.8及以上版本,利用内置`requests`库即可实现对接。
- 前置检查
确保服务启动:终端运行`ollama serve`。
确认模型名称:使用`ollama list`核对已下载模型,名称需完全一致。 - 依赖安装
使用pip安装requests库:`pip install requests`。
02实战代码:基础单轮对话
以下代码适用于简单问答场景。通过`/api/chat`接口发送请求,设置`stream`为False以一次性获取结果。
import requests
import json
OLLAMA_API_URL = "http://localhost:11434/api/chat"
def ollama_chat(question, model_name="qwen2.5:7b"):
payload = {
"model": model_name,
"messages": [{"role": "user", "content": question}],
"stream": False,
"temperature": 0.7
}
try:
response = requests.post(OLLAMA_API_URL, json=payload)
response.raise_for_status()
result = response.json()
return result["message"]["content"]
except Exception as e:
return f"接口调用失败:{str(e)}"
if __name__ == "__main__":
user_question = "用通俗易懂的话解释什么是大模型本地化部署"
answer = ollama_chat(user_question)
print(" AI回复:")
print(answer)03实战代码:流式输出对话
流式输出可模拟逐字回复效果,提升交互体验。核心改动是将`stream`设为True,并逐行解析响应数据。
import requests
def ollama_stream_chat(question, model_name="qwen2.5:7b"):
payload = {
"model": model_name,
"messages": [{"role": "user", "content": question}],
"stream": True,
"temperature": 0.7
}
with requests.post("http://localhost:11434/api/chat", json=payload, stream=True) as response:
print(" AI回复:", end="", flush=True)
for line in response.iter_lines():
if line:
data = eval(line.decode("utf-8"))
if "message" in data:
print(data["message"]["content"], end="", flush=True)
print()
if __name__ == "__main__":
ollama_stream_chat("写一段Python自动化办公的入门代码")04实战代码:多轮记忆对话
通过维护一个全局的`chat_history`列表,将用户问题与AI回复持续追加,可实现具备上下文记忆的多轮连贯对话。
import requests
chat_history = []
def ollama_multi_chat(question, model_name="qwen2.5:7b"):
chat_history.append({"role": "user", "content": question})
payload = {
"model": model_name,
"messages": chat_history,
"stream": False
}
response = requests.post("http://localhost:11434/api/chat", json=payload)
result = response.json()
ai_answer = result["message"]["content"]
chat_history.append({"role": "assistant", "content": ai_answer})
return ai_answer
if __name__ == "__main__":
q1 = "我是一名Python新手,该怎么入门"
print(f" 我:{q1}")
print(f" AI:{ollama_multi_chat(q1)}")
q2 = "那入门后先学哪个库最实用"
print(f" 我:{q2}")
print(f" AI:{ollama_multi_chat(q2)}")05常见问题与处理
- 连接超时
检查`ollama serve`是否启动,确认11434端口未被占用。 - 模型不存在
使用`ollama list`核对模型名称,大小写及后缀必须完全一致。 - 无返回结果
尝试降低模型参数或更换量化版本,检查系统内存是否充足。 - 流式乱码
确保Python环境编码为UTF-8,并在迭代时正确解码。
当前文章无评论,是时候发表评论了