DeepSeek API 整合指南 - 新手教程

什么是 DeepSeek API?

DeepSeek API 是一个强大的人工智能接口,让开发者能够在自己的应用中集成高级的自然语言处理能力。DeepSeek 提供两种主要模型:

通过本教程,你将学习如何在HTML网页中集成DeepSeek API,让你的网站具备AI对话能力!

步骤 1 获取 DeepSeek API Key

在开始之前,你需要获取DeepSeek API Key:

  1. 访问 DeepSeek Open Platform
  2. 注册并登录你的账户
  3. 导航到API Keys选项卡
  4. 点击"创建新的API Key"
  5. 为你的API Key设置一个名称,然后复制它
安全警告: API Key是你的私人凭证,类似密码。永远不要在客户端代码中暴露它,不要将其公开分享,否则可能被滥用,并导致非预期的账单费用。在生产环境中,应该使用服务器端代码来保护你的API Key。本教程仅用于学习目的。

步骤 2 创建基本的HTML结构

首先,我们需要创建一个基本的HTML页面结构:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>DeepSeek API 演示</title>
    <style>
        body {
            font-family: 'Microsoft YaHei', sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }
        .container {
            border: 1px solid #ddd;
            padding: 20px;
            border-radius: 5px;
        }
        #apiKey {
            width: 100%;
            padding: 10px;
            margin: 10px 0;
        }
        #promptInput {
            width: 100%;
            padding: 10px;
            margin: 10px 0;
        }
        #response {
            background-color: #f5f5f5;
            padding: 15px;
            margin-top: 15px;
            min-height: 100px;
            white-space: pre-wrap;
        }
    </style>
</head>
<body>
    <h1>DeepSeek API 演示</h1>
    
    <div class="container">
        <h2>配置</h2>
        <label for="apiKey">输入你的 DeepSeek API Key:</label>
        <input type="password" id="apiKey" placeholder="sk-...">
        
        <h2>发送请求</h2>
        <label for="promptInput">输入你的提示词:</label>
        <textarea id="promptInput" rows="4" placeholder="请在这里输入你的问题..."></textarea>
        <button id="sendBtn">发送请求</button>
        
        <div id="loading" class="loading">处理中...</div>
        
        <h2>响应结果</h2>
        <div id="response"></div>
    </div>

    <!-- 在这里我们将添加 JavaScript 代码 -->
    
</body>
</html>

这段代码创建了一个简单的页面,包含输入API Key的字段、提示词输入框和发送按钮,以及一个显示响应结果的区域。

步骤 3 添加JavaScript代码实现API调用

现在,我们需要添加JavaScript代码来调用DeepSeek API。将以下代码添加到HTML文件的底部,在<!-- 在这里我们将添加 JavaScript 代码 -->注释的位置:

