主要任务:继续优化代码 完善函数封装
为了进一步与整体代码衔接以及为了方便测试人员调用,现在对大模型的调用接口进行进一步的优化和封装
1、固定化初始信息
//超时设置
static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().connectTimeout(5, TimeUnit.SECONDS) // 连接超时设置为20秒
.writeTimeout(15, TimeUnit.SECONDS) // 写入超时设置为30秒
.readTimeout(20, TimeUnit.SECONDS) // 读取超时设置为30秒
.build();
static Gson gson = new Gson();
//AI部署链接和密钥
static final String accessToken = "df4dfce285458e3f20b95d6ac9da24ebff6d28b6";
static final String url = "https://o1v0n08ck756f9ae.aistudio-hub.baidu.com/chat/completions";
// 历史对话信息
Map<String, List<ChatMsg>> mapChatList = new HashMap<String, List<ChatMsg>>();
//封装函数
2、封装以及优化函数
static String communicate(String massage) throws IOException {
// 结合prompt增强的当前待发送信息
ChatMsg chatMsg = new ChatMsg();
chatMsg.setRole("user");
chatMsg.setContent(massage);
// 当前发送消息数组
List<ChatMsg> messages = new ArrayList<ChatMsg>();
messages.add(chatMsg);
String messagesJson = gson.toJson(messages);
String content = "{\"messages\":" + messagesJson + "}";
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, content);
Request request = new Request.Builder().url(url).method("POST", body)
.addHeader("Content-Type", "application/json").addHeader("Authorization", "df4dfce285458e3f20b95d6ac9da24ebff6d28b6").build();
Response response = HTTP_CLIENT.newCall(request).execute();
String responseText = response.body().string();
ObjectMapper objectMapper = new ObjectMapper();
JsonNode rootNode = objectMapper.readTree(responseText);
String answer = rootNode.get("result").asText();
return answer;
}
3、编写测试主函数
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
String msg=sc.next();
while(!msg.equals("EOF"))
{
String answer=communicate(msg);
System.out.println(answer);
msg=sc.next();
}
}