创建一个 ReAct 代理
现在您已经了解了 LangChain 的基本组件,接下来就动手创建一个 ReAct 代理。它将使用工具 count_r_in_word 来统计任意单词中包含多少个字母 r。
以下对象已为您加载:tool、ChatOpenAI、create_react_agent、math 和 model。
本练习是课程的一部分
使用 LangChain 设计 Agentic 系统
练习说明
- 使用
create_react_agent()并传入model,同时在工具列表中加入count_r_in_word,来构建代理app。 - 定义一个
query变量,用字符串形式接收用户的问题。 - 使用
.invoke()调用app,并传入一个包含"messages"键的字典,将query标注为"human"。 - 访问
response中的最后一条消息,并打印其.content属性,以获得代理的答案。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Create the agent
____ = ____(model=____, tools=[____])
# Create a query
____ = "How many r's are in the word 'Terrarium'?"
# Invoke the agent and store the response
response = app.____({"messages": [("human", ____)]})
# Print the agent's response
print(____['messages'][____].____)