콘텐츠로 이동

도구

도구를 사용하면 에이전트가 데이터 가져오기, 코드 실행, 외부 API 호출, 컴퓨터 사용과 같은 작업을 수행할 수 있습니다. SDK는 다음 다섯 가지 카테고리를 지원합니다.

  • OpenAI 호스티드 툴: OpenAI 서버에서 모델을 위해 실행됩니다.
  • 로컬/런타임 실행 도구: ComputerTool 및 ApplyPatchTool은 항상 사용자의 환경에서 실행되며, ShellTool는 로컬 또는 호스티드 컨테이너에서 실행될 수 있습니다.
  • FunctionTool 인스턴스: 모든 Python 함수를 도구로 래핑합니다.
  • Agents as tools: 전체 핸드오프 없이 에이전트를 호출 가능한 도구로 노출합니다.
  • 실험적 기능: Codex 도구: 도구 호출을 통해 워크스페이스 범위의 Codex 작업을 실행합니다.

도구 유형 선택

이 페이지를 카탈로그로 활용한 다음, 제어하는 런타임에 해당하는 섹션으로 이동하세요.

원하는 작업 시작 위치
OpenAI 관리형 도구(웹 검색, 파일 검색, Code Interpreter, 호스티드 MCP, 이미지 생성) 사용 호스티드 툴
도구 검색을 사용하여 대규모 도구 표면을 런타임까지 지연 호스티드 툴 검색
생성된 JavaScript에서 여러 도구 호출 조정 프로그래밍 방식 도구 호출
자체 프로세스 또는 환경에서 도구 실행 로컬 런타임 도구
Python 함수를 도구로 래핑 함수 도구
핸드오프 없이 한 에이전트가 다른 에이전트를 호출하도록 설정 Agents as tools
에이전트에서 워크스페이스 범위의 Codex 작업 실행 실험적 기능: Codex 도구

호스티드 툴

OpenAI는 OpenAIResponsesModel을 사용할 때 몇 가지 기본 제공 도구를 제공합니다.

  • WebSearchTool를 사용하면 에이전트가 웹을 검색할 수 있습니다.
  • FileSearchTool를 사용하면 OpenAI 벡터 스토어에서 정보를 검색할 수 있습니다.
  • CodeInterpreterTool를 사용하면 LLM이 샌드박스 환경에서 코드를 실행할 수 있습니다.
  • HostedMCPTool는 원격 MCP 서버의 도구를 모델에 노출합니다.
  • ImageGenerationTool는 프롬프트로부터 이미지를 생성합니다.
  • ToolSearchTool를 사용하면 모델이 지연된 도구, 네임스페이스 또는 호스티드 MCP 서버를 필요할 때 로드할 수 있습니다.
  • ProgrammaticToolCallingTool를 사용하면 모델이 생성된 JavaScript에서 사용 가능한 도구를 조정할 수 있습니다.

고급 호스티드 검색 옵션:

  • FileSearchTool는 vector_store_ids 및 max_num_results 외에도 filters, ranking_options, include_search_results를 지원합니다. max_num_results을 1부터 50까지의 정수로 설정하세요. None 또는 0을 사용하면 제공자 기본값이 적용됩니다.
  • WebSearchTool은 filters, user_location, search_context_size, external_web_access, search_content_types, image_settings을 지원합니다.
from agents import Agent, FileSearchTool, Runner, WebSearchTool

agent = Agent(
    name="Assistant",
    tools=[
        WebSearchTool(
            search_content_types=["image", "text"],
            image_settings={"max_results": 3, "caption": True},
        ),
        FileSearchTool(
            max_num_results=3,
            vector_store_ids=["VECTOR_STORE_ID"],
        ),
    ],
)


async def main():
    result = await Runner.run(
        agent, "Find recent images and supporting text about the Golden Gate Bridge at sunset."
    )
    print(result.final_output)

웹 검색에서 이미지를 반환해야 하는 경우 search_content_types에 "image"을 포함하고, 모델에 근거가 되는 텍스트 결과도 필요한 경우 "text"도 포함하세요. image_settings.max_results은 양수 개수의 이미지 결과를 요청하며, image_settings.caption은 가능한 경우 짧은 설명을 요청합니다. "image"가 있으면 SDK가 자동으로 web_search_call.results을 요청합니다. 이러한 raw 결과는 어시스턴트 메시지와 별도로 RunResult.raw_responses의 web_search_call 항목에 저장되며, image_url, source_website_url, thumbnail_url, caption를 포함할 수 있습니다. OpenAI 이미지 검색 결과 가이드를 참조하세요.

도구 검색을 사용하면 OpenAI Responses 모델이 대규모 도구 표면을 런타임까지 지연하므로, 모델은 현재 턴에 필요한 하위 집합만 로드합니다. 함수 도구, 네임스페이스 그룹 또는 호스티드 MCP 서버가 많고 모든 도구를 처음부터 노출하지 않으면서 도구 스키마 토큰을 줄이려는 경우 유용합니다.

에이전트를 빌드할 때 후보 도구를 이미 알고 있다면 호스티드 툴 검색부터 시작하세요. 애플리케이션이 무엇을 로드할지 동적으로 결정해야 하는 경우 Responses API는 클라이언트 실행형 도구 검색도 지원하지만, 표준 Runner은 해당 모드를 자동 실행하지 않습니다.

from typing import Annotated

from agents import Agent, Runner, ToolSearchTool, tool_namespace
from agents.decorators import tool


@tool(defer_loading=True)
def get_customer_profile(
    customer_id: Annotated[str, "The customer ID to look up."],
) -> str:
    """Fetch a CRM customer profile."""
    return f"profile for {customer_id}"


@tool(defer_loading=True)
def list_open_orders(
    customer_id: Annotated[str, "The customer ID to look up."],
) -> str:
    """List open orders for a customer."""
    return f"open orders for {customer_id}"


crm_tools = tool_namespace(
    name="crm",
    description="CRM tools for customer lookups.",
    tools=[get_customer_profile, list_open_orders],
)


agent = Agent(
    name="Operations assistant",
    model="gpt-5.6-sol",
    instructions="Load the crm namespace before using CRM tools.",
    tools=[*crm_tools, ToolSearchTool()],
)

result = await Runner.run(agent, "Look up customer_42 and list their open orders.")
print(result.final_output)

