LangChain中的工具调用:代理应用背后的机制
将 Python 函数注册为 LangChain 工具,然后运行四步循环:模型选择工具,这些工具在外部执行,最终结果以消息形式返回。
来源: Agentic AI with LangChain — Part 3: Tool Calling in LangChain
这是“基于LangChain的智能体AI”系列文章的第三篇。第二篇介绍了如何使用LangGraph构建智能体RAG工作流。接下来的目标是将应用范围扩展到更多领域,如烹饪、游泳、古典音乐,甚至全球各城市的实时天气预报,同时避免因新增节点而使图结构变得过于复杂。
沿袭第二篇的做法,可以为每个领域添加一个检索节点,每个节点对应一个独立的Pinecone索引,再增加一个用于调用公共API的天气节点。随着节点数量不断增加,连接关系和分支也会随之增多,导致图结构越来越难以维护。
使用工具调用是解决问题的方法。无需为每个函数创建一个节点,只需将这些函数注册为 LangChain 工具,让模型决定何时调用它们、如何使用其结果以及如何将这些结果整合到最终答案中。这样既能简化工作流程,还能通过精确的计算、数据库查询、网络搜索和实时 API 扩展模型的功能。
接下来的内容将介绍 LangChain 中的核心理念以及工具调用循环。这些基础知识将为后续关于 ReAct 的文章做铺垫。理解了 ReAct 之后,就可以运用相同的理念简化第二部分中的工作流程。相关代码存放在 GitHub 仓库中。
主题:
- 什么是工具调用以及它为何重要。
- 如何实现 LangChain 工具。
- 四步工具调用循环的运作原理。
术语表
- LangChain 工具:一个用
@tool装饰的 Python 函数,可将自身的结构与使用说明提供给模型。 - 工具调用:模型请求外部函数运行的机制。
- 工具消息:将工具处理结果传回模型的消息类型。
- 工具调用循环:模型选择工具、在模型外部运行该工具、获取结果并将其整合到答案中的循环过程。
设置
创建一个包含 OpenAI 和 Tavily 密钥的 .env 文件。
OPENAI_API_KEY="<Your OpenAI API Key>"
TAVILY_API_KEY=<Your TAVILY API Key>
通过 Pydantic 设置类来加载它们。
class BaseConfig(BaseSettings):
OPENAI_API_KEY: Optional[str]
PINECONE_API_KEY: Optional[str]
TAVILY_API_KEY: Optional[str]
model_config = SettingsConfigDict(env_file=".env", extra="ignore")
该项目将工具放在tools包中,包含一些简单的示例,比如求和辅助函数和天气查询工具。
project/
|
├── tools
│ ├── get_sum.py # a simple LangChain tool example
| └── weather.py # get_weather LangChain tool using open source APIs
|
|── tool_call.py # implement tool-calling loop using LangChain tools
├── config.py # pydantic BaseConfig
├── .env # environment variable definition
├── .gitignore
└── requirements.txt # package requirements
什么是 LangChain 工具
工具其实就是带有 @tool 装饰器的普通 Python 函数。该装饰器会包裹这个函数,根据文档字符串和类型提示生成结构体,并为模型提供调用该函数的指令。
from langchain.tools import tool
@tool
def get_sum(a: int, b: int) -> int:
"""
get the summation of two integers
:param a: int, input integer
:param b: int, input integer
:return: int, the sum of a and b
"""
return a + b
天气工具
get_weather使用免费的Open-Meteo API。它首先查询城市的坐标,然后获取当前的天气信息。这种“先解析再获取”的模式是实时工具的典型做法。
工具调用循环
一旦有了这些工具,接下来的问题就是模型如何使用它们。答案是一个四步循环。
- 用户发送请求。
- 模型决定调用哪个或哪些工具,并发出包含工具名称及参数的消息。
- 这些工具在模型外部运行,其结果以工具消息的形式返回。
- 模型整合这些结果并生成最终答案。
模型本身从不直接执行工具。所有操作都在外部进行,输出结果以工具消息的形式返回,随后由模型进行处理。
该模型还可以在一次响应中请求多个工具,这被称为并行工具调用。当被询问波士顿的温度以及3和5的和时,它可能会同时调用get_weather和get_sum函数;在给出答案之前,它会先执行这两个函数。
在LangChain中实现该循环
WeatherAssistant类通过get_weather和tavily_search函数来整合天气查询与网络搜索功能。
大语言模型与工具
构造函数会初始化一个OpenAI模型、一个工具字典、一个能够调用这些工具的受限大语言模型、一个消息列表,以及用于告知模型何时使用各工具的系统提示。
class WeatherAssistant:
def __init__(self):
# initialize llm
self.llm = ChatOpenAI(api_key=api_key, model="gpt-4o-mini", temperature=0)
# initialize a tool dictionary
self.tools = {"get_weather": get_weather,
"tavily_search": TavilySearch(max_results=3, tavily_api_key=TAVILY_API_KEY)}
# bind LangChain tools to llm
self.llm_with_tools = self.llm.bind_tools(list(self.tools.values()))
# initialize messages to store message list
self.messages = []
# System prompt
self.system_prompt = f"""You are a helpful assistant for question-answering tasks.
When users ask about weather, use the get_weather tool to get weather. For other questions,
use web_search. If you don't know the answer, just say that you don't know.
Be conversational and helpful in your responses."""
self.messages.append(SystemMessage(content=self.system_prompt))
聊天方式
chat函数会先添加用户的消息,接着调用模型;如果存在工具调用,则会循环执行每个工具,将每个结果作为ToolMessage添加进去,最后再次调用模型以生成最终响应。该模式可处理单一调用和并行调用两种情况。
async def chat(self, message: str):
# Wrap User message in a HumanMessage and add it to message list
self.messages.append(HumanMessage(content=message))
# Get AI response (it may or may not contain tool calls)
response = await self.llm_with_tools.ainvoke(self.messages)
self.messages.append(response)
# If there is any tool calls in the AI response
if response.tool_calls:
# process tool calls
for tool_call in response.tool_calls:
# retrieve function name from tool_call, then
# retrieve the tool from tool dictionary, and invoke it,
# append resulting tool message to message list
tool = self.tools[tool_call["name"]]
tool_result = await tool.ainvoke(tool_call)
self.messages.append(tool_result)
# Get final response after tool execution
final_response = await self.llm_with_tools.ainvoke(self.messages)
self.messages.append(final_response)
快速测试
一个简小的异步主程序创建了助手,并询问东京的温度。
async def main():
print("hello tool calling!")
assistant = WeatherAssistant()
message = "What is the temperature in Tokyo?"
await assistant.chat(message)
for msg in assistant.messages:
msg.pretty_print()
if __name__ == "__main__":
asyncio.run(main())
消息列表会以清晰的顺序展示:一条包含问题的用户消息、一条使用get_weather工具调用的AI消息、一条包含天气数据的工具消息,以及最后一条包含语音回答的AI消息。
关于错误与重试的说明\n\n如果某个工具出现异常,循环应捕获该异常并将其转化为清晰的工具消息,由模型决定是重新尝试还是给出道歉。盲目地使用相同的错误参数进行重试只会浪费时间;最好将失败信息呈现出来,以便模型进行调整。\n\n## 这对整个系列为何重要
工具调用是ReAct以及所有能够自主决定行动的智能体所依赖的基础机制。一旦这个循环结构稳固下来,要新增功能就只需编写另一个@tool函数,而无需再添加新的图节点。这正是第二部分中繁琐工作流程所期待的简化方式。一旦工具被注册,新的功能领域就不再表现为新的图节点,而是变为模型能够通过其架构和文档字符串发现的新函数。接下来的文章将基于这种带有ReAct模式的循环结构进行深入探讨,随后再回到第二部分的图模型,展示当决策由工具调用承担后,需要处理的连接关系究竟减少了多少。