如何给agent正确的增加记忆

  • 将memory插入到提示词模板中


from langchain.agents import Tool
from langchain.agents import AgentType
from langchain.memory import ConversationBufferMemory
from langchain.chat_models import ChatOpenAI
from langchain.utilities import SerpAPIWrapper
from langchain.agents import initialize_agent
from langchain.chains import LLMMathChain
from langchain.prompts import  MessagesPlaceholder


llm=ChatOpenAI(
    temperature=0,
    model="gpt-4-1106-preview",
    )

import os
os.environ["SERPAPI_API_KEY"] = "f265b8d9834ed7692cba6db6618e2a8a9b24ed6964c457296a2626026e8ed594"
#构建一个搜索工具
search = SerpAPIWrapper()
#创建一个数学计算工具
llm_math_chain = LLMMathChain(
    llm=llm,
    verbose=True
)
tools = [
    Tool(
        name = "Search",
        func=search.run,
        description="useful for when you need to answer questions about current events or the current state of the world"
    ),
    Tool(
        name="Calculator",
        func=llm_math_chain.run,
        description="useful for when you need to answer questions about math"
    ),
]
#记忆组件
memory = ConversationBufferMemory(
    memory_key="chat_history",
    return_messages=True
)
#定义agent
agent_chain = initialize_agent(
    tools, 
    llm, 
    agent=AgentType.OPENAI_FUNCTIONS, 
    verbose=True, 
    handle_parsing_errors=True,#处理解析错误
    memory=memory #记忆组件
    )

agent_chain.run("我叫什么名字?")


需要使用agent_kwargs传递参数,将chat_history传入


agent_chain = initialize_agent(
    tools, 
    llm, 
    agent=AgentType.OPENAI_FUNCTIONS, 
    verbose=True, 
    handle_parsing_errors=True,#处理解析错误
    agent_kwargs={
        "extra_prompt_messages":[MessagesPlaceholder(variable_name="chat_history"),MessagesPlaceholder(variable_name="agent_scratchpad")],
    },
    memory=memory #记忆组件
    )

agent_chain.run("好厉害,刚才我们都聊了什么?")

在agent与tool之间共享记忆

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

创建一条链来总结对话

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,
)


构建工具

import os
os.environ["SERPAPI_API_KEY"] = "f265b8d9834ed7692cba6db6618e2a8a9b24ed6964c457296a2626026e8ed594"
#搜索工具
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)

创建记忆组件

memory = ConversationBufferMemory(
    memory_key="chat_history",
    return_messages=True,
)

创建Agent


agent_chain = initialize_agent(
    tools,
    llm,
    agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
    verbose=True,
    handle_parsing_errors=True,
    memory=memory,
)

print(agent_chain.agent.llm_chain.prompt.template)

prefix = """Have a conversation with a human, answering the following questions as best you can. You have access to the following tools:"""
suffix = """Begin!"
{chat_history}
Question: {input}
{agent_scratchpad}"""

agent_chain = initialize_agent(
    tools,
    llm,
    agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
    verbose=True,
    handle_parsing_errors=True,
    agent_kwargs={
        "prefix":prefix,
        "suffix":suffix,
        "agent_scratchpad":MessagesPlaceholder("agent_scratchpad"),
        "chat_history":MessagesPlaceholder("chat_history"),
        "input":MessagesPlaceholder("input"),
    },
    memory=memory,
)
print(agent_chain.agent.llm_chain.prompt.template)
Prev post

LangChain 019

Next post

LangChain 021