如需完整的文件索引,請參閱 llms.txt。在文件頁面的網址末尾加上 .md ,即可取得該頁面的 Markdown 版本。
主要導覽
主題

函式呼叫

讓模型取得新的功能與資料,以便遵循指示並回應提示詞。

函式呼叫(也稱為工具呼叫)讓 OpenAI 模型能靈活地與外部系統互動,取得訓練資料以外的資料。本指南說明如何讓模型存取應用程式提供的資料,並透過應用程式執行操作。你將學到如何使用以 JSON 結構描述定義的函式工具,以及能接收和輸出自由格式文字的自訂工具。

在 Agents API 工作階段中,請使用函式註冊函式並處理工作階段的動作請求。本指南的範例示範如何與 Responses API 和 Chat Completions 整合。

如果應用程式有許多函式或大型結構描述,可以搭配使用函式呼叫和工具搜尋,延後載入不常用的工具,等模型需要時再載入。只有 gpt-5.4 及後續模型支援 tool_search。

GPT-6 Astra 和 GPT-6.1 Sol 必須透過 Responses API 呼叫工具。Chat Completions 範例使用 GPT-5.6 Terra,並停用推理。如要更新現有的整合,請參閱遷移指南。

運作方式

先認識工具呼叫的幾個重要術語,再透過實例瞭解如何呼叫工具。

工具呼叫流程

工具呼叫是應用程式與模型透過 OpenAI API 進行的多步驟對話。流程大致分為五個步驟:

  1. 向模型發出請求,並提供可呼叫的工具
  2. 接收模型傳回的工具呼叫
  3. 使用工具呼叫中的輸入,在應用程式端執行程式碼
  4. 將工具輸出放入第二次請求,傳給模型
  5. 接收模型的最終回應(或更多工具呼叫)

函式呼叫流程步驟圖

使用 Responses 時,應用程式可以重複這個流程,直到完成任務所需的所有工具呼叫。如果希望透過框架處理這個迴圈中反覆出現的協調工作,請參閱 Responses API 與 Agents SDK 的比較。

函式工具範例

以下以查詢指定星座每日運勢的 get_horoscope 函式為例,示範完整的工具呼叫流程。

完整的工具呼叫範例
from openai import OpenAI
import json

client = OpenAI()

# 1. Define a list of callable tools for the model
tools = [
    {
        "type": "function",
        "name": "get_horoscope",
        "strict": True,
        "description": "Get today's horoscope for an astrological sign.",
        "parameters": {
            "type": "object",
            "properties": {
                "sign": {
                    "type": "string",
                    "description": "An astrological sign like Taurus or Aquarius",
                },
            },
            "required": ["sign"],
            "additionalProperties": False,
        },
    },
]


def get_horoscope(sign):
    return f"{sign}: Next Tuesday you will befriend a baby otter."


# Create a running input list we will add to over time
input_list = [{"role": "user", "content": "What is my horoscope? I am an Aquarius."}]

# 2. Prompt the model with tools defined
response = client.responses.create(
    model="gpt-6-astra",
    tools=tools,
    input=input_list,
)

# Save function call outputs for subsequent requests
input_list += response.output

for item in response.output:
    if item.type == "function_call":
        if item.name == "get_horoscope":
            # 3. Execute the function logic for get_horoscope
            sign = json.loads(item.arguments)["sign"]
            horoscope = get_horoscope(sign)

            # 4. Provide function call results to the model
            input_list.append(
                {
                    "type": "function_call_output",
                    "call_id": item.call_id,
                    "output": horoscope,
                }
            )

response = client.responses.create(
    model="gpt-6-astra",
    instructions="Respond only with a horoscope generated by a tool.",
    tools=tools,
    input=input_list,
)

# 5. The model should be able to give a response!
print(response.output_text)

使用 GPT-5 或 o4-mini 等推理模型時,如果模型在回應中一併傳回工具呼叫和推理項目,就必須將這些推理項目連同工具呼叫輸出一起傳回給模型。如需瞭解如何保留模型產生這些推理項目時所依據的對話歷程,請參閱變更前綴的最佳做法。

定義函式

通常會在每次 API 請求的 tools 參數中宣告函式。使用工具搜尋時,應用程式也可以等到互動過程中需要某個函式時再載入。無論何時載入,可呼叫的函式都使用相同格式的結構描述。函式定義包含以下屬性:

欄位 說明
type 一律設為 function
name 函式名稱(例如 get_weather)
description 詳細說明何時及如何使用函式
parameters 用來定義函式輸入引數的 JSON 結構描述
strict 是否強制函式呼叫使用嚴格模式

以下是 get_weather 函式的定義範例:

{
  "type": "function",
  "name": "get_weather",
  "description": "Retrieves current weather for the given location.",
  "parameters": {
    "type": "object",
    "properties": {
      "location": {
        "type": "string",
        "description": "City and country e.g. Bogotá, Colombia"
      },
      "units": {
        "type": "string",
        "enum": ["celsius", "fahrenheit"],
        "description": "Units the temperature will be returned in."
      }
    },
    "required": ["location", "units"],
    "additionalProperties": false
  },
  "strict": true
}

由於 parameters 是以 JSON 結構描述定義,你可以運用屬性型別、列舉、說明、巢狀物件和遞迴物件等功能。

定義命名空間

使用命名空間依領域將相關工具分組,例如 crm、billing 或 shipping。命名空間有助於整理相似的工具,尤其適合模型需要在用途不同或服務不同系統的工具之間做選擇的情況,例如 CRM 和客服工單系統各有一個搜尋工具。

{
  "type": "namespace",
  "name": "crm",
  "description": "CRM tools for customer lookup and order management.",
  "tools": [
    {
      "type": "function",
      "name": "get_customer_profile",
      "description": "Fetch a customer profile by customer ID.",
      "parameters": {
        "type": "object",
        "properties": {
          "customer_id": { "type": "string" }
        },
        "required": ["customer_id"],
        "additionalProperties": false
      }
    },
    {
      "type": "function",
      "name": "list_open_orders",
      "description": "List open orders for a customer ID.",
      "defer_loading": true,
      "parameters": {
        "type": "object",
        "properties": {
          "customer_id": { "type": "string" }
        },
        "required": ["customer_id"],
        "additionalProperties": false
      }
    }
  ]
}

工具搜尋

如果需要讓模型使用大量工具,可以透過 tool_search 延後載入部分或所有工具。tool_search 工具讓模型能搜尋相關工具,將其加入模型上下文,再加以使用。只有 gpt-5.4 及後續模型支援這項功能。如需詳細資訊,請參閱工具搜尋指南。

定義函式的最佳做法

  1. 為函式取清楚明確的名稱,並撰寫詳細的參數說明與使用指示。

    • 明確說明函式及各參數的用途(包括參數格式),並說明輸出代表什麼。
    • 在系統提示詞中說明何時應使用各個函式,以及何時不該使用。 原則上,應 明確 告訴模型該怎麼做。
    • 提供範例及邊界案例,尤其是針對反覆出現的錯誤。(注意: 加入範例可能會降低推理模型的表現。)
    • 對於延後載入的工具,請在函式說明中提供詳細指引,並讓命名空間說明保持簡潔。 命名空間協助模型選擇要載入的工具,函式說明則協助模型正確使用已載入的工具。
  2. 採用軟體工程的最佳做法。

    • 讓函式直覺易用,行為符合預期。(最小驚訝原則)
    • 使用列舉和物件結構來排除無效狀態。例如,toggle_light(on: bool, off: bool) 允許呼叫者傳入互相矛盾的值。
    • 請實習生試用。 實習生或其他人只看你提供給模型的資訊,就能正確使用函式嗎?(如果不能,他們會問哪些問題?請把答案加入提示詞。)
  3. 盡可能用程式碼處理,減輕模型的負擔。

    • 已知的引數不必讓模型填寫。 例如,如果你已經從先前的選單取得 order_id,就不必提供 order_id 參數。可以定義不帶參數的 submit_refund(),並在程式碼中傳入 order_id。
    • 合併一律依序呼叫的函式。 例如,如果 mark_location() 一律在 query_location() 之後呼叫,就把標記位置的邏輯移到查詢函式內。
  4. 減少一開始可用的函式數量,以提高準確度。

    • 評估實際表現,比較提供不同數量的函式時有何差異。
    • 每回合開始時,盡量讓可用函式少於 20 個,這只是建議,並非硬性限制。
    • 使用工具搜尋,延後載入數量龐大或不常用的那部分工具,避免一開始就提供所有工具。
  5. 善用 OpenAI 資源。

    • 產生並反覆調整函式結構描述,這些操作都可以在 Playground 中進行。
    • 考慮透過微調提高函式呼叫的準確度,尤其是在函式眾多或任務困難的情況下。(實作範例)

Token 用量

系統會使用模型在訓練期間學過的語法,將函式定義加入系統訊息。因此,可呼叫函式的定義會占用模型的上下文空間,並按輸入 Token 計費。如果遇到 Token 數量限制,建議減少一開始載入的函式數量、盡可能縮短說明,或使用工具搜尋,讓延後載入的工具在需要時才載入。

如果工具規格中定義了許多函式,也可以使用微調來減少 Token 用量。

處理函式呼叫

模型呼叫函式時,你必須執行函式並傳回結果。模型的回應可能包含零個、一個或多個呼叫,因此建議一律按照可能有多個呼叫的情況來處理。

回應的 output 陣列中會有 type 值為 function_call 的項目。每個這類項目都包含 call_id(稍後用於提交函式結果)、name 和以 JSON 編碼的 arguments。

包含多個函式呼叫的回應範例
[
    {
        "id": "fc_12345xyz",
        "call_id": "call_12345xyz",
        "type": "function_call",
        "name": "get_weather",
        "arguments": "{\"location\":\"Paris, France\"}"
    },
    {
        "id": "fc_67890abc",
        "call_id": "call_67890abc",
        "type": "function_call",
        "name": "get_weather",
        "arguments": "{\"location\":\"Bogotá, Colombia\"}"
    },
    {
        "id": "fc_99999def",
        "call_id": "call_99999def",
        "type": "function_call",
        "name": "send_email",
        "arguments": "{\"to\":\"bob@email.com\",\"body\":\"Hi bob\"}"
    }
]

如果使用工具搜尋,你可能還會看到 tool_search_call 和 tool_search_output 項目出現在 function_call 之前。函式載入後,即可用這裡示範的方式處理函式呼叫。

執行函式呼叫並附加結果
input_messages += response.output

for tool_call in response.output:
    if tool_call.type != "function_call":
        continue

    name = tool_call.name
    args = json.loads(tool_call.arguments)

    result = call_function(name, args)
    input_messages.append(
        {
            "type": "function_call_output",
            "call_id": tool_call.call_id,
            "output": json.dumps(result),
        }
    )

上述範例假設有一個 call_function 函式,負責將各個呼叫分派給對應的函式。以下是其中一種實作方式:

執行函式呼叫並附加結果
def call_function(name, args):
    if name == "get_weather":
        return get_weather(**args)
    if name == "send_email":
        return send_email(**args)
    raise ValueError(f"Unknown function: {name}")

設定結果格式

在 function_call_output 訊息中傳入的結果通常應為字串。你可以自行決定字串格式,例如 JSON、錯誤碼或純文字。模型會視需要解讀字串內容。

如果函式傳回圖片或檔案,可以傳入圖片或檔案物件的陣列來取代字串。

如果函式沒有回傳值(例如 send_email),請傳回表示成功或失敗的字串,例如 "success"。

讓模型根據結果產生回應

將結果附加到 input 後,就可以將這些輸入傳回給模型,取得最終回應。

將結果傳回給模型
response = client.responses.create(
    model="gpt-6-astra",
    input=input_messages,
    tools=responses_tools,
)
最終回應
"It's about 15°C in Paris, 18°C in Bogotá, and I've sent that email to Bob."

其他設定

選擇工具

依預設,模型會自行決定何時使用工具,以及使用幾個工具。你可以透過 tool_choice 參數強制採用特定行為。

  1. 自動:(預設)呼叫零個、一個或多個函式。tool_choice: "auto"
  2. 必要: 呼叫至少一個函式。 tool_choice: "required"
  3. 強制呼叫指定函式: 只呼叫指定的函式一次。 tool_choice: {"type": "function", "name": "get_weather"}
  4. 允許的工具: 限制模型只能呼叫可用工具中的某個子集。

何時使用 allowed_tools

如果希望在不同的模型請求中只開放部分工具,又想維持傳入的工具清單不變,可以設定 allowed_tools 清單,充分利用提示詞快取來節省費用。

"tool_choice": {
    "type": "allowed_tools",
    "mode": "auto",
    "tools": [
        { "type": "function", "name": "get_weather" },
        { "type": "function", "name": "search_docs" }
    ]
  }
}

你也可以將 tool_choice 設為 "none",讓模型的行為與未傳入任何函式時相同。

