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

個人智慧體的時間感知與非同步輸入

如何建構能考量時間限制,並在等待使用者輸入時持續工作的智慧體

作者: Kevin Whinnery

個人智慧體的時間感知與非同步輸入

如果你正在建構類似 dot 的個人智慧體,你會經常需要讓它在期限內把結果交給使用者。

假設我 15 分鐘後要和一位潛在客戶開會。我請智慧體研究對方的公司,整理一份會前摘要,並預留三分鐘讓我在開會前讀完。我平常上班時,差不多就是這樣趕著準備開會的 😬。

智慧體注意到,我沒說這場會議是要做技術評估,還是要討論價格。會議目的不同,要調查的細節和摘要該涵蓋的內容也會不同。

智慧體決定問我這場會議的重點。等待回覆時,它該怎麼運用剩下的時間?如果我回覆了,它該如何根據我的回答調整摘要?如果我一直沒回答,它又該如何按時交出一份有用的摘要?

時間感知與非同步輸入

時間感知是 Agents API 最近新增的功能。它會定期提醒模型目前的時間,讓模型能依照期限調整工作。非同步函式工具 則讓智慧體在應用程式等待使用者回答時繼續工作。

距離開會還有 15 分鐘,智慧體有 12 分鐘可以準備摘要。接近交付期限時,智慧體可以優先查證最有根據的發現,動筆撰寫摘要,把探索新問題的優先順序往後排。如果給的時間比較充裕,模型也能據此擴大研究範圍,深入調查。

像「我 15 分鐘後要開會。請幫我準備一份摘要,留三分鐘給我閱讀」這樣的要求,就訂出了交付期限。有了時間感知功能,即使還在等待搜尋結果或使用者回覆,模型也能掌握目前的時間。

4:00下午
摘要須於 4:12 前交付
開始摘要截止會議
智慧體
正在研究公司背景
想請問你
尚未指定會議重點
筆記
Pied Piper
會前摘要
公司背景
近期公告

我們來設定一個協助使用者準備會議的智慧體,看看這些功能如何運作。在上圖的例子中,我在世界協調時間(UTC)下午 4 點提出要求,希望在 4 點 12 分前拿到摘要,為 4 點 15 分的會議做準備。接下來會說明如何設定智慧體、更新時間、處理工具呼叫,以及取得並交付最終結果。

你也可以直接查看慣用程式語言的完整範例程式碼。

建立智慧體

為了協助使用者準備會議,智慧體需要研究公司、詢問尚未提供的會議背景,並掌握撰寫摘要還剩多少時間。這需要三項功能:網頁搜尋、向使用者提問的非同步工具,以及時間感知。

我們採用以下設定,透過 SDK 的智慧體建立方法建立智慧體:

  • 將 experimental.time_awareness 設為 true,讓模型定期收到目前時間的提醒。
  • 啟用內建的 web_search 工具,並使用 live 模式,讓智慧體能在網路上搜尋最新資訊。
  • 定義一個函式工具,命名為 request_user_input_async。將 async 設為 true,讓智慧體在應用程式收集回覆時繼續工作。

選用具備 Agents API 存取權的專案所提供的金鑰,將其設為 OPENAI_API_KEY 的值。請依照 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 分鐘後」和「留三分鐘給我閱讀」這類時間描述換算成絕對時間戳記,讓模型和應用程式都使用相同的時間資料。以下程式碼會告訴智慧體,會議將在 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"
  }
}

傳回工具結果

使用者的回答能幫助智慧體根據實際的會議目的撰寫摘要。即使使用者一直沒回答,智慧體仍需要時間完成摘要,因此應用程式會在交付前兩分鐘,也就是下午 4 點 10 分,關閉尚未回答的問題。

在智慧體執行期間,為每個待處理的呼叫傳回一個工具結果:

  • 收到回覆時,將 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),
        }
    ],
)

取得並交付答案

精簡的會前摘要一準備好就交付,讓使用者在開會前至少有三分鐘可以閱讀。如果先到了交付期限,請傳回最近完成的摘要。如果尚無查證完畢的發現,就告知使用者。

收到 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 請求都會附上最新的時間提醒。應用程式的計時器會在整個迴圈執行期間持續計時,因此即使某個請求或工具耗時過長,應用程式仍會準時交付結果。

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 的時間感知功能也能幫助你在自己的應用程式中實作這種模式。歡迎和我們分享你的作品!