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

非同步工具呼叫

讓模型在應用程式於背景執行工具時繼續工作。

非同步工具呼叫讓模型在呼叫工具後繼續工作,無須等待工具回傳結果。你可以用這種方式提早發出耗時的查詢,讓模型先回答請求中不依賴查詢結果的部分,等應用程式取得結果後再回傳。

非同步工具的運作方式

一般的函式呼叫會讓模型暫停目前的回合,等待工具回應。在函式或自訂工具的定義中設定 async: true,模型就能在發出呼叫後繼續工作,無須等應用程式回傳輸出。

工具仍由你的應用程式執行。使用非同步工具不會將工具交由 OpenAI 執行,也不會代你管理背景作業。

背景模式會以非同步方式產生回應。非同步工具呼叫則讓模型在應用程式執行工具的同時繼續工作。

作業完成後,在後續的 Responses 請求中加入該作業的輸出。使用原始 API 呼叫的 call_id 將結果對應到該次呼叫:

工具類型 呼叫項目 輸出項目
函式 function_call function_call_output
自訂 custom_tool_call custom_tool_call_output

呼叫非同步工具

在工具定義中加入 async: true。response.output 中對應的呼叫項目會包含 async: true。

在背景查詢天氣
import json
from concurrent.futures import ThreadPoolExecutor

from openai import OpenAI
from openai.types.responses import FunctionToolParam


def get_weather(city):
    # Demo data. Replace this function with your weather service.
    weather = {
        "Paris": {
            "city": "Paris",
            "temperature_c": 22,
            "condition": "Clear",
            "source": "demo weather snapshot",
        }
    }
    return weather[city]


worker = ThreadPoolExecutor()


def main():
    client = OpenAI()
    model = "gpt-6-astra"
    tools: list[FunctionToolParam] = [
        {
            "type": "function",
            "name": "get_weather",
            "description": "Read the demo weather snapshot for a city.",
            "async": True,
            "strict": True,
            "parameters": {
                "type": "object",
                "properties": {"city": {"type": "string"}},
                "required": ["city"],
                "additionalProperties": False,
            },
        },
    ]

    instructions = (
        "Start the weather lookup and answer the independent packing "
        "question without waiting. Use the actual tool result when it "
        "arrives; never invent it. Identify the weather as demo data."
    )
    response = client.responses.create(
        model=model,
        tools=tools,
        instructions=instructions,
        input=(
            "Check the demo weather in Paris. Meanwhile, "
            "list three essentials for any city trip."
        ),
    )

    call = next(item for item in response.output if item.type == "function_call")
    arguments = json.loads(call.arguments)
    if call.name != "get_weather" or arguments != {"city": "Paris"}:
        raise ValueError("Expected a weather lookup for Paris")

    latest_response_id = response.id
    if call.async_:
        job = worker.submit(get_weather, **arguments)
        print(response.output_text)
        # Independent work or conversation turns can happen here.
        # Update latest_response_id after each continuation.
        result = job.result()
    else:
        result = get_weather(**arguments)

    response = client.responses.create(
        model=model,
        tools=tools,
        instructions=instructions,
        previous_response_id=latest_response_id,
        input=[
            {
                "type": "function_call_output",
                "call_id": call.call_id,
                "output": json.dumps(result),
            },
        ],
    )
    print(response.output_text)


if __name__ == "__main__":
    try:
        main()
    finally:
        worker.shutdown(wait=True)

同一則回應可以同時包含非同步呼叫和答案。如果作業完成前對話又進行了其他回合,請更新 latest_response_id,以便從最新的回應接續對話,同時保留原始工具呼叫的 call_id。

如果使用串流,收到完整的呼叫項目時就可以啟動作業,同時繼續讀取回應的後續內容。

新增等待工具

等待工具讓模型自行決定何時需要尚未回傳的結果。例如,模型可以發出兩個價格查詢請求,先處理不依賴這些結果的工作,等到準備比較價格時再等待結果。

為每個非同步工具新增 task_handle 引數。模型會為每次呼叫指定一個任務識別碼,再由應用程式將該識別碼與原始 API 呼叫的 call_id 和執行中的作業建立關聯。整段對話中的任務識別碼都必須唯一。即使任務已完成,或再次發出相同的查詢,也不能重複使用識別碼。

將等待工具定義為一般的同步函式:省略 async,或將其設為 false。這個工具的結構描述和行為由你的應用程式定義。wait_for_tasks 並非 Responses 的內建工具。

在請求的 tools 陣列中加入以下定義:

[
  {
    "type": "function",
    "name": "lookup_price",
    "async": true,
    "description": "Look up a product price in the background. Choose a fresh task_handle unique within this conversation, including completed tasks.",
    "strict": true,
    "parameters": {
      "type": "object",
      "properties": {
        "sku": { "type": "string" },
        "task_handle": { "type": "string" }
      },
      "required": ["sku", "task_handle"],
      "additionalProperties": false
    }
  },
  {
    "type": "function",
    "name": "wait_for_tasks",
    "description": "Wait for selected tasks whose results you need. Pass a nonempty list of distinct task_handles from your earlier async tool calls. Results arrive on their original calls; this tool returns status only. Do not wait again for results that have already arrived.",
    "strict": true,
    "parameters": {
      "type": "object",
      "properties": {
        "task_handles": {
          "type": "array",
          "items": { "type": "string" }
        }
      },
      "required": ["task_handles"],
      "additionalProperties": false
    }
  }
]

登錄每個作業

先登錄並啟動每個作業,再處理需要等待這些作業的呼叫。這些呼叫可能出現在同一則回應,也可能分散在多則回應中。以下輸出項目示範兩次啟動作業的呼叫,以及一次等待這兩個作業的呼叫:

