05-如何让agent与tool共享记忆

工具类只能只读 memory。

0 在agent与tool之间共享记忆

  • 自定义一个工具用来LLMChain来总结内容
  • 使用readonlymemory来共享记忆
  • 观察共享与不共享的区别

1 创建一条链来总结对话

python 复制代码
template = """以下是一段AI机器人和人类的对话:
{chat_history}
根据输入和上面的对话记录写一份对话总结.
输入: {input}"""

prompt = PromptTemplate(
    input_variables=["input","chat_history"],
    template=template,
)

memory = ConversationBufferMemory(
    memory_key="chat_history",
    return_messages=True,
)
readonlymemory = ReadOnlySharedMemory(memory=memory)
summary_chain = LLMChain(
    llm=llm,
    prompt=prompt,
    verbose=True,
    memory=readonlymemory,
)

2 构建工具

python 复制代码
# 搜索工具
search = SerpAPIWrapper()
# 总结工具
def SummaryChainFun(history):
    print("\n==============总结链开始运行==============")
    print("输入历史: ",history)
    summary_chain.run(history)

tools = [
    Tool(
        name="Search",
        func=search.run,
        description="当需要了解实时的信息或者你不知道的事时候可以使用搜索工具",
    ),
    Tool(
        name="Summary",
        func=SummaryChainFun,
        description="当你被要求总结一段对话的时候可以使用这个工具,工具输入必须为字符串,只在必要时使用",
    ),
]
print(tools)

3 创建记忆组件

python 复制代码
memory = ConversationBufferMemory(
    memory_key="chat_history",
    return_messages=True,
)

4 创建agent

python 复制代码
agent_chain = initialize_agent(
    tools,
    llm,
    agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
    verbose=True,
    handle_parsing_errors=True,
    memory=memory,
)
python 复制代码
print(agent_chain.agent.llm_chain.prompt.template)
python 复制代码
agent_chain.run(input="美国第45任总统是谁?")
python 复制代码
agent_chain.run(input="他的夫人叫什么名字?")
python 复制代码
print(agent_chain.memory.buffer)
python 复制代码
agent_chain.run(input="我们都聊了什么?")
python 复制代码
agent_chain.run(input="帮我总结下目前的对话内容,给我5岁的儿子看看")
python 复制代码
print(agent_chain.memory.buffer)
相关推荐
Cosolar44 分钟前
从 Model 到 System:AI Agent Infra 工程师的技术全景与学习路径
langchain·aigc·agent
GISer_Jing1 天前
GitHub热点I
后端·ai·langchain
M--Y1 天前
LangGraph 架构基石:持久化与运行控制
python·langchain·大模型·llm·持久化·langgraph
xyphf_和派孔明1 天前
第十章: LangGraph的人机交互Human-in-the-loop实践
langchain·llm
xyphf_和派孔明1 天前
第六章: LangGraph的工具调用代理-Tool Calling Agent
langchain·llm
M--Y2 天前
LangGraph 工作流模式
开发语言·javascript·python·langchain·大模型·llm·langgraph
xyphf_和派孔明2 天前
第五章: LangGraph的路由代理-Router Agent介绍
langchain·llm
Flynn Liang2 天前
Agentic 工作流:子代理、Supervisor 与人工介入
java·langchain·多智能体·supervisor·agentic·langchain4j
GISer_Jing3 天前
Agent核心内容
后端·ai·langchain
Flynn Liang3 天前
可观测性与成本治理:一次对话的 17 个观测点
java·langchain·可观测性·micrometer·langchain4j·token 成本·llm 监控