02_chatbot.py

"""
聊天机器人案例:智能客服系统
==========================

本案例展示如何使用 LangGraph 构建一个智能聊天机器人,
具备以下功能:
1. 自然语言理解
2. 多轮对话管理
3. 上下文记忆
4. 意图识别和路由
5. 外部工具调用
"""

from typing import TypedDict, Annotated, List, Optional, Dict, Any
from langgraph.graph import StateGraph, END
from langgraph.checkpoint.memory import MemorySaver
import operator
from datetime import datetime
from enum import Enum
import json

# 由于我们可能没有真实的 OpenAI API 密钥,我们将使用模拟的 LLM
class MockLLM:
    """模拟的 LLM 用于演示"""
    
    def __init__(self, model="gpt-3.5-turbo"):
        self.model = model
    
    def invoke(self, messages: List[Dict]) -> Dict:
        """模拟 LLM 调用"""
        last_message = messages[-1]["content"] if messages else ""
        
        # 简单的意图识别
        if "天气" in last_message:
            response = "今天天气晴朗,温度25°C,适合外出。"
        elif "时间" in last_message:
            response = f"现在是 {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
        elif "帮助" in last_message or "功能" in last_message:
            response = "我可以帮您查询天气、时间,还可以回答一般问题。"
        elif "笑话" in last_message:
            response = "为什么程序员喜欢黑暗模式?因为光会吸引bug!"
        else:
            response = f"我理解您说:'{last_message}'。这是一个模拟响应。"
        
        return {
            "content": response,
            "role": "assistant"
        }

# 定义对话状态枚举
class DialogState(Enum):
    INIT = "init"  # 初始状态
    GREETING = "greeting"  # 问候
    UNDERSTANDING = "understanding"  # 理解意图
    PROCESSING = "processing"  # 处理请求
    CLARIFYING = "clarifying"  # 澄清问题
    COMPLETED = "completed"  # 完成
    ERROR = "error"  # 错误

# 定义意图类型
class Intent(Enum):
    GREETING = "greeting"  # 问候
    WEATHER = "weather"  # 天气查询
    TIME = "time"  # 时间查询
    HELP = "help"  # 帮助
    JOKE = "joke"  # 笑话
    UNKNOWN = "unknown"  # 未知意图
    GOODBYE = "goodbye"  # 告别

# 定义聊天状态类型
class ChatState(TypedDict):
    """聊天状态定义"""
    user_id: str  # 用户ID
    session_id: str  # 会话ID
    messages: Annotated[List[Dict], operator.add]  # 消息历史
    current_intent: Intent  # 当前意图
    dialog_state: DialogState  # 对话状态
    context: Dict[str, Any]  # 上下文信息
    needs_clarification: bool  # 是否需要澄清
    clarification_question: str  # 澄清问题
    response: str  # 当前响应
    timestamp: datetime  # 时间戳
    error_message: str  # 错误信息

# 工具函数
class ChatTools:
    """聊天工具集合"""
    
    @staticmethod
    def extract_intent(message: str) -> Intent:
        """提取用户意图"""
        message_lower = message.lower()
        
        if any(word in message_lower for word in ["你好", "嗨", "hello", "hi"]):
            return Intent.GREETING
        elif any(word in message_lower for word in ["天气", "weather"]):
            return Intent.WEATHER
        elif any(word in message_lower for word in ["时间", "几点", "time"]):
            return Intent.TIME
        elif any(word in message_lower for word in ["帮助", "help", "功能"]):
            return Intent.HELP
        elif any(word in message_lower for word in ["笑话", "joke", "搞笑"]):
            return Intent.JOKE
        elif any(word in message_lower for word in ["再见", "拜拜", "goodbye"]):
            return Intent.GOODBYE
        else:
            return Intent.UNKNOWN
    
    @staticmethod
    def generate_greeting() -> str:
        """生成问候语"""
        hour = datetime.now().hour
        if hour < 12:
            greeting = "早上好"
        elif hour < 18:
            greeting = "下午好"
        else:
            greeting = "晚上好"
        
        return f"{greeting}!我是智能客服,有什么可以帮您?"
    
    @staticmethod
    def get_weather_info(location: str = "北京") -> str:
        """获取天气信息"""
        # 模拟天气数据
        weather_data = {
            "北京": "晴朗,25°C,微风",
            "上海": "多云,23°C,东南风3级",
            "广州": "阵雨,28°C,南风2级",
            "深圳": "晴转多云,27°C,微风"
        }
        
        return weather_data.get(location, "抱歉,暂时无法获取该地区天气信息")
    
    @staticmethod
    def get_current_time() -> str:
        """获取当前时间"""
        return datetime.now().strftime("%Y年%m月%d日 %H:%M:%S")
    
    @staticmethod
    def get_help_info() -> str:
        """获取帮助信息"""
        return """我可以帮您:
1. 查询天气 - 例如:"北京天气怎么样?"
2. 查询时间 - 例如:"现在几点了?"
3. 讲笑话 - 例如:"讲个笑话"
4. 其他问题 - 我会尽力回答

您有什么需要帮助的吗?"""
    
    @staticmethod
    def get_joke() -> str:
        """获取笑话"""
        jokes = [
            "为什么程序员喜欢黑暗模式?因为光会吸引bug!",
            "程序员最讨厌的单词:undefined",
            "为什么程序员总是分不清万圣节和圣诞节?因为 Oct 31 == Dec 25",
            "程序员面试:面试官问'你最大的缺点是什么?' 程序员回答:'我太诚实了。' 面试官:'我不认为这是缺点。' 程序员:'我才不在乎你怎么想。'"
        ]
        import random
        return random.choice(jokes)

