Golang

关注公众号 jb51net

关闭
首页 > 脚本专栏 > Golang > Go调用DeepSeek API

Go语言调用DeepSeek API实现流式输出和对话

作者:老大白菜

DeepSeek是一个强大的AI模型服务平台,本文将详细介绍如何使用Go语言调用DeepSeek API实现流式输出和对话功能,感兴趣的小伙伴可以了解一下

引言

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
}

参数说明:

3.3 对话记录

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

4. 使用示例

运行程序:

go run main.go

输入问题,比如:

请输入您的问题: 介绍一下 DeepSeek 的主要特点

观察实时输出和 conversation.txt 文件记录

5. 错误处理和最佳实践

1.API 密钥管理

2.错误处理

3.性能优化

总结

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

到此这篇关于Go语言调用DeepSeek API的完整指南的文章就介绍到这了,更多相关Go调用DeepSeek API内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文