Python 调用本地部署DeepSeek的API 详细指南
使用 http://localhost:11434/api/generate 进行推理,而不是 OpenAI 的 /v1/chat/completions。API_URL = “http://localhost:11434/api/generate”# Ollama API 端点。“model” 需要匹配你的 Ollama 里安装的 DeepSeek 模型,比如 “deepseek-coder”。
B站先查看deepseek的应用和API调用和本地化部署这三方面知识
- 确认 Ollama 是否正确运行
如果你使用 Ollama 部署了 DeepSeek,默认 API 运行在 11434 端口。首先,检查 Ollama 是否正常运行:
curl http://localhost:11434/api/tags
如果返回:
{“models”:[“deepseek-coder:latest”, “deepseek-chat:latest”]}
说明 Ollama 运行正常,并且已安装 DeepSeek 模型。
- 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 回复。
- 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 实现流式输出,提高交互体验。
火山引擎开发者社区是火山引擎打造的AI技术生态平台,聚焦Agent与大模型开发,提供豆包系列模型(图像/视频/视觉)、智能分析与会话工具,并配套评测集、动手实验室及行业案例库。社区通过技术沙龙、挑战赛等活动促进开发者成长,新用户可领50万Tokens权益,助力构建智能应用。
更多推荐
所有评论(0)