rymcu/forest

ChatGPT功能修复

Closed this issue · 2 comments

@PostMapping("/chat")
public GlobalResult<List> chat(@RequestBody JSONObject jsonObject) {
//获取JSON数组
JSONArray jsonArray = jsonObject.getJSONArray("message");
//构建消息数组
String[] contents = new String[jsonArray.size()];
//遍历JSON数组,取出key为content的值存进消息数组中
for (int i = 0; i < jsonArray.size(); i++) {
JSONObject obj = jsonArray.getJSONObject(i);
contents[i] = obj.getString("content");
}
// 参数校验
if (StringUtils.isBlank(contents[0])) {
// 参数异常
throw new IllegalArgumentException("参数异常!");
}
// 构建问答列表 用于存储用户输入
List list = new ArrayList();
for (int i = contents.length-1; i >= 0; i--){
if((i+1)%2==0) {
ChatMessage chatMessage1 = new ChatMessage("assistant", contents[i]);
list.add(chatMessage1);
}else{
ChatMessage chatMessage1 = new ChatMessage("user", contents[i]);
list.add(chatMessage1);
}
}
// 调用openapi接口,构建请求头header
//触发拦截器,获取token 用于请求头
OpenAiService service = new OpenAiService(token, Duration.ofSeconds(600));

    // 构建完整的请求
    // model: 机器人模型
    // messages: 用户输入
    ChatCompletionRequest completionRequest = ChatCompletionRequest.builder()
            .model("gpt-3.5-turbo")
            .messages(list)
            .build();

    // 获取机器人回复 将请求参数传入结合token请求openapi接口 这里是发送请求的主要函数
    List<ChatCompletionChoice> choices =  service.createChatCompletion(completionRequest).getChoices();
    // 返回结果
    return GlobalResultGenerator.genSuccessResult(choices);

}

这样可以实现连续对话,而不是一句一句的回复。

😉 欢迎 PR, 可以考虑顺带实现一下流式接口

已实现连续对话