알아둘 사항:

  • 호스티드 툴 검색은 OpenAI Responses 모델에서만 사용할 수 있습니다.
  • 에이전트에 지연 로딩 표면을 구성할 때 ToolSearchTool()을 정확히 하나 추가하세요.
  • 검색 가능한 표면에는 @function_tool(defer_loading=True), tool_namespace(name=..., description=..., tools=[...]), HostedMCPTool(tool_config={..., "defer_loading": True})가 포함됩니다.
  • 지연 로딩 함수 도구는 ToolSearchTool()와 함께 사용해야 합니다. 네임스페이스 전용 설정에서는 모델이 필요할 때 올바른 그룹을 로드할 수 있도록 ToolSearchTool()도 사용할 수 있습니다.
  • tool_namespace()은 FunctionTool 인스턴스를 공유 네임스페이스 이름과 설명 아래에 그룹화합니다. crm, billing, shipping처럼 관련 도구가 많은 경우 일반적으로 가장 적합합니다.
  • OpenAI의 공식 모범 사례 지침은 가능하면 네임스페이스 사용입니다.
  • 가능하면 개별적으로 지연된 여러 함수보다 네임스페이스 또는 호스티드 MCP 서버를 우선 사용하세요. 일반적으로 모델에 더 나은 상위 수준 검색 표면을 제공하고 토큰도 더 많이 절약합니다.
  • 네임스페이스에는 즉시 사용 가능한 도구와 지연된 도구를 함께 포함할 수 있습니다. defer_loading=True가 없는 도구는 계속 즉시 호출할 수 있으며, 동일한 네임스페이스의 지연된 도구는 도구 검색을 통해 로드됩니다.
  • 일반적으로 각 네임스페이스는 비교적 작게 유지하고, 가능하면 함수 수를 10개 미만으로 유지하세요.
  • 이름이 지정된 tool_choice은 단독 네임스페이스 이름이나 지연 전용 도구를 대상으로 지정할 수 없습니다. auto, required 또는 실제 최상위 호출 가능 도구 이름을 사용하는 것이 좋습니다.
  • ToolSearchTool(execution="client")은 수동 Responses 오케스트레이션용입니다. 모델이 클라이언트 실행형 tool_search_call을 내보내면 표준 Runner은 이를 대신 실행하지 않고 예외를 발생시킵니다.
  • 도구 검색 활동은 전용 항목 및 이벤트 유형과 함께 RunResult.new_items 및 RunItemStreamEvent에 표시됩니다.
  • 네임스페이스 기반 로딩과 최상위 지연 도구를 모두 다루는 실행 가능한 전체 예제는 examples/tools/tool_search.py을 참조하세요.
  • 공식 플랫폼 가이드: 도구 검색

프로그래밍 방식 도구 호출

프로그래밍 방식 도구 호출을 사용하면 지원되는 OpenAI Responses 모델이 사용 가능한 도구를 호출하고, 출력을 결합하고, 하나의 결과를 모델에 반환하는 JavaScript를 생성할 수 있습니다. 모든 도구 호출 후에 모델을 왕복하지 않고도 루프, 분기, 병렬 호출 또는 중간 계산의 이점을 활용할 수 있는 범위가 제한된 워크플로에 유용합니다.

생성된 프로그램은 새로운 호스티드 V8 환경에서 실행됩니다. Node.js API, 파일 시스템 또는 네트워크 액세스를 사용할 수 없으며 지속되는 프로세스도 없습니다. 프로그램은 명시적으로 허용한 도구와만 상호작용할 수 있습니다.

from pydantic import BaseModel

from agents import (
    Agent,
    ModelSettings,
    ProgrammaticToolCallingTool,
    Runner,
)
from agents.decorators import tool


class InventoryOutput(BaseModel):
    sku: str
    available_units: int


@tool(allowed_callers=["programmatic"])
def get_inventory(sku: str) -> InventoryOutput:
    return InventoryOutput(sku=sku, available_units=42)


agent = Agent(
    name="Inventory planner",
    model="gpt-5.6",
    model_settings=ModelSettings(tool_choice="programmatic_tool_calling"),
    tools=[get_inventory, ProgrammaticToolCallingTool()],
)

result = Runner.run_sync(agent, "Check inventory for desk-lamp and summarize it.")
print(result.final_output)

알아둘 사항:

  • 프로그래밍 방식 도구 호출은 지원되는 OpenAI Responses 모델에서만 사용할 수 있습니다. ProgrammaticToolCallingTool() 및 tool_choice="programmatic_tool_calling"은 Chat Completions 모델과 Responses가 아닌 백엔드에서 거부됩니다.
  • 에이전트에 ProgrammaticToolCallingTool()을 최대 하나만 추가하세요. 에이전트는 프로그래밍 방식으로 호출 가능한 도구를 하나 이상 노출해야 하며, 네임스페이스, 지연된 함수 또는 지연된 호스티드 MCP 서버를 기반으로 하는 ToolSearchTool()나 불투명한 프롬프트 관리형 도구 표면도 사용할 수 있습니다. 검색 가능한 표면이 없는 단독 ToolSearchTool()은 거부됩니다.
  • allowed_callers은 도구를 호출할 수 있는 방식을 제어합니다. 생략하면 모델의 직접 호출만 허용됩니다. 프로그램 전용 액세스에는 ["programmatic"]을 사용하고, 두 방식 모두 허용하려면 ["direct", "programmatic"]를 사용하세요.
  • 이 기능을 사용하도록 설정할 수 있는 SDK 도구 유형은 FunctionTool, CustomTool, ShellTool, ApplyPatchTool, HostedMCPTool, CodeInterpreterTool입니다. 함수, 사용자 지정, 셸, 패치 적용 도구는 allowed_callers을 직접 노출합니다. 호스티드 MCP 및 Code Interpreter의 경우 tool_config 내부에 allowed_callers을 설정하세요.
  • @function_tool(allowed_callers=[...])의 경우 Pydantic 모델, TypedDict 또는 데이터 클래스와 같은 구조화된 반환 어노테이션은 자동으로 엄격한 객체 출력 스키마가 되며, 반환값은 프로그램에 반환되기 전에 해당 스키마에 대해 검증됩니다. 함수에 사용할 수 있는 어노테이션이 없으면 output_type=...을 사용하고, 엄격한 객체 스키마가 이미 있다면 더 저수준의 우회 수단인 output_json_schema={...}을 사용하세요. output_type와 output_json_schema은 함께 사용할 수 없습니다. str, Any, None의 반환 어노테이션은 출력 스키마를 만들지 않습니다. 스키마를 기반으로 하고 프로그램이 소유하는 호출에서는 자유 형식 텍스트가 출력 스키마를 충족하지 않으므로 기본 실패 포매터가 비활성화됩니다. 따라서 스키마를 준수하는 JSON을 반환하는 사용자 지정 failure_error_function을 제공하지 않으면 핸들러 예외가 전파됩니다.
  • 프로그램이 소유하는 SDK 도구도 일반적인 Runner 수명 주기를 계속 사용합니다. 도구 입력 및 출력 가드레일, 훅, 타임아웃, 동시성 제한, 승인, 세션, RunState 일시 중지/재개 동작이 계속 적용되며, SDK는 각 하위 호출과 프로그램 호출자 간의 관계를 보존합니다.
  • ProgrammaticToolCallingTool()가 있으면 프로그램이 실행되기 전이라도 모델 요청 재시도에 더 엄격한 재실행 안전 경계가 적용됩니다. SDK는 이러한 요청에 대해 제공자 관리형 재시도와 WebSocket 사전 이벤트 재시도를 비활성화합니다. Runner 재시도 정책은 제공자 권고에서 재실행이 안전하다고 명시적으로 표시한 경우에만 재시도합니다. retry_policies.network_error()만으로는 이 경계를 재정의하지 않습니다.
  • 승인이 중요하거나 영향이 큰 도구는 각 작업이 더 큰 프로그램의 일부가 되기 전에 사람이 검토할 수 있도록 직접 호출로 유지하는 것이 일반적으로 더 적합합니다. 프로그램 소유 호출이 승인을 위해 일시 중지되면 RunState을 통해 인터럽션(중단 처리)을 해결하고 평소처럼 원래 실행을 재개하세요.
  • 프로그래밍 방식 도구 호출은 호스티드 툴 검색과 함께 사용할 수 있습니다. 생성된 프로그램이 지연된 도구를 호출하려면 모델이 먼저 해당 도구를 로드해야 합니다.
  • program 항목과 일반적인 프로그램 소유 하위 도구 호출은 ToolCallItem 항목으로 표시됩니다. 일치하는 program_output는 ToolCallOutputItem로 표시됩니다. 호스티드 MCP 승인 요청 및 도구 카탈로그는 대신 특수 MCP 항목과 스트림 이벤트를 사용합니다. 검사에 관한 자세한 내용은 결과 및 스트리밍을 참조하세요.
  • 완전한 동시성 재고 계획 예제는 examples/tools/programmatic_tool_calling.py을 참조하세요.
  • 공식 플랫폼 가이드: 프로그래밍 방식 도구 호출