[
  {
    "type": "function_call",
    "name": "lookup_price",
    "async": true,
    "call_id": "call_widget",
    "arguments": "{\"sku\":\"WIDGET\",\"task_handle\":\"widget_price_1\"}"
  },
  {
    "type": "function_call",
    "name": "lookup_price",
    "async": true,
    "call_id": "call_gadget",
    "arguments": "{\"sku\":\"GADGET\",\"task_handle\":\"gadget_price_1\"}"
  },
  {
    "type": "function_call",
    "name": "wait_for_tasks",
    "call_id": "call_wait",
    "arguments": "{\"task_handles\":[\"widget_price_1\",\"gadget_price_1\"]}"
  }
]

應用程式的登錄表會記錄每個任務識別碼所對應的原始呼叫和執行中的作業:

任務識別碼 原始呼叫 ID 作業
widget_price_1 call_widget 查詢 WIDGET 的價格
gadget_price_1 call_gadget 查詢 GADGET 的價格

在整段對話期間保留登錄表,以免重複使用已完成任務的識別碼。

先回傳結果,再回傳等待狀態

在登錄表中找出指定的任務識別碼,只等待這些識別碼對應的作業。使用各作業原始呼叫的 call_id 回傳剛完成的作業結果,再使用等待呼叫本身的 call_id 回傳狀態。依照這個順序,模型恢復工作時就能取得結果。

例如,在下一個請求的 input 陣列中傳送以下輸出項目。價格僅供示範:

[
  {
    "type": "function_call_output",
    "call_id": "call_widget",
    "output": "{\"task_handle\":\"widget_price_1\",\"price_cents\":1200,\"currency\":\"USD\"}"
  },
  {
    "type": "function_call_output",
    "call_id": "call_gadget",
    "output": "{\"task_handle\":\"gadget_price_1\",\"price_cents\":1500,\"currency\":\"USD\"}"
  },
  {
    "type": "function_call_output",
    "call_id": "call_wait",
    "output": "{\"status\":\"completed\",\"completed_task_handles\":[\"widget_price_1\",\"gadget_price_1\"]}"
  }
]

將 previous_response_id 設為最新回應的 ID,並在接續對話的請求中包含工具和指令。應用程式也可以在取得各項結果時立即回傳,無須等待模型呼叫等待工具。只有當模型的下一步需要尚未收到的結果時,才使用等待工具。

新增向使用者提問的工具

非同步工具可以向使用者提問,同時讓模型繼續處理不依賴答案的工作。例如,模型可以先詢問報告的讀者是誰,在使用者作答期間蒐集資料,再根據答案調整報告內容。

定義一個設有 async: true 的函式,用來向使用者詢問缺少的資訊或個人偏好。應用程式負責顯示問題、收集答覆,並將答覆作為工具結果回傳。這個工具的結構描述和行為由你的應用程式定義。request_user_input_async 並非 Responses 的內建工具。

將以下定義加入請求的 tools 陣列,與 wait_for_tasks 一併提供:

{
  "type": "function",
  "name": "request_user_input_async",
  "async": true,
  "description": "Ask the user for missing information or a preference. Choose a fresh task_handle unique within this conversation, including completed tasks. Continue independent work while the answer is pending. Use wait_for_tasks when your next step depends on the answer.",
  "strict": true,
  "parameters": {
    "type": "object",
    "properties": {
      "question": { "type": "string" },
      "task_handle": { "type": "string" }
    },
    "required": ["question", "task_handle"],
    "additionalProperties": false
  }
}

顯示問題

收到完整的呼叫項目後,先登錄問題的 task_handle 和原始 call_id,再向使用者顯示問題。以下輸出項目示範如何詢問報告的讀者是誰:

{
  "type": "function_call",
  "name": "request_user_input_async",
  "async": true,
  "call_id": "call_audience",
  "arguments": "{\"question\":\"Who is the report for: executives or engineers?\",\"task_handle\":\"report_audience_1\"}"
}

在等待工具使用的同一份登錄表中,將問題維持在待答狀態。在使用者作答期間,繼續讀取模型的回應。請勿以「已顯示問題」作為完成工具呼叫的回覆,這次呼叫的結果應是使用者的答案。

回傳使用者的答案

收到使用者的答覆後,使用問題原始呼叫的 call_id 回傳答案。例如,在下一個請求的 input 陣列中加入以下輸出項目:

[
  {
    "type": "function_call_output",
    "call_id": "call_audience",
    "output": "{\"task_handle\":\"report_audience_1\",\"answer\":\"Executives\"}"
  }
]

將 previous_response_id 設為最新回應的 ID,並在接續對話的請求中包含工具和指令。如果模型呼叫了 wait_for_tasks 來等待 report_audience_1,請先回傳答案,再回傳等待狀態,如等待工具範例所示。

非同步執行不會讓回應一直保持開啟,直到使用者答覆。請指示模型繼續處理不依賴答案的工作,等到下一步需要答案時再等待。如果應用程式允許使用者關閉問題,或設有作答時限,請在問題遭關閉或逾時時回傳明確表示未獲答覆的結果,讓模型決定接下來如何處理。

相容性

GPT-6 Astra 及後續模型支援非同步工具呼叫。

非同步執行適用於由你的應用程式執行的函式工具和自訂工具,不適用於代管的內建工具。請直接呼叫工具,勿將非同步工具設定為透過程式化工具呼叫執行。

在多智慧體模式中,請勿搭配使用非同步工具與平行工具呼叫。