Error of unexpected EOF with OpenAI endpoint

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.

@fifthwheel8

You might consider being more “discrete” posting here and revealing you are using the API from China using a proxy server:

China is banned by OpenAI policy from using the API (the last time we checked) and this site is monitored by OpenAI dev staff.

If an OpenAI dev staff reads your post, they might likely refer your post to their internal IT security team or Cloudflare to block.

In addition, it is not clear to me if OpenAI permits community members to support users from banned countries. OpenAI tends to be “conservative to an extreme”, as you might have read in the news media.

Just some friendly thoughts, nothing personal against China.

:slight_smile:

1 Like