@
nonfu 这是 Bing 生成的 Go 调用 ChatGPT 的代码
···go
package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)
type Request struct {
Messages []string `json:"messages"`
}
type Response struct {
Text string `json:"text"`
}
func main() {
url := "
https://api.openai.com/v1/engines/chatgpt/completions"
reqBody := Request{
Messages: []string{
"system: Hello, this is Bing.",
"user: Hi. Can you help me with something?",
"system: Sure. What can I do for you?",
"user: How can I call ChatGPT API with Go?",
// add more messages here
},
}
reqBytes, err := json.Marshal(reqBody)
if err != nil {
panic(err)
}
req, err := http.NewRequest("POST", url, bytes.NewBuffer(reqBytes))
if err != nil {
panic(err)
}
req.Header.Set("Authorization", "sk-your token") // replace your token with your API key
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err :=
client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
respBody, err := ioutil.ReadAll(resp.Body)
if err != nil {
panic(err)
}
var respData Response
err = json.Unmarshal(respBody, &respData)
if err != nil {
panic(err)
}
fmt.Println(respData.Text) // print the generated text
}
···