使用LangChain构建第一个ReAct Agent
准备环境
使用Anaconda
安装python 3.10
安装langchain、langchain_openai、langchain_community (安装命令 pip install XXX)
申请DeepSeek API:https://platform.deepseek.com/api_keys(也可以用kimi:https://platform.moonshot.cn/console/api-keys)
代码
from langchain import hub
from langchain.agents import create_structured_chat_agent, AgentExecutor
from langchain.memory import ConversationBufferMemory
from langchain.schema import HumanMessage
from langchain.tools import BaseTool
from langchain_openai import ChatOpenAI
from langchain.agents import initialize_agent, Tool
# 模型 DeepSeek
# model = ChatOpenAI(model="deepseek-chat",
# openai_api_key="xx", #填写自己DeepSeek的api
# openai_api_base="https://api.deepseek.com/v1")
# kimi
model = ChatOpenAI(model="moonshot-v1-8k",
openai_api_key="sk-xx", #填写自己kimi的api
openai_api_base="https://api.moonshot.cn/v1")
from langchain_community.tools import WikipediaQueryRun
from langchain_community.utilities import WikipediaAPIWrapper
api_wrapper = WikipediaAPIWrapper(top_k_results=3, doc_content_chars_max=2000)
tool = WikipediaQueryRun(api_wrapper=api_wrapper)
# 提示词,直接从langchain hub上下载,因为写这个ReAct机制的prompt比较复杂,直接用现成的。
prompt = hub.pull("hwchase17/structured-chat-agent")
print(prompt)
tools = [tool]
# 定义AI Agent
agent = create_structured_chat_agent(
llm=model,
tools=tools,
prompt=prompt
)<