跳到主要內容

如何使用聊天模型呼叫工具

先決條件

本指南假設您熟悉以下概念

工具呼叫允許聊天模型透過「呼叫工具」來回應給定的提示。

請記住,雖然名稱「工具呼叫」暗示模型正在直接執行某些動作,但事實並非如此!模型僅產生工具的引數,而實際執行工具(或不執行)取決於使用者。

工具呼叫是一種通用技術,可從模型產生結構化輸出,即使您不打算調用任何工具,也可以使用它。其中一個用例是從非結構化文本中擷取

Diagram of calling a tool

如果您想了解如何使用模型產生的工具呼叫來實際執行工具,請查看本指南

支援的模型

工具呼叫並非通用功能,但許多流行的 LLM 提供者都支援。您可以在此處找到支援工具呼叫的所有模型列表

LangChain 實作了標準介面,用於定義工具、將其傳遞給 LLM 以及表示工具呼叫。本指南將介紹如何將工具綁定到 LLM,然後調用 LLM 以產生這些引數。

定義工具綱要

為了讓模型能夠呼叫工具,我們需要傳入工具綱要,描述工具的功能及其引數。支援工具呼叫功能的聊天模型實作了 .bind_tools() 方法,用於將工具綱要傳遞給模型。工具綱要可以作為 Python 函數(帶有類型提示和文件字串)、Pydantic 模型、TypedDict 類別或 LangChain Tool 物件傳入。後續的模型調用將連同提示一起傳入這些工具綱要。

Python 函數

我們的工具綱要可以是 Python 函數

# The function name, type hints, and docstring are all part of the tool
# schema that's passed to the model. Defining good, descriptive schemas
# is an extension of prompt engineering and is an important part of
# getting models to perform well.
def add(a: int, b: int) -> int:
"""Add two integers.

Args:
a: First integer
b: Second integer
"""
return a + b


def multiply(a: int, b: int) -> int:
"""Multiply two integers.

Args:
a: First integer
b: Second integer
"""
return a * b

LangChain 工具

LangChain 也實作了 @tool 裝飾器,可進一步控制工具綱要,例如工具名稱和引數描述。有關詳細資訊,請參閱此處的操作指南。

Pydantic 類別

您可以使用 Pydantic 等效地定義沒有隨附函數的綱要。

請注意,除非提供預設值,否則所有欄位都是 required

from pydantic import BaseModel, Field


class add(BaseModel):
"""Add two integers."""

a: int = Field(..., description="First integer")
b: int = Field(..., description="Second integer")


class multiply(BaseModel):
"""Multiply two integers."""

a: int = Field(..., description="First integer")
b: int = Field(..., description="Second integer")

TypedDict 類別

需要 langchain-core>=0.2.25

或使用 TypedDicts 和註釋

from typing_extensions import Annotated, TypedDict


class add(TypedDict):
"""Add two integers."""

# Annotations must have the type and can optionally include a default value and description (in that order).
a: Annotated[int, ..., "First integer"]
b: Annotated[int, ..., "Second integer"]


class multiply(TypedDict):
"""Multiply two integers."""

a: Annotated[int, ..., "First integer"]
b: Annotated[int, ..., "Second integer"]


tools = [add, multiply]

為了實際將這些綱要綁定到聊天模型,我們將使用 .bind_tools() 方法。這會處理將 addmultiply 綱要轉換為模型適當的格式。然後,每次調用模型時,都會傳入工具綱要。

pip install -qU langchain-openai
import getpass
import os

if not os.environ.get("OPENAI_API_KEY"):
os.environ["OPENAI_API_KEY"] = getpass.getpass("Enter API key for OpenAI: ")

from langchain_openai import ChatOpenAI

llm = ChatOpenAI(model="gpt-4o-mini")
llm_with_tools = llm.bind_tools(tools)

query = "What is 3 * 12?"

llm_with_tools.invoke(query)
AIMessage(content='', additional_kwargs={'tool_calls': [{'id': 'call_iXj4DiW1p7WLjTAQMRO0jxMs', 'function': {'arguments': '{"a":3,"b":12}', 'name': 'multiply'}, 'type': 'function'}], 'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 17, 'prompt_tokens': 80, 'total_tokens': 97}, 'model_name': 'gpt-4o-mini-2024-07-18', 'system_fingerprint': 'fp_483d39d857', 'finish_reason': 'tool_calls', 'logprobs': None}, id='run-0b620986-3f62-4df7-9ba3-4595089f9ad4-0', tool_calls=[{'name': 'multiply', 'args': {'a': 3, 'b': 12}, 'id': 'call_iXj4DiW1p7WLjTAQMRO0jxMs', 'type': 'tool_call'}], usage_metadata={'input_tokens': 80, 'output_tokens': 17, 'total_tokens': 97})

正如我們所見,我們的 LLM 產生了工具的引數!您可以查看 bind_tools() 的文件,以了解所有自訂 LLM 選擇工具方式的方法,以及本指南,了解如何強制 LLM 呼叫工具,而不是讓它自行決定。

工具呼叫

如果工具呼叫包含在 LLM 回應中,它們會附加到對應的訊息訊息區塊,作為 .tool_calls 屬性中的工具呼叫物件列表。

請注意,聊天模型可以一次呼叫多個工具。

ToolCall 是一個類型化的字典,包含工具名稱、引數值字典和(可選)識別碼。沒有工具呼叫的訊息預設為此屬性的空列表。

query = "What is 3 * 12? Also, what is 11 + 49?"

llm_with_tools.invoke(query).tool_calls
[{'name': 'multiply',
'args': {'a': 3, 'b': 12},
'id': 'call_1fyhJAbJHuKQe6n0PacubGsL',
'type': 'tool_call'},
{'name': 'add',
'args': {'a': 11, 'b': 49},
'id': 'call_fc2jVkKzwuPWyU7kS9qn1hyG',
'type': 'tool_call'}]

.tool_calls 屬性應包含有效的工具呼叫。請注意,有時模型提供者可能會輸出格式錯誤的工具呼叫(例如,引數不是有效的 JSON)。當在這些情況下解析失敗時,.invalid_tool_calls 屬性中會填入 InvalidToolCall 的實例。InvalidToolCall 可以有名稱、字串引數、識別碼和錯誤訊息。

解析

如果需要,輸出解析器可以進一步處理輸出。例如,我們可以使用 PydanticToolsParser.tool_calls 上填入的現有值轉換為 Pydantic 物件

from langchain_core.output_parsers import PydanticToolsParser
from pydantic import BaseModel, Field


class add(BaseModel):
"""Add two integers."""

a: int = Field(..., description="First integer")
b: int = Field(..., description="Second integer")


class multiply(BaseModel):
"""Multiply two integers."""

a: int = Field(..., description="First integer")
b: int = Field(..., description="Second integer")


chain = llm_with_tools | PydanticToolsParser(tools=[add, multiply])
chain.invoke(query)
API 參考:PydanticToolsParser
[multiply(a=3, b=12), add(a=11, b=49)]

後續步驟

現在您已了解如何將工具綱要綁定到聊天模型,並讓模型呼叫工具。

接下來,查看本指南,了解如何透過調用函數並將結果傳遞回模型來實際使用該工具

您也可以查看工具呼叫的一些更具體的用途


此頁面是否有幫助?