【deepseek】官方API的申请和调用
文章目录
- 申请API
- 查看API文档
- API调用实验
- 实验一:cURL 调用方案
- 实验二:Python 调用方案
- 实验三:Node.js 调用方案
申请API
https://www.deepseek.com/
API价格参考
查看API文档
API调用实验
实验设计要点:
curl:在命令行中使用,展示最基础的HTTP请求。
Python:使用requests库,简洁明了。
Node.js:使用原生http模块或axios库(Express框架更容易,不过这里我们不需要框架,只需要发起请求)。
注意:由于是实验,我们假设已经有了API密钥(API_KEY)和API端点(API_URL)。为了安全,实验中应提醒用户替换自己的API密钥。
实验一:cURL 调用方案
适用场景:快速验证接口可用性/命令行调试
核心代码:
curl https://api.deepseek.com/chat/completions \-H "Content-Type: application/json" \-H "Authorization: Bearer <DeepSeek API Key>" \-d '{"model": "deepseek-chat","messages": [{"role": "system", "content": "You are a helpful assistant."},{"role": "user", "content": "解释量子纠缠现象"}],"stream": false}'
实验设计:
环境准备:终端安装 curl(Linux/macOS 默认支持,Windows 需安装 curl)
实验二:Python 调用方案
适用场景:自动化脚本/数据处理密集型任务
核心代码:
# Please install OpenAI SDK first: `pip3 install openai`from openai import OpenAIclient = OpenAI(api_key="<DeepSeek API Key>", base_url="https://api.deepseek.com")response = client.chat.completions.create(model="deepseek-chat",messages=[{"role": "system", "content": "You are a helpful assistant"},{"role": "user", "content": "解释量子纠缠现象"},],stream=False
)print(response.choices[0].message.content)
实验前提:
1.pip3 install openai
#必做
2. python -m pip install --upgrade pip
#选做
实验结果如下图
实验三:Node.js 调用方案
适用场景:高并发服务/实时应用
核心代码:
// Please install OpenAI SDK first: `npm install openai`import OpenAI from "openai";const openai = new OpenAI({baseURL: 'https://api.deepseek.com',apiKey: '<DeepSeek API Key>'
});async function main() {const completion = await openai.chat.completions.create({messages: [{ role: "system", content: "You are a helpful assistant." }],model: "deepseek-chat",});console.log(completion.choices[0].message.content);
}main();