有保障的广州网站建设/茂名seo快速排名外包
准备工作
- 注册获取
openAI
的key
,这个自己弄。 - 注册并获取
Google Search API
的key
,为了可以在工具中使用google
查询,https://serpapi.com/search-api
概述
本笔记本介绍了如何对 OpenAI Functions
代理进行持久化。
内容
import os
# 自己的openai 的Key
os.environ["OPENAI_API_KEY"] = "xxx"
# https://serpapi.com/search-api
os.environ["SERPAPI_API_KEY"] = "xxx"
from langchain import (LLMMathChain,OpenAI,SerpAPIWrapper,SQLDatabase,SQLDatabaseChain,
)
from langchain.agents import initialize_agent, Tool
from langchain.agents import AgentType
from langchain.chat_models import ChatOpenAI#可能会有的警告:/Users/harrisonchase/.pyenv/versions/3.9.1/envs/langchain/lib/python3.9/site-packages/deeplake/util/check_latest_version.py:32: UserWarning: A newer version of deeplake (3.6.4) is available.
#需要安装:It's recommended that you update to the latest version using `pip install -U deeplake`.# 得到大模型
llm = ChatOpenAI(temperature=0, model="gpt-3.5-turbo-0613")
# Google搜索工具
search = SerpAPIWrapper()
# 得到llmMathchain
llm_math_chain = LLMMathChain.from_llm(llm=llm, verbose=True)
# 持久化的DB
db = SQLDatabase.from_uri("sqlite:///../../../../../notebooks/Chinook.db")
# 得到db chain
db_chain = SQLDatabaseChain.from_llm(llm, db, verbose=True)
# 工具列表
tools = [Tool(name="Search",func=search.run,description="useful for when you need to answer questions about current events. You should ask targeted questions",),Tool(name="Calculator",func=llm_math_chain.run,description="useful for when you need to answer questions about math",),Tool(name="FooBar-DB",func=db_chain.run,description="useful for when you need to answer questions about FooBar. Input should be in the form of a question containing full context",),
]from langchain.prompts import MessagesPlaceholder
from langchain.memory import ConversationBufferMemory
agent_kwargs = {"extra_prompt_messages": [MessagesPlaceholder(variable_name="memory")],
}
memory = ConversationBufferMemory(memory_key="memory", return_messages=True)agent = initialize_agent(tools, llm, agent=AgentType.OPENAI_FUNCTIONS, verbose=True, agent_kwargs=agent_kwargs, memory=memory
)agent.run("hi")"""
> Entering new chain...
Hello! How can I assist you today?> Finished chain.'Hello! How can I assist you today?'
"""
总结
- 创建大模型
- Google搜索组件、数学计算组件、DB组件
- 将2中的组件,整合成工具列表
- 初始化代理,并得到代理对象
- 通过代理对象,开始启动
参考地址:
https://python.langchain.com/docs/modules/agents/how_to/add_memory_openai_functions