增强LLMs和聊天模型的即席工具调用能力
引言
在现代AI应用中,语言模型(LLMs)和聊天模型常常需要调用外部工具完成复杂任务。然而,并非所有模型都原生支持工具调用。这篇文章将介绍如何通过提示工程为不支持工具调用的模型添加即席工具调用功能,帮助开发者灵活应对不同的应用场景。
主要内容
1. 环境设置
首先,我们需要安装必要的软件包:
%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()
2. 选择模型
本指南中,我们将使用phi3
模型,该模型不具备原生工具调用支持。你可以根据需要选择合适的模型。
3. 创建工具
接下来,我们创建两个简单的工具: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]
# 打印工具信息
for t in tools:
print("--")
print(t.name)
print(t.description)
print(t.args)
4. 创建提示
我们将编写一个提示,让模型依据用户输入调用适当的工具,并以JSON格式返回调用信息。
from langchain_core.output_parsers import JsonOutputParser
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}")]
)
chain = prompt | model
message = chain.invoke({"input": "what's 3 plus 1132"})
print(message.content)
5. 工具调用逻辑
我们为工具调用编写实际执行逻辑。
from typing import Any, Dict, Optional, TypedDict
from langchain_core.runnables import RunnableConfig
class ToolCallRequest(TypedDict):
name: str
arguments: Dict[str, Any]
def invoke_tool(tool_call_request: ToolCallRequest, config: Optional[RunnableConfig] = None):
tool_name_to_tool = {tool.name: tool for tool in tools}
requested_tool = tool_name_to_tool[tool_call_request["name"]]
return requested_tool.invoke(tool_call_request["arguments"], config=config)
# 测试工具调用
invoke_tool({"name": "multiply", "arguments": {"x": 3, "y": 5}})
常见问题和解决方案
错误处理
在使用复杂工具时,模型的输出可能会出现错误。建议使用以下策略来提高输出质量:
- 提供少样本示例。
- 添加错误处理,例如捕获异常并要求模型纠正输出。
总结和进一步学习资源
通过本文介绍的方法,你可以为不支持工具调用的模型添加这种能力。在实践中,你可能需要根据具体情况调整工具和提示来提高效果。
参考资料
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
—END—