如需查看完整的文档索引,请参阅 llms.txt。在文档页面的 URL 末尾加上 .md 即可查看该页面的 Markdown 版本。
主导航
Nov 20, 2026 API

个人智能体的时间感知与异步输入

如何构建能根据时限安排工作、在等待用户输入时也能继续执行任务的智能体

作者: Kevin Whinnery

个人智能体的时间感知与异步输入

如果您正在构建类似 dot 的个人智能体,通常会希望它能按时向用户交付结果。

假设再过 15 分钟,我就要和一位潜在客户开会。我请智能体调研对方的公司,准备一份简报,给我留出 3 分钟在会前阅读。工作日里,我经常就是这样赶着准备会议的 😬。

智能体注意到,我没有说明这次会议是要做技术评估,还是要讨论价格。会议目的不同,需要调查的细节和简报应涵盖的内容也会不同。

于是,智能体决定问问我这次会议的重点。在等待我回复时,它该如何利用剩余时间?如果我回复了,它该如何根据回复调整简报?即使我一直没有回答,它又该如何按时交付一份有用的简报?

时间感知与异步输入

时间感知是 Agents API 最近新增的功能。它定期向模型提醒当前时间,让模型可以根据截止时间调整工作安排。借助**异步函数工具**,智能体可以在应用等待最终用户回复时继续工作。

会议将在 15 分钟后开始,智能体有 12 分钟准备简报。临近交付时,它可以优先核实证据最充分的发现并撰写简报,暂缓调查新线索。如果给出的时间更充裕,模型也就知道自己有时间深入调查,查找更多资料。

用户可以这样指定截止时间:“我 15 分钟后要开会。请准备一份简报,给我留出 3 分钟阅读。”在等待搜索结果或用户输入期间,时间感知功能会持续提醒模型当前时间。

4:00下午
简报须在 4:12 前交付
开始简报交付截止会议
智能体
正在调研这家公司
想请您确认
尚未明确会议重点
笔记
Pied Piper
会议简报
公司背景
近期公告

下面我们将设置一个帮助用户做会前准备的智能体,看看这两项功能如何配合。在图示中,我在 UTC 时间 16:00 提出请求,要求智能体在 16:12 前交付简报,为 16:15 的会议做准备。我们将介绍如何配置智能体、向它提供最新时间、处理它发起的工具调用,以及处理最终结果。

您可以直接查看所用编程语言的完整示例代码。

创建智能体

为了帮助用户做会前准备,智能体需要调研公司、询问尚不明确的会议背景,并掌握准备简报的剩余时间。这需要用到网页搜索、用于征求用户意见的异步工具,以及时间感知功能。

按以下配置,使用 SDK 的智能体创建方法创建智能体:

  • 将 experimental.time_awareness 设为 true,让模型定期收到当前时间提醒。
  • 启用内置的 web_search 工具,并将模式设为 live,让智能体可以通过网页搜索获取最新信息。
  • 定义一个函数工具,将其命名为 request_user_input_async。将 async 设为 true,这样在应用收集用户回复期间,智能体可以继续工作。

将 OPENAI_API_KEY 设为具有 Agents API 访问权限的项目所提供的密钥。按照 SDK 库指南安装官方 SDK,并创建下文使用的 client。有关所需权限,请参阅 Agents API 快速入门的前提条件。

创建用于会前准备的智能体
async def create_agent(client: AsyncOpenAI):
    return await client.beta.agents.create(
        name="Personal assistant",
        model="gpt-6.2-astra",
        experimental={"time_awareness": True},
        instructions=(
            "You are a personal assistant. Deliver useful, well-sourced answers "
            "within the user's time constraints. Ask for clarification when it "
            "would materially improve the result, and keep making progress while "
            "a reply is pending. State important uncertainties."
        ),
        tools=[
            {"type": "web_search", "mode": "live"},
            {
                "type": "function",
                "name": "request_user_input_async",
                "description": "Ask for missing context while continuing independent work.",
                "async": True,
                "parameters": {
                    "type": "object",
                    "properties": {
                        "question": {"type": "string"},
                        "choices": {"type": "array", "items": {"type": "string"}},
                    },
                    "required": ["question"],
                    "additionalProperties": False,
                },
            },
        ],
    )

