在这个最新的 DeepSeek API 集成教程中,我将详细介绍如何在 Docusaurus 博客中开发 AI 对话助手。本教程基于实际项目实践,包含完整的代码示例和实现步骤。
1. 基础环境准备
1.1 安装依赖
首先需要安装必要的依赖包:
pnpm add openai
1.2 项目结构
我们需要创建以下文件:
src/
├── components/
│ └── DeepseekChat/
│ └── index.tsx # 聊天组件
├── utils/
│ └── deepseek.ts # DeepSeek 工具类
└── pages/
└── ai-chat.tsx # AI 聊天页面
2. 核心代码实现
2.1 DeepSeek 工具类
在 src/utils/deepseek.ts
中实现 DeepSeek API 的调用:
import OpenAI from 'openai';
import type { ChatCompletionMessageParam } from 'openai/resources/chat/completions';
// 创建 OpenAI 客户端工厂函数
function createOpenAIClient(apiKey: string) {
return new OpenAI({
baseURL: 'https://api.deepseek.com',
apiKey,
dangerouslyAllowBrowser: true // 警告:这种方式在生产环境中不安全
});
}
// 基本的聊天完成函数
export async function chatWithDeepseek(
messages: ChatCompletionMessageParam[],
apiKey: string,
model: string = 'deepseek-chat'
) {
const openai = createOpenAIClient(apiKey);
try {
const completion = await openai.chat.completions.create({
messages,
model,
});
return completion.choices[0]?.message?.content || '';
} catch (error) {
console.error('Deepseek API 调用错误:', error);
throw error;
}
}
// 使用系统预设的聊天函数
export async function chatWithSystem(
content: string,
apiKey: string,
systemPrompt: string = 'You are a helpful assistant.'
) {
const messages: ChatCompletionMessageParam[] = [
{ role: 'system', content: systemPrompt },
{ role: 'user', content }
];
return chatWithDeepseek(messages, apiKey);
}