Go語言調(diào)用DeepSeek?API實(shí)現(xiàn)流式輸出和對話
引言
DeepSeek 是一個強(qiáng)大的 AI 模型服務(wù)平臺,本文將詳細(xì)介紹如何使用 Go 語言調(diào)用 DeepSeek API,實(shí)現(xiàn)流式輸出和對話功能。
Deepseek的api因?yàn)楸还粢巡荒苡?,本文?DeepSeek:https://cloud.siliconflow.cn/i/vnCCfVaQ 為例子進(jìn)行講解。
1. 環(huán)境準(zhǔn)備
首先,我們需要準(zhǔn)備以下內(nèi)容:
Go 語言環(huán)境
DeepSeek API 訪問權(quán)限
開發(fā)工具(如 VS Code)
2. 基礎(chǔ)代碼實(shí)現(xiàn)
2.1 創(chuàng)建項(xiàng)目結(jié)構(gòu)
mkdir deepseek-go cd deepseek-go go mod init deepseek-go
2.2 核心代碼實(shí)現(xiàn)
package main
import (
"bufio"
"encoding/json"
"fmt"
"net/http"
"os"
"strings"
"time"
)
// 定義響應(yīng)結(jié)構(gòu)
type ChatResponse struct {
Choices []struct {
Delta struct {
Content string `json:"content"`
} `json:"delta"`
} `json:"choices"`
}
func main() {
// 創(chuàng)建輸出文件
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
}
// 記錄對話時(shí)間
timestamp := time.Now().Format("2006-01-02 15:04:05")
file.WriteString(fmt.Sprintf("\n[%s] Question:\n%s\n\n", timestamp, question))
// 構(gòu)建請求體
payload := fmt.Sprintf(`{
"model": "deepseek-ai/DeepSeek-V3",
"messages": [
{
"role": "user",
"content": "%s"
}
],
"stream": true,
"max_tokens": 2048,
"temperature": 0.7
}`, question)
// 發(fā)送請求
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
// 獲取響應(yīng)
res, _ := http.DefaultClient.Do(req)
defer res.Body.Close()
// 處理流式響應(yīng)
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),通過設(shè)置 "stream": true,我們可以實(shí)現(xiàn)實(shí)時(shí)顯示 AI 回復(fù)的效果。這帶來了更好的用戶體驗(yàn):
- 即時(shí)看到響應(yīng)內(nèi)容
- 減少等待時(shí)間
- 更自然的對話體驗(yàn)
3.2 參數(shù)配置
{
"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
}
參數(shù)說明:
- model: 選擇使用的模型
- max_tokens: 最大輸出長度
- temperature: 溫度參數(shù),控制輸出的隨機(jī)性
- top_p, top_k: 控制采樣策略
- frequency_penalty: 控制重復(fù)度
3.3 對話記錄
程序會自動將所有對話保存到 conversation.txt 文件中,包含:
- 時(shí)間戳
- 用戶問題
- AI 回答
- 格式化的分隔符
4. 使用示例
運(yùn)行程序:
go run main.go
輸入問題,比如:
請輸入您的問題: 介紹一下 DeepSeek 的主要特點(diǎn)
觀察實(shí)時(shí)輸出和 conversation.txt 文件記錄
5. 錯誤處理和最佳實(shí)踐
1.API 密鑰管理
- 使用環(huán)境變量存儲 API 密鑰
- 不要在代碼中硬編碼密鑰
- 定期輪換密鑰
2.錯誤處理
- 檢查網(wǎng)絡(luò)連接
- 驗(yàn)證 API 響應(yīng)
- 處理流式輸出中斷
3.性能優(yōu)化
- 使用適當(dāng)?shù)?buffer 大小
- 及時(shí)關(guān)閉連接
- 處理并發(fā)請求
總結(jié)
通過本文的介紹,你應(yīng)該已經(jīng)掌握了如何使用 Go 語言調(diào)用 DeepSeek API 的基本方法。DeepSeek 提供了強(qiáng)大的 AI 能力,配合 Go 語言的高效性能,可以構(gòu)建出各種有趣的應(yīng)用。
到此這篇關(guān)于Go語言調(diào)用DeepSeek API的完整指南的文章就介紹到這了,更多相關(guān)Go調(diào)用DeepSeek API內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
gorm整合進(jìn)go-zero的實(shí)現(xiàn)方法
go-zero提供的代碼生成器里面,沒有提供orm框架操作,但是提供了遍歷的緩存操作,所以可以利用gorm當(dāng)作一個sql語句的生成器,把生成后的sql語句放到go-zero生成的模板中去執(zhí)行,對gorm整合進(jìn)go-zero的實(shí)現(xiàn)方法感興趣的朋友一起看看吧2022-03-03
Go單體服務(wù)開發(fā)最佳實(shí)踐總結(jié)
這篇文章主要介紹了Go單體服務(wù)開發(fā)最佳實(shí)踐,通過本文詳細(xì)跟大家分享一下如何使用?go-zero?快速開發(fā)一個有多個模塊的單體服務(wù),需要的朋友可以參考下2022-04-04
Golang 實(shí)現(xiàn) RTP音視頻傳輸示例詳解
這篇文章主要為大家介紹了Golang實(shí)現(xiàn)RTP音視頻傳輸?shù)氖纠斀猓行枰呐笥芽梢越梃b參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-07-07
Go 并發(fā)編程Goroutine的實(shí)現(xiàn)示例
Go語言中的并發(fā)編程主要通過Goroutine和Channel來實(shí)現(xiàn),本文就來介紹一下Go 并發(fā)編程的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2024-12-12