启动有截止时间的任务

现在可以请智能体为客户会议做准备了。请求中给出公司名称、会议时间和简报交付时间,由智能体自行决定要调研什么,以及是否需要进一步询问用户。

启动一个会话时,请使用 SDK 的会话创建方法,并在智能体工作期间以流式方式接收更新。

应用需要将“15 分钟后”和“留出 3 分钟阅读”之类的相对时间表述转换为绝对时间戳,以便模型和应用使用相同的时间数据。以下代码告诉智能体会议将在 15 分钟后开始,并要求它在 12 分钟后交付简报。

启动会前准备会话
now = datetime.now(UTC)
meeting = (now + timedelta(minutes=15)).isoformat(timespec="seconds")
delivery = (now + timedelta(minutes=12)).isoformat(timespec="seconds")
stream = await client.beta.agents.sessions.create(
    agent_id=agent.id,
    environment={"type": "none"},
    input=(
        f"I am meeting with Pied Piper (example.com) about our customer-support software at "
        f"{meeting}. Get me up to speed on their business, recent product "
        f"announcements, and questions I should ask. Send me a concise briefing by "
        f"{delivery} so I have time to read it before the meeting."
    ),
    stream=True,
    timeout=12 * 60,
)

显示待回答的问题

当智能体询问会议重点时,应用需要显示问题,同时让智能体继续调研公司。使用独立任务收集回复,应用就能持续接收智能体的更新。

当模型通过工具调用请求用户补充信息时,收集用户输入的工作由应用代码负责。

监听会话事件流中的 agent.session.turn.item.done 事件,查找其中包含 request_user_input_async 函数调用的事件。从 item.arguments 中读取问题和建议选项(如有)。会话的 required_actions 列表记录的是阻塞操作,如果在这里等待新条目,可能会漏掉异步问题。

保存会话 ID 以及此次调用的 turn_id 和 call_id,以便将回复与问题关联。跟踪待回答的问题,确保每个问题只显示和处理一次,并在智能体运行结束时取消相应的输入处理程序:

处理待回答的问题
item = event.item
if (
    isinstance(item, AgentFunctionCallItem)
    and item.name == "request_user_input_async"
    and item.call_id not in questions
):
    questions[item.call_id] = asyncio.create_task(
        respond(
            client,
            event.session_id,
            item,
            replies,
            prompt_lock,
            reply_cutoff,
        )
    )

问题以函数调用事件的形式到达:

{
  "type": "agent.session.turn.item.done",
  "item": {
    "type": "function_call",
    "name": "request_user_input_async",
    "arguments": {
      "question": "Is this meeting mainly a technical evaluation or a commercial discussion?",
      "choices": ["Technical evaluation", "Commercial discussion"]
    },
    "turn_id": "turn_789abcd",
    "call_id": "call_012ef34"
  }
}

返回工具结果

用户的回答能帮助智能体围绕会议目的撰写简报。如果用户一直没有回答,智能体仍需要时间完成撰写,因此应用会在 16:10 关闭尚未回答的问题,距离交付还有 2 分钟。

在智能体仍在运行时,为每个待处理的调用返回一个工具结果:

  • 收到回复时,将 status 设为 answered,并将用户输入的文本或所选选项写入 answer。
  • 到达回复截止时间时,如果同一 call_id 对应的调用仍待处理且用户尚未回复,则返回 {"status":"no_answer"}。

通过 SDK 的会话事件方法发送结果,使用之前保存的标识符将结果与问题匹配。提交结果时,继续读取事件流。如果智能体提前完成任务,请在界面中关闭待回答的问题。

