以下为 Vue3 对接 DeepSeek 的完整指南,包含核心场景、常见问题解决方案及代码示例。内容综合官方文档与实战经验,覆盖开发全流程。
一、基础对接流程
1. API 密钥获取
- 注册 DeepSeek 账号并创建 API Key(官网入口)
- 建议将密钥存储在环境变量中(如
.env.local
):VITE_DEEPSEEK_API_KEY=sk-your-api-key VITE_DEEPSEEK_BASE_URL=https://api.deepseek.com
2. Vue3 项目集成
<script setup>
import { ref } from 'vue'
import axios from 'axios'
const apiKey = import.meta.env.VITE_DEEPSEEK_API_KEY
const baseURL = import.meta.env.VITE_DEEPSEEK_BASE_URL
const messages = ref([{ role: 'system', content: '你是一个专业的助手' }])
const userInput = ref('')
const isLoading = ref(false)
const sendToDeepSeek = async () => {
try {
isLoading.value = true
const response = await axios.post(
`${baseURL}/chat/completions`,
{
model: 'deepseek-chat',
messages: [...messages.value, { role: 'user', content: userInput.value }],
temperature: 0.7,
stream: false // 流式传输需特殊处理
},
{
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
}
}
)
messages.value.push(response.data.choices[0].message)
} catch (error) {
console.error('API调用失败:', error.response?.data || error.message)
} finally {
isLoading.value = false
}
}
</script>
二、核心应用场景
1. 智能对话系统
- 实现效果:类 ChatGPT 交互界面
- 优化点:
- 添加流式响应(需使用
EventSource
或 WebSocket) - 通过
temperature
参数控制回答创意性(0-1,值越大越随机)
- 添加流式响应(需使用
2. 内容生成引擎
// 生成营销文案示例