# 节点函数定义
def initialize_chat(state: ChatState) -> dict:
    """初始化聊天节点"""
    print(f"[{datetime.now()}] 初始化聊天会话: {state['session_id']}")
    
    return {
        "dialog_state": DialogState.INIT,
        "timestamp": datetime.now(),
        "messages": [{"role": "system", "content": "聊天会话已初始化"}],
        "response": "聊天系统已就绪"
    }

def greet_user(state: ChatState) -> dict:
    """问候用户节点"""
    print(f"[{datetime.now()}] 问候用户: {state['user_id']}")
    
    greeting = ChatTools.generate_greeting()
    
    return {
        "dialog_state": DialogState.GREETING,
        "messages": [{"role": "assistant", "content": greeting}],
        "response": greeting,
        "timestamp": datetime.now()
    }

def understand_intent(state: ChatState) -> dict:
    """理解用户意图节点"""
    print(f"[{datetime.now()}] 分析用户意图")
    
    # 获取最后一条用户消息
    user_messages = [msg for msg in state["messages"] if msg["role"] == "user"]
    last_user_message = user_messages[-1]["content"] if user_messages else ""
    
    # 提取意图
    intent = ChatTools.extract_intent(last_user_message)
    
    # 更新上下文
    context = state.get("context", {})
    context["last_intent"] = intent.value
    context["last_user_message"] = last_user_message
    
    return {
        "current_intent": intent,
        "dialog_state": DialogState.UNDERSTANDING,
        "context": context,
        "timestamp": datetime.now(),
        "response": f"识别到意图: {intent.value}"
    }

def process_request(state: ChatState) -> dict:
    """处理用户请求节点"""
    print(f"[{datetime.now()}] 处理用户请求")
    
    intent = state["current_intent"]
    context = state.get("context", {})
    last_user_message = context.get("last_user_message", "")
    
    response = ""
    
    if intent == Intent.GREETING:
        response = ChatTools.generate_greeting()
    elif intent == Intent.WEATHER:
        # 简单提取地点(实际应用中需要更复杂的NLP)
        location = "北京"  # 默认
        if "上海" in last_user_message:
            location = "上海"
        elif "广州" in last_user_message:
            location = "广州"
        elif "深圳" in last_user_message:
            location = "深圳"
        
        weather_info = ChatTools.get_weather_info(location)
        response = f"{location}的天气:{weather_info}"
    elif intent == Intent.TIME:
        current_time = ChatTools.get_current_time()
        response = f"现在是:{current_time}"
    elif intent == Intent.HELP:
        help_info = ChatTools.get_help_info()
        response = help_info
    elif intent == Intent.JOKE:
        joke = ChatTools.get_joke()
        response = joke
    elif intent == Intent.GOODBYE:
        response = "再见!感谢使用我们的服务,祝您有美好的一天!"
    else:  # UNKNOWN
        response = "抱歉,我没有完全理解您的意思。您可以尝试问天气、时间,或者请求帮助。"
    
    return {
        "dialog_state": DialogState.PROCESSING,
        "response": response,
        "messages": [{"role": "assistant", "content": response}],
        "timestamp": datetime.now()
    }