返回用户回复或问题过期的结果
result = (
    {"status": "answered", "answer": answer} if answer else {"status": "no_answer"}
)
await client.beta.agents.sessions.events.create(
    session_id,
    events=[
        {
            "type": "agent.session.input.tool_result",
            "turn_id": call.turn_id,
            "call_id": call.call_id,
            "success": True,
            "output": json.dumps(result),
        }
    ],
)

获取并交付答案

简报应简明扼要,完成后立即交付,让用户在会前至少有 3 分钟阅读。如果先到了截止时间,请返回最近完成的简报,或者告知用户目前还没有已核实的发现可供分享。

收到 agent.session.turn.completed 时,获取已保存的条目。为此,请调用 SDK 的轮次条目查询方法,找到 phase 为 final_answer 且已完成的智能体消息。

如果事件流提前关闭,请列出会话中的各个轮次,查看已保存的状态。有关重新连接和获取已保存工作成果的方法,请参阅恢复事件流。

获取最终简报
def final_text(item: AgentSessionItem | AgentOutputItem) -> str:
    if (
        item.type == "message"
        and item.role == "assistant"
        and item.status == "completed"
        and item.phase == "final_answer"
    ):
        return "\n".join(
            part.text for part in item.content if part.type == "output_text"
        )
    return ""


async def retrieve_answer(client: AsyncOpenAI, session_id: str, turn_id: str) -> str:
    async for item in client.beta.agents.sessions.turns.items.list(
        turn_id, session_id=session_id, order="desc"
    ):
        if text := final_text(item):
            return text
    return ""

完整示例代码

下面每种语言的示例都在一个文件中实现了完整的会前准备流程,包括设置客户端、处理异步回复、设置交付计时器和清理资源。每个脚本都会从环境变量中读取 OPENAI_API_KEY,并在终端中接收用户回复。

会前准备完整示例
import asyncio
import json
import os
import sys
from contextlib import AsyncExitStack, suppress
from datetime import UTC, datetime, timedelta
from threading import Thread

from openai import AsyncOpenAI, ConflictError
from openai.types.beta import AgentFunctionCallItem, AgentOutputItem, AgentSessionItem

client = AsyncOpenAI(max_retries=0)


async def create_agent(client: AsyncOpenAI):
    return await client.beta.agents.create(
        name="Personal assistant",
        model="gpt-6.2-astra",
        experimental={"time_awareness": True},
        instructions=(
            "You are a personal assistant. Deliver useful, well-sourced answers "
            "within the user's time constraints. Ask for clarification when it "
            "would materially improve the result, and keep making progress while "
            "a reply is pending. State important uncertainties."
        ),
        tools=[
            {"type": "web_search", "mode": "live"},
            {
                "type": "function",
                "name": "request_user_input_async",
                "description": "Ask for missing context while continuing independent work.",
                "async": True,
                "parameters": {
                    "type": "object",
                    "properties": {
                        "question": {"type": "string"},
                        "choices": {"type": "array", "items": {"type": "string"}},
                    },
                    "required": ["question"],
                    "additionalProperties": False,
                },
            },
        ],
    )




def console_replies() -> asyncio.Queue[str]:
    loop = asyncio.get_running_loop()
    replies: asyncio.Queue[str] = asyncio.Queue()

    def read_lines():
        with os.fdopen(
            os.dup(sys.stdin.fileno()), encoding=sys.stdin.encoding
        ) as terminal:
            for line in terminal:
                try:
                    loop.call_soon_threadsafe(replies.put_nowait, line.strip())
                except RuntimeError:
                    return  # The session and its event loop have closed.

    # A pending terminal read must not keep the program open after delivery.
    Thread(target=read_lines, daemon=True).start()
    return replies


