为什么Go和ChatGPT是理想的组合?
\n您是否曾想过,如何快速“教会”您的Go程序像真人一样与用户交流?或者,您可能想自动化内容生成、创建智能助手,或者只是为您的服务增添一些“亮点”?在Go中集成ChatGPT API不仅是一种流行趋势,更是一个强大的工具,它为您打开了通往人工智能世界的大门。Go凭借其速度和简洁性,非常适合创建快速且可靠的神经网络请求。在本文中,我们不仅会分析理论,还会编写可以直接在您的项目中使用的实际代码。
\n\n准备工作:开始需要什么?
\n在深入代码之前,让我们确保拥有所有必要的东西。您需要:
\n- \n
- 已安装的Go(版本1.21或更高,以便使用所有现代功能)。 \n
- OpenAI API密钥。您可以在OpenAI平台上获取。请像对待银行卡密码一样对待它——务必保密! \n
- 对HTTP请求和Go数据结构的基本理解。 \n
为了简化结构,本文中的所有代码我们将写在一个文件main.go中。开始吧!
步骤1:创建HTTP客户端并发送第一个请求
\n我们集成的核心将是标准包net/http。它轻量、快速,且无需第三方依赖。我们的任务是向端点https://api.openai.com/v1/chat/completions发送一个带有正确主体和标头的POST请求。
请求结构
\nChatGPT API期望特定格式的JSON。让我们创建与这种格式完全匹配的Go结构体:
\npackage main\n\nimport (\n "bytes"\n "encoding/json"\n "fmt"\n "io"\n "net/http"\n "os"\n)\n\ntype ChatMessage struct {\n Role string `json:"role"`\n Content string `json:"content"`\n}\n\ntype ChatRequest struct {\n Model string `json:"model"`\n Messages []ChatMessage `json:"messages"`\n}\n\ntype ChatResponse struct {\n Choices []struct {\n Message ChatMessage `json:"message"`\n } `json:"choices"`\n}\n请注意json:"..."标签。它们确保Go能够正确地将我们的数据“打包”(序列化)成OpenAI能够理解的JSON。
发送函数
\n现在让我们编写一个函数,负责所有“脏活累活”:构建请求、发送请求并解析响应。
\nfunc askChatGPT(apiKey, prompt string) (string, error) {\n reqBody := ChatRequest{\n Model: "gpt-3.5-turbo",\n Messages: []ChatMessage{\n {Role: "user", Content: prompt},\n },\n }\n\n jsonData, err := json.Marshal(reqBody)\n if err != nil {\n return "", fmt.Errorf("序列化错误: %w", err)\n }\n\n request, err := http.NewRequest("POST", "https://api.openai.com/v1/chat/completions", bytes.NewBuffer(jsonData))\n if err != nil {\n return "", fmt.Errorf("创建请求错误: %w", err)\n }\n\n request.Header.Set("Content-Type", "application/json")\n request.Header.Set("Authorization", "Bearer "+apiKey)\n\n client := &http.Client{}\n response, err := client.Do(request)\n if err != nil {\n return "", fmt.Errorf("执行请求错误: %w", err)\n }\n defer response.Body.Close()\n\n body, err := io.ReadAll(response.Body)\n if err != nil {\n return "", fmt.Errorf("读取响应错误: %w", err)\n }\n\n // 检查状态码\n if response.StatusCode != http.StatusOK {\n return "", fmt.Errorf("API返回错误: %s, 主体: %s", response.Status, string(body))\n }\n\n var chatResp ChatRes