前提:要有chatgpt账号,不会注册的关注抖音:21402780125,有免费教程!!
要在 Go 中调用 ChatGPT API,您可以使用 Go 的 net/http
包或其他 HTTP 客户端库来发送 HTTP 请求。
以下是使用 net/http
包调用 ChatGPT API 的示例代码:
package main import ( "encoding/json" "fmt" "io/ioutil" "net/http" "strings" ) func main() { url := "https://api.openai.com/v1/engines/davinci-codex/completions" prompt := "Hello, how are you?" temperature := 0.7 maxTokens := 100 data := map[string]interface{}{ "prompt": prompt, "temperature": temperature, "max_tokens": maxTokens, } jsonData, err := json.Marshal(data) if err != nil { fmt.Println("Error:", err) return } req, err := http.NewRequest("POST", url, strings.NewReader(string(jsonData))) if err != nil { fmt.Println("Error:", err) return } req.Header.Set("Content-Type", "application/json") req.Header.Set("Authorization", "Bearer YOUR_API_SECRET_KEY") client := &http.Client{} resp, err := client.Do(req) if err != nil { fmt.Println("Error:", err) return } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { fmt.Println("Error:", err) return } var jsonResponse map[string]interface{} if err := json.Unmarshal(body, &jsonResponse); err != nil { fmt.Println("Error:", err) return } fmt.Println(jsonResponse) }
标签:return,err,fmt,Println,api,Error,go,http,chatgpt From: https://www.cnblogs.com/ow-dwh/p/17153616.html