async def respond(client, session_id, call, replies, prompt_lock, cutoff):
    loop = asyncio.get_running_loop()
    try:
        async with asyncio.timeout_at(cutoff), prompt_lock:
            if loop.time() >= cutoff:
                raise TimeoutError
            print(call.arguments["question"], file=sys.stderr, flush=True)
            for choice in call.arguments.get("choices", []):
                print(f"  {choice}", file=sys.stderr, flush=True)
            reply = await replies.get()
            answer = reply if loop.time() < cutoff else ""
    except TimeoutError:
        answer = ""

    result = (
        {"status": "answered", "answer": answer} if answer else {"status": "no_answer"}
    )
    await client.beta.agents.sessions.events.create(
        session_id,
        events=[
            {
                "type": "agent.session.input.tool_result",
                "turn_id": call.turn_id,
                "call_id": call.call_id,
                "success": True,
                "output": json.dumps(result),
            }
        ],
    )


def final_text(item: AgentSessionItem | AgentOutputItem) -> str:
    if (
        item.type == "message"
        and item.role == "assistant"
        and item.status == "completed"
        and item.phase == "final_answer"
    ):
        return "\n".join(
            part.text for part in item.content if part.type == "output_text"
        )
    return ""


async def retrieve_answer(client: AsyncOpenAI, session_id: str, turn_id: str) -> str:
    async for item in client.beta.agents.sessions.turns.items.list(
        turn_id, session_id=session_id, order="desc"
    ):
        if text := final_text(item):
            return text
    return ""




async def main():
    async with client, AsyncExitStack() as cleanup:
        agent = await create_agent(client)
        cleanup.push_async_callback(client.beta.agents.delete, agent.id)
        sessions = client.beta.agents.sessions
        session_id = None
        active = False
        saved_answer = ""
        questions = {}
        prompt_lock = asyncio.Lock()
        replies = console_replies()
        loop = asyncio.get_running_loop()
        started = loop.time()
        reply_cutoff = started + 10 * 60
        try:
            async with asyncio.timeout_at(started + 12 * 60):
                now = datetime.now(UTC)
                meeting = (now + timedelta(minutes=15)).isoformat(timespec="seconds")
                delivery = (now + timedelta(minutes=12)).isoformat(timespec="seconds")
                stream = await client.beta.agents.sessions.create(
                    agent_id=agent.id,
                    environment={"type": "none"},
                    input=(
                        f"I am meeting with Pied Piper (example.com) about our customer-support software at "
                        f"{meeting}. Get me up to speed on their business, recent product "
                        f"announcements, and questions I should ask. Send me a concise briefing by "
                        f"{delivery} so I have time to read it before the meeting."
                    ),
                    stream=True,
                    timeout=12 * 60,
                )
                async with stream:
                    async for event in stream:
                        if event.type == "agent.session.created":
                            session_id = event.session.id
                            # A cancelled turn can take a moment to release its session.
                            cleanup_sessions = client.with_options(
                                max_retries=4, timeout=10
                            ).beta.agents.sessions
                            cleanup.push_async_callback(
                                cleanup_sessions.delete, session_id
                            )
                            active = True
                        elif event.type == "agent.session.turn.item.done":
                            item = event.item
                            if (
                                isinstance(item, AgentFunctionCallItem)
                                and item.name == "request_user_input_async"
                                and item.call_id not in questions
                            ):
                                questions[item.call_id] = asyncio.create_task(
                                    respond(
                                        client,
                                        event.session_id,
                                        item,
                                        replies,
                                        prompt_lock,
                                        reply_cutoff,
                                    )
                                )
                            saved_answer = final_text(item) or saved_answer
                        elif event.type == "agent.session.turn.completed":
                            active = False
                            for question in questions.values():
                                question.cancel()
                            # Allow the creation stream to finish releasing its connection.
                            with suppress(TimeoutError):
                                async with asyncio.timeout(1):
                                    async for _ in stream:
                                        continue
                            answer = await retrieve_answer(
                                client, event.session_id, event.turn.id
                            )
                            print(
                                answer
                                or saved_answer
                                or "No verified findings were available.",
                                flush=True,
                            )
                            return
                        elif event.type in (
                            "agent.session.failed",
                            "agent.session.environment.failed",
                            "agent.session.turn.failed",
                            "agent.session.turn.cancelled",
                            "error",
                        ):
                            active = False
                            raise RuntimeError(
                                f"Meeting briefing stopped: {event.type}"
                            )
                        for question in questions.values():
                            if question.done():
                                error = question.exception()
                                # A finished turn can reject a reply still in flight.
                                if error is not None and not isinstance(
                                    error, ConflictError
                                ):
                                    raise error
                raise RuntimeError("The event stream closed before the turn completed.")
        except TimeoutError:
            print(
                saved_answer or "No verified findings were available by the deadline.",
                flush=True,
            )
        finally:
            for question in questions.values():
                question.cancel()
            await asyncio.gather(*questions.values(), return_exceptions=True)
            if active and session_id:
                await sessions.events.create(
                    session_id, events=[{"type": "agent.session.input.cancel"}]
                )