호스티드 컨테이너 셸 및 스킬

ShellTool은 OpenAI 호스티드 컨테이너 실행도 지원합니다. 로컬 런타임이 아닌 관리형 컨테이너에서 모델이 셸 명령을 실행하도록 하려면 이 모드를 사용하세요.

from agents import Agent, Runner, ShellTool, ShellToolSkillReference

csv_skill: ShellToolSkillReference = {
    "type": "skill_reference",
    "skill_id": "skill_698bbe879adc81918725cbc69dcae7960bc5613dadaed377",
    "version": "1",
}

agent = Agent(
    name="Container shell agent",
    model="gpt-5.6-sol",
    instructions="Use the mounted skill when helpful.",
    tools=[
        ShellTool(
            environment={
                "type": "container_auto",
                "network_policy": {"type": "disabled"},
                "skills": [csv_skill],
            }
        )
    ],
)

result = await Runner.run(
    agent,
    "Use the configured skill to analyze CSV files in /mnt/data and summarize totals by region.",
)
print(result.final_output)

이후 실행에서 기존 컨테이너를 재사용하려면 environment={"type": "container_reference", "container_id": "cntr_..."}을 설정하세요.

알아둘 사항:

  • 호스티드 셸은 Responses API 셸 도구를 통해 사용할 수 있습니다.
  • container_auto는 요청을 위한 컨테이너를 프로비저닝하며, container_reference은 기존 컨테이너를 재사용합니다.
  • container_auto에는 file_ids 및 memory_limit도 포함할 수 있습니다.
  • environment.skills는 스킬 참조 및 인라인 스킬 번들을 허용합니다.
  • 호스티드 환경에서는 ShellTool에 executor, needs_approval, on_approval을 설정하지 마세요.
  • network_policy는 disabled 및 allowlist 모드를 지원합니다.
  • 허용 목록 모드에서는 network_policy.domain_secrets가 이름으로 도메인 범위의 시크릿을 주입할 수 있습니다.
  • 전체 예제는 examples/tools/container_shell_skill_reference.py 및 examples/tools/container_shell_inline_skill.py를 참조하세요.
  • OpenAI 플랫폼 가이드: 셸 및 스킬

로컬 런타임 도구

로컬 런타임 도구는 모델 응답 자체 외부에서 실행됩니다. 모델이 여전히 호출 시점을 결정하지만, 실제 작업은 애플리케이션 또는 구성된 실행 환경에서 수행됩니다.

ComputerTool와 ApplyPatchTool은 항상 사용자가 제공하는 로컬 구현이 필요합니다. ShellTool은 두 모드를 모두 지원합니다. 관리형 실행을 원하면 위의 호스티드 컨테이너 구성을 사용하고, 자체 프로세스에서 명령을 실행하려면 아래의 로컬 런타임 구성을 사용하세요.

로컬 런타임 도구에는 사용자가 구현을 제공해야 합니다.

  • ComputerTool: GUI/브라우저 자동화를 활성화하려면 Computer 또는 AsyncComputer 인터페이스를 구현하세요.
  • ShellTool: 로컬 실행과 호스티드 컨테이너 실행을 모두 지원하는 최신 셸 도구입니다.
  • LocalShellTool: 기존 로컬 셸 통합입니다.
  • ApplyPatchTool: 로컬에서 diff를 적용하려면 ApplyPatchEditor를 구현하세요.
  • 로컬 셸 스킬은 ShellTool(environment={"type": "local", "skills": [...]})와 함께 사용할 수 있습니다.

셸 작업 타임아웃은 유한한 타임아웃에 양의 정수 밀리초를 사용합니다. 0은 실행기 구현 전반에서 이식 가능한 의미를 갖지 않으므로 SDK는 로컬 ShellTool 실행기를 호출하기 전에 0과 None을 모두 명시적 타임아웃 없음으로 처리합니다. 다른 값은 실행기 호출 전에 거부됩니다. 이는 타임아웃 필드에만 해당합니다. max_output_length=0는 캡처된 빈 출력을 요청하는 용도로 계속 지원됩니다.

로컬 셸 및 파일 편집 승인

로컬 ShellTool과 ApplyPatchTool의 기본값은 needs_approval=False입니다. 이 설정에서는 SDK가 승인을 요청하지 않고 실행기 또는 편집기를 호출할 수 있습니다. 구현은 명령이 실행되거나 파일이 변경되는 위치를 결정하고 의도한 리소스 권한 및 격리를 적용해야 합니다. SDK 승인은 샌드박스를 제공하지 않습니다.

검토가 필요한 명령 또는 파일 편집의 경우 도구에 needs_approval=True을 설정하거나, 승인이 필요한 호출에 대해 True를 반환하는 호출 가능한 정책을 제공하세요. on_approval 콜백이 없으면 실행기 또는 편집기를 호출하기 전에 실행이 일시 중지되고, result.interruptions에 대기 중인 요청이 반환됩니다. RunState을 통해 해당 요청을 승인하거나 거부한 다음 휴먼인더루프 가이드에 설명된 대로 실행을 재개하세요.

애플리케이션 코드에서 즉시 결정하려면 needs_approval과 on_approval를 모두 설정하세요. SDK는 호출에 승인이 필요하고 기존 승인 결정이 없는 경우에만 on_approval을 호출합니다. 콜백만 설정해서는 승인이 활성화되지 않습니다. CLI 프롬프트는 examples/tools/shell.py을, 수동 인터럽션(중단 처리) 처리는 examples/tools/shell_human_in_the_loop.py를 참조하세요. 반면 examples/tools/apply_patch.py 예제는 파일을 변경하기 전에 편집기 내부에서 확인을 요청합니다.

로컬 ShellTool 및 ApplyPatchTool에 대한 지속적 결정은 유형과 이름이 같은 다른 에이전트의 도구로 핸드오프할 때나 동일한 RunContextWrapper을 재사용하는 별도 실행 간에 유지될 수 있습니다. 실행기 또는 편집기 권한이 서로 다르면 호출별 결정을 사용하고, 다른 실행 권한으로 새 실행을 시작할 때는 새 래퍼를 사용하세요. 재개 중 호출별 결정과 컨텍스트 재정의가 저장된 승인을 지우지 않는 이유를 포함한 자세한 내용은 승인 범위 경고를 참조하세요.

