[如何为LLMs和聊天模型添加即席工具调用功能]

46 阅读3分钟
# 如何为LLMs和聊天模型添加即席工具调用功能

在现代应用中,大型语言模型(LLMs)和聊天模型已成为开发者的宠儿。然而,有时候我们需要模型调用外部工具(如计算器、翻译器等)来完成特定任务。本文将探讨如何为不具备本地工具调用能力的模型添加即席工具调用支持。

## 引言

工具调用对于增强LLMs的功能至关重要。尽管一些模型已经过专门训练以支持工具调用,但仍存在未具备此功能的模型。本文旨在为这些模型提供一种解决方案,利用提示编写(prompt engineering)实现工具调用。

## 主要内容

### 1. 基础设置

首先,确保安装了所需的软件包:

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

选择适合的模型进行实验,例如,Ollama模型不具备本地工具调用功能,非常适合我们的实验证明。

2. 创建工具

我们将创建两个简单的工具:addmultiply

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]

3. 编写提示

编写提示以指导模型调用合适的工具,并指定输出格式:

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

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
result = chain.invoke({"input": "what's thirteen times 4.14137281"})
print(result)  # 输出: 53.83784653

常见问题和解决方案

在使用较复杂的工具时,模型可能会输出错误信息。可以通过以下方法提高输出质量:

  • 提供示例:在提示中加入几例工具调用的示例。
  • 错误处理:捕获异常,并要求LLM修正其输出。

总结和进一步学习资源

通过本文,我们实现了为不具备本地工具调用能力的模型添加工具调用功能的方案。更多关于提示工程和工具调用的学习资源:

参考资料

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

---END---