if __name__ == "__main__":
    asyncio.run(main())

在 Responses API 循环中实现时间感知

如果个人智能体使用自行编写的 Responses API 循环,就需要由应用持续告知模型还剩多少时间准备简报。只需计算一次截止时间,然后在每次向模型发送请求之前追加一条最新的时间提醒,提交工具结果的请求也不例外。

以下步骤实现了相同的会前准备任务。每次 Responses API 请求都包含给模型的最新时间提醒。应用的计时器在整个循环期间持续运行,即使某个请求或工具耗时过长,也能保证按时交付。

1. 设置会议开始时间和简报交付时间

告知智能体需要调研哪家公司,以及何时交付简报。沿用前面的总体指令和异步提问工具,由模型决定是否需要询问用户。

会议在 15 分钟后开始,简报须在 12 分钟内交付,应用在任务开始 10 分钟后关闭尚未回答的问题。这些时间点在整个任务期间保持固定。

配置 Responses API 会前准备任务
import asyncio
import json
import os
import sys
from contextlib import suppress
from dataclasses import dataclass, field
from datetime import UTC, datetime, timedelta
from threading import Thread

from openai import APITimeoutError, AsyncOpenAI, OpenAIError
from openai.types.responses import (
    Response,
    ResponseFunctionToolCall,
    ResponseInputItemParam,
    ToolParam,
)

instructions = (
    "You are a personal assistant. Deliver useful, well-sourced answers "
    "within the user's time constraints. Ask for clarification when it "
    "would materially improve the result, and keep making progress while "
    "a reply is pending. State important uncertainties."
)
tools: list[ToolParam] = [
    {"type": "web_search"},
    {
        "type": "function",
        "name": "request_user_input_async",
        "description": "Ask for missing context while continuing independent work.",
        "async": True,
        "strict": False,
        "parameters": {
            "type": "object",
            "properties": {
                "question": {"type": "string"},
                "choices": {"type": "array", "items": {"type": "string"}},
            },
            "required": ["question"],
            "additionalProperties": False,
        },
    },
]

@dataclass
class State:
    response_ids: list[str] = field(default_factory=list)
    questions: dict[str, asyncio.Task[ResponseInputItemParam]] = field(
        default_factory=dict
    )
    seen_calls: set[str] = field(default_factory=set)
    latest_response_id: str | None = None
    saved_answer: str = ""

def configure_task():
    now = datetime.now(UTC)
    started = asyncio.get_running_loop().time()
    meeting = (now + timedelta(minutes=15)).isoformat(timespec="seconds")
    delivery = (now + timedelta(minutes=12)).isoformat(timespec="seconds")
    reply_cutoff = started + 10 * 60
    delivery_cutoff = started + 12 * 60
    input_items = [
        {
            "role": "user",
            "content": (
                f"I am meeting with Pied Piper (example.com) about our customer-support software at "
                f"{meeting}. Get me up to speed on their business, recent product "
                f"announcements, and questions I should ask. Send me a concise briefing by "
                f"{delivery} so I have time to read it before the meeting."
            ),
        }
    ]
    return input_items, reply_cutoff, delivery_cutoff