def ask_for_clarification(state: ChatState) -> dict:
    """请求澄清节点"""
    print(f"[{datetime.now()}] 请求用户澄清")
    
    clarification_question = "您能再详细说明一下吗?或者告诉我您具体想了解什么?"
    
    return {
        "dialog_state": DialogState.CLARIFYING,
        "needs_clarification": True,
        "clarification_question": clarification_question,
        "response": clarification_question,
        "messages": [{"role": "assistant", "content": clarification_question}],
        "timestamp": datetime.now()
    }

def complete_conversation(state: ChatState) -> dict:
    """完成对话节点"""
    print(f"[{datetime.now()}] 完成对话")
    
    # 保留之前的回复,不要覆盖
    return {
        "dialog_state": DialogState.COMPLETED,
        "timestamp": datetime.now()
    }

def handle_error(state: ChatState) -> dict:
    """处理错误节点"""
    print(f"[{datetime.now()}] 处理错误")
    
    error_msg = state.get("error_message", "未知错误")
    
    return {
        "dialog_state": DialogState.ERROR,
        "response": f"抱歉,发生了错误:{error_msg}",
        "messages": [{"role": "assistant", "content": f"错误:{error_msg}"}],
        "timestamp": datetime.now()
    }

# 条件判断函数
def check_intent_clear(state: ChatState) -> str:
    """检查意图是否清晰"""
    if state["current_intent"] == Intent.UNKNOWN:
        return "needs_clarification"
    else:
        return "process_request"

def check_conversation_complete(state: ChatState) -> str:
    """检查对话是否完成"""
    if state["current_intent"] == Intent.GOODBYE:
        return "complete"
    else:
        return "continue"

def check_for_errors(state: ChatState) -> str:
    """检查是否有错误"""
    if state.get("error_message"):
        return "error"
    else:
        return "normal"

# 构建聊天机器人图
def build_chatbot_graph():
    """构建聊天机器人图"""
    workflow = StateGraph(ChatState)
    
    # 添加节点
    workflow.add_node("initialize", initialize_chat)
    workflow.add_node("greet", greet_user)
    workflow.add_node("understand", understand_intent)
    workflow.add_node("process", process_request)
    workflow.add_node("clarify", ask_for_clarification)
    workflow.add_node("complete", complete_conversation)
    workflow.add_node("error", handle_error)
    
    # 设置入口点
    workflow.set_entry_point("initialize")
    
    # 添加边
    workflow.add_edge("initialize", "greet")
    
    # 添加条件边
    workflow.add_conditional_edges(
        "greet",
        check_for_errors,
        {
            "error": "error",
            "normal": "understand"
        }
    )
    
    workflow.add_conditional_edges(
        "understand",
        check_intent_clear,
        {
            "needs_clarification": "clarify",
            "process_request": "process"
        }
    )
    
    workflow.add_edge("process", "complete")
    
    workflow.add_edge("clarify", "complete")
    
    # 添加结束边
    workflow.add_edge("complete", END)
    workflow.add_edge("error", END)
    
    # 添加检查点支持(用于多轮对话)
    memory = MemorySaver()
    
    # 编译图
    return workflow.compile(checkpointer=memory)

# 聊天机器人包装类
class SmartChatbot:
    """智能聊天机器人"""
    
    def __init__(self):
        self.graph = build_chatbot_graph()
        self.config = {"configurable": {"thread_id": "default"}}
    
    def process_message(self, user_id: str, message: str) -> Dict[str, Any]:
        """处理用户消息"""
        # 创建或获取会话ID
        session_id = f"session_{user_id}_{datetime.now().strftime('%Y%m%d')}"
        
        # 准备初始状态
        initial_state = {
            "user_id": user_id,
            "session_id": session_id,
            "messages": [{"role": "user", "content": message}],
            "current_intent": Intent.UNKNOWN,
            "dialog_state": DialogState.INIT,
            "context": {},
            "needs_clarification": False,
            "clarification_question": "",
            "response": "",
            "timestamp": datetime.now(),
            "error_message": ""
        }
        
        # 执行图
        result = self.graph.invoke(
            initial_state,
            config=self.config
        )
        
        return result
    
    def multi_turn_conversation(self, user_id: str, messages: List[str]) -> List[Dict[str, Any]]:
        """多轮对话"""
        results = []
        
        for i, message in enumerate(messages):
            print(f"\n第{i+1}轮对话:")
            print(f"用户: {message}")
            
            result = self.process_message(user_id, message)
            results.append(result)
            
            print(f"机器人: {result['response']}")
            print(f"意图: {result['current_intent'].value}")
            print(f"对话状态: {result['dialog_state'].value}")
        
        return results

