以下是一个简单的 DeepSeek 编程示例,通过 API 调用实现智能对话功能:文末有链接
一、环境准备
pip install requests # 安装 HTTP 请求库:ml-citation{ref="2" data="citationList"}
二、代码实现
import requests
def chat_with_deepseek(prompt):
api_url = "https://api.deepseek.com/v1/chat/completions"
headers = {
"Authorization": "Bearer sk-your-api-key-here", # 替换为实际 API Key:ml-citation{ref="3" data="citationList"}
"Content-Type": "application/json"
}
data = {
"model": "deepseek-chat",
"messages": [{"role": "user", "content": prompt}]
}
response = requests.post(api_url, headers=headers, json=data)
return response.json()['choices']['message']['content']
# 示例调用
response = chat_with_deepseek("用Python写一个计算阶乘的函数")
print(response)
三、输出示例
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
四、操作说明
- API Key 获取:登录 DeepSeek 官网创建 API Key3
- 参数说明:
model
可选deepseek-chat
(通用对话)或deepseek-coder
(代码生成)3- 通过修改
messages
数组实现多轮对话2
五、进阶应用(可选)
- 增加流式输出:通过 SSE 技术实现逐字打印效果3
- 错误处理:添加
try-except
块捕获 API 异常2
注:完整项目配置可参考 Solon 框架集成方案3,复杂需求建议采用分步指令优化5
我用夸克网盘分享了「无需网络快速部署deepseek」
链接:https://pan.quark.cn/s/ef2952713469