在向https://api.openai.com/v1/completions发起http请求之前,使用java.net包下面的Proxy进行代理。
代码如下:
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");
我在使用的时候忘记设置了Content-Type,结果一直报错,后面反复观看文档才发现这个必须得设置。文章来源:https://www.toymoban.com/news/detail-505049.html
下面是OpenAiAnswerer方法里面形参类CompletionRequest,这里使用了Lombok插件里的@Data注解,自动填入get、set方法和无参构造。(如果添加了有参构造,那么务必加上无参构造)文章来源地址https://www.toymoban.com/news/detail-505049.html
@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;
}
到了这里,关于调用OpenAi出现连接超时的解决方案的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!