# 运行示例
def run_chatbot_example():
    """运行聊天机器人示例"""
    print("=" * 60)
    print("智能聊天机器人示例")
    print("=" * 60)
    
    # 创建聊天机器人
    chatbot = SmartChatbot()
    
    # 测试用例1:简单问候
    print("\n测试用例1:简单问候")
    print("-" * 40)
    
    result1 = chatbot.process_message("user001", "你好")
    print(f"用户: 你好")
    print(f"机器人: {result1['response']}")
    print(f"意图: {result1['current_intent'].value}")
    
    # 测试用例2:多轮对话
    print("\n测试用例2:多轮对话")
    print("-" * 40)
    
    conversation = [
        "你好",
        "今天天气怎么样?",
        "上海呢?",
        "现在几点了?",
        "讲个笑话",
        "再见"
    ]
    
    results = chatbot.multi_turn_conversation("user002", conversation)
    
    # 测试用例3:未知意图
    print("\n测试用例3:未知意图处理")
    print("-" * 40)
    
    result3 = chatbot.process_message("user003", "随便说点什么")
    print(f"用户: 随便说点什么")
    print(f"机器人: {result3['response']}")
    print(f"意图: {result3['current_intent'].value}")
    
    return chatbot

# 对话分析工具
class ConversationAnalyzer:
    """对话分析工具"""
    
    @staticmethod
    def analyze_conversation(results: List[Dict]) -> Dict[str, Any]:
        """分析对话结果"""
        analysis = {
            "total_turns": len(results),
            "intents": [],
            "states": [],
            "response_times": [],
            "success_rate": 0
        }
        
        successful_turns = 0
        
        for result in results:
            analysis["intents"].append(result["current_intent"].value)
            analysis["states"].append(result["dialog_state"].value)
            
            # 计算响应时间(简化)
            if result["dialog_state"] != DialogState.ERROR:
                successful_turns += 1
        
        analysis["success_rate"] = successful_turns / len(results) if results else 0
        
        return analysis
    
    @staticmethod
    def print_analysis(analysis: Dict[str, Any]):
        """打印分析结果"""
        print("\n对话分析报告:")
        print(f"总轮数: {analysis['total_turns']}")
        print(f"成功率: {analysis['success_rate']:.1%}")
        print(f"意图分布: {', '.join(analysis['intents'])}")
        print(f"状态变化: {', '.join(analysis['states'])}")

# 高级功能:带记忆的聊天机器人
class MemoryChatbot(SmartChatbot):
    """带记忆的聊天机器人"""
    
    def __init__(self):
        super().__init__()
        self.conversation_history = {}
    
    def process_message_with_memory(self, user_id: str, message: str) -> Dict[str, Any]:
        """处理带记忆的消息"""
        # 获取历史对话
        history = self.conversation_history.get(user_id, [])
        
        # 添加上下文信息
        context = {
            "previous_messages": history[-5:] if len(history) > 5 else history,  # 最近5条
            "total_conversations": len(history)
        }
        
        # 处理消息
        result = self.process_message(user_id, message)
        
        # 更新结果中的上下文
        result["context"].update(context)
        
        # 保存到历史
        history.append({
            "user_message": message,
            "bot_response": result["response"],
            "timestamp": datetime.now(),
            "intent": result["current_intent"].value
        })
        
        self.conversation_history[user_id] = history
        
        return result
    
    def get_conversation_summary(self, user_id: str) -> Dict[str, Any]:
        """获取对话摘要"""
        history = self.conversation_history.get(user_id, [])
        
        if not history:
            return {"message": "暂无对话历史"}
        
        # 统计信息
        intents = [item["intent"] for item in history]
        intent_counts = {}
        for intent in intents:
            intent_counts[intent] = intent_counts.get(intent, 0) + 1
        
        return {
            "total_messages": len(history),
            "first_conversation": history[0]["timestamp"] if history else None,
            "last_conversation": history[-1]["timestamp"] if history else None,
            "intent_distribution": intent_counts,
            "recent_messages": history[-3:] if len(history) > 3 else history
        }

