DeepSeek 是一个强大的 AI 模型服务平台,本文将详细介绍如何使用 Go 语言调用 DeepSeek API,实现流式输出和对话功能。
Deepseek的api因为被功击已不能用,本文以 DeepSeek:https://cloud.siliconflow.cn/i/vnCCfVaQ 为例子进行讲解。
首先,我们需要准备以下内容:
mkdir deepseek-go
cd deepseek-go
go mod init deepseek-go
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)
}
}
}
}
}
DeepSeek API 支持流式输出(Stream),通过设置 "stream": true
,我们可以实现实时显示 AI 回复的效果。这带来了更好的用户体验:
{
"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
: 控制重复度程序会自动将所有对话保存到 conversation.txt
文件中,包含:
go run main.go
请输入您的问题: 介绍一下 DeepSeek 的主要特点
通过本文的介绍,你应该已经掌握了如何使用 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