Python 调用本地部署DeepSeek的API

Python 调用本地部署DeepSeek的API 详细指南

1. 确认 Ollama 是否正确运行

如果你使用 Ollama 部署了 DeepSeek,默认 API 运行在 11434 端口。首先,检查 Ollama 是否正常运行:

curl http://localhost:11434/api/tags

如果返回:

{"models":["deepseek-coder:latest", "deepseek-chat:latest"]}

说明 Ollama 运行正常,并且已安装 DeepSeek 模型。


2. Python 调用 Ollama 运行的 DeepSeek

2.1 发送对话请求

Ollama 的 API 端点与 OpenAI 兼容 API 不同,需要使用 /api/generate

import requests
import json

API_URL = "http://localhost:11434/api/generate"  # Ollama API 端点

headers = {
    "Content-Type": "application/json"
}

data = {
    "model": "deepseek-coder",  # 你的 DeepSeek 模型名称
    "prompt": "请介绍一下 DeepSeek。",
    "stream": False  # 关闭流式输出
}

response = requests.post(API_URL, headers=headers, json=data)

if response.status_code == 200:
    result = response.json()
    print("AI 回复:", result["response"])
else:
    print("请求失败:", response.status_code, response.text)

📌 注意

  • "model" 需要匹配你的 Ollama 里安装的 DeepSeek 模型,比如 "deepseek-coder"
  • Ollama API 采用 "prompt" 而不是 "messages"
  • 端口是 11434,不是 8000

2.2 开启流式输出

如果希望让 Ollama 流式返回 DeepSeek 的回复,可以这样处理:

import requests
import json

API_URL = "http://localhost:11434/api/generate"

headers = {
    "Content-Type": "application/json"
}

data = {
    "model": "deepseek-coder",
    "prompt": "请介绍一下 DeepSeek。",
    "stream": True  # 开启流式输出
}

response = requests.post(API_URL, headers=headers, json=data, stream=True)

for line in response.iter_lines():
    if line:
        json_data = json.loads(line.decode("utf-8"))
        print(json_data.get("response", ""), end="", flush=True)

这样可以实时打印 DeepSeek 的 AI 回复。


3. Ollama 支持的 API 端点

端点 说明
http://localhost:11434/api/generate 生成文本(DeepSeek LLM)
http://localhost:11434/api/tags 列出可用模型
http://localhost:11434/api/show?name=deepseek-coder 查看模型信息
http://localhost:11434/api/pull 下载新模型

你可以在终端输入以下命令来查看 DeepSeek 模型是否正确加载:

curl http://localhost:11434/api/show?name=deepseek-coder

返回示例:

{
    "name": "deepseek-coder",
    "size": "33b",
    "parameters": {...}
}

4. 总结

  1. Ollama 运行的 DeepSeek 端口是 11434,不是 8000
  2. 使用 http://localhost:11434/api/generate 进行推理,而不是 OpenAI 的 /v1/chat/completions
  3. Ollama API 采用 "prompt" 代替 "messages",请求格式不同
  4. 可以使用 stream=True 实现流式输出,提高交互体验

如果你在调用过程中遇到问题,可以检查 API 端点或错误日志,或者反馈给我们! 🚀

posted @   李东阳  阅读(1888)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek “源神”启动!「GitHub 热点速览」
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 我与微信审核的“相爱相杀”看个人小程序副业
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· spring官宣接入deepseek,真的太香了~
点击右上角即可分享
微信分享提示