解锁大型语言模型的即席工具调用功能
在现代AI和编程的交汇处,大型语言模型(LLMs)和聊天模型提供了强大的交互能力。这篇文章将探讨如何为不支持工具调用的聊天模型添加即席工具调用功能。
引言
随着LLM和聊天模型的广泛应用,工具调用成为提高这些模型功能的重要手段。虽然一些模型已经经过微调以支持这一功能,但对于那些尚不具备此功能的模型,我们还有其他方法。本文将介绍一种通过提示设计实现工具调用的替代方法。
主要内容
前提条件
在开始之前,您需要对以下概念有基本了解:
- LangChain 工具
- 函数/工具调用
- 聊天模型和LLMs
设置
首先,安装必要的包:
%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()
选择模型
虽然许多模型已经支持工具调用,但对于不具备此功能的模型,我们可以使用提示策略。以下是一些可选模型:
- OpenAI
- Anthropic
- Azure
- Cohere
- NVIDIA
- FireworksAI
- Groq
- MistralAI
- TogetherAI
创建工具
我们将创建一个简单的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]
创建提示
编写提示以指导模型工具的调用:
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}")]
)
调用工具
编写函数以调用工具:
from typing import Any, Dict, Optional, TypedDict
class ToolCallRequest(TypedDict):
name: str
arguments: Dict[str, Any]
def invoke_tool(tool_call_request: ToolCallRequest):
tool_name_to_tool = {tool.name: tool for tool in tools}
name = tool_call_request["name"]
requested_tool = tool_name_to_tool[name]
return requested_tool.invoke(tool_call_request["arguments"])
代码示例
# 使用API代理服务提高访问稳定性
chain = prompt | model | JsonOutputParser() | invoke_tool
result = chain.invoke({"input": "what's thirteen times 4"})
print(result) # 输出:52.0
常见问题和解决方案
- 模型误调用工具:提供少样例(few shot examples)以提高准确性。
- 处理错误:添加异常处理,并将错误反馈给模型,要求其修正。
总结和进一步学习资源
通过本文介绍的方法,您可以为不支持工具调用的LLM添加即席工具调用功能。要深入学习,请参考以下资源:
参考资料
- LangChain 官方文档
- Chat Models 使用指南
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
---END---