애플리케이션이 자동 실행을 의도적으로 승인하는 경우(예: 샌드박스 정책을 적용하는 실행기를 사용하는 경우) needs_approval=False을 유지하세요. 호스티드 셸 환경은 SDK의 로컬 needs_approval 또는 on_approval 설정을 지원하지 않습니다.

ComputerTool 및 Responses 컴퓨터 도구

ComputerTool은 여전히 로컬 하네스입니다. 사용자가 Computer 또는 AsyncComputer 구현을 제공하면 SDK가 해당 하네스를 OpenAI Responses API 컴퓨터 표면에 매핑합니다.

Agent가 model를 설정하지 않으면 일반적인 SDK 모델 선택 우선순위가 적용됩니다. 현재 gpt-5.6-luna인 기본 제공 SDK 기본값은 컴퓨터 사용을 지원합니다. OPENAI_DEFAULT_MODEL 또는 RunConfig.model이 해당 기본값을 재정의하는 경우 컴퓨터 사용을 지원하는 모델을 선택하세요. 컴퓨터 사용 워크로드에 대해 다른 기능 및 비용 프로필을 선택하려면 에이전트에 model을 설정하세요. 아래 예제에서는 OpenAI가 GPT-5.6 Sol로 라우팅하는 gpt-5.6 별칭을 사용합니다. 대신 GPT-5.6 Terra 또는 GPT-5.6 Luna처럼 컴퓨터 사용을 지원하는 다른 모델을 선택할 수 있습니다.

gpt-5.6처럼 GA 기본 제공 컴퓨터 도구를 지원하는 모델에 명시적으로 요청하면 SDK가 {"type": "computer"} 페이로드를 전송합니다. 이전 computer-use-preview 모델에 대한 요청에서는 SDK가 계속 미리 보기 페이로드 {"type": "computer_use_preview", "environment": ..., "display_width": ..., "display_height": ...}을 전송합니다. 이는 플랫폼의 computer-use-preview에서 마이그레이션을 따릅니다.

  • 모델: computer-use-preview -> gpt-5.6-sol
  • 도구 선택자: computer_use_preview -> computer
  • 컴퓨터 호출 형태: computer_call당 하나의 action -> computer_call의 일괄 처리된 actions[]
  • 잘림: 미리 보기 경로에서 ModelSettings(truncation="auto") 필수 -> GA 경로에서는 필수 아님

SDK는 실제 Responses 요청의 유효 모델에 따라 해당 전송 형식을 선택합니다. 프롬프트 템플릿을 사용하고 프롬프트가 모델을 소유하므로 요청에서 model를 생략하는 경우, model="gpt-5.6"와 같이 지원되는 GA 모델을 명시하거나 ModelSettings(tool_choice="computer") 또는 ModelSettings(tool_choice="computer_use")로 GA 선택자를 강제하지 않는 한 SDK는 미리 보기 호환 컴퓨터 페이로드를 유지합니다.

ComputerTool이 있는 경우 tool_choice="computer", "computer_use", "computer_use_preview"이 모두 허용되며 유효 요청 모델에 맞는 기본 제공 선택자로 정규화됩니다. ComputerTool가 없으면 이러한 문자열은 계속 일반 함수 이름처럼 동작합니다.

ComputerTool이 ComputerProvider 팩토리를 기반으로 하는 경우 이 차이가 중요합니다. GA computer 페이로드는 직렬화 시점에 environment 또는 크기가 필요하지 않으므로 팩토리가 Computer 또는 AsyncComputer 인스턴스를 생성하기 전에 직렬화할 수 있습니다. 미리 보기 호환 직렬화에는 SDK가 environment, display_width, display_height을 전송할 수 있도록 확인된 Computer 또는 AsyncComputer 인스턴스가 여전히 필요합니다.

런타임에서는 두 경로 모두 동일한 로컬 하네스를 계속 사용합니다. 미리 보기 응답은 단일 action가 포함된 computer_call 항목을 내보냅니다. GA 응답은 일괄 처리된 actions[]을 내보낼 수 있으며, SDK는 computer_call_output 스크린샷 항목을 생성하기 전에 이를 순서대로 실행합니다. 실행 가능한 Playwright 기반 하네스는 examples/tools/computer_use.py을 참조하세요.

from agents import Agent, ApplyPatchTool, ComputerTool, ShellTool
from agents.computer import AsyncComputer
from agents.editor import ApplyPatchResult, ApplyPatchOperation, ApplyPatchEditor


class NoopComputer(AsyncComputer):
    environment = "browser"
    dimensions = (1024, 768)

    async def screenshot(self):
        return ""

    async def click(self, x, y, button): ...
    async def double_click(self, x, y): ...
    async def scroll(self, x, y, scroll_x, scroll_y): ...
    async def type(self, text): ...
    async def wait(self): ...
    async def move(self, x, y): ...
    async def keypress(self, keys): ...
    async def drag(self, path): ...


class NoopEditor(ApplyPatchEditor):
    async def create_file(self, op: ApplyPatchOperation):
        return ApplyPatchResult(status="completed")

    async def update_file(self, op: ApplyPatchOperation):
        return ApplyPatchResult(status="completed")

    async def delete_file(self, op: ApplyPatchOperation):
        return ApplyPatchResult(status="completed")


async def run_shell(request):
    return "shell output"


agent = Agent(
    name="Local tools agent",
    tools=[
        ShellTool(executor=run_shell),
        ApplyPatchTool(editor=NoopEditor()),
        ComputerTool(computer=NoopComputer()),
    ],
    # Optional: omit this argument to use the configured or built-in default model.
    model="gpt-5.6",
)

대기 중인 컴퓨터 안전 검사

Responses API는 애플리케이션이 검토해야 할 문제를 표시하기 위해 computer_call에 pending_safety_checks를 포함할 수 있습니다. 각 검사에는 문제 유형을 설명하고 세부 정보를 제공하는 id과 선택적 code 및 message 필드가 있습니다. 이러한 검사는 API에서 제공되며 Agents SDK는 이를 콜백에 전달합니다. pending_safety_checks 및 acknowledged_safety_checks에 대해서는 Responses API 참조를, 애플리케이션 수준의 예방 조치에 대해서는 컴퓨터 사용 안전 지침을 참조하세요.

표시된 컴퓨터 호출을 계속 진행할지 결정하려면 ComputerTool.on_safety_check을 구성하세요. SDK는 호출에 대기 중인 검사가 포함된 경우에만 호출 작업을 실행하기 전에 이 콜백을 호출합니다.

콜백은 한 번에 하나의 ComputerToolSafetyCheckData을 받습니다. 해당 검사를 확인하려면 True을 반환하세요. False를 반환하면 호출 작업이나 스크린샷이 실행되기 전에 UserError가 발생합니다. 콜백이 구성된 경우 SDK는 보고된 모든 검사를 확인하도록 요구합니다. 콜백은 동기식 또는 비동기식일 수 있습니다.

on_safety_check을 생략하면 SDK는 검사를 확인하지 않은 상태로 실행을 계속합니다. SDK는 사람에게 자동으로 확인을 요청하지 않습니다. 애플리케이션에서 표시된 호출을 검토해야 하는 경우 콜백을 명시적으로 구성하세요. 예를 들어 다음과 같은 보수적 정책은 표시된 모든 호출을 거부합니다.