<script>
    document.getElementById('sendBtn').addEventListener('click', async function() {
        // 获取用户输入
        const apiKey = document.getElementById('apiKey').value;
        const promptText = document.getElementById('promptInput').value;
        const responseElement = document.getElementById('response');
        const loadingElement = document.getElementById('loading');
        
        // 验证输入
        if (!apiKey || !promptText) {
            responseElement.textContent = "请输入API Key和提示词";
            return;
        }
        
        // 显示加载提示
        loadingElement.style.display = 'block';
        responseElement.textContent = "";
        
        try {
            // 准备请求数据
            const requestData = {
                model: "deepseek-chat", // 使用deepseek-chat模型,你也可以换成deepseek-reasoner
                messages: [
                    { role: "system", content: "你是一个有帮助的助手。" },
                    { role: "user", content: promptText }
                ],
                stream: false // 设置为true可以获得流式响应
            };
            
            // 发送请求到DeepSeek API
            const response = await fetch('https://api.deepseek.com/chat/completions', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${apiKey}`
                },
                body: JSON.stringify(requestData)
            });
            
            // 处理响应
            if (!response.ok) {
                const errorData = await response.json();
                throw new Error(`API错误: ${errorData.error?.message || '未知错误'}`);
            }
            
            const data = await response.json();
            responseElement.textContent = data.choices[0].message.content;
        } catch (error) {
            responseElement.textContent = `发生错误: ${error.message}`;
            console.error('API调用错误:', error);
        } finally {
            // 隐藏加载提示
            loadingElement.style.display = 'none';
        }
    });
</script>

这段JavaScript代码完成了以下任务:

  1. 监听"发送请求"按钮的点击事件
  2. 获取用户输入的API Key和提示词
  3. 验证输入并显示加载状态
  4. 准备请求数据并发送到DeepSeek API
  5. 处理API响应并显示结果或错误信息

步骤 4 使用OpenAI SDK更简便的方法(可选)

DeepSeek API兼容OpenAI的API格式,因此我们也可以使用OpenAI的JavaScript SDK来调用它。这种方法在某些情况下更简洁。

首先,我们需要在HTML头部添加OpenAI SDK:

<script src="https://unpkg.com/[email protected]/dist/index.js"></script>

然后,替换之前的JavaScript代码为:

<script>
    document.getElementById('sendBtn').addEventListener('click', async function() {
        // 获取用户输入
        const apiKey = document.getElementById('apiKey').value;
        const promptText = document.getElementById('promptInput').value;
        const responseElement = document.getElementById('response');
        const loadingElement = document.getElementById('loading');
        
        // 验证输入
        if (!apiKey || !promptText) {
            responseElement.textContent = "请输入API Key和提示词";
            return;
        }
        
        // 显示加载提示
        loadingElement.style.display = 'block';
        responseElement.textContent = "";
        
        try {
            // 使用OpenAI SDK创建客户端
            const openai = new OpenAI({
                apiKey: apiKey,
                baseURL: 'https://api.deepseek.com',
                dangerouslyAllowBrowser: true // 注意:在生产环境中不建议在浏览器中直接使用API Key
            });
            
            // 发送请求
            const completion = await openai.chat.completions.create({
                messages: [
                    { role: "system", content: "你是一个有帮助的助手。" },
                    { role: "user", content: promptText }
                ],
                model: "deepseek-chat",
            });
            
            // 显示响应
            responseElement.textContent = completion.choices[0].message.content;
        } catch (error) {
            responseElement.textContent = `发生错误: ${error.message}`;
            console.error('API调用错误:', error);
        } finally {
            // 隐藏加载提示
            loadingElement.style.display = 'none';
        }
    });
</script>
重要提示: 这种方法使用了dangerouslyAllowBrowser: true参数,这在生产环境中是不安全的,因为它会在客户端暴露你的API Key。实际应用中,应该通过服务器端代码来处理API请求。

步骤 5 测试你的集成

现在你可以保存HTML文件并在浏览器中打开它,测试你的DeepSeek API集成了。

  1. 输入你的DeepSeek API Key
  2. 在提示词框中输入一个问题
  3. 点击"发送请求"按钮
  4. 等待响应显示在结果区域
提示: 如果遇到跨域问题,这是因为浏览器的安全策略。在实际应用中,你应该使用服务器端代码来代理API请求,或设置适当的CORS头。

生产环境中的最佳实践

在实际应用中,应遵循以下最佳实践:

  1. 保护你的API Key:永远不要在客户端代码中暴露API Key。使用服务器端代码来处理API请求。
  2. 实现错误处理:添加完善的错误处理,以提供更好的用户体验。
  3. 添加速率限制:实现速率限制,以防止API滥用和意外的费用。
  4. 考虑流式响应:对于更好的用户体验,可以使用流式响应(stream=true)来实现打字机效果。
  5. 实现上下文对话:保存对话历史,以实现多轮对话支持。

演示(仅供参考)

DeepSeek API 演示

处理中...

响应结果

注意: 这个演示界面不会实际工作,因为这只是一个静态HTML示例。要测试功能,请将完整代码保存为HTML文件并在本地浏览器中打开。

进一步学习

恭喜!你已经学会了如何在HTML网页中集成DeepSeek API。如果你想进一步提升你的集成,可以考虑:

要了解更多信息,请访问DeepSeek API官方文档