如何为LLMs和Chat模型添加即席工具调用能力

121 阅读3分钟

如何为LLMs和Chat模型添加即席工具调用能力

在当今的AI领域,模型的工具调用能力让LLMs和Chat模型变得更加灵活和实用。然而,并不是所有的模型都经过工具调用能力的微调。在这篇文章中,我们将探讨如何通过简单的提示设计为不支持工具调用的模型增加即席工具调用支持。

引言

许多现代的AI模型已经被增强以支持工具调用,大大增加了它们的功能。对于那些没有此功能的模型,我们可以通过构建特定的提示和逻辑,使其能够调用我们自定义的工具。本文将引导您完成这一过程,展示如何使用LangChain等库以及创建自定义工具。

主要内容

设置

首先,我们需要安装一些关键的包:

%pip install --upgrade --quiet langchain langchain-community

如果您想使用LangSmith,可以设置相应的API key。

import getpass
import os

os.environ["LANGCHAIN_TRACING_V2"] = "true"  # 根据需要取消注释
os.environ["LANGCHAIN_API_KEY"] = getpass.getpass("Enter your LangChain API key: ")

创建工具

我们将创建两个简单的工具:addmultiply,并使用langchain_core中的工具装饰器。

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]

构建提示

我们需要为模型编写一个提示,以便它知道如何使用这些工具,输出格式为包含名字和参数的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.

The `arguments` should be a dictionary, with keys corresponding 
to the argument names and the values corresponding to the requested values.
"""

prompt = ChatPromptTemplate.from_messages(
    [("system", system_prompt), ("user", "{input}")]
)

工具调用的实现

接下来,我们创建调用工具的逻辑,并测试其功能。

from typing import Any, Dict, Optional, TypedDict
from langchain_core.runnables import RunnableConfig

class ToolCallRequest(TypedDict):
    """A typed dict that shows the inputs into the invoke_tool function."""
    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}
    name = tool_call_request["name"]
    requested_tool = tool_name_to_tool[name]
    return requested_tool.invoke(tool_call_request["arguments"], config=config)

# 测试工具调用
print(invoke_tool({"name": "multiply", "arguments": {"x": 3, "y": 5}}))  # 输出: 15.0

常见问题和解决方案

在更复杂的工具中,模型可能会输出错误信息。为此,建议提供一些示例或实施错误处理机制,例如捕获异常并让LLM纠正其输出。

总结和进一步学习资源

通过本教程,您可以为无法直接调用工具的模型添加这种能力。然而,仍需注意在现实应用中可能遇到的挑战,建议继续探索LangChain的官方文档以及相关社区教程。

参考资料

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

---END---