开始使用免费开始使用

创建一个 ReAct 代理

现在您已经了解了 LangChain 的基本组件,接下来就动手创建一个 ReAct 代理。它将使用工具 count_r_in_word 来统计任意单词中包含多少个字母 r。

以下对象已为您加载:toolChatOpenAIcreate_react_agentmathmodel

本练习是课程的一部分

使用 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'][____].____)
编辑并运行代码