Chat API
DeepSeek Chat API 提供强大的对话生成能力,支持多轮对话、上下文理解和智能回复。
基本用法
发送聊天请求
bash
curl -X POST "https://api.deepseek.com/v1/chat/completions" \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "deepseek-chat",
"messages": [
{
"role": "user",
"content": "你好,请介绍一下 DeepSeek"
}
]
}'
响应格式
json
{
"id": "chatcmpl-123",
"object": "chat.completion",
"created": 1677652288,
"model": "deepseek-chat",
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "DeepSeek 是一个先进的人工智能平台..."
},
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": 12,
"completion_tokens": 100,
"total_tokens": 112
}
}
参数说明
参数 | 类型 | 必需 | 描述 |
---|---|---|---|
model | string | 是 | 使用的模型名称 |
messages | array | 是 | 对话消息列表 |
temperature | number | 否 | 控制输出随机性 (0-2) |
max_tokens | integer | 否 | 最大生成 token 数 |
stream | boolean | 否 | 是否启用流式输出 |
高级功能
多轮对话
javascript
const messages = [
{ role: "user", content: "什么是机器学习?" },
{ role: "assistant", content: "机器学习是人工智能的一个分支..." },
{ role: "user", content: "能举个具体例子吗?" }
];
流式输出
javascript
const response = await fetch('https://api.deepseek.com/v1/chat/completions', {
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
body: JSON.stringify({
model: 'deepseek-chat',
messages: messages,
stream: true
})
});
最佳实践
- 上下文管理: 合理控制对话历史长度
- 错误处理: 实现重试机制和错误恢复
- 性能优化: 使用流式输出提升用户体验
- 安全考虑: 妥善保管 API 密钥