전체 문서 색인은 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 기준 오후 4시에 브리핑을 요청합니다. 미팅은 오후 4시 15분이고, 브리핑을 받아야 하는 시각은 오후 4시 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,
)

답을 기다리는 질문 표시하기

에이전트가 미팅의 목적을 물으면 애플리케이션은 사용자에게 질문을 표시해야 합니다. 그동안 에이전트는 고객사 조사를 계속합니다. 별도 작업에서 답을 받으면 애플리케이션은 에이전트의 진행 상황을 계속 수신할 수 있습니다.

모델이 도구 호출을 통해 추가 정보를 요청할 때 사용자 입력을 받는 일은 애플리케이션 코드에서 처리해야 합니다.

세션 이벤트 스트림에서 request_user_input_async 함수 호출이 포함된 agent.session.turn.item.done 이벤트를 확인하세요. 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분 전인 오후 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),
        }
    ],
)

최종 답변 조회 및 전달하기

간결한 브리핑을 준비되는 대로 전달해 사용자가 미팅 전에 자료를 읽을 시간을 최소 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. 준비된 결과를 반영해 루프 이어가기

조사 중에 사용자가 답하면 다음 브리핑에 그 내용을 반영해야 합니다. 응답이 완료될 때마다 준비된 도구 결과를 모아 요청 헬퍼 함수로 보내세요. 이 함수가 현재 시각을 알려 주는 메시지를 새로 추가합니다. 도구 결과가 이전 응답에서 나온 질문에 대한 것이더라도 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의 시간 인식 기능이 여러분의 에이전트에도 이런 방식을 구현하는 데 도움이 되길 바랍니다. 어떤 에이전트를 만들었는지 알려 주세요!