The solution to the connection timeout when calling OpenAi

Before initiating an HTTP request to https://api.openai.com/v1/completions, use the Proxy under the java.net package for proxying.

code show as below:

public class OpenAiApi {


    public String OpenAiAnswerer(CompletionRequest request, String openAiApiKey) {

        //代理
        String proxyHost = "代理地址";
        int proxyPort = 代理端口;
        String url = "https://api.openai.com/v1/completions";
        // json为请求体
        String json = JSONUtil.toJsonStr(request);
        String result = "";
        Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
        try {
            HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(proxy);
            connection.setRequestProperty("Authorization", "Bearer " + openAiApiKey);
            connection.setRequestProperty("Content-Type", "application/json");

            connection.setRequestMethod("POST");

            connection.setDoOutput(true);
            byte[] requestBodyBytes = json.getBytes(StandardCharsets.UTF_8);
            try (OutputStream outputStream = connection.getOutputStream()) {
                outputStream.write(requestBodyBytes, 0, requestBodyBytes.length);
            }
            try (InputStream inputStream = connection.getInputStream()) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
                StringBuilder response = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                result = response.toString();

            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return JSONUtil.toBean(result, CompletionResponse.class);
    }

}

connection.setRequestProperty("Authorization", "Bearer " + openAiApiKey);
connection.setRequestProperty("Content-Type", "application/json");

I forgot to set the Content-Type when I was using it, and the result kept reporting an error. After reading the document repeatedly, I found out that this must be set.

The following is the formal parameter class CompletionRequest in the OpenAiAnswerer method. Here, the @Data annotation in the Lombok plug-in is used to automatically fill in the get, set methods and no-argument construction. (If a parameterized construction is added, be sure to add a non-parametric construction)

@Data 
public class CompletionRequest {
    private String model;

    private String prompt;

    private Integer max_tokens;

    private Integer temperature;

    private Integer top_p;

    private Integer n;

    private Boolean stream;

    private Integer logprobs;

    private String stop;

}

Guess you like

Origin blog.csdn.net/dantui_/article/details/130072028