前端调用deepseek api
时间: 2025-02-18 22:45:58 AIGC 浏览: 241
### 如何在前端 JavaScript 中调用 DeepSeek API
为了在前端项目中集成并调用 DeepSeek API,开发者可以利用 Fetch API 或 Axios 库发送 HTTP 请求到指定的端点。下面是一个基于 Fetch API 的简单例子,展示了如何构建请求以及处理来自 DeepSeek API 的响应。
#### 使用 Fetch API 调用 DeepSeek API
```javascript
async function callDeepSeekApi(prompt, apiKey) {
const url = 'https://api.deepseek.com/v1/chat/completions'; // 假设这是官方提供的API地址[^2]
try {
const response = await fetch(url, {
method: 'POST',
headers: new Headers({
'Content-Type': 'application/json',
Authorization: `Bearer ${apiKey}`
}),
body: JSON.stringify({
messages: [{ role: "user", content: prompt }],
stream: false // 如果希望启用流式输出,则设置为true
})
});
if (!response.ok) throw Error(response.statusText);
let data = await response.json();
console.log('Response from DeepSeek:', data);
return data;
} catch (error) {
console.error('Error calling the DeepSeek API:', error.message);
}
}
```
此函数接受两个参数:`prompt` 和 `apiKey`。前者代表要传递给 AI 模型的消息文本;后者则是用于身份验证的服务密钥。通过调整 `stream` 参数的布尔值状态,可以选择同步还是异步接收回复数据。
阅读全文
相关推荐




