使用工具搜尋時,tool_choice 仍適用於該回合目前可呼叫的工具。當你已載入部分工具,並希望限制模型只能使用這些工具時,這項設定特別有用。

平行呼叫函式

從 GPT-5 起,在支援這項功能的模型上,即使同時提供內建工具,也可以平行呼叫函式。但同一批平行執行的函式呼叫中不能包含內建工具。

模型可能會在同一回合呼叫多個函式。若要避免這種情況,可以將 parallel_tool_calls 設為 false,確保每回合最多只有一次工具呼叫。

注意: 目前,如果使用經過微調的模型,且模型在同一回合呼叫多個函式,這些呼叫的嚴格模式就會停用。

關於 gpt-4.1-nano-2025-04-14 的注意事項: 啟用平行工具呼叫時,這個 gpt-4.1-nano 快照有時會對同一個工具發出多個呼叫。使用這個快照時,建議停用此功能。

嚴格模式

將 strict 設為 true,即可確保函式呼叫確實符合函式的結構描述,而非僅盡可能符合。建議一律啟用嚴格模式。

嚴格模式透過結構化輸出功能運作,因此有以下兩項要求:

  1. additionalProperties 必須設為 false,且 parameters 中的每個物件都要設定。
  2. properties 中的所有欄位都必須標示為 required。

如果欄位是選填的,可以加入 null 作為 type 選項(請參閱下方範例)。

如果傳送 strict: true,但結構描述不符合上述要求,API 會拒絕請求,並詳細說明缺少哪些限制條件。如果省略 strict,預設行為會因 API 而異。Responses 會盡可能將請求中的結構描述調整為符合嚴格模式的格式。如果無法調整為相容格式,就會改用非嚴格模式,盡可能讓函式呼叫符合結構描述。此時,回應中的工具會顯示 strict: false。Chat Completions 請求預設仍使用非嚴格模式。如果希望 Responses 直接使用非嚴格模式,讓函式呼叫盡可能符合結構描述,請明確設定 strict: false。

{
    "type": "function",
    "name": "get_weather",
    "description": "Retrieves current weather for the given location.",
    "strict": true,
    "parameters": {
        "type": "object",
        "properties": {
            "location": {
                "type": "string",
                "description": "City and country e.g. Bogotá, Colombia"
            },
            "units": {
                "type": ["string", "null"],
                "enum": ["celsius", "fahrenheit"],
                "description": "Units the temperature will be returned in."
            }
        },
        "required": ["location", "units"],
        "additionalProperties": false
    }
}

在 Playground 中產生的所有結構描述都已啟用嚴格模式。

我們建議啟用嚴格模式,但使用時有以下限制:

  1. 嚴格模式僅支援部分 JSON 結構描述功能。(請參閱支援的結構描述。)

使用經過微調的模型時,還有以下限制:

  1. 首次請求時,系統會對結構描述進行額外處理,然後加以快取。如果每次請求的結構描述都不同,延遲可能會增加。
  2. 為了提升效能,系統會快取結構描述,因此結構描述不適用於零資料保留。

串流

透過串流,可以在模型填入引數時顯示它正在呼叫哪個函式,甚至即時顯示引數內容,讓使用者掌握進度。

串流函式呼叫的方式與串流一般回應相同:將 stream 設為 true,即可接收不同的 event 物件。

串流函式呼叫
from openai import OpenAI

client = OpenAI()

tools = [
    {
        "type": "function",
        "name": "get_weather",
        "strict": True,
        "description": "Get current temperature for a given location.",
        "parameters": {
            "type": "object",
            "properties": {
                "location": {
                    "type": "string",
                    "description": "City and country e.g. Bogotá, Colombia",
                }
            },
            "required": ["location"],
            "additionalProperties": False,
        },
    }
]

stream = client.responses.create(
    model="gpt-6-astra",
    input=[{"role": "user", "content": "What's the weather like in Paris today?"}],
    tools=tools,
    stream=True,
)

for event in stream:
    print(event)
