如何在Vue 3项目中引入和使用DeepSeek
时间: 2025-07-20 20:19:08 AIGC 浏览: 19
<think>我们正在讨论在Vue 3项目中集成DeepSeek。由于DeepSeek是一个AI模型,通常通过API调用使用,因此我们需要在Vue 3中调用其API。
步骤:
1. 注册DeepSeek账号并获取API密钥。
2. 在Vue项目中安装HTTP客户端(如axios)用于发送请求。
3. 创建服务模块来封装与DeepSeek API的交互。
4. 在Vue组件中调用该服务。
注意:由于DeepSeek API的具体细节可能随时间变化,请参考其官方文档获取最新信息。
以下是一个示例实现:
步骤1:获取DeepSeek API密钥
访问DeepSeek官网(https://platform.deepseek.com/)注册账号并获取API密钥。
步骤2:创建Vue 3项目(如果已有项目则跳过)
使用Vite创建项目:
```bash
npm create vite@latest my-deepseek-app -- --template vue
cd my-deepseek-app
```
步骤3:安装axios
```bash
npm install axios
```
步骤4:创建封装DeepSeek API的服务文件
在src目录下创建services/deepseek.js文件:
```javascript
import axios from 'axios';
const DEEPSEEK_API_URL = 'https://api.deepseek.com/v1/chat/completions'; // 假设这是DeepSeek聊天API的URL,请以官方文档为准
const API_KEY = 'your-api-key'; // 替换为你的API密钥
const deepseekApi = axios.create({
baseURL: DEEPSEEK_API_URL,
headers: {
'Authorization': `Bearer ${API_KEY}`,
'Content-Type': 'application/json'
}
});
export default {
getCompletion(prompt, model = 'deepseek-chat') {
const data = {
model: model,
messages: [
{ role: 'user', content: prompt }
]
};
return deepseekApi.post('', data);
}
};
```
步骤5:在Vue组件中使用
例如在App.vue中:
```vue
<script setup>
import { ref } from 'vue';
import deepseekService from './services/deepseek';
const userInput = ref('');
const response = ref('');
const isLoading = ref(false);
async function sendRequest() {
isLoading.value = true;
try {
const res = await deepseekService.getCompletion(userInput.value);
response.value = res.data.choices[0].message.content; // 根据实际API响应调整
} catch (error) {
console.error(error);
response.value = '请求失败';
} finally {
isLoading.value = false;
}
}
</script>
<template>
<div>
<textarea v-model="userInput"></textarea>
<button @click="sendRequest" :disabled="isLoading">发送</button>
<div v-if="isLoading">加载中...</div>
<div v-else>{{ response }}</div>
</div>
</template>
```
注意事项:
1. 上述代码中的API端点(DEEPSEEK_API_URL)和请求格式(data)需要根据DeepSeek官方文档调整。
2. 将API密钥存储在客户端代码中可能不安全,特别是当你的应用公开时。在生产环境中,建议通过你自己的后端服务器转发请求,以避免暴露API密钥。
安全建议:通过你自己的后端服务调用DeepSeek API,前端调用你的后端接口。这样你可以保护API密钥,并且可以在后端进行访问控制、缓存等。
如果必须在前端直接调用,请考虑使用环境变量来存储API密钥(但注意,前端环境变量仍然可能被用户看到)。在Vite项目中,可以创建.env.local文件(确保该文件不被提交到版本控制):
```
VITE_DEEPSEEK_API_KEY=your_api_key
```
然后在deepseek.js中通过`import.meta.env.VITE_DEEPSEEK_API_KEY`获取。
但是,强烈建议不要在前端直接使用敏感密钥,而是通过自己的后端代理。
以上示例仅供参考,具体实现需根据DeepSeek API的实际情况调整。
相关问题:
1. 如何在Vue 3中安全地存储和使用API密钥?
2. DeepSeek API的调用频率限制和费用是怎样的?
3. 如何处理DeepSeek API返回的错误?
4. 如何优化Vue 3应用中的API调用体验(如添加加载状态、错误提示)?</think>在 Vue 3 项目中集成 DeepSeek 主要涉及 API 调用和前端交互实现。以下是详细步骤:
### 1. 准备工作
- **获取 DeepSeek API Key**
注册 DeepSeek 账号并创建 API Key([官网入口](https://platform.deepseek.com/))
- **安装必要依赖**
```bash
npm install axios # HTTP 请求库
```
### 2. 创建 API 服务模块
在 `/src/services/deepseek.js` 中:
```javascript
import axios from 'axios';
const DEEPSEEK_API_URL = 'https://api.deepseek.com/v1/chat/completions';
export const askDeepSeek = async (prompt) => {
try {
const response = await axios.post(
DEEPSEEK_API_URL,
{
model: "deepseek-chat", // 指定模型
messages: [{ role: "user", content: prompt }]
},
{
headers: {
Authorization: `Bearer ${import.meta.env.VITE_DEEPSEEK_API_KEY}`,
"Content-Type": "application/json"
}
}
);
return response.data.choices[0].message.content;
} catch (error) {
console.error("DeepSeek API Error:", error.response?.data || error.message);
return "请求失败,请稍后重试";
}
};
```
### 3. 配置环境变量
在项目根目录创建 `.env.local` 文件:
```env
VITE_DEEPSEEK_API_KEY=your_api_key_here
```
### 4. 在 Vue 组件中使用
示例组件 `/src/components/DeepSeekChat.vue`:
```vue
<script setup>
import { ref } from 'vue';
import { askDeepSeek } from '@/services/deepseek';
const userInput = ref('');
const response = ref('');
const isLoading = ref(false);
const submitQuery = async () => {
if (!userInput.value.trim()) return;
isLoading.value = true;
try {
response.value = await askDeepSeek(userInput.value);
} finally {
isLoading.value = false;
}
};
</script>
<template>
<div class="chat-container">
<textarea v-model="userInput" placeholder="输入问题..."></textarea>
<button @click="submitQuery" :disabled="isLoading">
{{ isLoading ? '思考中...' : '提问' }}
</button>
<div v-if="response" class="response-box">
<h3>DeepSeek 回答:</h3>
<pre>{{ response }}</pre>
</div>
</div>
</template>
<style scoped>
.chat-container {
max-width: 600px;
margin: 0 auto;
}
textarea {
width: 100%;
height: 100px;
}
.response-box {
margin-top: 20px;
padding: 15px;
border: 1px solid #eee;
border-radius: 8px;
}
</style>
```
### 5. 安全注意事项
1. **API 密钥保护**
- 永远不要在前端代码硬编码 API Key
- 使用环境变量(Vite 通过 `import.meta.env` 读取)
- 生产环境建议通过后端代理转发请求(Node.js/Express 示例):
```javascript
// 后端路由示例
app.post('/api/deepseek', async (req, res) => {
const response = await axios.post(DEEPSEEK_API_URL, req.body, {
headers: { Authorization: `Bearer ${process.env.DEEPSEEK_API_KEY}` }
});
res.json(response.data);
});
```
2. **速率限制处理**
DeepSeek API 有调用频率限制(参考官方文档),建议:
- 前端添加请求间隔(至少 1 秒)
- 重要功能使用后端缓存
### 6. 扩展功能建议
- 添加对话历史记忆功能
- 实现流式响应(使用 WebSocket)
- 集成 Markdown 渲染(使用 `marked` 库)
- 添加代码语法高亮(使用 `highlight.js`)
> 提示:DeepSeek 的模型参数可通过 `temperature`(0-2)控制创造性,`max_tokens` 控制响应长度,具体参数参考 [API 文档](https://platform.deepseek.com/api-docs/)。
阅读全文
相关推荐




















