codecamp

OpenAI 异步工具调用

异步工具调用允许模型发出工具调用后继续工作,不必等待结果。它适合提前发起较慢的查询、先回答请求中互不依赖的部分,再在应用取得结果时补充回答。

异步工具如何工作

普通函数调用会暂停模型当前轮次,等待工具响应。在函数工具或自定义工具定义中设置 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。

以下示例在应用后台查询演示天气。指令要求:先启动天气查询,同时回答独立的行李问题;实际结果到达后再使用,不能编造,并说明天气是演示数据。用户请求为“查询巴黎的演示天气,同时列出城市旅行的三件必需品”。各语言保留其原始英文字符串。

来源示例1(javascript)

程序中的自然语言译释102:

不等待天气查询完成,先处理独立问题;演示天气结果到达后再使用,不得编造。这个JavaScript指令没有额外要求明确标注演示数据,不能把其他语言的该要求算入此段。

程序中的自然语言译释110:

读取某城市的演示天气快照。

程序中的自然语言译释111:

查询巴黎的演示天气,同时处理独立的旅行必需品问题。

// [中文] 将get_weather声明为异步工具;应用启动演示天气任务,再用原call_id返回结果。
import OpenAI from "openai";

const client = new OpenAI();
const model = "gpt-6-astra";

const tools = [
  {
    type: "function",
    name: "get_weather",
    description: "Read a demo weather snapshot for a city.",
    async: true,
    strict: true,
    parameters: {
      type: "object",
      properties: { city: { type: "string" } },
      required: ["city"],
      additionalProperties: false,
    },
  },
];
async function getWeather(city) {
  const snapshots = {
    Paris: {
      city: "Paris",
      temperature_c: 22,
      condition: "Clear",
      source: "demo weather snapshot",
    },
  };
  if (typeof city !== "string" || !Object.hasOwn(snapshots, city)) {
    throw new Error(`No demo weather snapshot for ${city}.`);
  }
  return snapshots[city];
}
const instructions =
  "Start the weather lookup and answer the independent packing question " +
  "without waiting. Use the demo weather result when it arrives; never invent it.";

let response = await client.responses.create({
  model,
  tools,
  instructions,
  input:
    "Check the demo weather snapshot for Paris. Meanwhile, " +
    "list three essentials for any city trip.",
});

const call = response.output.find((item) => item.type === "function_call");
if (!call || call.name !== "get_weather") {
  throw new Error("The response did not include a weather call.");
}
const { city } = JSON.parse(call.arguments);
let latestResponseId = response.id;

// [中文] 调用异步函数会立即启动应用侧任务。
// 调用异步函数会立即启动应用中的任务。
const job = getWeather(city).catch((error) => ({ error: error.message }));
if (!call.async) {
  // [中文] 普通同步调用须先完成,模型才能继续。
  // 普通同步调用必须完成后,模型才能继续。
  await job;
}
console.log(response.output);
// [中文] 这里可以处理互不依赖的工作或其他会话轮次。
// 可以在此处执行独立工作或进行其他对话轮次。
// [中文] 每次续接后更新latestResponseId。
// 每次继续请求后更新 latestResponseId。
const result = await job;
response = await client.responses.create({
  model,
  tools,
  instructions,
  previous_response_id: latestResponseId,
  input: [
    {
      type: "function_call_output",
      call_id: call.call_id,
      output: JSON.stringify(result),
    },
  ],
});
latestResponseId = response.id;
console.log(response.output);

来源示例2(python)

程序中的自然语言译释0:

启动天气查询,不必等待,先回答独立的行李问题。实际工具结果到达后再使用,绝不编造;明确天气是演示数据。

程序中的自然语言译释1:

读取某城市的演示天气快照。

程序中的自然语言译释2:

查询巴黎的演示天气;同时列出任意城市旅行的三件必需品。

程序中的自然语言译释3:

预期收到查询巴黎天气的调用。

## [中文] 将get_weather声明为异步工具;应用启动演示天气任务,再用原call_id返回结果。
import json
from concurrent.futures import ThreadPoolExecutor

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


