跳到主要內容
Open In ColabOpen on GitHub

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

先決條件

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

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

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

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

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 等效地定義模式,而無需附帶函數。

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

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.chat_models import init_chat_model

llm = init_chat_model("gpt-4o-mini", model_provider="openai")
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)。當在這些情況下解析失敗時,InvalidToolCall 的實例會填充在 .invalid_tool_calls 屬性中。 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)]

後續步驟

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

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

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


此頁面是否對您有幫助?