前端直连大模型:使用 Vite 调用 DeepSeek API 实战指南
1. 核心思想
- 大语言模型(如 DeepSeek)可通过标准 HTTP 请求从前端直接调用。
- 使用
fetchAPI 发送 POST 请求到 LLM 的 RESTful 接口。 - 需要 API Key 进行身份认证,建议通过环境变量管理密钥。
2. 项目初始化(基于 Vite)
创建原生 HTML/JS 项目
npm create vite@latest my-llm-app -- --template vanilla
cd my-llm-app
npm install
环境变量配置(.env 文件)
在项目根目录创建 .env 文件:
VITE_DEEPSEEK_API_KEY=your_actual_api_key_here
✅ Vite 会自动加载以
VITE_开头的环境变量,并在客户端代码中通过import.meta.env.VITE_DEEPSEEK_API_KEY访问。
3. HTML 结构示例
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite + DeepSeek</title>
<link rel="stylesheet" href="/style.css" />
</head>
<body>
<h1>你好 DeepSeek</h1>
<div id="reply"></div>
<script type="module" src="/main.js"></script>
</body>
</html>
4. JavaScript 调用 LLM(main.js)
// LLM API 地址
const endpoint = 'https://api.deepseek.com/chat/completions';
// 请求头(含认证)
const headers = {
'Content-Type': 'application/json',
'Authorization': `Bearer ${import.meta.env.VITE_DEEPSEEK_API_KEY}`
};
// 请求体(注意:messages 是数组,每个消息有 role 和 content)
const payload = {
model: 'deepseek-chat',
messages: [
{ role: 'system', content: 'You are a helpful assistant.' },
{ role: 'user', content: '你好 DeepSeek' }
]
};
// 发送请求(使用 async/await 更简洁)
(async () => {
try {
const response = await fetch(endpoint, {
method: 'POST',
headers,
body: JSON.stringify(payload)
});
const data = await response.json();
console.log(data);
// 显示回复内容
document.getElementById('reply').textContent = data.choices[0].message.content;
} catch (error) {
console.error('请求失败:', error);
document.getElementById('reply').textContent = '请求出错,请检查网络或 API Key。';
}
})();
⚠️ 注意:
messages数组中不能重复定义role键!原始代码中有语法错误(两个role在同一个对象里),已修正为两个独立消息对象。
5. HTTP 请求详解(LLM 调用)
| 组成部分 | 说明 |
|---|---|
| Method | POST(因为需要发送请求体) |
| URL | https://api.deepseek.com/chat/completions |
| Headers | - Content-Type: application/json - Authorization: Bearer <API_KEY> |
| Body | JSON 字符串,包含 model 和 messages 字段 |
| 响应 | 返回 JSON,结果在 data.choices[0].message.content 中 |
6. 安全与工程化建议
-
🔒 不要将 API Key 硬编码在代码中 → 使用
.env+VITE_前缀。 -
🛡️ 生产环境中应通过后端代理调用 LLM,避免前端暴露密钥(当前方式仅适合演示或内部工具)。
-
🧪 开发命令:
npm run dev # 启动本地开发服务器
7. 常见问题
- Authentication Fails:检查
.env中的 API Key 是否正确,是否以VITE_开头,是否重启了 dev server。 - CORS 错误:部分 LLM API 不允许浏览器直接跨域请求,此时需搭建代理(如 Vite 的
server.proxy或自建后端)。
💡 提示:虽然前端可直接调用 LLM,但出于安全和性能考虑,正式项目推荐通过自己的后端服务中转请求。