admin管理员组文章数量:1607704
如今chatgpt运用在各行各业,那么Java接入ChatGPT API如何接入呢,直接上代码
public class GPTJavaDemo {
private static final String OPENAI_API_KEY = "your-api-key";
private static final String MODEL_ENDPOINT = "https://api.openai/v1/completions";
public static void main(String[] args) throws IOException {
String prompt = "Once upon a time";
int maxTokens = 50; // 最大生成标记数
String response = generateText(prompt, maxTokens);
System.out.println("Generated text: " + response);
}
public static String generateText(String prompt, int maxTokens) throws IOException {
OkHttpClient client = new OkHttpClient();
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType,
"{\"model\":\"text-davinci-003\"," +
"\"prompt\":\"" + prompt + "\"," +
"\"max_tokens\":" + maxTokens + "}");
Request request = new Request.Builder()
.url(MODEL_ENDPOINT)
.post(body)
.addHeader("Content-Type", "application/json")
.addHeader("Authorization", "Bearer " + OPENAI_API_KEY)
.build();
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
String responseBody = response.body().string();
JSONObject jsonResponse = new JSONObject(responseBody);
String text = jsonResponse.getJSONArray("choices").getJSONObject(0).getString("text");
return text;
} catch (JSONException e) {
e.printStackTrace();
return null;
}
}
}
版权声明:本文标题:Java接入ChatGPT API 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://m.elefans.com/xitong/1728529460a1162142.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论