增强LLMs与聊天模型的临时工具调用能力

94 阅读3分钟

引言

在当今的人工智能领域,增强语言模型(LLM)和聊天模型的工具调用能力是一个备受关注的话题。虽然有些模型已通过微调支持工具调用,但如何在不支持工具调用的模型中实现这一功能仍然具有挑战性。本文将探讨如何通过提示策略,为不具备原生工具调用功能的模型添加临时工具调用能力。

主要内容

理解工具调用与LangChain工具

在开始之前,请确保您熟悉以下概念:

  • LangChain Tools:用于构建和管理不同工具的库。
  • 工具调用:让模型在适当时候调用外部工具。
  • 聊天模型与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()

选择一个不支持原生工具调用的模型示例:

from langchain_community.llms import Ollama
model = Ollama(model="phi3")

创建工具

我们将创建两个简单的工具:加法和乘法。

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.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}")]
)

解析与调用

使用JSON解析器解析输出,调用相应工具:

from langchain_core.output_parsers import JsonOutputParser

chain = prompt | model | JsonOutputParser()

chain.invoke({"input": "what's thirteen times 4"})

实现工具调用功能

编写函数以调用工具:

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}
    name = tool_call_request["name"]
    requested_tool = tool_name_to_tool[name]
    return requested_tool.invoke(tool_call_request["arguments"], config=config)

测试

通过一体化的链条测试工具调用:

chain = prompt | model | JsonOutputParser() | invoke_tool
chain.invoke({"input": "what's thirteen times 4.14137281"})

常见问题和解决方案

  1. 输出不准确:使用少样本学习(few-shot learning)提高模型输出质量。
  2. 错误处理:增加异常捕获,利用LLM纠正输出。

总结和进一步学习资源

尽管我们可以通过提示策略实现临时工具调用,但对于需要高可靠性和精确性的应用,使用支持原生工具调用的模型更为合适。欲了解更多,请参阅以下资源:

参考资料

  • LangChain API文档
  • Ollama模型说明

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