if __name__ == "__main__":
    # 运行示例
    chatbot = run_chatbot_example()
    
    print("\n" + "=" * 60)
    print("聊天机器人案例总结:")
    print("1. 意图识别和路由")
    print("2. 多轮对话管理")
    print("3. 上下文记忆")
    print("4. 错误处理机制")
    print("5. 可扩展的工具调用")
    print("=" * 60)
    
    # 演示带记忆的聊天机器人
    print("\n演示带记忆的聊天机器人:")
    memory_bot = MemoryChatbot()
    
    # 模拟多轮对话
    test_messages = [
        "你好",
        "今天天气怎么样?",
        "谢谢,再见"
    ]
    
    for msg in test_messages:
        result = memory_bot.process_message_with_memory("test_user", msg)
        print(f"用户: {msg}")
        print(f"机器人: {result['response'][:50]}...")
    
    # 获取对话摘要
    summary = memory_bot.get_conversation_summary("test_user")
    print(f"\n对话摘要:")
    print(f"总消息数: {summary['total_messages']}")
    print(f"意图分布: {summary['intent_distribution']}")
    
    # 演示对话分析
    print("\n演示对话分析:")
    analyzer = ConversationAnalyzer()
    
    # 创建测试对话结果
    test_results = []
    for msg in test_messages:
        test_results.append(memory_bot.process_message_with_memory("analyze_user", msg))
    
    analysis = analyzer.analyze_conversation(test_results)
    analyzer.print_analysis(analysis)
============================================================
智能聊天机器人示例
============================================================

测试用例1:简单问候
----------------------------------------
[2026-03-25 21:40:53.966589] 初始化聊天会话: session_user001_20260325
[2026-03-25 21:40:53.967516] 问候用户: user001
[2026-03-25 21:40:53.968638] 分析用户意图
[2026-03-25 21:40:53.969489] 处理用户请求
[2026-03-25 21:40:53.969805] 完成对话
用户: 你好
机器人: 晚上好!我是智能客服,有什么可以帮您?
意图: greeting

测试用例2:多轮对话
----------------------------------------

第1轮对话:
用户: 你好
Deserializing unregistered type __main__.Intent from checkpoint. This will be blocked in a future version. Add to allowed_msgpack_modules to silence: [('__main__', 'Intent')]
Deserializing unregistered type __main__.DialogState from checkpoint. This will be blocked in a future version. Add to allowed_msgpack_modules to silence: [('__main__', 'DialogState')]
[2026-03-25 21:40:53.972329] 初始化聊天会话: session_user002_20260325
[2026-03-25 21:40:53.972604] 问候用户: user002
[2026-03-25 21:40:53.973006] 分析用户意图
[2026-03-25 21:40:53.973594] 处理用户请求
[2026-03-25 21:40:53.973872] 完成对话
机器人: 晚上好!我是智能客服,有什么可以帮您?
意图: greeting
对话状态: completed

第2轮对话:
用户: 今天天气怎么样?
Deserializing unregistered type __main__.Intent from checkpoint. This will be blocked in a future version. Add to allowed_msgpack_modules to silence: [('__main__', 'Intent')]
Deserializing unregistered type __main__.DialogState from checkpoint. This will be blocked in a future version. Add to allowed_msgpack_modules to silence: [('__main__', 'DialogState')]
[2026-03-25 21:40:53.975680] 初始化聊天会话: session_user002_20260325
[2026-03-25 21:40:53.975948] 问候用户: user002
[2026-03-25 21:40:53.976472] 分析用户意图
[2026-03-25 21:40:53.976793] 处理用户请求
[2026-03-25 21:40:53.977180] 完成对话
机器人: 北京的天气:晴朗,25°C,微风
意图: weather
对话状态: completed

第3轮对话:
用户: 上海呢?
Deserializing unregistered type __main__.Intent from checkpoint. This will be blocked in a future version. Add to allowed_msgpack_modules to silence: [('__main__', 'Intent')]
Deserializing unregistered type __main__.DialogState from checkpoint. This will be blocked in a future version. Add to allowed_msgpack_modules to silence: [('__main__', 'DialogState')]
[2026-03-25 21:40:53.978985] 初始化聊天会话: session_user002_20260325
[2026-03-25 21:40:53.979281] 问候用户: user002
[2026-03-25 21:40:53.979713] 分析用户意图
[2026-03-25 21:40:53.980152] 请求用户澄清
[2026-03-25 21:40:53.980491] 完成对话
机器人: 您能再详细说明一下吗?或者告诉我您具体想了解什么?
意图: unknown
对话状态: completed

第4轮对话:
用户: 现在几点了?
Deserializing unregistered type __main__.Intent from checkpoint. This will be blocked in a future version. Add to allowed_msgpack_modules to silence: [('__main__', 'Intent')]
Deserializing unregistered type __main__.DialogState from checkpoint. This will be blocked in a future version. Add to allowed_msgpack_modules to silence: [('__main__', 'DialogState')]
[2026-03-25 21:40:53.982315] 初始化聊天会话: session_user002_20260325
[2026-03-25 21:40:53.982631] 问候用户: user002
[2026-03-25 21:40:53.983266] 分析用户意图
[2026-03-25 21:40:53.983691] 处理用户请求
[2026-03-25 21:40:53.984053] 完成对话
机器人: 现在是:2026年03月25日 21:40:53
意图: time
对话状态: completed

第5轮对话:
用户: 讲个笑话
Deserializing unregistered type __main__.Intent from checkpoint. This will be blocked in a future version. Add to allowed_msgpack_modules to silence: [('__main__', 'Intent')]
Deserializing unregistered type __main__.DialogState from checkpoint. This will be blocked in a future version. Add to allowed_msgpack_modules to silence: [('__main__', 'DialogState')]
[2026-03-25 21:40:53.986503] 初始化聊天会话: session_user002_20260325
[2026-03-25 21:40:53.987409] 问候用户: user002
[2026-03-25 21:40:53.987983] 分析用户意图
[2026-03-25 21:40:53.988748] 处理用户请求
[2026-03-25 21:40:53.989100] 完成对话
机器人: 程序员面试:面试官问'你最大的缺点是什么?' 程序员回答:'我太诚实了。' 面试官:'我不认为这是缺点。' 程序员:'我才不在乎你怎么想。'
意图: joke
对话状态: completed

第6轮对话:
用户: 再见
Deserializing unregistered type __main__.Intent from checkpoint. This will be blocked in a future version. Add to allowed_msgpack_modules to silence: [('__main__', 'Intent')]
Deserializing unregistered type __main__.DialogState from checkpoint. This will be blocked in a future version. Add to allowed_msgpack_modules to silence: [('__main__', 'DialogState')]
[2026-03-25 21:40:53.991149] 初始化聊天会话: session_user002_20260325
[2026-03-25 21:40:53.991429] 问候用户: user002
[2026-03-25 21:40:53.991854] 分析用户意图
[2026-03-25 21:40:53.992286] 处理用户请求
[2026-03-25 21:40:53.992869] 完成对话
机器人: 再见!感谢使用我们的服务,祝您有美好的一天!
意图: goodbye
对话状态: completed

测试用例3:未知意图处理
----------------------------------------
Deserializing unregistered type __main__.Intent from checkpoint. This will be blocked in a future version. Add to allowed_msgpack_modules to silence: [('__main__', 'Intent')]
Deserializing unregistered type __main__.DialogState from checkpoint. This will be blocked in a future version. Add to allowed_msgpack_modules to silence: [('__main__', 'DialogState')]
[2026-03-25 21:40:53.994675] 初始化聊天会话: session_user003_20260325
[2026-03-25 21:40:53.995047] 问候用户: user003
[2026-03-25 21:40:53.995532] 分析用户意图
[2026-03-25 21:40:53.996088] 请求用户澄清
[2026-03-25 21:40:53.996476] 完成对话
用户: 随便说点什么
机器人: 您能再详细说明一下吗?或者告诉我您具体想了解什么?
意图: unknown

============================================================
聊天机器人案例总结:
1. 意图识别和路由
2. 多轮对话管理
3. 上下文记忆
4. 错误处理机制
5. 可扩展的工具调用
============================================================

