当前位置:   article > 正文

Java接入ChatGPT API

Java接入ChatGPT API

如今chatgpt运用在各行各业,那么Java接入ChatGPT API如何接入呢,直接上代码

  1. public class GPTJavaDemo {
  2. private static final String OPENAI_API_KEY = "your-api-key";
  3. private static final String MODEL_ENDPOINT = "https://api.openai.com/v1/completions";
  4. public static void main(String[] args) throws IOException {
  5. String prompt = "Once upon a time";
  6. int maxTokens = 50; // 最大生成标记数
  7. String response = generateText(prompt, maxTokens);
  8. System.out.println("Generated text: " + response);
  9. }
  10. public static String generateText(String prompt, int maxTokens) throws IOException {
  11. OkHttpClient client = new OkHttpClient();
  12. MediaType mediaType = MediaType.parse("application/json");
  13. RequestBody body = RequestBody.create(mediaType,
  14. "{\"model\":\"text-davinci-003\"," +
  15. "\"prompt\":\"" + prompt + "\"," +
  16. "\"max_tokens\":" + maxTokens + "}");
  17. Request request = new Request.Builder()
  18. .url(MODEL_ENDPOINT)
  19. .post(body)
  20. .addHeader("Content-Type", "application/json")
  21. .addHeader("Authorization", "Bearer " + OPENAI_API_KEY)
  22. .build();
  23. try (Response response = client.newCall(request).execute()) {
  24. if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
  25. String responseBody = response.body().string();
  26. JSONObject jsonResponse = new JSONObject(responseBody);
  27. String text = jsonResponse.getJSONArray("choices").getJSONObject(0).getString("text");
  28. return text;
  29. } catch (JSONException e) {
  30. e.printStackTrace();
  31. return null;
  32. }
  33. }
  34. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/1020616
推荐阅读
相关标签
  

闽ICP备14008679号