将 Ollama 集成到 Python 中:REST API 和 Python 客户端示例

使用思考型大语言模型的具体示例

目录

在本文中,我们将探讨两种连接您的 Python 应用程序到 Ollama 的方法:1. 通过 HTTP REST API;2. 通过 官方 Ollama Python 库

我们将涵盖 聊天生成 调用,然后讨论如何有效地使用 “思考模型”

ollama and python

Ollama 迅速成为运行大型语言模型 (LLMs) 本地的最方便方式之一。凭借其简单的界面和对流行开源模型如 Llama 3MistralQwen2.5 的支持,甚至是像 qwen3 这样的“思考”变体,您可以轻松地将 AI 能力直接嵌入到 Python 项目中——而无需依赖外部云 API。


🧩 前置条件

在深入探讨之前,请确保您已经安装并本地运行了以下内容:

pip install requests ollama

通过执行以下命令确认 Ollama 已运行:

ollama list

您应该能看到可用模型,如 llama3mistralqwen3


⚙️ 选项 1:使用 Ollama 的 REST API

REST API 在您需要最大控制权或与已处理 HTTP 请求的框架集成时非常理想。

示例 1:聊天 API

import requests
import json

url = "http://localhost:11434/api/chat"

payload = {
    "model": "llama3.1",
    "messages": [
        {"role": "system", "content": "您是 Python 助手。"},
        {"role": "user", "content": "编写一个反转字符串的函数。"}
    ]
}

response = requests.post(url, json=payload, stream=True)

for line in response.iter_lines():
    if line:
        data = json.loads(line)
        print(data.get("message", {}).get("content", ""), end="")

👉 Ollama REST API 按行流式传输响应(类似于 OpenAI 的流式 API)。您可以累积内容或实时显示聊天机器人或 CLI 工具的内容。


示例 2:生成 API

如果不需要聊天上下文或角色,请使用更简单的 /api/generate 端点:

import requests

url = "http://localhost:11434/api/generate"
payload = {
    "model": "llama3.1",
    "prompt": "用一句话解释递归。"
}

response = requests.post(url, json=payload, stream=True)
for line in response.iter_lines():
    if line:
        print(line.decode("utf-8"))

此端点非常适合一次性文本生成任务——摘要、代码片段等。


🐍 选项 2:使用 Ollama Python 库

Ollama Python 客户端 为喜欢完全在 Python 中工作的开发者提供了更清晰的界面。

示例 1:聊天 API

import ollama

response = ollama.chat(
    model="llama3.1",
    messages=[
        {"role": "system", "content": "您是代码助手。"},
        {"role": "user", "content": "生成一个列出目录中所有文件的 Python 脚本。"}
    ]
)

print(response['message']['content'])

这将返回最终消息作为字典。如果需要流式传输,可以迭代聊天流:

stream = ollama.chat(
    model="llama3.1",
    messages=[
        {"role": "user", "content": "写一首关于递归的俳句。"}
    ],
    stream=True
)

for chunk in stream:
    print(chunk['message']['content'], end='', flush=True)

示例 2:生成 API

import ollama

output = ollama.generate(
    model="llama3.1",
    prompt="总结 Python 中装饰器的概念。"
)

print(output['response'])

或者流式传输结果:

stream = ollama.generate(
    model="llama3.1",
    prompt="列出三个使用 Python 进行 AI 项目的优点。",
    stream=True
)

for chunk in stream:
    print(chunk['response'], end='', flush=True)

🧠 使用“思考”模型

Ollama 支持 “思考模型”,如 [qwen3](https://www.glukhov.org/zh-cn/post/2025/09/llm-structured-output-with-ollama-in-python-and-go/ "使用 Ollama 和 Qwen3 的结构化输出"),这些模型设计用于显示其中间推理步骤。这些模型产生的结构化输出通常格式如下:

<think>
  推理步骤在这里...
</think>
最终答案在这里。

这使它们非常适合:

  • 调试模型推理
  • 对可解释性进行研究
  • 构建将 思考输出 分离的工具

示例:使用思考模型

import ollama

response = ollama.chat(
    model="qwen3",
    messages=[
        {"role": "user", "content": "澳大利亚的首都是哪里?"}
    ]
)

content = response['message']['content']

# 可选地提取“思考”部分
import re
thinking = re.findall(r"<think>(.*?)</think>", content, re.DOTALL)
answer = re.sub(r"<think>.*?</think>", "", content, flags=re.DOTALL)

print("🧠 思考过程:\n", thinking[0].strip() if thinking else "N/A")
print("\n✅ 最终答案:\n", answer.strip())

何时使用思考模型

用例 推荐模型 原因
可解释性 / 调试 qwen3 查看推理轨迹
性能敏感应用 qwen3 非思考模式 快速,简洁
教育 / 说明 qwen3 展示逐步逻辑

✅ 摘要

任务 REST API Python Client
简单文本生成 /api/generate ollama.generate()
对话聊天 /api/chat ollama.chat()
流式支持
支持思考模型

Ollama 的本地优先设计使其非常适合安全、离线或隐私敏感的 AI 应用。无论您是构建交互式聊天机器人还是后台数据增强服务,都可以将 LLMs 无缝集成到 Python 工作流中——完全控制模型、延迟和数据。

有用链接