当前位置:   article > 正文

如何调用Chatgpt3.5的api,实现交互?,本人实操有效。_chatgpt的apikey怎么获取

chatgpt的apikey怎么获取

一.我们需要准备的东西

        API密钥:如果仅仅只是学习的项目中作为展示测试,而不会长期使用,这边建议我们去某宝或其他平台低价购入一个,博主就是在某宝话0.45元购入用作测试,如下图图示。

 二.我们要了解我们做的项目的结构。

        1.用户在输入框输入的内容传到后端的那个数据里面(例:我们用户传的数据在chatMessage对象里面)

        2.Chatgpt3.5传回来的内容又存在那个数据里面(例:以下代码有展示)

三.开始举例:

        1.我们创建一个调用API的工具类(名字你可以更改,以我为例):ChatGPT3Client

        ChatGPT3Client工具类如下:

  1. package com.XXXX.utils;
  2. import okhttp3.*;
  3. import org.json.JSONArray;
  4. import org.json.JSONObject;
  5. import java.io.IOException;
  6. import java.util.concurrent.TimeUnit;
  7. public class ChatGPT3Client {
  8. private final String apiKey;//购买的api密钥
  9. private final String model;//我们选的是哪个模型 如“gpt-3.5-turbo”
  10. private final String apiUrl;//路由请求!!!根据实际更改!!!!!
  11. public ChatGPT3Client(String apiKey, String model) {
  12. this.apiKey = apiKey;
  13. this.model = model;
  14. this.apiUrl = "https://api.openai.com/v1/chat/completions";
  15. }
  16. public String generateResponse(String prompt) throws IOException {//prompt就是我们用户 提的问题
  17. //这里是设置请求响应的时间的
  18. OkHttpClient client = new OkHttpClient.Builder()
  19. .connectTimeout(60, TimeUnit.SECONDS) // 连接超时 单位是秒
  20. .writeTimeout(60, TimeUnit.SECONDS) // 写超时
  21. .readTimeout(60, TimeUnit.SECONDS) // 读超时
  22. .build();
  23. JSONObject message = new JSONObject();
  24. message.put("role", "user");
  25. message.put("content", prompt);
  26. JSONObject requestBody = new JSONObject();
  27. requestBody.put("model", this.model);
  28. requestBody.put("messages", new JSONArray().put(message));
  29. RequestBody body = RequestBody.create(
  30. requestBody.toString(),
  31. MediaType.parse("application/json; charset=utf-8")
  32. );
  33. Request request = new Request.Builder()
  34. .url(this.apiUrl)
  35. .post(body)
  36. .addHeader("Authorization", "Bearer " + this.apiKey)
  37. .build();
  38. try (Response response = client.newCall(request).execute()) {
  39. if (!response.isSuccessful()) {
  40. throw new IOException("Unexpected response code: " + response);
  41. }
  42. String responseBody = response.body().string();
  43. JSONObject jsonResponse = new JSONObject(responseBody);
  44. JSONArray choices = jsonResponse.getJSONArray("choices");
  45. JSONObject choice = choices.getJSONObject(0);
  46. // 从 choice 对象中获取 messageDto 对象,然后获取 content 字段
  47. JSONObject messageDto = choice.getJSONObject("message");
  48. String generatedText = messageDto.getString("content");
  49. //以我购买的api的客户提供的路由请求路径为例,返回的内容存在 messageDto对象的content里面
  50. System.out.println("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"+messageDto);//可以打印来看下在什么位置。
  51. return generatedText;//返回回复的内容
  52. }
  53. }
  54. }

         这里是我提出问题:世界

        gpt返回的内容:

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