📖 本章预览
本章为预览版本,展示部分核心内容。完整内容包含详细源码解析、实战代码和面试要点,加入知识星球即可解锁全部章节。
第21章 多轮对话:打造丝滑交互体验
21.1 对话状态机设计
21.1.1 状态机概念
多轮对话 = 有限状态机(FSM)
示例:订餐对话流程
┌────────┐ 选择餐厅 ┌────────┐ 选择菜品 ┌────────┐ 确认 ┌────────┐
│ 初始状态 │ ────────► │ 选餐厅 │ ────────► │ 选菜品 │ ────► │ 下单 │
└────────┘ └────┬───┘ └────┬───┘ └────────┘
│ 取消 │ 返回
▼ ▼
┌────────┐ ┌────────┐
│ 结束 │ │ 选餐厅 │
└────────┘ └────────┘
21.1.2 实现对话状态机
/**
* 对话状态机
*/
public class DialogStateMachine {
private final Map<String, DialogState> states = new HashMap<>();
private String currentState;
public void addState(String name, DialogState state) {
states.put(name, state);
}
public void setInitialState(String name) {
this.currentState = name;
}
/** 处理用户输入,返回回复并可能转移状态 */
public String process(String userInput, Map<String, Object> context) {
DialogState state = states.get(currentState);
if (state == null) {
return "对话已结束。";
}
// 执行当前状态的处理逻辑
StateResult result = state.handle(userInput, context);
// 状态转移
if (StringUtils.isNotBlank(result.nextState())) {
this.currentState = result.nextState();
}
return result.reply();
}
public String getCurrentState() {
return currentState;
}
}
/** 状态处理结果 */
record StateResult(String reply, String nextState) {}
/** 对话状态接口 */
interface DialogState {
StateResult handle(String userInput, Map<String, Object> context);
}
21.1.3 订餐对话实战
/**
* 订餐对话状态机
*/
@Service
public class OrderFoodDialog {
@Autowired
private ChatModel chatModel;
public DialogStateMachine create() {
DialogStateMachine fsm = new DialogStateMachine();
// 状态1:选择餐厅
fsm.addState("selectRestaurant", (input, ctx) -> {
String reply = chatModel.call("""
用户想订餐,请根据用户输入推荐餐厅。如果用户已选择,提取餐厅名。
用户说:""" + input);
if (reply.contains("已选择")) {
ctx.put("restaurant", extractRestaurant(reply));
return new StateResult("好的,已选择餐厅。请问想吃什么菜?", "selectDish");
}
return new StateResult(reply, null); // 留在当前状态
});
// 状态2:选择菜品
fsm.addState("selectDish", (input, ctx) -> {
🔒 解锁完整内容
本章剩余内容需要解锁后查看
以上仅为本章部分预览内容,完整内容包含更多深度源码解析、实战代码和面试要点。
加入知识星球你将获得:
- ✅ 全部 26 章完整内容 + 持续更新
- ✅ 配套源码 + 实战项目
- ✅ 一对一答疑 + 面试辅导
- ✅ 简历优化 + 内推机会
📚 本章完整目录
以下为本章完整目录结构,加入知识星球即可解锁全部内容。