from agents import AsyncComputer, Computer, ComputerTool
from agents.tool import ComputerToolSafetyCheckData


def reject_flagged_call(data: ComputerToolSafetyCheckData) -> bool:
    return False


def computer_tool_with_safety_checks(computer: Computer | AsyncComputer) -> ComputerTool:
    return ComputerTool(computer=computer, on_safety_check=reject_flagged_call)

검토된 호출을 허용하려면 reject_flagged_call를 애플리케이션 검토자에게 data.safety_check 및 제안된 data.tool_call를 제시하고, 결정을 기다린 후 해당 결정을 반환하는 콜백으로 바꾸세요. 알 수 없는 검사 코드도 검토가 필요한 것으로 처리하세요.

대기 중인 검사가 없는 컴퓨터 호출은 이 콜백을 호출하지 않습니다. 모든 컴퓨터 작업에 적용해야 하는 정책은 컴퓨터 하네스에서 적용하세요. 사람의 결정을 수집하려면 콜백이 해당 상호작용을 마련하고 결정을 반환해야 합니다. SDK는 RunResult.interruptions를 채우지 않으며 휴먼인더루프에 설명된 일시 중지 및 재개 흐름을 사용하지 않습니다.

함수 도구

모든 Python 함수를 도구로 사용할 수 있습니다. Agents SDK가 도구를 자동으로 설정합니다.

  • 도구 이름은 Python 함수의 이름이 됩니다(또는 이름을 직접 제공할 수 있습니다)
  • 도구 설명은 함수의 docstring에서 가져옵니다(또는 설명을 직접 제공할 수 있습니다)
  • 함수 입력 스키마는 함수의 인수로부터 자동 생성됩니다
  • 비활성화하지 않는 한 각 입력의 설명은 함수의 docstring에서 가져옵니다

@tool으로 생성한 도구는 읽기 전용 __wrapped__ 속성을 통해 원래 Python 호출 가능 객체를 노출합니다. 이는 검사와 테스트에 유용하지만, 직접 호출하면 스키마 검증, 컨텍스트 주입, 가드레일, 타임아웃, 실패 처리, 트레이싱을 포함한 도구 런타임 파이프라인을 우회합니다. 직접 생성한 FunctionTool 인스턴스는 __wrapped__를 노출하지 않습니다.

함수 시그니처를 추출하기 위해 Python의 inspect 모듈을 사용하고, docstring을 파싱하기 위해 griffe를, 스키마 생성을 위해 pydantic를 함께 사용합니다.

OpenAI Responses 모델을 사용하는 경우 @function_tool(defer_loading=True)은 ToolSearchTool()가 함수 도구를 로드할 때까지 해당 도구를 숨깁니다. tool_namespace()를 사용하여 관련 함수 도구를 그룹화할 수도 있습니다. 전체 설정과 제약 조건은 호스티드 툴 검색을 참조하세요.

import json

from typing_extensions import TypedDict, Any

from agents import Agent, FunctionTool, RunContextWrapper
from agents.decorators import tool


class Location(TypedDict):
    lat: float
    long: float


@tool  # (1)!
async def fetch_weather(location: Location) -> str:
    # (2)!
    """Fetch the weather for a given location.

    Args:
        location: The location to fetch the weather for.
    """
    # In real life, we'd fetch the weather from a weather API
    return "sunny"


@tool(name_override="fetch_data")  # (3)!
def read_file(ctx: RunContextWrapper[Any], path: str, directory: str | None = None) -> str:
    """Read the contents of a file.

    Args:
        path: The path to the file to read.
        directory: The directory to read the file from.
    """
    # In real life, we'd read the file from the file system
    return "<file contents>"


agent = Agent(
    name="Assistant",
    tools=[fetch_weather, read_file],  # (4)!
)

for tool in agent.tools:
    if isinstance(tool, FunctionTool):
        print(tool.name)
        print(tool.description)
        print(json.dumps(tool.params_json_schema, indent=2))
        print()
  1. 모든 Python 유형을 함수의 인수로 사용할 수 있으며, 함수는 동기식 또는 비동기식일 수 있습니다.
  2. docstring이 있는 경우 설명 및 인수 설명을 가져오는 데 사용됩니다.
  3. 함수는 선택적으로 실행 컨텍스트를 첫 번째 인수로 받을 수 있습니다. 도구 이름, 설명, 사용할 docstring 스타일 등의 재정의도 설정할 수 있습니다.
  4. 데코레이트된 함수를 도구 목록에 전달할 수 있습니다.
출력 펼쳐 보기
fetch_weather
Fetch the weather for a given location.
{
"$defs": {
  "Location": {
    "properties": {
      "lat": {
        "title": "Lat",
        "type": "number"
      },
      "long": {
        "title": "Long",
        "type": "number"
      }
    },
    "required": [
      "lat",
      "long"
    ],
    "title": "Location",
    "type": "object"
  }
},
"properties": {
  "location": {
    "$ref": "#/$defs/Location",
    "description": "The location to fetch the weather for."
  }
},
"required": [
  "location"
],
"title": "fetch_weather_args",
"type": "object"
}

fetch_data
Read the contents of a file.
{
"properties": {
  "path": {
    "description": "The path to the file to read.",
    "title": "Path",
    "type": "string"
  },
  "directory": {
    "anyOf": [
      {
        "type": "string"
      },
      {
        "type": "null"
      }
    ],
    "default": null,
    "description": "The directory to read the file from.",
    "title": "Directory"
  }
},
"required": [
  "path"
],
"title": "fetch_data_args",
"type": "object"
}

함수 도구의 이미지 또는 파일 반환

텍스트 출력뿐 아니라 하나 이상의 이미지 또는 파일을 함수 도구의 출력으로 반환할 수 있습니다. 다음 중 하나를 반환하면 됩니다.

사용자 지정 함수 도구

Python 함수를 도구로 사용하지 않으려는 경우도 있습니다. 원하는 경우 FunctionTool를 직접 생성할 수 있습니다. 다음을 제공해야 합니다.

  • name
  • description
  • 인수에 대한 JSON 스키마인 params_json_schema
  • ToolContext와 JSON 문자열 형식의 인수를 받아 도구 출력(예: 텍스트, 구조화된 도구 출력 객체 또는 출력 목록)을 반환하는 비동기 함수인 on_invoke_tool
from typing import Any

from pydantic import BaseModel

from agents import RunContextWrapper, FunctionTool


def do_some_work(data: str) -> str:
    return "done"


class FunctionArgs(BaseModel):
    username: str
    age: int


async def run_function(ctx: RunContextWrapper[Any], args: str) -> str:
    parsed = FunctionArgs.model_validate_json(args)
    return do_some_work(data=f"{parsed.username} is {parsed.age} years old")


tool = FunctionTool(
    name="process_user",
    description="Processes extracted user data",
    params_json_schema=FunctionArgs.model_json_schema(),
    on_invoke_tool=run_function,
)

인수 및 docstring 자동 파싱

