Go語言調(diào)用DeepSeek?API實現(xiàn)流式輸出和對話
引言
DeepSeek 是一個強大的 AI 模型服務平臺,本文將詳細介紹如何使用 Go 語言調(diào)用 DeepSeek API,實現(xiàn)流式輸出和對話功能。
Deepseek的api因為被功擊已不能用,本文以 DeepSeek:https://cloud.siliconflow.cn/i/vnCCfVaQ 為例子進行講解。
1. 環(huán)境準備
首先,我們需要準備以下內(nèi)容:
Go 語言環(huán)境
DeepSeek API 訪問權限
開發(fā)工具(如 VS Code)
2. 基礎代碼實現(xiàn)
2.1 創(chuàng)建項目結構
mkdir deepseek-go cd deepseek-go go mod init deepseek-go
2.2 核心代碼實現(xiàn)
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() { // 創(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 } // 記錄對話時間 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) // 發(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 // 獲取響應 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,我們可以實現(xiàn)實時顯示 AI 回復的效果。這帶來了更好的用戶體驗:
- 即時看到響應內(nèi)容
- 減少等待時間
- 更自然的對話體驗
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ù),控制輸出的隨機性
- top_p, top_k: 控制采樣策略
- frequency_penalty: 控制重復度
3.3 對話記錄
程序會自動將所有對話保存到 conversation.txt 文件中,包含:
- 時間戳
- 用戶問題
- AI 回答
- 格式化的分隔符
4. 使用示例
運行程序:
go run main.go
輸入問題,比如:
請輸入您的問題: 介紹一下 DeepSeek 的主要特點
觀察實時輸出和 conversation.txt 文件記錄
5. 錯誤處理和最佳實踐
1.API 密鑰管理
- 使用環(huán)境變量存儲 API 密鑰
- 不要在代碼中硬編碼密鑰
- 定期輪換密鑰
2.錯誤處理
- 檢查網(wǎng)絡連接
- 驗證 API 響應
- 處理流式輸出中斷
3.性能優(yōu)化
- 使用適當?shù)?buffer 大小
- 及時關閉連接
- 處理并發(fā)請求
總結
通過本文的介紹,你應該已經(jīng)掌握了如何使用 Go 語言調(diào)用 DeepSeek API 的基本方法。DeepSeek 提供了強大的 AI 能力,配合 Go 語言的高效性能,可以構建出各種有趣的應用。
到此這篇關于Go語言調(diào)用DeepSeek API的完整指南的文章就介紹到這了,更多相關Go調(diào)用DeepSeek API內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Go 并發(fā)編程Goroutine的實現(xiàn)示例
Go語言中的并發(fā)編程主要通過Goroutine和Channel來實現(xiàn),本文就來介紹一下Go 并發(fā)編程的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2024-12-12