admin管理员组文章数量:1631722
一.我们需要准备的东西
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/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返回的内容:👇
2.创建好了那我们接下来就是调用传参数啦:假如我们用户传的数据在chatMessage对象里面
获取:chatMessage.getMessageContent();
调用工具类:
String apiKey = "sk-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
String model = "gpt-3.5-turbo";
String prompt =chatMessage.getMessageContent();//用户提的问题
ChatGPT3Client client = new ChatGPT3Client(apiKey, model);//创建工具对象
String response = client.generateResponse(prompt);调用方法获得gpt返回值
//至于这后面我们都拿到了返回值了,传输给用户就可以了。
能力不足,希望可以帮到你们 。
本文标签: API
版权声明:本文标题:如何调用Chatgpt3.5的api,实现交互?,本人实操有效。 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://www.elefans.com/dongtai/1729104459a1186838.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论