輸出事件
{"type":"response.output_item.added","response_id":"resp_1234xyz","output_index":0,"item":{"type":"function_call","id":"fc_1234xyz","call_id":"call_1234xyz","name":"get_weather","arguments":""}}
{"type":"response.function_call_arguments.delta","response_id":"resp_1234xyz","item_id":"fc_1234xyz","output_index":0,"delta":"{\""}
{"type":"response.function_call_arguments.delta","response_id":"resp_1234xyz","item_id":"fc_1234xyz","output_index":0,"delta":"location"}
{"type":"response.function_call_arguments.delta","response_id":"resp_1234xyz","item_id":"fc_1234xyz","output_index":0,"delta":"\":\""}
{"type":"response.function_call_arguments.delta","response_id":"resp_1234xyz","item_id":"fc_1234xyz","output_index":0,"delta":"Paris"}
{"type":"response.function_call_arguments.delta","response_id":"resp_1234xyz","item_id":"fc_1234xyz","output_index":0,"delta":","}
{"type":"response.function_call_arguments.delta","response_id":"resp_1234xyz","item_id":"fc_1234xyz","output_index":0,"delta":" France"}
{"type":"response.function_call_arguments.delta","response_id":"resp_1234xyz","item_id":"fc_1234xyz","output_index":0,"delta":"\"}"}
{"type":"response.function_call_arguments.done","response_id":"resp_1234xyz","item_id":"fc_1234xyz","output_index":0,"arguments":"{\"location\":\"Paris, France\"}"}
{"type":"response.output_item.done","response_id":"resp_1234xyz","output_index":0,"item":{"type":"function_call","id":"fc_1234xyz","call_id":"call_1234xyz","name":"get_weather","arguments":"{\"location\":\"Paris, France\"}"}}

處理一般回應時,你會將片段合併成單一 content 字串。處理函式呼叫時,則要將片段合併成以 JSON 編碼的 arguments 物件。

模型呼叫一個或多個函式時,系統會針對每個函式呼叫發出一個 response.output_item.added 事件,其中包含下列欄位:

欄位 說明
response_id 函式呼叫所屬回應的 ID
output_index 輸出項目在回應中的索引,用來區分回應中的各個函式呼叫。
item 進行中的函式呼叫項目,包含 name、arguments 和 id 欄位

接著,你會收到一連串 response.function_call_arguments.delta 事件,其中的 delta 是 arguments 欄位的增量資料。這些事件包含下列欄位:

欄位 說明
response_id 函式呼叫所屬回應的 ID
item_id 增量資料所屬函式呼叫項目的 ID
output_index 輸出項目在回應中的索引,用來區分回應中的各個函式呼叫。
delta arguments 欄位的增量資料。

以下程式碼片段示範如何將各個 delta 合併成最終的 tool_call 物件。

累積 tool_call 的增量資料
final_tool_calls = {}

for event in stream:
    if (
        event.type == "response.output_item.added"
        and event.item.type == "function_call"
    ):
        final_tool_calls[event.output_index] = event.item
    elif event.type == "response.function_call_arguments.delta":
        index = event.output_index

        if final_tool_calls[index]:
            final_tool_calls[index].arguments += event.delta
累積後的 final_tool_calls[0]
{
    "type": "function_call",
    "id": "fc_1234xyz",
    "call_id": "call_2345abc",
    "name": "get_weather",
    "arguments": "{\"location\":\"Paris, France\"}"
}

模型完成函式呼叫後,系統會發出 response.function_call_arguments.done 事件。此事件包含完整的函式呼叫,其中有下列欄位:

欄位 說明
response_id 函式呼叫所屬回應的 ID
output_index 輸出項目在回應中的索引,用來區分回應中的各個函式呼叫。
item 函式呼叫項目,包含 name、arguments 和 id 欄位。

自訂工具

自訂工具的運作方式與使用 JSON 結構描述的函式工具大致相同。差別在於,你不必明確指定工具需要哪些輸入,模型可以直接將任意字串傳給工具作為輸入。這樣就不必將回應額外包裝成 JSON,也可以為回應套用自訂文法(詳見下文)。

以下程式碼範例示範如何建立自訂工具,讓工具接收模型傳回的文字字串,其中包含 Python 程式碼。

自訂工具呼叫範例
from openai import OpenAI

client = OpenAI()

response = client.responses.create(
    model="gpt-6-astra",
    input="Use the code_exec tool to print hello world to the console.",
    tools=[
        {
            "type": "custom",
            "name": "code_exec",
            "description": "Executes arbitrary Python code.",
        }
    ],
)
print(response.output)

和先前一樣,output 陣列會包含模型產生的工具呼叫,不過這次工具呼叫的輸入是純文字。