2. 在每次请求模型前添加当前时间

模型在决定下一步行动时需要知道当前时间。首次请求和后续每次请求都使用同一个辅助函数,以便统一更新时间。

在即将调用 Responses API 时,将当前 UTC 时间作为一条开发者消息,追加在用户输入或工具结果之后。每次请求都要发送指令和工具定义。最初设定的截止时间会保留在对话历史记录中。

更新时间并创建响应
async def start_response(input_items, previous_response_id, delivery_cutoff):
    remaining = delivery_cutoff - asyncio.get_running_loop().time()
    if remaining <= 0:
        raise TimeoutError
    current_time = datetime.now(UTC).isoformat(timespec="seconds")
    return await client.responses.create(
        model="gpt-6.2-astra",
        instructions=instructions,
        tools=tools,
        previous_response_id=previous_response_id,
        input=[
            *input_items,
            {"role": "developer", "content": f"Current time: {current_time}."},
        ],
        store=True,
        stream=True,
        timeout=remaining,
    )
3. 在继续调研的同时收集回复

当智能体询问会议重点时,显示问题,并独立于响应生成过程收集用户回复。输入收集程序收到回复时返回答案,如果到截止时间仍未收到回复,则返回 no_answer。它使用原始 call_id 将结果与相应的问题关联。

异步收集用户对问题的回复
def console_replies() -> asyncio.Queue[str]:
    loop = asyncio.get_running_loop()
    replies: asyncio.Queue[str] = asyncio.Queue()

    def read_lines():
        with os.fdopen(
            os.dup(sys.stdin.fileno()), encoding=sys.stdin.encoding
        ) as terminal:
            for line in terminal:
                try:
                    loop.call_soon_threadsafe(replies.put_nowait, line.strip())
                except RuntimeError:
                    return

    Thread(target=read_lines, daemon=True).start()
    return replies

async def collect_reply(call, replies, prompt_lock, reply_cutoff):
    arguments = json.loads(call.arguments)
    answer = ""
    # An expired question keeps the empty answer and returns no_answer.
    with suppress(TimeoutError):
        async with asyncio.timeout_at(reply_cutoff), prompt_lock:
            if asyncio.get_running_loop().time() >= reply_cutoff:
                raise TimeoutError
            print(arguments["question"], file=sys.stderr, flush=True)
            for choice in arguments.get("choices", []):
                print(f"  {choice}", file=sys.stderr, flush=True)
            reply = await replies.get()
            if asyncio.get_running_loop().time() < reply_cutoff:
                answer = reply
    result = (
        {"status": "answered", "answer": answer} if answer else {"status": "no_answer"}
    )
    return {
        "type": "function_call_output",
        "call_id": call.call_id,
        "output": json.dumps(result),
    }
4. 处理问题和已完成的响应

一旦从响应流收到完整问题,就启动输入收集程序。在用户考虑如何回答时继续读取事件,让模型可以继续在网上调研。

每当一个响应完成时,保存其 ID 供下一次请求使用,并保留已完成的简报,以备交付。事件处理程序还会记录响应 ID,供后续清理使用。

从事件流中读取问题和已完成的答案
def final_text(response: Response) -> str:
    return "\n".join(
        part.text
        for item in response.output
        if item.type == "message"
        and item.status == "completed"
        and item.phase in (None, "final_answer")
        for part in item.content
        if part.type == "output_text"
    )

async def read_response(stream, state, replies, prompt_lock, reply_cutoff):
    async with stream:
        async for event in stream:
            if event.type == "response.created":
                state.response_ids.append(event.response.id)
            elif event.type == "response.output_item.done":
                call = event.item
                if (
                    isinstance(call, ResponseFunctionToolCall)
                    and call.name == "request_user_input_async"
                    and call.call_id not in state.seen_calls
                ):
                    state.seen_calls.add(call.call_id)
                    state.questions[call.call_id] = asyncio.create_task(
                        collect_reply(call, replies, prompt_lock, reply_cutoff)
                    )
            elif event.type == "response.completed":
                state.latest_response_id = event.response.id
                answer = final_text(event.response)
                state.saved_answer = answer or state.saved_answer
                # Give the transport a moment to finish after the terminal event.
                with suppress(TimeoutError):
                    async with asyncio.timeout(1):
                        async for _ in stream:
                            continue
                return answer
            elif event.type in ("response.failed", "response.incomplete", "error"):
                raise RuntimeError(f"Meeting briefing stopped: {event.type}")
    raise RuntimeError("The response stream closed before completion.")
