目录
[1. 环境准备和基础概念](#1. 环境准备和基础概念)
[2. 基础入门:单智能体工作流](#2. 基础入门:单智能体工作流)
[3. 进阶:Multi-Agent协作系统](#3. 进阶:Multi-Agent协作系统)
[4. 实战案例:电商客服超级智能体系统](#4. 实战案例:电商客服超级智能体系统)
[5. 高级特性:记忆、工具和监控](#5. 高级特性:记忆、工具和监控)
[6. 主程序:完整演示](#6. 主程序:完整演示)
[7. 部署和生产化建议](#7. 部署和生产化建议)
什么是LangGraph?

LangGraph是一个基于图的高级编排框架,专门用于构建AI代理。它建立在LangChain之上,通过状态图来管理代理之间的交互,相比传统的线性工作流提供了更强大的功能。
官方地址:https://github.com/langchain-ai/langgraph
核心特点
图形化架构:使用有向图表示代理工作流,支持循环和条件分支
内置持久化:自动管理状态持久化和工作流进度保存
循环处理:支持代理与工具的重复交互,创建反馈循环
人机集成:内置人工介入操作支持,允许专家审查和干预
状态管理:跨所有组件维护共享状态,实现无缝通信
与LangChain的区别
LangChain:提供基础功能,适合简单的线性工作流,需要手动设置内存、持久化等
LangGraph:提供更复杂的能力,支持状态管理、循环工作流和人工监督的开箱即用功能
关键组件
节点(Nodes):执行特定任务的处理单元
边(Edges):节点之间的连接和关系,决定信息流向
状态管理(State Management):维护代理操作的当前上下文和进度
Multi-Agent超级智能体案例概要设计
本文将使用LangGraph来构建一个多智能体系统。这个系统将包含多个智能体,它们可以相互协作以完成复杂任务。我们将设计一个简单的案例:一个智能体用于查询天气,另一个智能体用于根据天气情况给出出行建议,再有一个智能体用于管理对话流程和协调其他智能体。
步骤:
-
1、定义智能体:我们将创建两个智能体,一个天气查询智能体和一个建议智能体,另外还需要一个主控智能体来协调。
-
2、定义状态:使用一个共享的状态(State)来在智能体之间传递信息。
-
3、定义图:使用LangGraph来构建一个流程图,决定智能体之间的调用顺序。
注意:为了简化,我们不会真正调用天气API,而是模拟天气查询。重点在于展示多智能体系统的架构。
我们将实现以下流程:
用户输入地点 -> 主控智能体 -> 天气查询智能体 -> 建议智能体 -> 输出结果
状态(State)将包含:
-
location: 用户输入的地点
-
weather: 天气查询结果
-
advice: 给出的建议
智能体:
-
主控智能体(MasterAgent):接收用户输入,决定调用哪个智能体,并整理最终回答。
-
天气查询智能体(WeatherAgent):根据地点查询天气(模拟)。
-
建议智能体(AdviceAgent):根据天气给出出行建议。
我们将构建一个图,其中节点是智能体,边根据状态条件决定流程。
由于LangGraph允许我们构建有向图,我们可以定义循环和条件分支。
在这个例子中,我们假设流程是线性的:主控智能体 -> 天气查询智能体 -> 建议智能体 -> 主控智能体(整理回答)。
但是,为了展示LangGraph的能力,我们可以设计一个更复杂的流程,例如,如果天气查询失败,则重新询问用户。
然而,为了简单起见,我们先实现一个线性流程。
我们将使用langgraph库,它需要安装:pip install langgraph
注意:这个例子中,我们不会使用真实的LLM,而是用模拟函数来代表智能体的核心逻辑。在实际应用中,你可以将每个智能体替换为调用LLM的函数。
Multi-Agent超级智能体案例详细设计与案例实现
1. 环境准备和基础概念
python
# requirements.txt
"""
langgraph>=0.0.40
langchain>=0.1.0
langchain-openai>=0.0.5
pydantic>=2.0.0
pyvis>=0.3.1
networkx>=3.1
"""
# 安装依赖
!pip install langgraph langchain langchain-openai pyvis networkx duckduckgo-search
2. 基础入门:单智能体工作流
python
from typing import TypedDict, List, Annotated, Dict, Any
import operator
from langgraph.graph import StateGraph, END
from langchain_openai import ChatOpenAI
from langchain.schema import HumanMessage
import json
# 定义状态结构
class AgentState(TypedDict):
"""智能体状态定义"""
messages: Annotated[List[Dict], operator.add] # 消息历史
context: str # 上下文信息
task: str # 当前任务
result: str # 处理结果
# 初始化LLM
llm = ChatOpenAI(
model="gpt-4",
temperature=0.7,
api_key="your-api-key" # 实际使用中替换
)
def research_agent(state: AgentState) -> AgentState:
"""研究智能体:收集和分析信息"""
task = state.get('task', '')
# 模拟研究过程
research_prompt = f"""
请对以下任务进行深入研究分析:
任务:{task}
请提供:
1. 关键信息点
2. 潜在风险
3. 建议方案
格式化为JSON结构。
"""
response = llm.invoke([
HumanMessage(content=research_prompt)
])
# 解析响应
try:
result = json.loads(response.content)
except:
result = {"analysis": response.content}
return {
**state,
"context": "研究完成",
"result": json.dumps(result, ensure_ascii=False, indent=2)
}
def writing_agent(state: AgentState) -> AgentState:
"""写作智能体:基于研究结果撰写报告"""
context = state.get('context', '')
research_result = state.get('result', '')
writing_prompt = f"""
基于以下研究结果,撰写一份专业的报告:
研究背景:{context}
研究结果:{research_result}
要求:
1. 结构清晰(摘要、正文、结论)
2. 专业性强
3. 可执行建议明确
报告长度约500字。
"""
response = llm.invoke([
HumanMessage(content=writing_prompt)
])
return {
**state,
"result": response.content,
"context": "报告撰写完成"
}
def review_agent(state: AgentState) -> AgentState:
"""评审智能体:审核报告质量"""
report = state.get('result', '')
review_prompt = f"""
请评审以下报告的质量:
{report}
请提供:
1. 质量评分(1-10分)
2. 主要优点
3. 改进建议
4. 是否通过审核
"""
response = llm.invoke([
HumanMessage(content=review_prompt)
])
review_result = {
"report": report,
"review": response.content,
"status": "待定"
}
# 简单的审核逻辑
if "通过" in response.content or "批准" in response.content:
review_result["status"] = "通过"
elif "不通过" in response.content or "拒绝" in response.content:
review_result["status"] = "不通过"
return {
**state,
"result": json.dumps(review_result, ensure_ascii=False, indent=2)
}
def conditional_edge(state: AgentState) -> str:
"""条件路由:基于评审结果决定下一步"""
result_str = state.get('result', '{}')
try:
result = json.loads(result_str)
status = result.get('status', '待定')
if status == "通过":
return "finalize"
elif status == "不通过":
return "rewrite"
else:
return "review" # 重新评审
except:
return "review"
# 创建基础工作流图
def create_basic_workflow():
"""创建基础智能体工作流"""
workflow = StateGraph(AgentState)
# 添加节点
workflow.add_node("research", research_agent)
workflow.add_node("write", writing_agent)
workflow.add_node("review", review_agent)
# 添加边
workflow.add_edge("research", "write")
workflow.add_edge("write", "review")
# 条件路由
workflow.add_conditional_edges(
"review",
conditional_edge,
{
"finalize": END,
"rewrite": "write",
"review": "review"
}
)
# 设置入口点
workflow.set_entry_point("research")
return workflow.compile()
# 运行基础工作流
def run_basic_workflow():
"""运行基础工作流示例"""
# 创建工作流
graph = create_basic_workflow()
# 初始状态
initial_state = AgentState(
messages=[],
context="",
task="分析AI在金融风控中的应用趋势",
result=""
)
# 执行工作流
result = graph.invoke(initial_state)
print("=" * 50)
print("基础工作流执行完成")
print("=" * 50)
print(f"任务: {result['task']}")
print(f"最终结果:\n{result['result'][:500]}...")
return result
# 可视化工作流
def visualize_graph(graph):
"""可视化工作流图"""
from IPython.display import Image, display
import matplotlib.pyplot as plt
import networkx as nx
# 创建NetworkX图
G = nx.DiGraph()
# 添加节点和边
for node in graph.nodes:
G.add_node(node)
# 获取边信息(简化版本)
# 在实际应用中,需要从graph结构解析
# 绘制图形
plt.figure(figsize=(10, 6))
pos = nx.spring_layout(G)
nx.draw(G, pos, with_labels=True, node_color='lightblue',
node_size=3000, font_size=10, font_weight='bold')
plt.title("智能体工作流图")
plt.show()
return G
3. 进阶:Multi-Agent协作系统
python
from datetime import datetime
from langgraph.checkpoint import MemorySaver
from langgraph.graph import StateGraph, START
from langchain.tools import Tool
from langchain.agents import AgentExecutor, create_openai_tools_agent
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
class MultiAgentState(TypedDict):
"""多智能体状态定义"""
user_input: str
task_type: str # 任务类型
current_agent: str # 当前执行的智能体
agents_used: List[str] # 已使用的智能体
intermediate_results: Dict[str, Any] # 中间结果
final_output: str # 最终输出
error_log: List[str] # 错误日志
metadata: Dict[str, Any] # 元数据
class SpecializedAgent:
"""专业化智能体基类"""
def __init__(self, name, role, capabilities):
self.name = name
self.role = role
self.capabilities = capabilities
self.llm = ChatOpenAI(model="gpt-4", temperature=0.7)
def process(self, state: MultiAgentState) -> MultiAgentState:
"""处理任务的核心方法"""
raise NotImplementedError
class ResearchAgent(SpecializedAgent):
"""研究分析智能体"""
def __init__(self):
super().__init__(
name="ResearchAgent",
role="信息收集与分析专家",
capabilities=["网络研究", "数据分析", "趋势预测"]
)
# 可以集成搜索工具
from langchain_community.tools import DuckDuckGoSearchRun
self.search_tool = DuckDuckGoSearchRun()
def process(self, state: MultiAgentState):
task = state.get('user_input', '')
prompt = f"""
作为研究分析专家,请完成以下任务:
任务:{task}
请提供:
1. 关键事实和数据
2. 最新趋势
3. 权威来源(如适用)
4. 初步分析结论
格式:JSON格式
"""
response = self.llm.invoke([HumanMessage(content=prompt)])
# 更新状态
new_state = {
**state,
"current_agent": self.name,
"agents_used": state.get('agents_used', []) + [self.name],
"intermediate_results": {
**state.get('intermediate_results', {}),
"research": response.content
}
}
print(f"[{self.name}] 研究任务完成")
return new_state
class StrategyAgent(SpecializedAgent):
"""战略规划智能体"""
def __init__(self):
super().__init__(
name="StrategyAgent",
role="战略规划专家",
capabilities=["SWOT分析", "路线图制定", "风险评估"]
)
def process(self, state: MultiAgentState):
research_result = state.get('intermediate_results', {}).get('research', '')
prompt = f"""
基于以下研究结果,制定战略规划:
研究结果:{research_result}
请提供:
1. SWOT分析
2. 短期和长期目标
3. 实施路线图
4. 风险评估与缓解措施
格式:JSON格式
"""
response = self.llm.invoke([HumanMessage(content=prompt)])
new_state = {
**state,
"current_agent": self.name,
"agents_used": state.get('agents_used', []) + [self.name],
"intermediate_results": {
**state.get('intermediate_results', {}),
"strategy": response.content
}
}
print(f"[{self.name}] 战略规划完成")
return new_state
class CreativeAgent(SpecializedAgent):
"""创意生成智能体"""
def __init__(self):
super().__init__(
name="CreativeAgent",
role="创意内容专家",
capabilities=["创意构思", "内容创作", "故事叙述"]
)
def process(self, state: MultiAgentState):
strategy_result = state.get('intermediate_results', {}).get('strategy', '')
prompt = f"""
基于以下战略规划,生成创意内容:
战略规划:{strategy_result}
请提供:
1. 创意概念
2. 营销标语
3. 内容大纲
4. 视觉建议
格式:JSON格式
"""
response = self.llm.invoke([HumanMessage(content=prompt)])
new_state = {
**state,
"current_agent": self.name,
"agents_used": state.get('agents_used', []) + [self.name],
"intermediate_results": {
**state.get('intermediate_results', {}),
"creative": response.content
}
}
print(f"[{self.name}] 创意生成完成")
return new_state
class QualityAgent(SpecializedAgent):
"""质量保证智能体"""
def __init__(self):
super().__init__(
name="QualityAgent",
role="质量审核专家",
capabilities=["质量检查", "一致性验证", "改进建议"]
)
def process(self, state: MultiAgentState):
all_results = state.get('intermediate_results', {})
prompt = f"""
请审核以下所有智能体的输出质量:
{json.dumps(all_results, ensure_ascii=False, indent=2)}
请提供:
1. 质量评分(1-10)
2. 一致性检查
3. 改进建议
4. 是否批准发布
格式:JSON格式
"""
response = self.llm.invoke([HumanMessage(content=prompt)])
new_state = {
**state,
"current_agent": self.name,
"agents_used": state.get('agents_used', []) + [self.name],
"intermediate_results": {
**state.get('intermediate_results', {}),
"quality_check": response.content
}
}
print(f"[{self.name}] 质量审核完成")
return new_state
class SupervisorAgent:
"""监督者智能体:协调其他智能体"""
def __init__(self):
self.llm = ChatOpenAI(model="gpt-4", temperature=0.5)
self.agents = {
"research": ResearchAgent(),
"strategy": StrategyAgent(),
"creative": CreativeAgent(),
"quality": QualityAgent()
}
def decide_next_agent(self, state: MultiAgentState) -> str:
"""决定下一个执行的智能体"""
task_type = state.get('task_type', 'general')
agents_used = state.get('agents_used', [])
# 决策逻辑
if len(agents_used) == 0:
return "research"
elif "research" in agents_used and "strategy" not in agents_used:
return "strategy"
elif "strategy" in agents_used and "creative" not in agents_used:
return "creative"
elif "creative" in agents_used and "quality" not in agents_used:
return "quality"
else:
return END
def supervise(self, state: MultiAgentState) -> MultiAgentState:
"""监督执行"""
next_agent = self.decide_next_agent(state)
if next_agent == END:
# 整合最终结果
final_output = self.integrate_results(state)
return {
**state,
"final_output": final_output,
"current_agent": "supervisor",
"metadata": {
"completion_time": datetime.now().isoformat(),
"total_agents": len(state.get('agents_used', [])),
"status": "completed"
}
}
else:
# 执行下一个智能体
agent = self.agents[next_agent]
return agent.process(state)
def integrate_results(self, state: MultiAgentState) -> str:
"""整合所有智能体的结果"""
results = state.get('intermediate_results', {})
integration_prompt = f"""
请整合以下所有智能体的工作成果,生成一份完整的报告:
{json.dumps(results, ensure_ascii=False, indent=2)}
报告结构:
1. 执行摘要
2. 详细分析
3. 战略建议
4. 创意方案
5. 质量评估
6. 实施建议
确保报告连贯、专业、可执行。
"""
response = self.llm.invoke([HumanMessage(content=integration_prompt)])
return response.content
def create_multi_agent_system():
"""创建多智能体系统"""
workflow = StateGraph(MultiAgentState)
# 创建监督者
supervisor = SupervisorAgent()
# 添加监督节点
workflow.add_node("supervisor", supervisor.supervise)
# 设置路由
workflow.add_edge(START, "supervisor")
workflow.add_edge("supervisor", "supervisor") # 循环直到完成
# 添加检查点
memory = MemorySaver()
# 编译图
return workflow.compile(checkpointer=memory)
def run_multi_agent_example():
"""运行多智能体系统示例"""
# 创建系统
multi_agent_system = create_multi_agent_system()
# 配置初始状态
config = {"configurable": {"thread_id": "test_thread_1"}}
# 初始状态
initial_state = MultiAgentState(
user_input="为一家新的AI教育科技创业公司制定市场进入策略",
task_type="business_strategy",
current_agent="",
agents_used=[],
intermediate_results={},
final_output="",
error_log=[],
metadata={}
)
print("=" * 60)
print("开始执行多智能体协作系统")
print("=" * 60)
# 执行工作流
final_state = None
for step, state in enumerate(multi_agent_system.stream(initial_state, config)):
print(f"\n[步骤 {step + 1}] 当前智能体: {state['current_agent']}")
if state.get('final_output'):
print(f"任务完成!")
final_state = state
break
if final_state:
print("\n" + "=" * 60)
print("多智能体系统执行完成")
print("=" * 60)
print(f"使用的智能体: {final_state['agents_used']}")
print(f"\n最终报告摘要:\n{final_state['final_output'][:800]}...")
# 保存结果
with open('multi_agent_result.json', 'w', encoding='utf-8') as f:
json.dump(dict(final_state), f, ensure_ascii=False, indent=2)
return final_state
4. 实战案例:电商客服超级智能体系统
python
class EcommerceState(TypedDict):
"""电商客服状态"""
customer_query: str
customer_history: List[Dict]
current_intent: str
agent_pool: Dict[str, Any]
processed_steps: List[str]
response: str
requires_human: bool
sentiment: str
class EcommerceSuperAgent:
"""电商客服超级智能体"""
def __init__(self):
# 初始化专业化智能体
self.agents = {
"intent_classifier": self.create_intent_classifier(),
"product_expert": self.create_product_expert(),
"order_tracker": self.create_order_tracker(),
"return_handler": self.create_return_handler(),
"complaint_resolver": self.create_complaint_resolver(),
"sales_advisor": self.create_sales_advisor(),
"sentiment_analyzer": self.create_sentiment_analyzer(),
"escalation_manager": self.create_escalation_manager()
}
# 主协调LLM
self.coordinator_llm = ChatOpenAI(model="gpt-4", temperature=0.3)
def create_intent_classifier(self):
"""意图分类智能体"""
prompt = ChatPromptTemplate.from_messages([
("system", """你是一个意图分类专家。分析用户查询,返回以下分类之一:
1. product_inquiry - 产品咨询
2. order_status - 订单状态
3. return_refund - 退货退款
4. complaint - 投诉
5. purchase - 购买咨询
6. other - 其他
只返回分类名称,不要其他内容。"""),
("human", "{query}")
])
chain = prompt | self.coordinator_llm
return lambda query: chain.invoke({"query": query}).content.strip()
def create_product_expert(self):
"""产品专家智能体"""
# 模拟产品数据库
products = {
"laptop": {
"name": "AI超极本 Pro",
"price": 9999,
"specs": "16GB RAM, 1TB SSD, RTX 4060",
"stock": 50
},
"phone": {
"name": "智能旗舰手机",
"price": 5999,
"specs": "6.8寸AMOLED, 200MP相机",
"stock": 100
}
}
def expert_function(query, product_db=products):
prompt = f"""
作为产品专家,回答以下产品咨询:
用户查询:{query}
可用产品信息:{json.dumps(product_db, indent=2)}
请提供:
1. 相关产品推荐
2. 详细规格说明
3. 价格信息
4. 库存状态
5. 购买建议
回答要专业、有帮助。
"""
response = self.coordinator_llm.invoke([HumanMessage(content=prompt)])
return response.content
return expert_function
def create_order_tracker(self):
"""订单追踪智能体"""
# 模拟订单数据库
orders = {
"ORD12345": {
"status": "已发货",
"items": ["AI超极本 Pro"],
"tracking": "SF123456789",
"estimated_delivery": "2024-12-25"
}
}
def tracker_function(order_id, order_db=orders):
if order_id in order_db:
order = order_db[order_id]
return f"""
订单状态信息:
订单号:{order_id}
状态:{order['status']}
商品:{', '.join(order['items'])}
物流单号:{order['tracking']}
预计送达:{order['estimated_delivery']}
"""
else:
return "未找到该订单信息,请确认订单号是否正确。"
return tracker_function
def create_sentiment_analyzer(self):
"""情感分析智能体"""
def analyze_function(text):
prompt = f"""
分析以下文本的情感倾向:
文本:{text}
返回JSON格式:
{{
"sentiment": "positive/neutral/negative",
"confidence": 0.0-1.0,
"key_phrases": [],
"urgency_level": "low/medium/high"
}}
"""
response = self.coordinator_llm.invoke([HumanMessage(content=prompt)])
try:
return json.loads(response.content)
except:
return {"sentiment": "neutral", "confidence": 0.5}
return analyze_function
def coordinate_agents(self, state: EcommerceState) -> EcommerceState:
"""协调所有智能体处理客户查询"""
query = state["customer_query"]
print(f"[SuperAgent] 处理查询: {query}")
# 1. 分析情感
sentiment_result = self.agents["sentiment_analyzer"](query)
state["sentiment"] = sentiment_result.get("sentiment", "neutral")
# 2. 分类意图
intent = self.agents["intent_classifier"](query)
state["current_intent"] = intent
print(f"[SuperAgent] 检测到意图: {intent}")
print(f"[SuperAgent] 情感分析: {sentiment_result}")
# 3. 路由到相应智能体
response = ""
if intent == "product_inquiry":
response = self.agents["product_expert"](query)
elif intent == "order_status":
# 提取订单号(简化处理)
import re
order_match = re.search(r'[A-Z]{3}\d{5,}', query)
if order_match:
order_id = order_match.group()
response = self.agents["order_tracker"](order_id)
else:
response = "请提供您的订单号以便查询状态。"
elif intent == "return_refund":
response = "退货退款处理需要您的订单信息,已为您转接退货专员。"
elif intent == "complaint":
if sentiment_result.get("urgency_level") == "high":
response = "检测到紧急投诉,已为您优先转接客服经理。"
else:
response = "抱歉给您带来不便,我们的客服专员将尽快处理您的问题。"
elif intent == "purchase":
response = self.agents["product_expert"](query)
response += "\n\n如需购买帮助,请输入:购买 [产品名称]"
else:
response = "请问您需要什么帮助?您可以咨询产品、订单、退货等问题。"
# 4. 检查是否需要人工介入
requires_human = (
sentiment_result.get("sentiment") == "negative" and
sentiment_result.get("confidence", 0) > 0.7
) or intent in ["complaint", "return_refund"]
if requires_human:
response += "\n\n[系统提示] 已为您标记需要人工客服跟进。"
state["response"] = response
state["requires_human"] = requires_human
state["processed_steps"].append(intent)
return state
def create_ecommerce_workflow():
"""创建电商客服工作流"""
workflow = StateGraph(EcommerceState)
# 创建超级智能体
super_agent = EcommerceSuperAgent()
# 添加节点
workflow.add_node("super_agent", super_agent.coordinate_agents)
# 设置路由
workflow.add_edge(START, "super_agent")
workflow.add_edge("super_agent", END)
return workflow.compile()
def run_ecommerce_demo():
"""运行电商客服演示"""
workflow = create_ecommerce_workflow()
test_cases = [
"我想买一台性能好的笔记本电脑,有什么推荐吗?",
"我的订单ORD12345到哪里了?",
"你们的产品质量太差了!我要投诉!",
"手机屏幕摔坏了,可以保修吗?",
"我想了解一下你们的旗舰手机"
]
results = []
for i, query in enumerate(test_cases):
print(f"\n{'='*60}")
print(f"测试案例 {i+1}: {query}")
print(f"{'='*60}")
initial_state = EcommerceState(
customer_query=query,
customer_history=[],
current_intent="",
agent_pool={},
processed_steps=[],
response="",
requires_human=False,
sentiment="neutral"
)
result = workflow.invoke(initial_state)
results.append(result)
print(f"意图分类: {result['current_intent']}")
print(f"情感分析: {result['sentiment']}")
print(f"是否需要人工: {result['requires_human']}")
print(f"\n智能体回复:\n{result['response']}")
print(f"\n处理步骤: {result['processed_steps']}")
return results
def analyze_performance(results):
"""分析智能体性能"""
print("\n" + "="*60)
print("性能分析报告")
print("="*60)
total_cases = len(results)
human_intervention = sum(1 for r in results if r['requires_human'])
avg_steps = sum(len(r['processed_steps']) for r in results) / total_cases
print(f"总处理案例: {total_cases}")
print(f"需要人工介入: {human_intervention} ({human_intervention/total_cases*100:.1f}%)")
print(f"平均处理步骤: {avg_steps:.2f}")
print(f"意图分布: {', '.join(set(r['current_intent'] for r in results))}")
# 生成改进建议
if human_intervention / total_cases > 0.3:
print("\n改进建议: 需要加强自动处理能力,特别是投诉和退货场景。")
else:
print("\n改进建议: 系统自动化程度良好,可继续优化产品推荐精准度。")
5. 高级特性:记忆、工具和监控
python
class AdvancedAgentSystem:
"""高级智能体系统:包含记忆、工具和监控"""
def __init__(self):
self.llm = ChatOpenAI(model="gpt-4", temperature=0.7)
# 工具定义
self.tools = self.define_tools()
# 长期记忆存储
self.memory_store = {}
# 性能监控
self.metrics = {
"total_requests": 0,
"successful_responses": 0,
"average_response_time": 0,
"tool_usage": {}
}
def define_tools(self):
"""定义智能体可用的工具"""
from langchain.tools import tool
@tool
def search_web(query: str) -> str:
"""搜索最新网络信息"""
# 简化版本,实际可以接入搜索引擎API
return f"搜索 '{query}' 的结果摘要..."
@tool
def calculate(expression: str) -> str:
"""计算数学表达式"""
try:
return str(eval(expression))
except:
return "计算错误"
@tool
def get_current_time() -> str:
"""获取当前时间"""
return datetime.now().strftime("%Y-%m-%d %H:%M:%S")
@tool
def format_json(data: str) -> str:
"""格式化JSON数据"""
try:
parsed = json.loads(data)
return json.dumps(parsed, indent=2, ensure_ascii=False)
except:
return "无效的JSON格式"
return [search_web, calculate, get_current_time, format_json]
def create_agent_with_tools(self, system_prompt: str):
"""创建带有工具的智能体"""
prompt = ChatPromptTemplate.from_messages([
("system", system_prompt),
("human", "{input}"),
MessagesPlaceholder(variable_name="agent_scratchpad")
])
agent = create_openai_tools_agent(self.llm, self.tools, prompt)
return AgentExecutor(agent=agent, tools=self.tools, verbose=True)
def run_advanced_demo(self):
"""运行高级功能演示"""
print("高级智能体系统演示")
print("=" * 50)
# 创建带工具的智能体
system_prompt = """你是一个多功能的AI助手,可以使用工具完成各种任务。
可用工具:
1. search_web - 搜索最新信息
2. calculate - 计算数学表达式
3. get_current_time - 获取当前时间
4. format_json - 格式化JSON数据
请根据用户需求选择合适的工具,并给出完整回答。"""
agent = self.create_agent_with_tools(system_prompt)
# 测试案例
test_queries = [
"计算 (125 * 34) / 5 的结果",
"现在是什么时间?",
"搜索'人工智能最新发展'",
"格式化这个JSON: {\"name\":\"测试\",\"value\":123}"
]
for query in test_queries:
print(f"\n查询: {query}")
try:
result = agent.invoke({"input": query})
print(f"结果: {result['output'][:200]}...")
# 更新指标
self.metrics["total_requests"] += 1
self.metrics["successful_responses"] += 1
except Exception as e:
print(f"错误: {e}")
# 显示性能指标
self.show_metrics()
def show_metrics(self):
"""显示性能指标"""
print("\n" + "=" * 50)
print("系统性能指标")
print("=" * 50)
print(f"总请求数: {self.metrics['total_requests']}")
print(f"成功响应数: {self.metrics['successful_responses']}")
success_rate = (self.metrics['successful_responses'] /
self.metrics['total_requests'] * 100 if self.metrics['total_requests'] > 0 else 0)
print(f"成功率: {success_rate:.1f}%")
6. 主程序:完整演示
python
def main():
"""主演示程序"""
print("LangGraph多智能体系统完整演示")
print("=" * 60)
# 1. 基础工作流演示
print("\n1. 基础智能体工作流演示")
print("-" * 40)
basic_result = run_basic_workflow()
# 2. 多智能体系统演示
print("\n\n2. 多智能体协作系统演示")
print("-" * 40)
multi_agent_result = run_multi_agent_example()
# 3. 电商客服案例演示
print("\n\n3. 电商客服超级智能体演示")
print("-" * 40)
ecommerce_results = run_ecommerce_demo()
# 4. 高级功能演示
print("\n\n4. 高级智能体系统(带工具)演示")
print("-" * 40)
advanced_system = AdvancedAgentSystem()
advanced_system.run_advanced_demo()
# 5. 性能分析
print("\n\n5. 系统性能分析")
print("-" * 40)
analyze_performance(ecommerce_results)
# 6. 保存所有结果
print("\n\n6. 结果汇总")
print("-" * 40)
all_results = {
"basic_workflow": dict(basic_result) if 'basic_result' in locals() else None,
"multi_agent": dict(multi_agent_result) if 'multi_agent_result' in locals() else None,
"ecommerce_cases": [dict(r) for r in ecommerce_results],
"timestamp": datetime.now().isoformat()
}
with open('langgraph_demo_results.json', 'w', encoding='utf-8') as f:
json.dump(all_results, f, ensure_ascii=False, indent=2)
print("所有结果已保存到 'langgraph_demo_results.json'")
print("=" * 60)
print("演示完成!")
# 运行演示
if __name__ == "__main__":
# 注意:在实际运行前,请确保:
# 1. 安装所有依赖包
# 2. 配置OpenAI API密钥
# 3. 根据需求调整模型参数
main()
7. 部署和生产化建议
python
class ProductionAgentSystem:
"""生产环境就绪的智能体系统"""
def __init__(self):
# 配置管理
self.config = self.load_config()
# 监控系统
self.monitor = self.setup_monitoring()
# 容错机制
self.fallback_agents = self.setup_fallback()
# 缓存系统
self.cache = {}
def load_config(self):
"""加载配置文件"""
return {
"max_retries": 3,
"timeout_seconds": 30,
"rate_limit": 10, # 每分钟请求数
"log_level": "INFO"
}
def setup_monitoring(self):
"""设置监控"""
import logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler('agent_system.log'),
logging.StreamHandler()
]
)
return logging.getLogger(__name__)
def setup_fallback(self):
"""设置备用智能体"""
fallback_llm = ChatOpenAI(
model="gpt-3.5-turbo", # 使用成本更低的模型作为备用
temperature=0.3
)
def fallback_response(query: str) -> str:
"""备用响应函数"""
return f"主智能体暂时不可用,备用响应:我们已记录您的查询 '{query}',稍后将为您处理。"
return fallback_response
def with_error_handling(self, func):
"""错误处理装饰器"""
import functools
@functools.wraps(func)
def wrapper(*args, **kwargs):
retries = self.config["max_retries"]
for attempt in range(retries):
try:
self.monitor.info(f"尝试执行 {func.__name__}, 第 {attempt + 1} 次")
result = func(*args, **kwargs)
self.monitor.info(f"{func.__name__} 执行成功")
return result
except Exception as e:
self.monitor.error(f"{func.__name__} 执行失败: {str(e)}")
if attempt == retries - 1:
self.monitor.warning("所有重试失败,使用备用方案")
return self.fallback_agents(
kwargs.get('query', args[0] if args else '')
)
# 等待后重试
import time
time.sleep(2 ** attempt) # 指数退避
return self.fallback_agents("")
return wrapper
def rate_limited(self, func):
"""限流装饰器"""
import time
import functools
last_called = 0
@functools.wraps(func)
def wrapper(*args, **kwargs):
nonlocal last_called
# 计算需要等待的时间
current_time = time.time()
time_to_wait = 60 / self.config["rate_limit"] - (current_time - last_called)
if time_to_wait > 0:
time.sleep(time_to_wait)
last_called = time.time()
return func(*args, **kwargs)
return wrapper
def cached_response(self, ttl_seconds=300):
"""缓存装饰器"""
import time
import functools
def decorator(func):
cache = {}
@functools.wraps(func)
def wrapper(*args, **kwargs):
# 创建缓存键
cache_key = f"{func.__name__}:{str(args)}:{str(kwargs)}"
# 检查缓存
if cache_key in cache:
cache_time, result = cache[cache_key]
if time.time() - cache_time < ttl_seconds:
self.monitor.info(f"使用缓存响应: {cache_key}")
return result
# 执行函数
result = func(*args, **kwargs)
# 更新缓存
cache[cache_key] = (time.time(), result)
return result
return wrapper
return decorator
# 生产环境使用示例
def production_example():
"""生产环境示例"""
production_system = ProductionAgentSystem()
# 创建生产就绪的智能体
@production_system.with_error_handling
@production_system.rate_limited
@production_system.cached_response(ttl_seconds=600)
def production_agent(query: str) -> str:
"""生产环境智能体"""
llm = ChatOpenAI(model="gpt-4", temperature=0.7)
response = llm.invoke([
HumanMessage(content=f"处理查询: {query}")
])
return response.content
# 测试
test_queries = [
"如何部署LangGraph系统?",
"多智能体系统的监控指标有哪些?",
"如何优化智能体响应时间?"
]
for query in test_queries:
print(f"\n查询: {query}")
response = production_agent(query=query)
print(f"响应: {response[:200]}...")
总结
这个完整的LangGraph演示涵盖了:
核心要点:
-
基础工作流:单智能体的线性流程
-
多智能体协作:专业化智能体分工合作
-
业务案例:电商客服的实际应用
-
高级特性:工具集成、记忆、监控
-
生产就绪:错误处理、限流、缓存
关键技术栈:
-
LangGraph:工作流编排核心
-
LangChain:智能体框架基础
-
OpenAI GPT:核心大模型能力
-
自定义智能体:专业化智能体设计
应用场景:
-
客户服务自动化
-
内容创作流水线
-
数据分析与报告
-
决策支持系统
进阶方向:
-
知识图谱集成:增强智能体的领域知识
-
联邦学习:多智能体协同学习
-
实时流处理:处理实时数据流
-
自主优化:智能体自我改进机制
这个系统展示了如何从简单的单智能体工作流逐步构建复杂的Multi-Agent超级智能体系统,满足企业级应用的需求。