[
  {
    "id": "rs_6890e972fa7c819ca8bc561526b989170694874912ae0ea6",
    "type": "reasoning",
    "content": [],
    "summary": []
  },
  {
    "id": "ctc_6890e975e86c819c9338825b3e1994810694874912ae0ea6",
    "type": "custom_tool_call",
    "status": "completed",
    "call_id": "call_aGiFQkRWSWAIsMQ19fKqxUgb",
    "input": "print(\"hello world\")",
    "name": "code_exec"
  }
]

上下文無關文法

上下文無關文法(CFG)是一組規則,用來定義如何產生符合指定格式的有效文字。你可以為自訂工具提供 CFG,以限制模型傳給工具的文字輸入。

設定自訂工具時,可以透過 grammar 參數提供自訂 CFG。目前支援兩種定義 CFG 的語法:lark 和 regex。

Lark CFG

Lark 上下文無關文法範例
from openai import OpenAI

client = OpenAI()

grammar = """
start: expr
expr: term (SP ADD SP term)* -> add
| term
term: factor (SP MUL SP factor)* -> mul
| factor
factor: INT
SP: " "
ADD: "+"
MUL: "*"
%import common.INT
"""

response = client.responses.create(
    model="gpt-6-astra",
    input="Use the math_exp tool to add four plus four.",
    tools=[
        {
            "type": "custom",
            "name": "math_exp",
            "description": "Creates valid mathematical expressions",
            "format": {
                "type": "grammar",
                "syntax": "lark",
                "definition": grammar,
            },
        }
    ],
)
print(response.output)

工具的輸出應符合你定義的 Lark CFG:

[
  {
    "id": "rs_6890ed2b6374819dbbff5353e6664ef103f4db9848be4829",
    "type": "reasoning",
    "content": [],
    "summary": []
  },
  {
    "id": "ctc_6890ed2f32e8819daa62bef772b8c15503f4db9848be4829",
    "type": "custom_tool_call",
    "status": "completed",
    "call_id": "call_pmlLjmvG33KJdyVdC4MVdk5N",
    "input": "4 + 4",
    "name": "math_exp"
  }
]

文法使用 Lark 的變體來定義,並透過 LLGuidance 限制模型取樣。目前不支援下列 Lark 功能:

  • 詞法分析器正規表示式中的前後查看斷言
  • 詞法分析器正規表示式中的非貪婪修飾符(*?、+?、??)
  • 終結符號的優先順序
  • 範本
  • 匯入(以內建 %import 匯入 common 的情況除外)
  • %declare 宣告

建議使用 Lark IDE 試驗自訂文法。

限制文法複雜度

文法應只包含工具所需的規則和模式。如果文法過於複雜,OpenAI API 可能會傳回錯誤,因此請先確認所需文法與 API 相容,再正式使用。

Lark 文法有時很難調整到理想狀態。簡單的文法通常最可靠。使用複雜文法時,往往需要反覆調整文法定義、提示詞和工具說明,以免模型產生偏離訓練分布的輸出。

正確與錯誤的模式

正確做法(使用單一、有明確邊界的終結符號):

start: SENTENCE
SENTENCE: /[A-Za-z, ]*(the hero|a dragon|an old man|the princess)[A-Za-z, ]*(fought|saved|found|lost)[A-Za-z, ]*(a treasure|the kingdom|a secret|his way)[A-Za-z, ]*\./

請勿採用以下做法(拆成多個規則或終結符號)。這種寫法試圖讓規則切分終結符號之間的自由文字,但詞法分析器會以貪婪方式比對自由文字片段,導致你無法控制切分位置:

start: sentence
sentence: /[A-Za-z, ]+/ subject /[A-Za-z, ]+/ verb /[A-Za-z, ]+/ object /[A-Za-z, ]+/

只有終結符號的定義能決定如何從輸入中切出終結符號,以小寫命名的規則無法影響這個過程。如果需要比對「錨點之間的自由文字」,請將整個模式寫成一個正規表示式終結符號,讓詞法分析器按照預期結構一次完成比對。

終結符號與規則的差異

Lark 使用終結符號來定義詞法分析器的詞法單元(名稱慣例為 UPPERCASE),使用規則來定義語法分析器的產生式(名稱慣例為 lowercase)。若要確保文法只使用支援的功能,並避免意外結果,最實際的做法是寫出明確的文法,避免不必要的複雜度,並清楚區分終結符號和規則各自負責的工作。

終結符號使用 Rust regex 套件的語法,與 Python 的 re 模組不同。

重要概念與最佳做法

詞法分析先於語法分析