5. 将已就绪的结果用于下一轮请求

如果在调研期间收到用户回复,下一版简报应参考该回复。每个响应完成后,收集所有已就绪的工具结果,通过请求辅助函数发送,该函数会添加一条新的时间提醒。即使结果对应的问题来自更早的响应,也要使用最近完成的响应 ID 作为 previous_response_id。

按顺序发送请求,确保每个请求都基于最新的对话状态。如果简报已完成且没有已就绪的工具结果,就交付简报并关闭待回答的问题。否则,根据最新时间继续工作,无需停下来等待回复。

继续调研并将用户回复纳入简报
async def run_loop(input_items, state, replies, reply_cutoff, delivery_cutoff):
    prompt_lock = asyncio.Lock()
    while True:
        stream = await start_response(
            input_items, state.latest_response_id, delivery_cutoff
        )
        answer = await read_response(stream, state, replies, prompt_lock, reply_cutoff)
        await asyncio.sleep(0)  # Let ready input handlers finish.
        input_items = []
        for call_id, task in list(state.questions.items()):
            if task.done():
                input_items.append(task.result())
                del state.questions[call_id]
        if input_items:
            continue  # Incorporate replies that arrived during generation.
        if answer:
            return answer
        input_items = [
            {
                "role": "developer",
                "content": "Continue working on the briefing while replies are pending.",
            }
        ]
6. 在请求尚未结束时也能按时交付

应用通过计时器确保按时交付简报,为用户留出阅读时间。计时范围应覆盖整个循环,包括发起 API 请求和读取事件流的过程。

到达截止时间时,停止当前请求,交付已保存的简报,或告知用户目前还没有已核实的发现可供分享。交付后,关闭仍在等待输入的处理程序,并删除已存储的响应。

按时交付并释放任务资源
async def main():
    state = State()
    replies = console_replies()
    input_items, reply_cutoff, delivery_cutoff = configure_task()
    async with client:
        try:
            async with asyncio.timeout_at(delivery_cutoff):
                answer = await run_loop(
                    input_items, state, replies, reply_cutoff, delivery_cutoff
                )
            print(answer, flush=True)
        except (TimeoutError, APITimeoutError):
            print(
                state.saved_answer
                or "No verified findings were available by the deadline.",
                flush=True,
            )
        finally:
            for task in state.questions.values():
                task.cancel()
            await asyncio.gather(*state.questions.values(), return_exceptions=True)
            for response_id in reversed(state.response_ids):
                try:
                    await client.responses.delete(response_id, timeout=10)
                except OpenAIError as error:
                    print(f"Could not delete {response_id}: {error}", file=sys.stderr)


if __name__ == "__main__":
    asyncio.run(main())

结语

个人智能体有时需要在规定时间内完成工作。理想情况下,它会向用户询问缺失的信息,以改善结果。即使用户没有补充说明,它也需要完成有用的工作。

我们为智能体设定了截止时间并启用了时间感知,让它能判断何时该继续调查、核实某项发现,或是完成简报的撰写。借助异步函数工具,在用户考虑如何回答问题时,智能体仍能继续调研。即使用户没有回答,智能体掌握的信息也足以写出一份有用的会议简报。

ChatGPT 和其他智能体执行框架也采用这种方式,在向用户询问更多信息的同时继续工作。我们希望 Agents API 中的时间感知功能能帮助您在自己的应用中实现这种模式。欢迎告诉我们您用它构建了什么!