def get_weather(city):
    # [中文] 这里是演示数据,应替换为自己的天气服务。
    # 此处为演示数据,请换成自己的天气服务。
    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)
        # [中文] 这里可以处理互不依赖的工作或其他会话轮次。
        # 可以在此处执行独立工作或进行其他对话轮次。
        # [中文] 每次续接后更新latest_response_id。
        # 每次继续请求后更新 latest_response_id。
        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)

来源示例3(go)

本段复用的中文释义:译释0、译释1、译释2。

// [中文] 将get_weather声明为异步工具;应用启动演示天气任务,再用原call_id返回结果。
package main

import (
    "context"
    "encoding/json"
    "fmt"

    "github.com/openai/openai-go/v3"
    "github.com/openai/openai-go/v3/responses"
)

type weatherArguments struct {
    City string `json:"city"`
}

type weatherSnapshot struct {
    City         string `json:"city"`
    TemperatureC int    `json:"temperature_c"`
    Condition    string `json:"condition"`
    Source       string `json:"source"`
}

func getWeather(city string) weatherSnapshot {
    // [中文] 这里是演示数据,应替换为自己的天气服务。
    // 此处为演示数据,请换成自己的天气服务。
    if city != "Paris" {
        panic("No demo weather snapshot for " + city)
    }
    return weatherSnapshot{
        City: city, TemperatureC: 22, Condition: "Clear", Source: "demo weather snapshot",
    }
}

func main() {
    client := openai.NewClient()
    ctx := context.Background()
    tool := responses.ToolParamOfFunction("get_weather", map[string]any{
        "type":                 "object",
        "properties":           map[string]any{"city": map[string]string{"type": "string"}},
        "required":             []string{"city"},
        "additionalProperties": false,
    }, true)
    tool.OfFunction.Description = openai.String("Read the demo weather snapshot for a city.")
    tool.OfFunction.Async = openai.Bool(true)
    tools := []responses.ToolUnionParam{tool}
    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, err := client.Responses.New(ctx, responses.ResponseNewParams{
        Model:        "gpt-6-astra",
        Tools:        tools,
        Instructions: openai.String(instructions),
        Input:        responses.ResponseNewParamsInputUnion{OfString: openai.String("Check the demo weather in Paris. Meanwhile, list three essentials for any city trip.")},
    })
    if err != nil {
        panic(err)
    }
    var call responses.ResponseFunctionToolCall
    for _, item := range response.Output {
        if item.Type == "function_call" && item.AsFunctionCall().Name == "get_weather" {
            call = item.AsFunctionCall()
            break
        }
    }
    if call.CallID == "" {
        panic("The response did not include a weather call.")
    }
    var arguments weatherArguments
    if err := json.Unmarshal([]byte(call.Arguments), &arguments); err != nil {
        panic(err)
    }
    latestResponseID := response.ID
    var result weatherSnapshot
    if call.Async {
        job := make(chan weatherSnapshot, 1)
        go func() { job <- getWeather(arguments.City) }()
        fmt.Println(response.OutputText())
        // [中文] 这里可以处理互不依赖的工作或其他会话轮次。
        // 可以在此处执行独立工作或进行其他对话轮次。
        // [中文] 每次续接后更新latestResponseID。
        // 每次继续请求后更新 latestResponseID。
        result = <-job
    } else {
        result = getWeather(arguments.City)
    }
    output, err := json.Marshal(result)
    if err != nil {
        panic(err)
    }
    functionOutput := responses.ResponseInputItemParamOfFunctionCallOutput(string(output))
    functionOutput.OfFunctionCallOutput.CallID = openai.String(call.CallID)
    response, err = client.Responses.New(ctx, responses.ResponseNewParams{
        Model:              "gpt-6-astra",
        Tools:              tools,
        Instructions:       openai.String(instructions),
        PreviousResponseID: openai.String(latestResponseID),
        Input:              responses.ResponseNewParamsInputUnion{OfInputItemList: responses.ResponseInputParam{functionOutput}},
    })
    if err != nil {
        panic(err)
    }
    fmt.Println(response.OutputText())
}

来源示例4(java)

本段复用的中文释义:译释0、译释1、译释2。

