3.1 系统化的Agent设计¶
学习目标¶
- 掌握系统化Agent的整体设计
- 掌握系统化Agent的重要组件
- 掌握系统化Agent的工作流程
一、系统化的Agent设计¶
第一部分提到的是大模型做智能体的潜力,如果要充分发挥这种潜力,可以考虑把这些能力整合起来,形成系统的智能体系统。

二、重要组件¶
1 大语言模型(LLM)¶
在基于大语言模型的智能体中,大语言模型是整个系统的中心,负责协调和执行各种任务。它通过与其他模块的交互来实现目标。
2 记忆(Memory)¶
记忆模块分为短期记忆和长期记忆:
短期记忆,是指在执行任务的过程中的上下文,会在子任务的执行过程产生和暂存,在任务完结后被清空。
长期记忆是长时间保留的信息,一般是指外部知识库,通常用数据库来存储和检索。
from langgraph.graph import StateGraph, START,END
from langchain_ollama import ChatOllama
from typing_extensions import TypedDict
from typing import Annotated
from langgraph.graph.message import add_messages
from langgraph.checkpoint.memory import MemorySaver
class State(TypedDict):
messages: Annotated[list, add_messages]
llm = ChatOllama(model="qwen2.5:7b")
def chatbot(state: State):
return {"messages": [llm.invoke(state["messages"])]}
def buildGraph():
graphBuilder = StateGraph(State)
graphBuilder.add_node("chatbot", chatbot)
graphBuilder.add_edge(START, "chatbot")
graphBuilder.add_edge("chatbot",END)
graph = graphBuilder.compile()
return graph
def buildGraphWithMemory():
graphBuilder = StateGraph(State)
#实例化memory
memory = MemorySaver()
graphBuilder.add_node("chatbot", chatbot)
graphBuilder.add_edge(START, "chatbot")
graphBuilder.add_edge("chatbot",END)
#编译图的时候指定memory
graph = graphBuilder.compile(checkpointer=memory)
return graph
def singleRound(graph):
while True:
try:
userInput = input("User: ")
if userInput.lower() in ["quit", "exit", "q"]:
print("Goodbye!")
break
state = {"messages": [{"role": "user", "content": userInput}]}
result = graph.invoke(state)
# print(result)
print("Assitant:", result["messages"][-1].content)
except Exception as e:
print("发生错误:"+str(e))
def multiRound(graph,config):
while True:
try:
userInput = input("User: ")
if userInput.lower() in ["quit", "exit", "q"]:
print("Goodbye!")
break
state = {"messages": [{"role": "user", "content": userInput}]}
result = graph.invoke(state, config=config)
print(result)
print("Assitant:", result["messages"][-1].content)
except Exception as e:
print("发生错误:"+str(e))
if __name__ == "__main__":
#graph = buildGraph()
#singleRound(graph)
graphWithMemory = buildGraphWithMemory()
config = {"configurable": {"thread_id": "1"}}
multiRound(graphWithMemory,config)
3 工具(Tools)¶
智能体可以使用各种工具来完成任务,包括:
- 日历:用于时间管理和日程安排。
- 计算器:进行数学计算。
- 代码解释器:执行代码和脚本。
- 搜索:进行信息检索。
等,有了这些工具,智能体就可以与物理世界发生交互,解决问题
from langgraph.graph import StateGraph, START,END
from langchain_ollama import ChatOllama
from typing_extensions import TypedDict
from typing import Annotated
from langgraph.graph.message import add_messages
from langgraph.prebuilt import create_react_agent
#第一步:初始化模型和工具
def getID():
"""explain your identity"""
return f"我是凯瑞汽车的档案管理助手"
llm = create_react_agent(
model = ChatOllama(model="qwen2.5:7b"),
tools=[getID],
prompt="You are a helpful assistant"
)
def chatbot(state):
return llm.invoke(state)
#第二步:初始化图和状态
class State(TypedDict):
messages: Annotated[list, add_messages]
graphBuilder = StateGraph(dict)
#第三步:定义节点
graphBuilder.add_node("chatbot", chatbot)
#第四步:定义边和出入口
graphBuilder.add_edge(START, "chatbot")
graphBuilder.add_edge("chatbot",END)
#第五步:编译图
graph = graphBuilder.compile()
#第六步:执行图
userInput = input("User: ")
state:State = {"messages": [{"role": "user", "content": userInput}]}
result = graph.invoke(state)
print("Assistant:"+str(result["messages"][-1].content))
4 规划(Planning)¶
智能体会把大型任务分解为子任务,并规划执行任务的流程;智能体会对任务执行的过程进行思考和反思,从而决定是继续执行任务,或判断任务完结并终止运行。
from langgraph.graph import StateGraph, START, END
from langchain_ollama import ChatOllama
from langgraph.types import Send
from typing_extensions import TypedDict
from typing import Annotated
from pydantic import BaseModel, Field
import operator
class Section(BaseModel):
num: int = Field(description="章节序号")
name: str = Field(description="章节标题,采用“【第三章】 迷雾重现”的形式")
description: str = Field(
description="章节描述,最前面是章节标题,后面是章节内容。章节标题采用“【第三章】 迷雾重现”的形式,单独一行")
class Sections(BaseModel):
sections: list[Section] = Field(description="文章的各个子章节")
class State(TypedDict):
storyLine: str
sections: list[Section]
completedSections: Annotated[list, operator.add]
novel: str
class WorkerState(TypedDict):
section: Section
completedSections: Annotated[list, operator.add]
llm = ChatOllama(model="qwen2.5:7b")
def getWholeStory(state):
prompt = "你是一位著名小说家,正在创作一部精彩的侦探小说,首先给出故事梗概,1000字左右。"
state["storyLine"] = llm.invoke(prompt).content
print("storyLine " + "*" * 80)
print(state["storyLine"])
return state
def orchestrate(state):
planner = llm.with_structured_output(Sections)
result = planner.invoke("""你是一位著名小说家,正在创作一部精彩的侦探小说,根据下面的【故事梗概】,将小说分成10个章节,并给出章节的剧情发展。1000字左右。
【故事梗概】
""" + state["storyLine"])
state["sections"] = result.sections
print("sections " + "*" * 80)
for section in state["sections"]:
print(str(section.name + ' ' + section.description))
return state
def buildGraph():
graphBuilder = StateGraph(State)
graphBuilder.add_node("getWholeStory", getWholeStory)
graphBuilder.add_node("orchestrate", orchestrate)
graphBuilder.add_edge(START, "getWholeStory")
graphBuilder.add_edge("getWholeStory", "orchestrate")
graph = graphBuilder.compile()
return graph
if __name__ == "__main__":
graph = buildGraph()
from tools import showGraph
showGraph.showGraphInCode(graph, "graph.jpg")
state: State = {}
result = graph.invoke(state)
print("final " + "*" * 80)
print(result["novel"])
5 行动(Action)¶
根据规划模块制定的计划,智能体执行具体的行动。例如:
- 使用搜索引擎搜集资料
- 使用sql语句从本地数据库中查询数据
- 通过网站api下订单
- 把整理好的报告保存到本地
......
6 交互协作(Interaction and Collaboration)¶
- 智能体之间可以通过交互协作来共同完成任务,实现更复杂的功能。
- 旅行规划智能体通知订票智能体按照特定要求订购车票和机场接送预约
- 旅行规划智能体通知旅居智能体按照特定要求订购酒店
- 旅行规划智能体通知家居智能体按照特定要求将行程所有行李清单发送到用户邮箱
- 旅行规划智能体订购景点门票
......
三、工作流程¶
输入信息:智能体接收任务或指令。
记忆检索:智能体从短期记忆和长期记忆中检索相关信息。
工具选择:智能体根据任务需求选择合适的工具。
规划制定:智能体制定详细的执行计划。
行动执行:智能体根据计划执行具体行动。
反思和调整:智能体对执行结果进行反思和调整,优化未来的决策和行动。
交互协作:智能体与其他智能体协作,共同完成任务。
通过这些模块和流程,智能体能够有效地处理各种任务,实现智能化的决策和执行。