앞서 언급했듯이 도구의 스키마를 추출하기 위해 함수 시그니처를 자동으로 파싱하고, 도구와 개별 인수의 설명을 추출하기 위해 docstring을 파싱합니다. 관련 참고 사항은 다음과 같습니다.

  1. 시그니처 파싱은 inspect 모듈을 통해 수행됩니다. 타입 어노테이션을 사용하여 인수의 유형을 파악하고 전체 스키마를 나타내는 Pydantic 모델을 동적으로 빌드합니다. Python 기본 유형, Pydantic 모델, TypedDict 등 대부분의 유형을 지원합니다.
  2. docstring 파싱에는 griffe를 사용합니다. 지원되는 docstring 형식은 google, sphinx, numpy입니다. docstring 형식을 자동으로 감지하려고 하지만 최선형 방식이므로 function_tool을 호출할 때 명시적으로 설정할 수 있습니다. use_docstring_info를 False로 설정하여 docstring 파싱을 비활성화할 수도 있습니다. Google 스타일 docstring의 경우 파서는 요약 텍스트 바로 다음에 빈 줄 없이 나오는 Args:, Arguments:, Params:, Parameters: 섹션도 허용합니다.

스키마 추출 코드는 agents.function_schema에 있습니다.

Pydantic Field를 통한 인수 제약 및 설명

Pydantic의 Field를 사용하여 도구 인수에 제약 조건(예: 숫자의 최솟값/최댓값, 문자열의 길이 또는 패턴)과 설명을 추가할 수 있습니다. Pydantic과 마찬가지로 기본값 기반 형식(arg: int = Field(..., ge=1))과 Annotated 형식(arg: Annotated[int, Field(..., ge=1)])을 모두 지원합니다. 생성되는 JSON 스키마와 검증에 이러한 제약 조건이 포함됩니다.

가변 매개변수의 경우 어노테이션은 수집되는 각 값을 설명합니다. 따라서 SDK는 *args 또는 **kwargs을 통해 제공된 각 값에 Annotated[..., Field(...)] 제약 조건을 적용하지만, 생략된 가변 매개변수는 유효한 빈 컬렉션으로 유지됩니다.

SDK는 가변 매개변수(*args 또는 **kwargs)의 어노테이션에서 Field(description=...)을 무시합니다. 수집되는 매개변수를 설명하려면 함수 docstring의 매개변수 항목이나 Annotated의 문자열(예: *scores: Annotated[int, "Exam scores", Field(ge=0, le=100)])을 사용하세요. docstring 파싱이 활성화되어 있고 두 소스 모두 설명을 제공하면 docstring 설명이 우선합니다.

**kwargs의 경우 @tool(strict_mode=False)를 사용하고 매개변수 이름을 딴 중첩 객체에 키워드 값을 제공하세요. 예를 들어 **scores: int가 있는 도구는 {"scores": {"exam": 90}}을 받습니다.

스칼라 위치 값을 *args: T로 어노테이션하세요. 각 위치 값 자체가 동종 튜플이라면 *args: tuple[T, ...]을 사용하세요. 고정된 하나의 튜플 형태로는 가변 위치 값 시퀀스를 설명할 수 없으므로 SDK는 *args: tuple[int, str]와 같은 고정 길이 튜플 어노테이션을 거부합니다.

from typing import Annotated
from pydantic import Field
from agents.decorators import tool


# Default-based form
@tool
def score_a(score: int = Field(..., ge=0, le=100, description="Score from 0 to 100")) -> str:
    return f"Score recorded: {score}"


# Annotated form
@tool
def score_b(
    score: Annotated[int, Field(..., ge=0, le=100, description="Score from 0 to 100")],
) -> str:
    return f"Score recorded: {score}"

함수 도구 타임아웃

@function_tool(timeout=...)을 사용하여 비동기 함수 도구에 호출별 타임아웃을 설정할 수 있습니다.

import asyncio
from agents import Agent
from agents.decorators import tool


@tool(timeout=2.0)
async def slow_lookup(query: str) -> str:
    await asyncio.sleep(10)
    return f"Result for {query}"


agent = Agent(
    name="Timeout demo",
    instructions="Use tools when helpful.",
    tools=[slow_lookup],
)

타임아웃에 도달하면 기본 동작은 timeout_behavior="error_as_result"이며, 모델에 표시되는 타임아웃 메시지(예: Tool 'slow_lookup' timed out after 2 seconds.)를 전송합니다.

타임아웃 처리를 제어할 수 있습니다.

  • timeout_behavior="error_as_result"(기본값): 모델이 복구할 수 있도록 타임아웃 메시지를 반환합니다.
  • timeout_behavior="raise_exception": ToolTimeoutError를 발생시키고 실행을 실패 처리합니다.
  • timeout_error_function=...: error_as_result을 사용할 때 타임아웃 메시지를 사용자 지정합니다.
import asyncio
from agents import Agent, Runner, ToolTimeoutError
from agents.decorators import tool


@tool(timeout=1.5, timeout_behavior="raise_exception")
async def slow_tool() -> str:
    await asyncio.sleep(5)
    return "done"


agent = Agent(name="Timeout hard-fail", tools=[slow_tool])

try:
    await Runner.run(agent, "Run the tool")
except ToolTimeoutError as e:
    print(f"{e.tool_name} timed out in {e.timeout_seconds} seconds")

Note

타임아웃 구성은 비동기 @function_tool 핸들러에만 지원됩니다.

함수 도구의 오류 처리

@function_tool를 통해 함수 도구를 생성할 때 failure_error_function을 전달할 수 있습니다. 이는 도구 호출이 중단될 경우 LLM에 오류 응답을 제공하는 함수입니다.

  • 기본적으로(아무것도 전달하지 않으면) 오류가 발생했음을 LLM에 알리는 default_tool_error_function을 실행합니다.
  • 자체 오류 함수를 전달하면 대신 해당 함수를 실행하고 응답을 LLM에 전송합니다.
  • None를 명시적으로 전달하면 모든 도구 호출 오류가 다시 발생하므로 직접 처리할 수 있습니다. 모델이 잘못된 JSON을 생성한 경우 ModelBehaviorError일 수 있고, 코드가 중단된 경우 UserError일 수 있습니다.
from agents import RunContextWrapper
from agents.decorators import tool
from typing import Any


def my_custom_error_function(context: RunContextWrapper[Any], error: Exception) -> str:
    """A custom function to provide a user-friendly error message."""
    print(f"A tool call failed with the following error: {error}")
    return "An internal server error occurred. Please try again later."


@tool(failure_error_function=my_custom_error_function)
def get_user_profile(user_id: str) -> str:
    """Fetches a user profile from a mock API.
    This function demonstrates a 'flaky' or failing API call.
    """
    if user_id == "user_123":
        return "User profile for user_123 successfully retrieved."
    else:
        raise ValueError(
            f"Could not retrieve profile for user_id: {user_id}. API returned an error."
        )

FunctionTool 객체를 수동으로 생성하는 경우 on_invoke_tool 함수 내부에서 오류를 처리해야 합니다.

Agents as tools

일부 워크플로에서는 제어권을 핸드오프하는 대신 중앙 에이전트가 전문 에이전트 네트워크를 오케스트레이션하도록 할 수 있습니다. 에이전트를 도구로 모델링하여 이를 구현할 수 있습니다.

import asyncio

from agents import Agent, Runner

spanish_agent = Agent(
    name="Spanish agent",
    instructions="You translate the user's message to Spanish",
)

french_agent = Agent(
    name="French agent",
    instructions="You translate the user's message to French",
)

