新增百度文言一心GPT接口模块

This commit is contained in:
2023-07-25 14:48:11 +08:00
parent 00cdf7b96e
commit 9fdf670c26
6 changed files with 178 additions and 1 deletions

View File

@@ -0,0 +1,82 @@
package com.yutou.qqbot.utlis;
import com.alibaba.fastjson2.JSONObject;
import com.yutou.qqbot.data.baidu.Message;
import com.yutou.qqbot.data.baidu.ResponseMessage;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class BaiduGPTManager {
private static int MAX_MESSAGE = 5;
private static BaiduGPTManager manager;
private static final String url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions";
private static final String AppID = "36668599";
private static final String ApiKey = "eyHo6K2ILBm7i378701Az1eT";
private static final String SecretKey = "U4vXt8AOTM9FgB0Omft5IOh6vwhzoDgZ";
private final Map<String, List<Message>> msgMap;
private BaiduGPTManager() {
msgMap = new HashMap<>();
}
public static BaiduGPTManager getManager() {
if (manager == null) {
manager = new BaiduGPTManager();
}
return manager;
}
public int setMaxMessageCount(int count) {
MAX_MESSAGE = count;
return MAX_MESSAGE;
}
public void clear() {
msgMap.clear();
}
private String getToken() {
String _url = String.format("https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=%s&client_secret=%s"
, ApiKey
, SecretKey
);
String get = HttpTools.get(_url);
JSONObject response = JSONObject.parseObject(get);
return response.getString("access_token");
}
public ResponseMessage sendMessage(String user, String message) {
List<Message> messages = msgMap.getOrDefault(user, new ArrayList<>());
if (messages.size() > MAX_MESSAGE * 2) {
messages.remove(0);
messages.remove(1);
}
messages.add(Message.create(message));
JSONObject json = new JSONObject();
json.put("messages", messages);
System.out.println("json = " + json);
String post = HttpTools.post(url + "?access_token=" + getToken()
, json.toJSONString().getBytes(StandardCharsets.UTF_8));
System.out.println("post = " + post);
ResponseMessage response = JSONObject.parseObject(post, ResponseMessage.class);
messages.add(Message.create(response.getResult(), true));
msgMap.put(user, messages);
System.out.println("\n\n");
return response;
}
public static void main(String[] args) throws Exception {
BaiduGPTManager.getManager().sendMessage("test", "定义个变量西瓜它的值是5");
Thread.sleep(1000);
BaiduGPTManager.getManager().sendMessage("test", "西瓜的值的多少");
Thread.sleep(1000);
BaiduGPTManager.getManager().clear();
BaiduGPTManager.getManager().sendMessage("test2", "西瓜的值的多少");
}
}