在套用任何 CFG 規則之前,詞法分析器就會先以貪婪方式比對終結符號,取最長的相符片段。如果試圖將一個終結符號拆到多個規則中,藉此控制比對範圍,這些規則並不會引導詞法分析器。它只依據終結符號的正規表示式進行比對。

從自由格式文字擷取片段時,優先使用單一終結符號

如果需要辨識任意文字中的某個模式(例如自然語言中,錨點之間可以出現「任何內容」),請將整個模式寫成單一終結符號。請勿交錯使用自由文字終結符號和語法分析規則。採用貪婪比對的詞法分析器不會遵循你預期的邊界,模型也很可能產生偏離訓練分布的輸出。

使用規則組合個別詞法單元

如果要將邊界明確的終結符號(例如數字、關鍵字和標點符號)組合成較大的結構,規則最適合這項工作。但規則不適合用來限制兩個終結符號「中間的內容」。

讓終結符號用途明確、範圍有限且定義完整

優先使用明確的字元類別和有上限的量詞(例如 {0,10},避免到處使用沒有上限的 *)。如果需要比對「直到句點為止的任意文字」,建議採用類似 /[^.\n]{0,10}*\./ 的寫法,避免使用 /.+\./,以免比對範圍無限擴張。

用規則組合詞法單元,避免用規則控制正規表示式內部的比對方式

適當使用規則的範例:

start: expr
NUMBER: /[0-9]+/
PLUS: "+"
MINUS: "-"
expr: term (("+"|"-") term)*
term: NUMBER

明確處理空白字元

請勿依賴沒有長度上限的 %ignore 指令。忽略範圍沒有上限,可能導致文法過於複雜、模型產生偏離訓練分布的輸出,或兩種情況同時發生。建議在每個允許空白字元的位置明確加入對應的終結符號。

疑難排解

  • 如果 API 因文法過於複雜而拒絕接受,請簡化規則與終結符號,並移除沒有上限的 %ignore 指令。
  • 如果自訂工具收到非預期的詞法單元,請確認終結符號的比對範圍沒有重疊,並檢查詞法分析器的貪婪比對行為。
  • 如果模型的輸出「偏離訓練分布」(表現為輸出過長或內容反覆,語法正確但語意錯誤):
    • 收緊文法限制。
    • 反覆調整提示詞(加入少樣本範例)和工具說明(解釋文法,並指示模型進行推理、遵循文法)。
    • 試著提高推理強度(例如從「中」調至「高」)。

正規表示式 CFG

正規表示式上下文無關文法範例
from openai import OpenAI

client = OpenAI()

grammar = r"^(?P<month>January|February|March|April|May|June|July|August|September|October|November|December)\s+(?P<day>\d{1,2})(?:st|nd|rd|th)?\s+(?P<year>\d{4})\s+at\s+(?P<hour>0?[1-9]|1[0-2])(?P<ampm>AM|PM)$"

response = client.responses.create(
    model="gpt-6-astra",
    input="Use the timestamp tool to save a timestamp for August 7th 2025 at 10AM.",
    tools=[
        {
            "type": "custom",
            "name": "timestamp",
            "description": "Saves a timestamp in date + time in 24-hr format.",
            "format": {
                "type": "grammar",
                "syntax": "regex",
                "definition": grammar,
            },
        }
    ],
)
print(response.output)

工具的輸出應符合你定義的正規表示式 CFG:

[
  {
    "id": "rs_6894f7a3dd4c81a1823a723a00bfa8710d7962f622d1c260",
    "type": "reasoning",
    "content": [],
    "summary": []
  },
  {
    "id": "ctc_6894f7ad7fb881a1bffa1f377393b1a40d7962f622d1c260",
    "type": "custom_tool_call",
    "status": "completed",
    "call_id": "call_8m4XCnYvEmFlzHgDHbaOCFlK",
    "input": "August 7th 2025 at 10AM",
    "name": "timestamp"
  }
]

與 Lark 語法一樣,正規表示式使用 Rust regex 套件的語法,與 Python 的 re 模組不同。

目前不支援下列正規表示式功能:

  • 前後查看斷言
  • 非貪婪修飾符(*?、+?、??)

重要概念與最佳做法

模式必須寫在同一行

如果需要比對輸入中的換行字元,請使用跳脫序列 \n。請勿使用允許模式跨行撰寫的詳細或延伸模式。

直接以字串提供正規表示式模式

請勿將模式括在 // 中。