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

B站先查看deepseek的应用和API调用和本地化部署这三方面知识

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

curl http://localhost:11434/api/tags
如果返回:

{“models”:[“deepseek-coder:latest”, “deepseek-chat:latest”]}
说明 Ollama 运行正常,并且已安装 DeepSeek 模型。

  1. 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 回复。

  1. 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. 总结
Ollama 运行的 DeepSeek 端口是 11434,不是 8000。
使用 http://localhost:11434/api/generate 进行推理,而不是 OpenAI 的 /v1/chat/completions。
Ollama API 采用 “prompt” 代替 “messages”,请求格式不同。
可以使用 stream=True 实现流式输出,提高交互体验。

你可能感兴趣的:(python)