orchestrator_agent = Agent(
    name="orchestrator_agent",
    instructions=(
        "You are a translation agent. You use the tools given to you to translate. "
        "If asked for multiple translations, you call the relevant tools."
    ),
    tools=[
        spanish_agent.as_tool(
            tool_name="translate_to_spanish",
            tool_description="Translate the user's message to Spanish",
        ),
        french_agent.as_tool(
            tool_name="translate_to_french",
            tool_description="Translate the user's message to French",
        ),
    ],
)


async def main():
    result = await Runner.run(orchestrator_agent, input="Say 'Hello, how are you?' in Spanish.")
    print(result.final_output)


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

도구 에이전트 사용자 지정

agent.as_tool은 에이전트를 도구로 변환하는 편의 메서드입니다. max_turns, run_config, hooks, previous_response_id, conversation_id, session, needs_approval와 같은 일반적인 런타임 옵션을 지원합니다. 또한 parameters, input_builder, include_input_schema을 사용하는 구조화된 입력도 지원합니다.

상태 옵션은 도구 호출에 의해 시작되는 중첩 에이전트 실행을 구성합니다. 상위 실행의 대화 상태는 자동으로 상속되지 않습니다. 상위 실행과 중첩 실행 간에 클라이언트 관리형 기록을 공유하려면 동일한 session을 양쪽에 명시적으로 전달하세요. Runner.run와 마찬가지로 중첩 실행에는 하나의 상태 전략을 선택하세요. 클라이언트 관리형 session 또는 previous_response_id이나 conversation_id를 통한 서버 관리형 연속 실행 중 하나를 사용해야 합니다.

from agents.decorators import tool


@tool
async def run_my_agent() -> str:
    """A tool that runs the agent with custom configs"""

    agent = Agent(name="My agent", instructions="...")

    result = await Runner.run(agent, input="...", max_turns=5, run_config=...)

    return str(result.final_output)

도구 에이전트의 구조화된 입력

기본적으로 Agent.as_tool()은 문자열 필드 하나인 input({"input": "..."})가 포함된 객체를 기대하지만, parameters(Pydantic 모델 유형 또는 데이터 클래스 유형)을 전달하여 구조화된 스키마를 노출할 수 있습니다.

추가 옵션:

  • include_input_schema=True은 생성되는 중첩 입력에 전체 JSON Schema를 포함합니다.
  • input_builder=...을 사용하면 구조화된 도구 인수가 중첩 에이전트 입력으로 변환되는 방식을 완전히 사용자 지정할 수 있습니다.
  • RunContextWrapper.tool_input에는 중첩 실행 컨텍스트 내에서 파싱된 구조화 페이로드가 포함됩니다.
from pydantic import BaseModel, Field


class TranslationInput(BaseModel):
    text: str = Field(description="Text to translate.")
    source: str = Field(description="Source language.")
    target: str = Field(description="Target language.")


translator_tool = translator_agent.as_tool(
    tool_name="translate_text",
    tool_description="Translate text between languages.",
    parameters=TranslationInput,
    include_input_schema=True,
)

실행 가능한 전체 예제는 examples/agent_patterns/agents_as_tools_structured.py을 참조하세요.

도구 에이전트의 승인 게이트

Agent.as_tool(..., needs_approval=...)은 function_tool와 동일한 승인 흐름을 사용합니다. 승인이 필요하면 실행이 일시 중지되고 대기 중인 항목이 result.interruptions에 표시됩니다. 그런 다음 result.to_state()를 사용하고 state.approve(...) 또는 state.reject(...)을 호출한 후 실행을 재개하세요. 전체 일시 중지/재개 패턴은 휴먼인더루프 가이드를 참조하세요.

사용자 지정 출력 추출

경우에 따라 도구 에이전트의 출력을 중앙 에이전트에 반환하기 전에 수정할 수 있습니다. 다음과 같은 경우 유용할 수 있습니다.

  • 하위 에이전트의 채팅 기록에서 특정 정보(예: JSON 페이로드) 추출
  • 에이전트의 최종 답변 변환 또는 형식 변경(예: Markdown을 일반 텍스트 또는 CSV로 변환)
  • 출력 검증 또는 에이전트 응답이 누락되거나 형식이 잘못된 경우 대체 값 제공

as_tool 메서드에 custom_output_extractor 인수를 제공하여 이를 수행할 수 있습니다.

async def extract_json_payload(run_result: RunResult) -> str:
    # Scan the agent’s outputs in reverse order until we find a JSON-like message from a tool call.
    for item in reversed(run_result.new_items):
        if isinstance(item, ToolCallOutputItem) and item.output.strip().startswith("{"):
            return item.output.strip()
    # Fallback to an empty JSON object if nothing was found
    return "{}"


json_tool = data_agent.as_tool(
    tool_name="get_data_json",
    tool_description="Run the data agent and return only its JSON payload",
    custom_output_extractor=extract_json_payload,
)

사용자 지정 추출기 내에서 중첩된 RunResult는 agent_tool_invocation도 노출합니다. 이는 중첩 결과를 후처리할 때 외부 도구 이름, 호출 ID 또는 raw 인수가 필요한 경우 유용합니다. 결과 가이드를 참조하세요.

중첩 에이전트 실행 스트리밍

as_tool에 on_stream 콜백을 전달하면 중첩 에이전트가 내보내는 스트리밍 이벤트를 수신하면서 스트림이 완료된 후 최종 출력도 반환할 수 있습니다.

from agents import AgentToolStreamEvent


async def handle_stream(event: AgentToolStreamEvent) -> None:
    # Inspect the underlying StreamEvent along with agent metadata.
    print(f"[stream] {event['agent'].name} :: {event['event'].type}")


billing_agent_tool = billing_agent.as_tool(
    tool_name="billing_helper",
    tool_description="Answer billing questions.",
    on_stream=handle_stream,  # Can be sync or async.
)

예상 동작:

  • 이벤트 유형은 StreamEvent["type"]을 따릅니다. raw_response_event, run_item_stream_event, agent_updated_stream_event
  • on_stream을 제공하면 중첩 에이전트가 자동으로 스트리밍 모드에서 실행되며, 최종 출력을 반환하기 전에 스트림을 모두 소비합니다.
  • 핸들러는 동기식 또는 비동기식일 수 있으며, 각 이벤트는 도착하는 순서대로 전달됩니다.
  • 모델 도구 호출을 통해 도구가 호출되면 tool_call이 존재합니다. 직접 호출에서는 None일 수 있습니다.
  • 실행 가능한 전체 샘플은 examples/agent_patterns/agents_as_tools_streaming.py을 참조하세요.

조건부 도구 활성화

is_enabled 매개변수를 사용하여 런타임에 에이전트 도구를 조건부로 활성화하거나 비활성화할 수 있습니다. 이를 통해 컨텍스트, 사용자 기본 설정 또는 런타임 조건에 따라 LLM에서 사용할 수 있는 도구를 동적으로 필터링할 수 있습니다.

import asyncio
from agents import Agent, AgentBase, Runner, RunContextWrapper
from pydantic import BaseModel


class LanguageContext(BaseModel):
    language_preference: str = "french_spanish"


def french_enabled(ctx: RunContextWrapper[LanguageContext], agent: AgentBase) -> bool:
    """Enable French for French+Spanish preference."""
    return ctx.context.language_preference == "french_spanish"


