赞
踩
API密钥:如果仅仅只是学习的项目中作为展示测试,而不会长期使用,这边建议我们去某宝或其他平台低价购入一个,博主就是在某宝话0.45元购入用作测试,如下图图示。
1.用户在输入框输入的内容传到后端的那个数据里面(例:我们用户传的数据在chatMessage对象里面)
2.Chatgpt3.5传回来的内容又存在那个数据里面(例:以下代码有展示)
1.我们创建一个调用API的工具类(名字你可以更改,以我为例):ChatGPT3Client
ChatGPT3Client工具类如下:
- package com.XXXX.utils;
-
- import okhttp3.*;
- import org.json.JSONArray;
- import org.json.JSONObject;
-
- import java.io.IOException;
- import java.util.concurrent.TimeUnit;
-
- public class ChatGPT3Client {
-
- private final String apiKey;//购买的api密钥
- private final String model;//我们选的是哪个模型 如“gpt-3.5-turbo”
- private final String apiUrl;//路由请求!!!根据实际更改!!!!!
-
- public ChatGPT3Client(String apiKey, String model) {
- this.apiKey = apiKey;
- this.model = model;
- this.apiUrl = "https://api.openai.com/v1/chat/completions";
- }
-
- public String generateResponse(String prompt) throws IOException {//prompt就是我们用户 提的问题
- //这里是设置请求响应的时间的
- OkHttpClient client = new OkHttpClient.Builder()
- .connectTimeout(60, TimeUnit.SECONDS) // 连接超时 单位是秒
- .writeTimeout(60, TimeUnit.SECONDS) // 写超时
- .readTimeout(60, TimeUnit.SECONDS) // 读超时
- .build();
-
- JSONObject message = new JSONObject();
- message.put("role", "user");
- message.put("content", prompt);
-
- JSONObject requestBody = new JSONObject();
- requestBody.put("model", this.model);
- requestBody.put("messages", new JSONArray().put(message));
-
- RequestBody body = RequestBody.create(
- requestBody.toString(),
- MediaType.parse("application/json; charset=utf-8")
- );
-
- Request request = new Request.Builder()
- .url(this.apiUrl)
- .post(body)
- .addHeader("Authorization", "Bearer " + this.apiKey)
- .build();
-
- try (Response response = client.newCall(request).execute()) {
- if (!response.isSuccessful()) {
- throw new IOException("Unexpected response code: " + response);
- }
-
- String responseBody = response.body().string();
- JSONObject jsonResponse = new JSONObject(responseBody);
-
- JSONArray choices = jsonResponse.getJSONArray("choices");
- JSONObject choice = choices.getJSONObject(0);
-
- // 从 choice 对象中获取 messageDto 对象,然后获取 content 字段
- JSONObject messageDto = choice.getJSONObject("message");
- String generatedText = messageDto.getString("content");
- //以我购买的api的客户提供的路由请求路径为例,返回的内容存在 messageDto对象的content里面
- System.out.println("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"+messageDto);//可以打印来看下在什么位置。
-
- return generatedText;//返回回复的内容
- }
- }
- }

这里是我提出问题:世界
gpt返回的内容:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。