// [中文] 将get_weather声明为异步工具;应用启动演示天气任务,再用原call_id返回结果。
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.openai.core.JsonValue;
import com.openai.models.responses.FunctionTool;
import com.openai.models.responses.Response;
import com.openai.models.responses.ResponseCreateParams;
import com.openai.models.responses.ResponseFunctionToolCall;
import com.openai.models.responses.ResponseInputItem;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

record WeatherArguments(String city) {}

record WeatherSnapshot(
    String city,
    @JsonProperty("temperature_c") int temperatureC,
    String condition,
    String source) {}

static WeatherSnapshot getWeather(String city) {
  // [中文] 这里是演示数据,应替换为自己的天气服务。
  // 此处为演示数据,请换成自己的天气服务。
  if (!city.equals("Paris")) {
    throw new IllegalArgumentException("No demo weather snapshot for " + city);
  }
  return new WeatherSnapshot(city, 22, "Clear", "demo weather snapshot");
}

FunctionTool tool =
    FunctionTool.builder()
        .name("get_weather")
        .description("Read the demo weather snapshot for a city.")
        .async(true)
        .strict(true)
        .parameters(
            FunctionTool.Parameters.builder()
                .putAdditionalProperty("type", JsonValue.from("object"))
                .putAdditionalProperty(
                    "properties", JsonValue.from(Map.of("city", Map.of("type", "string"))))
                .putAdditionalProperty("required", JsonValue.from(List.of("city")))
                .putAdditionalProperty("additionalProperties", JsonValue.from(false))
                .build())
        .build();
String 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 response =
    client
        .responses()
        .create(
            ResponseCreateParams.builder()
                .model("gpt-6-astra")
                .addTool(tool)
                .instructions(instructions)
                .input(
                    "Check the demo weather in Paris. Meanwhile, list three essentials for any city trip.")
                .build());
ResponseFunctionToolCall call =
    response.output().stream()
        .flatMap(item -> item.functionCall().stream())
        .filter(item -> item.name().equals("get_weather"))
        .findFirst()
        .orElseThrow(
            () -> new IllegalStateException("The response did not include a weather call."));
WeatherArguments arguments = call.arguments(WeatherArguments.class);
String latestResponseId = response.id();
WeatherSnapshot result;
if (call.async().orElse(false)) {
  CompletableFuture<WeatherSnapshot> job =
      CompletableFuture.supplyAsync(() -> getWeather(arguments.city()));
  System.out.println(response.output());
  // [中文] 这里可以处理互不依赖的工作或其他会话轮次。
  // 可以在此处执行独立工作或进行其他对话轮次。
  // [中文] 每次续接后更新latestResponseId。
  // 每次继续请求后更新 latestResponseId。
  result = job.join();
} else {
  result = getWeather(arguments.city());
}
response =
    client
        .responses()
        .create(
            ResponseCreateParams.builder()
                .model("gpt-6-astra")
                .addTool(tool)
                .instructions(instructions)
                .previousResponseId(latestResponseId)
                .inputOfResponse(
                    List.of(
                        ResponseInputItem.ofFunctionCallOutput(
                            ResponseInputItem.FunctionCallOutput.builder()
                                .callId(call.callId())
                                .output(new ObjectMapper().writeValueAsString(result))
                                .build())))
                .build());
response.output().stream()
    .flatMap(item -> item.message().stream())
    .flatMap(message -> message.content().stream())
    .flatMap(content -> content.outputText().stream())
    .forEach(text -> System.out.println(text.text()));

来源示例5(ruby)

本段复用的中文释义:译释0、译释1、译释2。

## [中文] 将get_weather声明为异步工具;应用启动演示天气任务,再用原call_id返回结果。
require "json"
require "openai"

def get_weather(city)
  # [中文] 这里是演示数据,应替换为自己的天气服务。
  # 此处为演示数据,请换成自己的天气服务。
  raise "No demo weather snapshot for #{city}" unless city == "Paris"

  {
    city: city,
    temperature_c: 22,
    condition: "Clear",
    source: "demo weather snapshot"
  }
end

