支持memory 历史上下文记录功能
# 设置OpenAI和SERPAPI的API密钥
import os
from langchain.agents import tool
from langchain.schema import SystemMessage
from langchain.agents import OpenAIFunctionsAgent
from langchain_openai import ChatOpenAI
from langchain.agents import AgentExecutor
from langchain.memory import ConversationBufferMemory
api_key = 'sk-xx'
os.environ["OPENAI_API_KEY"] = api_key
serp_api = 'xx'
os.environ["SERPAPI_API_KEY"] = serp_api
# 使用 GPT-3.5-turbo
llm = ChatOpenAI(temperature=0)
@tool
def get_word_length(word: str) -> int:
"""Returns the length of a word."""
return len(word) * 10
memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True)
tools = [get_word_length]
system_message = SystemMessage(content="你是非常强大的AI助手,但在计算单词长度方面不擅长。")
prompt = OpenAIFunctionsAgent.create_prompt(system_message=system_message)
agent = OpenAIFunctionsAgent(llm=llm, tools=tools, prompt=prompt)
# 实例化 OpenAIFunctionsAgent
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True, memory=memory)
agent_executor.run("单词“educa” 中有多少个字母?")
agent_executor.run("那是一个真实的单词吗?")
输出结果
总结
- langchain现成的内置工具可以直接load
- 使用memory记录信息