You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

58 lines
2.9 KiB
Java

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package com.supervision.handler.gpt;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.supervision.ai.AiUtil;
import com.supervision.ai.dto.MessageDTO;
import com.supervision.enums.IdentifyIntentEnum;
import com.supervision.exception.IdentifyIntentException;
import io.lettuce.core.dynamic.annotation.CommandNaming;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
/**
* 意图识别handler
*/
@Slf4j
@Component
public class IdentifyIntentHandler {
public String identifyIntent(String question) {
// 首先生成提示词
List<MessageDTO> messageList = new ArrayList<>();
messageList.add(new MessageDTO("system", "假设你是一个意图识别模型,且精通社会保险业务中的事务分类," +
"现在我会给你一个意图列表以及意图列表可能的一些典型问法,你首先要根据意图列表和典型问法进行学习(典型问法只是参考,并不一定局限于典型问法范围)" +
"然后我再给你一个句子,请帮我的要求识别出这个句子中的意图.除了匹配的意图之外,不要回答其他的内容!如果该句子中不含有意图列表中任意意图,你可以输出:未识别"));
messageList.add(new MessageDTO("assistant", "好的"));
// 构建学习案例
StringBuilder stringBuilder = new StringBuilder();
for (IdentifyIntentEnum value : IdentifyIntentEnum.values()) {
stringBuilder.append("意图:").append(value.getIntent()).append(";").append("典型问法:").append(CollUtil.join(value.getExplainList(), ",")).append("\n");
}
messageList.add(new MessageDTO("user", stringBuilder.toString()));
messageList.add(new MessageDTO("assistant", "已学习"));
// 构建问题
messageList.add(new MessageDTO("user", "问题是:" + question));
messageList.add(new MessageDTO("assistant", "好的"));
messageList.add(new MessageDTO("user", "现在你可以根据你学习到的意图列表,来输出根据提供的问题所识别到的意图了"));
log.info("identifyIntent开始识别意图:{}", JSONUtil.toJsonStr(messageList));
// 进行提问
String intent = AiUtil.chatByMessage(messageList);
log.info("identifyIntent意图识别结果为:{}", intent);
// 尝试转为JSON的形式
if (StrUtil.isBlank(intent) || StrUtil.equals("未识别", intent) || intent.contains("未识别")) {
throw new IdentifyIntentException("意图未识别");
}
for (IdentifyIntentEnum value : IdentifyIntentEnum.values()) {
if (intent.contains(value.getIntent())){
return value.getIntent();
}
}
throw new IdentifyIntentException("意图未识别");
}
}