Here is my code,
func getResponse(question string) (response string, err error) {
proxyAddr := "http://xxxx:xxxx"
proxy, err := url.Parse(proxyAddr)
if err != nil {
return "", err
}
netTransport := &http.Transport{
Proxy: http.ProxyURL(proxy),
MaxIdleConnsPerHost: 10,
ResponseHeaderTimeout: time.Second * time.Duration(5),
}
httpClient := &http.Client{
Timeout: time.Second * 10,
Transport: netTransport,
}
data := Payload{
Prompt: question,
MaxTokens: 2048,
Temperature: 0.0,
TopP: 0,
FrequencyPenalty: 0,
PresencePenalty: 0,
Model: "text-davinci-003",
}
payloadBytes, err := json.Marshal(data)
if err != nil {
fmt.Println("json.Marshal")
return "", err
}
body := bytes.NewReader(payloadBytes)
req, err := http.NewRequest("POST", "https://api.openai.com/v1/chat/completions", body)
if err != nil {
fmt.Println("http.NewRequest")
return "", err
}
req.Close = true
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", fmt.Sprintf("%s %s", "Bearer", ASAK))
req.Header.Set("User-Agent", "chatGPT/1 CFNetwork/1402.0.8 Darwin/22.2.0")
req.Header.Set("Accept-encoding", "gzip, deflate, br")
req.Header.Set("Accept-language", "zh-CN,zh-Hans;q=0.9")
ctx := context.Background()
resp, err := httpClient.Do(req.WithContext(ctx))
if err != nil {
return "", err
}
defer resp.Body.Close()
all, err := io.ReadAll(resp.Body)
if err != nil {
fmt.Println("io.ReadAll")
return "", err
}
res := string(all)
fmt.Println(res)
return res, nil
}
There is an error: Post “https://api.openai.com/v1/chat/completions”: unexpected EOF that came from the line “resp, err := httpClient.Do(req.WithContext(ctx))” in the code. Does anyone know why I got this error and how to prevent this error? Thanks for your help and I really appreciate it.