使用 Go 语言调用 DeepSeek API:完整指南

时间:2025-02-05 08:21:59

引言

DeepSeek 是一个强大的 AI 模型服务平台,本文将详细介绍如何使用 Go 语言调用 DeepSeek API,实现流式输出和对话功能。
Deepseek的api因为被功击已不能用,本文以 DeepSeek:https://cloud.siliconflow.cn/i/vnCCfVaQ 为例子进行讲解。

1. 环境准备

首先,我们需要准备以下内容:

  • Go 语言环境
  • DeepSeek API 访问权限
  • 开发工具(如 VS Code)

2. 基础代码实现

2.1 创建项目结构

mkdir deepseek-go
cd deepseek-go
go mod init deepseek-go

2.2 核心代码实现

package main

import (
    "bufio"
    "encoding/json"
    "fmt"
    "net/http"
    "os"
    "strings"
    "time"
)

// 定义响应结构
type ChatResponse struct {
    Choices []struct {
        Delta struct {
            Content string `json:"content"`
        } `json:"delta"`
    } `json:"choices"`
}

func main() {
    // 创建输出文件
    file, err := os.OpenFile("conversation.txt", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
    if err != nil {
        fmt.Printf("Error opening file: %v\n", err)
        return
    }
    defer file.Close()

    // API 配置
    url := "https://api.siliconflow.cn/v1/chat/completions"
    
    for {
        // 获取用户输入
        fmt.Print("\n请输入您的问题 (输入 q 退出): ")
        reader := bufio.NewReader(os.Stdin)
        question, _ := reader.ReadString('\n')
        question = strings.TrimSpace(question)
        
        if question == "q" {
            break
        }

        // 记录对话时间
        timestamp := time.Now().Format("2006-01-02 15:04:05")
        file.WriteString(fmt.Sprintf("\n[%s] Question:\n%s\n\n", timestamp, question))

        // 构建请求体
        payload := fmt.Sprintf(`{
            "model": "deepseek-ai/DeepSeek-V3",
            "messages": [
                {
                    "role": "user",
                    "content": "%s"
                }
            ],
            "stream": true,
            "max_tokens": 2048,
            "temperature": 0.7
        }`, question)

        // 发送请求
        req, _ := http.NewRequest("POST", url, strings.NewReader(payload))
        req.Header.Add("Content-Type", "application/json")
        req.Header.Add("Authorization", "Bearer YOUR_API_KEY")  // 替换为你的 API Key

        // 获取响应
        res, _ := http.DefaultClient.Do(req)
        defer res.Body.Close()

        // 处理流式响应
        scanner := bufio.NewReader(res.Body)
        for {
            line, err := scanner.ReadString('\n')
            if err != nil {
                break
            }

            line = strings.TrimSpace(line)
            if line == "" || line == "data: [DONE]" {
                continue
            }

            if strings.HasPrefix(line, "data: ") {
                line = strings.TrimPrefix(line, "data: ")
            }

            var response ChatResponse
            if err := json.Unmarshal([]byte(line), &response); err != nil {
                continue
            }

            if len(response.Choices) > 0 {
                content := response.Choices[0].Delta.Content
                if content != "" {
                    fmt.Print(content)
                    file.WriteString(content)
                }
            }
        }
    }
}

3. 主要特性说明

3.1 流式输出

DeepSeek API 支持流式输出(Stream),通过设置 "stream": true,我们可以实现实时显示 AI 回复的效果。这带来了更好的用户体验:

  • 即时看到响应内容
  • 减少等待时间
  • 更自然的对话体验

3.2 参数配置

{
    "model": "deepseek-ai/DeepSeek-V3",
    "messages": [...],
    "stream": true,
    "max_tokens": 2048,
    "temperature": 0.7,
    "top_p": 0.7,
    "top_k": 50,
    "frequency_penalty": 0.5
}

参数说明:

  • model: 选择使用的模型
  • max_tokens: 最大输出长度
  • temperature: 温度参数,控制输出的随机性
  • top_p, top_k: 控制采样策略
  • frequency_penalty: 控制重复度

3.3 对话记录

程序会自动将所有对话保存到 conversation.txt 文件中,包含:

  • 时间戳
  • 用户问题
  • AI 回答
  • 格式化的分隔符

4. 使用示例

  1. 运行程序:
go run main.go
  1. 输入问题,比如:
请输入您的问题: 介绍一下 DeepSeek 的主要特点
  1. 观察实时输出和 conversation.txt 文件记录

5. 错误处理和最佳实践

  1. API 密钥管理
  • 使用环境变量存储 API 密钥
  • 不要在代码中硬编码密钥
  • 定期轮换密钥
  1. 错误处理
  • 检查网络连接
  • 验证 API 响应
  • 处理流式输出中断
  1. 性能优化
  • 使用适当的 buffer 大小
  • 及时关闭连接
  • 处理并发请求

总结

通过本文的介绍,你应该已经掌握了如何使用 Go 语言调用 DeepSeek API 的基本方法。DeepSeek 提供了强大的 AI 能力,配合 Go 语言的高效性能,可以构建出各种有趣的应用。

立即体验

想要体验 DeepSeek 的强大功能?现在就开始吧!

快来体验 DeepSeek:https://cloud.siliconflow.cn/i/vnCCfVaQ

快来体验 DeepSeek:https://cloud.siliconflow.cn/i/vnCCfVaQ

快来体验 DeepSeek:https://cloud.siliconflow.cn/i/vnCCfVaQ