# Create specialized agents
spanish_agent = Agent(
    name="spanish_agent",
    instructions="You respond in Spanish. Always reply to the user's question in Spanish.",
)

french_agent = Agent(
    name="french_agent",
    instructions="You respond in French. Always reply to the user's question in French.",
)

# Create orchestrator with conditional tools
orchestrator = Agent(
    name="orchestrator",
    instructions=(
        "You are a multilingual assistant. You use the tools given to you to respond to users. "
        "You must call ALL available tools to provide responses in different languages. "
        "You never respond in languages yourself, you always use the provided tools."
    ),
    tools=[
        spanish_agent.as_tool(
            tool_name="respond_spanish",
            tool_description="Respond to the user's question in Spanish",
            is_enabled=True,  # Always enabled
        ),
        french_agent.as_tool(
            tool_name="respond_french",
            tool_description="Respond to the user's question in French",
            is_enabled=french_enabled,
        ),
    ],
)


async def main():
    context = LanguageContext(language_preference="french_spanish")
    result = await Runner.run(orchestrator, "How are you?", context=context)
    print(result.final_output)


asyncio.run(main())

is_enabled 매개변수는 다음을 허용합니다.

  • 불리언 값: True(항상 활성화) 또는 False(항상 비활성화)
  • 호출 가능 함수: (context, agent)를 받아 불리언을 반환하는 함수
  • 비동기 함수: 복잡한 조건부 로직을 위한 비동기 함수

비활성화된 도구는 런타임에 LLM에서 완전히 숨겨지므로 다음과 같은 경우에 유용합니다.

  • 요청 범위의 기능 표시 여부
  • 환경별 도구 가용성(개발 환경과 프로덕션 환경)
  • 다양한 도구 구성의 A/B 테스트
  • 런타임 상태에 따른 동적 도구 필터링

로컬로 구성된 함수 도구의 경우 Runner는 호출 전에 is_enabled도 다시 평가합니다. 그러나 is_enabled은 표시 여부와 디스패치를 제어할 뿐, 도구 인수 또는 액세스하는 리소스에 따라 달라지는 권한 부여를 대체하지 않습니다. 이러한 검사는 도구 구현 내부에서 적용하거나, 적절한 경우 도구 입력 가드레일과 승인을 사용하세요. MCP 서버는 자체적으로 보호되는 작업에 권한을 부여해야 합니다.

함수 도구, MCP 도구 및 핸드오프 전반에 하나의 애플리케이션 정책을 적용하는 패턴은 컨텍스트 관리를 참조하세요.

실험적 기능: Codex 도구

codex_tool은 에이전트가 도구 호출 중 워크스페이스 범위의 작업(셸, 파일 편집, MCP 도구)을 실행할 수 있도록 Codex CLI를 래핑합니다. 이 표면은 실험적 기능이며 변경될 수 있습니다.

메인 에이전트가 현재 실행을 벗어나지 않고 범위가 제한된 워크스페이스 작업을 Codex에 위임하도록 하려면 사용하세요. 기본 도구 이름은 codex입니다. 사용자 지정 이름을 설정하는 경우 codex이거나 codex_로 시작해야 합니다. 에이전트에 여러 Codex 도구가 포함된 경우 각각 고유한 이름을 사용해야 합니다.

from agents import Agent
from agents.extensions.experimental.codex import ThreadOptions, TurnOptions, codex_tool

agent = Agent(
    name="Codex Agent",
    instructions="Use the codex tool to inspect the workspace and answer the question.",
    tools=[
        codex_tool(
            sandbox_mode="workspace-write",
            working_directory="/path/to/repo",
            default_thread_options=ThreadOptions(
                model="gpt-5.5",
                model_reasoning_effort="low",
                network_access_enabled=True,
                web_search_mode="disabled",
                approval_policy="never",
            ),
            default_turn_options=TurnOptions(
                idle_timeout_seconds=60,
            ),
            persist_session=True,
        )
    ],
)

다음 옵션 그룹부터 시작하세요.

  • 실행 표면: sandbox_mode와 working_directory은 Codex가 작업할 수 있는 위치를 정의합니다. 두 옵션을 함께 사용하고, 작업 디렉터리가 Git 저장소 내부에 없으면 skip_git_repo_check=True를 설정하세요.
  • 스레드 기본값: default_thread_options=ThreadOptions(...)는 모델, 추론 노력, 승인 정책, 추가 디렉터리, 네트워크 액세스, 웹 검색 모드를 구성합니다. 기존 web_search_enabled보다 web_search_mode을 우선 사용하세요.
  • 턴 기본값: default_turn_options=TurnOptions(...)은 idle_timeout_seconds 및 선택적 취소 signal과 같은 턴별 동작을 구성합니다.
  • 도구 I/O: 도구 호출에는 { "type": "text", "text": ... } 또는 { "type": "local_image", "path": ... }이 있는 inputs 항목을 하나 이상 포함해야 합니다. output_schema를 사용하면 구조화된 Codex 응답을 요구할 수 있습니다.

스레드 재사용과 지속성은 별도의 제어 항목입니다.

  • persist_session=True는 동일한 도구 인스턴스에 대한 반복 호출에 하나의 Codex 스레드를 재사용합니다.
  • use_run_context_thread_id=True은 동일한 가변 컨텍스트 객체를 공유하는 여러 실행에서 스레드 ID를 실행 컨텍스트에 저장하고 재사용합니다.
  • 스레드 ID 우선순위는 호출별 thread_id, 실행 컨텍스트 스레드 ID(활성화된 경우), 구성된 thread_id 옵션 순입니다.
  • 기본 실행 컨텍스트 키는 name="codex"의 경우 codex_thread_id이고, name="codex_<suffix>"의 경우 codex_thread_id_<suffix>입니다. run_context_thread_id_key으로 재정의할 수 있습니다.

런타임 구성:

  • 인증: CODEX_API_KEY(권장) 또는 OPENAI_API_KEY를 설정하거나 codex_options={"api_key": "..."}을 전달하세요.
  • 런타임: codex_options.base_url은 CLI 기본 URL을 재정의합니다.
  • 바이너리 확인: CLI 경로를 고정하려면 codex_options.codex_path_override 또는 CODEX_PATH를 설정하세요. 그렇지 않으면 SDK는 PATH에서 codex을 확인한 다음 번들로 제공되는 벤더 바이너리를 사용합니다.
  • 환경: codex_options.env는 하위 프로세스 환경을 완전히 제어합니다. 이 옵션이 제공되면 하위 프로세스는 os.environ을 상속하지 않습니다.
  • 스트림 제한: codex_options.codex_subprocess_stream_limit_bytes 또는 OPENAI_AGENTS_CODEX_SUBPROCESS_STREAM_LIMIT_BYTES는 stdout/stderr 리더 제한을 제어합니다. 유효 범위는 65536부터 67108864까지이며 기본값은 8388608입니다.
  • 스트리밍: on_stream는 스레드/턴 수명 주기 이벤트와 항목 이벤트(reasoning, command_execution, mcp_tool_call, file_change, web_search, todo_list, error 항목 업데이트)를 수신합니다.
  • 출력: 결과에는 response, usage, thread_id가 포함되며 사용량은 RunContextWrapper.usage에 추가됩니다.

참조: