ドキュメントの全ページの一覧は、 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
会議用資料
会社概要
最近の発表

この仕組みを、ユーザーの打ち合わせ準備を手伝うエージェントで実装してみましょう。図の例では、私は 16:15 の打ち合わせに先立ち、16:00(UTC)に、16:12 までに資料を用意するよう依頼しています。ここからは、エージェントの設定、現在時刻の通知、ツール呼び出しへの対応、最終結果の取り扱いを順に見ていきます。

お好みのプログラミング言語のサンプルコード全体に直接進むこともできます。

エージェントの作成

打ち合わせの準備を手伝うには、エージェントが先方の会社を調べ、打ち合わせについて足りない情報をユーザーに尋ね、資料作成に使える残り時間を把握する必要があります。そのために、ウェブ検索、ユーザーに入力を求める非同期ツール、時間認識を使用します。

次の設定で、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"
  }
}

ツール結果の返却

ユーザーから回答があれば、エージェントは打ち合わせの目的に合わせて資料の内容を絞り込めます。回答がない場合も資料を書き上げる時間が必要なので、アプリケーションは提出期限の 2 分前にあたる 16:10 に、未回答の質問を締め切ります。

エージェントの実行中に、保留中の呼び出しごとにツール結果を 1 件返します。

  • 回答を受け取ったときは、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 ""

サンプルコード全体

以下の言語別のサンプルでは、クライアントの設定、非同期での回答の受け付け、提出期限を管理するタイマー、終了時の後処理まで、打ち合わせ準備の一連の処理を 1 ファイルにまとめています。各スクリプトは環境変数から 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. モデルへの各リクエストの直前に現在時刻を追加

モデルが次の作業を決めるには、その時点の時刻が必要です。最初のリクエストにも、それに続くすべてのリクエストにも同じヘルパー関数を使い、時刻を更新する処理を 1 か所にまとめます。

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. 得られた結果を使ったループの継続

調査中にユーザーから回答が届いたら、次の版の資料に反映します。各レスポンスの完了後、その時点で得られたツール結果を集め、リクエスト用のヘルパー関数を通じて送ります。この関数が最新の時刻を追記します。ツール結果が以前のレスポンスで尋ねた質問に対するものであっても、previous_response_id には直近に完了したレスポンスの 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 の時間認識を、皆さんのエージェントに同じ仕組みを取り入れる際に役立てていただければ幸いです。どんなものを作ったか、ぜひ教えてください!