client = OpenAI::Client.new
tools = [
  OpenAI::Models::Responses::FunctionTool.new(
    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: "gpt-6-astra",
  tools: tools,
  instructions: instructions,
  input: "Check the demo weather in Paris. Meanwhile, list three essentials for any city trip."
)
call = response.output.find do |item|
  item.is_a?(OpenAI::Models::Responses::ResponseFunctionToolCall) && item.name == "get_weather"
end
unless call.is_a?(OpenAI::Models::Responses::ResponseFunctionToolCall)
  raise "The response did not include a weather call."
end

city = JSON.parse(call.arguments).fetch("city")
latest_response_id = response.id
result = if call.async
           job = Thread.new { get_weather(city) }
           puts(response.output_text)
           # [中文] 这里可以处理互不依赖的工作或其他会话轮次。
           # 可以在此处执行独立工作或进行其他对话轮次。
           # [中文] 每次续接后更新latest_response_id。
           # 每次继续请求后更新 latest_response_id。
           job.value
         else
           get_weather(city)
         end
response = client.responses.create(
  model: "gpt-6-astra",
  tools: tools,
  instructions: instructions,
  previous_response_id: latest_response_id,
  input: [
    OpenAI::Models::Responses::ResponseInputItem::FunctionCallOutput.new(
      call_id: call.call_id,
      output: JSON.generate(result)
    )
  ]
)
puts(response.output_text)

响应可以同时包含异步调用和回答。如果任务完成前发生了其他会话轮次,应更新 latest_response_id,从最新响应继续,同时保留工具原来的 call_id。

如需更早分派,可使用流式输出:完整调用项到达后便启动任务,同时继续消费响应流。

添加等待工具

等待工具让模型决定何时需要尚未完成的结果。例如先发起两项价格查询,处理独立工作,到比较价格时再等待。

为每个异步工具增加 task_handle 参数。模型为每次调用指定句柄,应用将它与原始 API call_id 和运行中的任务绑定。句柄在整个会话中必须唯一,已完成任务和重复查询也不能复用旧句柄。

将等待工具定义为普通同步函数:省略 async 或设置为 false。其模式与行为由应用定义,wait_for_tasks 不是 Responses 内置工具。将以下定义放入请求的 tools 数组。

来源示例6(json):以下保留协议载荷、配置、返回示意或语法定义;省略号及片段不代表完整可运行程序。

[
  {
    "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
    }
  }
]

登记每个任务

在处理依赖它们的等待调用前,先登记并启动每个任务。多个调用可能出现在同一响应,也可能分散在不同响应。以下输出示意先启动两个查询,再等待二者完成。

来源示例7(json):以下保留协议载荷、配置、返回示意或语法定义;省略号及片段不代表完整可运行程序。

[
  {
    "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 可以包含以下输出项,价格仅为示意。

来源示例8(json):以下保留协议载荷、配置、返回示意或语法定义;省略号及片段不代表完整可运行程序。

[
  {
    "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 内置工具。将以下定义与 wait_for_tasks 一起加入 tools。

来源示例9(json):以下保留协议载荷、配置、返回示意或语法定义;省略号及片段不代表完整可运行程序。

{
  "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,然后向用户显示问题。以下示意调用询问报告受众。

来源示例10(json):以下保留协议载荷、配置、返回示意或语法定义;省略号及片段不代表完整可运行程序。

{
  "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。

来源示例11(json):以下保留协议载荷、配置、返回示意或语法定义;省略号及片段不代表完整可运行程序。

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

设置最新的 previous_response_id,并携带工具和指令。如果模型已对 report_audience_1 调用了 wait_for_tasks,应像等待工具示例那样,先返回回答,再返回等待状态。

异步执行不会让某个响应一直保持打开直到用户回答。应指示模型继续独立工作,并在执行依赖回答的步骤前等待。如果应用支持关闭问题或超时,应显式返回“未回答”的结果,让模型决定如何继续。

兼容性

GPT-6 Astra及后续模型支持异步工具调用。异步执行适用于由应用运行的函数工具和自定义工具,不适用于托管内置工具。应直接调用工具,不要将异步工具配置为程序化工具调用。在多智能体模式下,不要将异步工具与并行工具调用组合使用。

OpenAI 文本生成
OpenAI 函数调用
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

其他能力与进阶指南

Embeddings 接口参考

审计日志接口参考

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }