LangGraph教程(四):智能客服系统实战指南(流程+代码)

LangGraph教程(四):智能客服系统实战指南(流程+代码)

智能客服系统是LangGraph框架的典型应用场景,其多轮对话、状态管理和工具调用能力能够有效解决传统客服系统的流程僵化问题。本文将通过一个完整的智能客服案例,从流程设计到代码实现进行系统讲解。

一、系统架构设计

1.1 核心功能模块

智能客服系统包含三大核心模块:

  • 意图识别模块:通过NLP模型理解用户输入
  • 对话管理模块:维护对话状态并控制流程
  • 工具集成模块:调用知识库、订单系统等外部服务
  1. graph TD
  2. A[用户输入] --> B[意图识别]
  3. B --> C{意图类型}
  4. C -->|查询类| D[调用知识库]
  5. C -->|操作类| E[调用业务系统]
  6. C -->|闲聊类| F[生成回复]
  7. D --> G[结果包装]
  8. E --> G
  9. F --> G
  10. G --> H[输出回复]

1.2 LangGraph适配方案

采用状态机模式实现对话控制,每个节点代表一个对话状态:

  • 初始状态:欢迎语和主菜单
  • 查询状态:处理知识库查询
  • 操作状态:处理业务操作
  • 结束状态:对话总结

二、完整代码实现

2.1 环境准备

  1. # 安装必要依赖
  2. pip install langgraph langchain-community pydantic

2.2 核心组件定义

  1. from langgraph.prebuilt import StateGraph
  2. from pydantic import BaseModel
  3. from typing import Optional
  4. class DialogueState(BaseModel):
  5. current_step: str = "welcome"
  6. query_context: Optional[str] = None
  7. session_id: str = "default"
  8. class ToolResult(BaseModel):
  9. success: bool
  10. message: str
  11. data: Optional[dict] = None

2.3 工具集成实现

  1. class KnowledgeBaseTool:
  2. def query(self, query: str) -> ToolResult:
  3. # 模拟知识库查询
  4. if "退款" in query:
  5. return ToolResult(
  6. success=True,
  7. message="退款政策查询成功",
  8. data={"policy": "支持7天无理由退款"}
  9. )
  10. return ToolResult(
  11. success=False,
  12. message="未找到相关政策"
  13. )
  14. class OrderSystemTool:
  15. def check_status(self, order_id: str) -> ToolResult:
  16. # 模拟订单查询
  17. return ToolResult(
  18. success=True,
  19. message="订单状态查询成功",
  20. data={"status": "已发货", "tracking": "123456"}
  21. )

2.4 状态机配置

  1. from langgraph.prebuilt import create_state_graph
  2. app = create_state_graph(DialogueState)
  3. # 欢迎节点
  4. @app.node("welcome")
  5. def welcome_node(state: DialogueState):
  6. return {"reply": "您好,欢迎使用智能客服,请问需要什么帮助?"}
  7. # 意图分类节点
  8. @app.node("intent_classification")
  9. def classify_intent(state: DialogueState, input: str):
  10. if "政策" in input or "规则" in input:
  11. return {"next_step": "knowledge_query"}
  12. elif "订单" in input or "发货" in input:
  13. return {"next_step": "order_query"}
  14. else:
  15. return {"next_step": "fallback"}
  16. # 知识查询流程
  17. @app.node("knowledge_query")
  18. def handle_knowledge(state: DialogueState, input: str):
  19. kb = KnowledgeBaseTool()
  20. result = kb.query(input)
  21. if result.success:
  22. return {"reply": result.message + f"\n详情:{result.data['policy']}"}
  23. return {"reply": result.message}
  24. # 订单查询流程
  25. @app.node("order_query")
  26. def handle_order(state: DialogueState, input: str):
  27. # 简单提取订单号(实际应使用正则)
  28. order_id = input.split("订单")[1].strip() if "订单" in input else "1001"
  29. os = OrderSystemTool()
  30. result = os.check_status(order_id)
  31. return {
  32. "reply": f"{result.message}\n状态:{result.data['status']}\n运单号:{result.data['tracking']}"
  33. }
  34. # 配置状态转移
  35. app.add_edge("welcome", "intent_classification")
  36. app.add_edge("intent_classification", "knowledge_query", condition=lambda x: x["next_step"] == "knowledge_query")
  37. app.add_edge("intent_classification", "order_query", condition=lambda x: x["next_step"] == "order_query")
  38. app.add_edge("intent_classification", "fallback", condition=lambda x: x["next_step"] == "fallback")

2.5 完整运行示例

  1. def run_dialogue():
  2. # 初始化状态机
  3. state = DialogueState()
  4. # 模拟对话轮次
  5. dialogues = [
  6. "你好",
  7. "我想了解退款政策",
  8. "我的订单123456发货了吗?",
  9. "谢谢"
  10. ]
  11. current_state = state
  12. for input_text in dialogues:
  13. if current_state.current_step == "welcome":
  14. output = app.step(current_state, input=input_text)["welcome"]
  15. else:
  16. # 实际应通过NLP模型获取意图,这里简化处理
  17. intent_output = app.step(current_state, input=input_text)["intent_classification"]
  18. next_step = intent_output["next_step"]
  19. output = app.step(current_state, input=input_text)[next_step]
  20. print(f"用户: {input_text}")
  21. print(f"系统: {output['reply']}\n")
  22. # 更新状态(实际应根据工具调用结果更新)
  23. current_state = DialogueState(
  24. current_step="welcome", # 简化处理,实际应动态更新
  25. session_id=current_state.session_id
  26. )
  27. if __name__ == "__main__":
  28. run_dialogue()

三、关键实现细节

3.1 状态持久化方案

建议使用Redis等外部存储实现跨会话状态管理:

  1. import redis
  2. class StateManager:
  3. def __init__(self):
  4. self.r = redis.Redis(host='localhost', port=6379, db=0)
  5. def save_state(self, session_id: str, state: DialogueState):
  6. self.r.set(f"dialogue:{session_id}", state.json())
  7. def load_state(self, session_id: str) -> Optional[DialogueState]:
  8. data = self.r.get(f"dialogue:{session_id}")
  9. return DialogueState.parse_raw(data) if data else None

3.2 异常处理机制

  1. @app.node("error_handler")
  2. def handle_error(state: DialogueState, error: Exception):
  3. return {
  4. "reply": f"系统处理出错:{str(error)}",
  5. "next_step": "welcome" # 错误后重置对话
  6. }
  7. # 在状态转移中添加错误边
  8. app.add_error_edge("knowledge_query", "error_handler")

四、性能优化建议

  1. 工具调用缓存:对频繁查询的知识库内容实施缓存
    ```python
    from functools import lru_cache

class CachedKnowledgeBase(KnowledgeBaseTool):
@lru_cache(maxsize=128)
def query(self, query: str) -> ToolResult:
return super().query(query)

  1. 2. **异步工具调用**:对耗时操作使用异步调用
  2. ```python
  3. import asyncio
  4. async def async_order_query(order_id: str):
  5. # 模拟异步IO
  6. await asyncio.sleep(0.5)
  7. return OrderSystemTool().check_status(order_id)
  1. 状态压缩:对大型状态对象实施序列化优化
    ```python
    import orjson

def compress_state(state: DialogueState) -> bytes:
return orjson.dumps(state.dict())

def decompress_state(data: bytes) -> DialogueState:
return DialogueState.parse_raw(data)

  1. ## 五、扩展性设计
  2. ### 5.1 插件式工具架构
  3. ```python
  4. from abc import ABC, abstractmethod
  5. class ToolBase(ABC):
  6. @abstractmethod
  7. def execute(self, input: str) -> ToolResult:
  8. pass
  9. class ToolRegistry:
  10. def __init__(self):
  11. self.tools = {}
  12. def register(self, name: str, tool: ToolBase):
  13. self.tools[name] = tool
  14. def execute(self, name: str, input: str) -> ToolResult:
  15. return self.tools[name].execute(input)

5.2 多轮对话记忆

  1. class DialogueMemory:
  2. def __init__(self):
  3. self.history = []
  4. def add_turn(self, user_input: str, system_reply: str):
  5. self.history.append({
  6. "role": "user",
  7. "content": user_input
  8. })
  9. self.history.append({
  10. "role": "system",
  11. "content": system_reply
  12. })
  13. def get_context(self, window_size: int = 3):
  14. return self.history[-window_size*2:]

六、部署最佳实践

  1. 容器化部署

    1. FROM python:3.9-slim
    2. WORKDIR /app
    3. COPY requirements.txt .
    4. RUN pip install -r requirements.txt
    5. COPY . .
    6. CMD ["python", "app.py"]
  2. 水平扩展方案

  • 使用消息队列(如Kafka)解耦对话处理
  • 状态存储使用分布式缓存
  • 无状态服务实例可随意扩展
  1. 监控指标
  • 对话完成率
  • 平均处理时长
  • 工具调用成功率
  • 状态转移错误率

本文提供的完整实现展示了如何使用LangGraph构建企业级智能客服系统。实际开发中,建议从简单流程开始,逐步添加复杂功能,并通过AB测试验证不同对话策略的效果。对于生产环境,还需考虑安全审计、多语言支持等高级特性。