演示带记忆的聊天机器人:
[2026-03-25 21:40:54.005135] 初始化聊天会话: session_test_user_20260325
[2026-03-25 21:40:54.005482] 问候用户: test_user
[2026-03-25 21:40:54.005994] 分析用户意图
[2026-03-25 21:40:54.006375] 处理用户请求
[2026-03-25 21:40:54.006776] 完成对话
用户: 你好
机器人: 晚上好!我是智能客服,有什么可以帮您?...
Deserializing unregistered type __main__.Intent from checkpoint. This will be blocked in a future version. Add to allowed_msgpack_modules to silence: [('__main__', 'Intent')]
Deserializing unregistered type __main__.DialogState from checkpoint. This will be blocked in a future version. Add to allowed_msgpack_modules to silence: [('__main__', 'DialogState')]
[2026-03-25 21:40:54.008452] 初始化聊天会话: session_test_user_20260325
[2026-03-25 21:40:54.008736] 问候用户: test_user
[2026-03-25 21:40:54.009099] 分析用户意图
[2026-03-25 21:40:54.009551] 处理用户请求
[2026-03-25 21:40:54.009893] 完成对话
用户: 今天天气怎么样?
机器人: 北京的天气:晴朗,25°C,微风...
Deserializing unregistered type __main__.Intent from checkpoint. This will be blocked in a future version. Add to allowed_msgpack_modules to silence: [('__main__', 'Intent')]
Deserializing unregistered type __main__.DialogState from checkpoint. This will be blocked in a future version. Add to allowed_msgpack_modules to silence: [('__main__', 'DialogState')]
[2026-03-25 21:40:54.011539] 初始化聊天会话: session_test_user_20260325
[2026-03-25 21:40:54.011880] 问候用户: test_user
[2026-03-25 21:40:54.012413] 分析用户意图
[2026-03-25 21:40:54.013032] 处理用户请求
[2026-03-25 21:40:54.013291] 完成对话
用户: 谢谢,再见
机器人: 再见!感谢使用我们的服务,祝您有美好的一天!...

对话摘要:
总消息数: 3
意图分布: {'greeting': 1, 'weather': 1, 'goodbye': 1}

演示对话分析:
Deserializing unregistered type __main__.Intent from checkpoint. This will be blocked in a future version. Add to allowed_msgpack_modules to silence: [('__main__', 'Intent')]
Deserializing unregistered type __main__.DialogState from checkpoint. This will be blocked in a future version. Add to allowed_msgpack_modules to silence: [('__main__', 'DialogState')]
[2026-03-25 21:40:54.015236] 初始化聊天会话: session_analyze_user_20260325
[2026-03-25 21:40:54.015555] 问候用户: analyze_user
[2026-03-25 21:40:54.015983] 分析用户意图
[2026-03-25 21:40:54.016470] 处理用户请求
[2026-03-25 21:40:54.016903] 完成对话
Deserializing unregistered type __main__.Intent from checkpoint. This will be blocked in a future version. Add to allowed_msgpack_modules to silence: [('__main__', 'Intent')]
Deserializing unregistered type __main__.DialogState from checkpoint. This will be blocked in a future version. Add to allowed_msgpack_modules to silence: [('__main__', 'DialogState')]
[2026-03-25 21:40:54.018703] 初始化聊天会话: session_analyze_user_20260325
[2026-03-25 21:40:54.018972] 问候用户: analyze_user
[2026-03-25 21:40:54.019393] 分析用户意图
[2026-03-25 21:40:54.019822] 处理用户请求
[2026-03-25 21:40:54.020201] 完成对话
Deserializing unregistered type __main__.Intent from checkpoint. This will be blocked in a future version. Add to allowed_msgpack_modules to silence: [('__main__', 'Intent')]
Deserializing unregistered type __main__.DialogState from checkpoint. This will be blocked in a future version. Add to allowed_msgpack_modules to silence: [('__main__', 'DialogState')]
[2026-03-25 21:40:54.021933] 初始化聊天会话: session_analyze_user_20260325
[2026-03-25 21:40:54.022266] 问候用户: analyze_user
[2026-03-25 21:40:54.022905] 分析用户意图
[2026-03-25 21:40:54.023286] 处理用户请求
[2026-03-25 21:40:54.023736] 完成对话

对话分析报告:
总轮数: 3
成功率: 100.0%
意图分布: greeting, weather, goodbye
状态变化: completed, completed, completed
Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