도구
도구는 에이전트가 데이터를 가져오고, 외부 API를 호출하고, 코드를 실행하거나, 심지어 컴퓨터를 사용하는 등 행동을 취할 수 있게 합니다. JavaScript/TypeScript SDK는 여섯 가지 카테고리를 지원합니다:
- OpenAI 호스티드 도구 – OpenAI 서버에서 모델과 함께 실행됨. (웹 검색, 파일 검색, 코드 인터프리터, 이미지 생성)
- 로컬 내장 도구 – 당신의 환경에서 실행됨. (컴퓨터 사용, shell, apply_patch)
- 함수 도구 – 어떤 로컬 함수든 JSON 스키마로 감싸 LLM이 호출할 수 있게 함
- Agents as tools – 전체 에이전트를 호출 가능한 도구로 노출
- MCP 서버 – Model Context Protocol 서버(로컬 또는 원격) 연결
- 실험적: Codex 도구 – Codex SDK를 함수 도구로 감싸 작업공간 인지 작업을 실행
도구 카테고리
섹션 제목: “도구 카테고리”이 문서의 나머지 부분에서는 각 도구 카테고리를 다룬 다음, 범용적인 도구 선택 및 프롬프트 작성 가이드를 요약합니다.
1. 호스티드 도구 (OpenAI Responses API)
섹션 제목: “1. 호스티드 도구 (OpenAI Responses API)”OpenAIResponsesModel을 사용할 때 다음 내장 도구를 추가할 수 있습니다:
| Tool | Type string | Purpose |
|---|---|---|
| Web search | 'web_search' | Internet search. |
| File / retrieval search | 'file_search' | Query vector stores hosted on OpenAI. |
| Code Interpreter | 'code_interpreter' | Run code in a sandboxed environment. |
| Image generation | 'image_generation' | Generate images based on text. |
import { Agent, codeInterpreterTool, fileSearchTool, imageGenerationTool, webSearchTool,} from '@openai/agents';
const agent = new Agent({ name: 'Travel assistant', tools: [ webSearchTool({ searchContextSize: 'medium' }), fileSearchTool('VS_ID', { maxNumResults: 3 }), codeInterpreterTool(), imageGenerationTool({ size: '1024x1024' }), ],});SDK는 호스티드 도구 정의를 반환하는 헬퍼 함수를 제공합니다:
| Helper function | Notes |
|---|---|
webSearchTool(options?) | searchContextSize, userLocation, filters.allowedDomains 같은 JS 친화적 옵션을 지원 |
fileSearchTool(ids, options?) | 첫 번째 인자로 하나 이상의 벡터 스토어 ID를 받고, maxNumResults, includeSearchResults, rankingOptions 및 필터 같은 옵션을 추가로 수용 |
codeInterpreterTool(options?) | container가 제공되지 않으면 자동 관리 컨테이너를 기본값으로 사용 |
imageGenerationTool(options?) | model, size, quality, background, inputFidelity, inputImageMask, moderation, outputCompression, partialImages 및 출력 형식 등의 이미지 생성 설정을 지원 |
이 헬퍼들은 JavaScript/TypeScript 친화적 옵션 이름을 기본 OpenAI Responses API 도구 페이로드로 매핑합니다. 전체 도구 스키마와 ranking 옵션 또는 semantic 필터 같은 고급 옵션은 OpenAI 공식 문서를 참고하세요.
2. 로컬 내장 도구
섹션 제목: “2. 로컬 내장 도구”로컬 내장 도구는 여러분의 환경에서 실행되며 구현을 제공해야 합니다:
- 컴퓨터 사용 –
Computer인터페이스를 구현하고computerTool()에 전달 - Shell – 로컬
Shell구현을 제공하거나 호스티드 컨테이너 환경을 구성 - Apply patch –
Editor인터페이스를 구현하고applyPatchTool()에 전달
Computer 및 apply-patch 도구는 로컬에서 실행되며 OpenAI가 호스트하지 않습니다. Shell 도구는 shellTool() 구성에 따라 로컬 또는 호스티드 컨테이너 환경에서 실행될 수 있습니다.
도구 호출은 여전히 모델의 응답에 의해 요청되지만, 해당 호출이 어떻게 실행될지는 애플리케이션이 제어합니다.
import { Agent, applyPatchTool, computerTool, shellTool, Computer, Editor, Shell,} from '@openai/agents';
const computer: Computer = { environment: 'browser', dimensions: [1024, 768], screenshot: async () => '', click: async () => {}, doubleClick: async () => {}, scroll: async () => {}, type: async () => {}, wait: async () => {}, move: async () => {}, keypress: async () => {}, drag: async () => {},};
const shell: Shell = { run: async () => ({ output: [ { stdout: '', stderr: '', outcome: { type: 'exit', exitCode: 0 }, }, ], }),};
const editor: Editor = { createFile: async () => ({ status: 'completed' }), updateFile: async () => ({ status: 'completed' }), deleteFile: async () => ({ status: 'completed' }),};
const agent = new Agent({ name: 'Local tools agent', tools: [ computerTool({ computer }), shellTool({ shell, needsApproval: true }), applyPatchTool({ editor, needsApproval: true }), ],});
void agent;호스티드 shell 환경의 경우, shellTool({ environment })를 다음 중 하나로 구성하세요:
type: 'container_auto'실행을 위해 관리형 컨테이너 생성(네트워크 정책, 메모리 제한, 스킬 지원)type: 'container_reference'containerId로 기존 컨테이너 재사용
엔드 투 엔드 사용법은 examples/tools/container-shell-skill-ref.ts 및 examples/tools/container-shell-inline-skill.ts를 참조하세요.
3. 함수 도구
섹션 제목: “3. 함수 도구”tool() 헬퍼로 어떤 함수든 도구로 바꿀 수 있습니다.
import { tool } from '@openai/agents';import { z } from 'zod';
const getWeatherTool = tool({ name: 'get_weather', description: 'Get the weather for a given city', parameters: z.object({ city: z.string() }), async execute({ city }) { return `The weather in ${city} is sunny.`; },});옵션 참조
섹션 제목: “옵션 참조”| Field | Required | Description |
|---|---|---|
name | No | 기본값은 함수 이름(예: get_weather) |
description | Yes | LLM에 표시되는 명확하고 사람이 읽을 수 있는 설명 |
parameters | Yes | Zod 스키마 또는 원문 JSON 스키마 객체 중 하나. Zod 매개변수는 자동으로 strict 모드를 활성화 |
strict | No | true(기본값)일 때 인수가 유효성 검사를 통과하지 못하면 SDK가 모델 오류를 반환. 퍼지 매칭이 필요하면 false로 설정 |
execute | Yes | (args, context, details) => string | unknown | Promise<...> – 비즈니스 로직. 문자열이 아닌 출력은 모델을 위해 직렬화됨. context는 선택적 RunContext; details에는 toolCall, resumeState, signal 같은 메타데이터 포함 |
errorFunction | No | 내부 오류를 사용자에게 표시할 문자열로 변환하는 커스텀 핸들러 (context, error) => string |
timeoutMs | No | 호출당 타임아웃(밀리초). 0보다 크고 2147483647 이하 |
timeoutBehavior | No | 타임아웃 모드: 기본값 error_as_result는 모델에 타임아웃 메시지를 반환, raise_exception은 ToolTimeoutError를 던짐 |
timeoutErrorFunction | No | timeoutBehavior가 error_as_result일 때 타임아웃 출력을 위한 커스텀 핸들러 (context, timeoutError) => string |
needsApproval | No | 실행 전에 인간 승인 요구. 휴먼 인 더 루프 (HITL) 가이드 참조 |
isEnabled | No | 실행별로 조건부로 도구를 노출; 불리언 또는 프레디케이트 수용 |
inputGuardrails | No | 도구 실행 전 실행되는 가드레일; 거부 또는 예외 발생 가능. 가드레일 참조 |
outputGuardrails | No | 도구 실행 후 실행되는 가드레일; 거부 또는 예외 발생 가능. 가드레일 참조 |
함수 도구 타임아웃
섹션 제목: “함수 도구 타임아웃”각 함수 도구 호출을 제한하려면 timeoutMs를 사용하세요.
timeoutBehavior: 'error_as_result'(기본값)은 모델에Tool '<name>' timed out after <timeoutMs>ms.를 반환timeoutBehavior: 'raise_exception'은ToolTimeoutError를 던지며, 실행 예외의 일부로 캐치할 수 있음timeoutErrorFunction으로error_as_result모드에서 타임아웃 텍스트를 커스터마이즈 가능- 타임아웃은
details.signal을 중단하므로, 장시간 실행 도구가 취소 신호를 수신해 즉시 중지할 수 있음
함수 도구를 직접 호출하는 경우, 일반 에이전트 실행과 동일한 타임아웃 동작을 적용하려면 invokeFunctionTool을 사용하세요.
비‑strict JSON‑스키마 도구
섹션 제목: “비‑strict JSON‑스키마 도구”모델이 유효하지 않거나 부분적인 입력을 추측 하도록 해야 하는 경우 원문 JSON 스키마 사용 시 strict 모드를 비활성화할 수 있습니다:
import { tool } from '@openai/agents';
interface LooseToolInput { text: string;}
const looseTool = tool({ description: 'Echo input; be forgiving about typos', strict: false, parameters: { type: 'object', properties: { text: { type: 'string' } }, required: ['text'], additionalProperties: true, }, execute: async (input) => { // because strict is false we need to do our own verification if (typeof input !== 'object' || input === null || !('text' in input)) { return 'Invalid input. Please try again'; } return (input as LooseToolInput).text; },});4. Agents as tools
섹션 제목: “4. Agents as tools”대화를 완전히 넘기지 않고 한 에이전트가 다른 에이전트를 지원 하도록 하고 싶을 때 agent.asTool()을 사용하세요:
import { Agent } from '@openai/agents';
const summarizer = new Agent({ name: 'Summarizer', instructions: 'Generate a concise summary of the supplied text.',});
const summarizerTool = summarizer.asTool({ toolName: 'summarize_text', toolDescription: 'Generate a concise summary of the supplied text.',});
const mainAgent = new Agent({ name: 'Research assistant', tools: [summarizerTool],});내부적으로 SDK는 다음을 수행합니다:
- 단일
input매개변수를 가진 함수 도구를 생성 - 도구가 호출되면 해당 입력으로 서브 에이전트를 실행
- 마지막 메시지 또는
customOutputExtractor가 추출한 출력을 반환
에이전트를 도구로 실행하면, Agents SDK는 기본 설정으로 러너를 생성하고 함수 실행 내에서 해당 에이전트를 실행합니다. runConfig 또는 runOptions의 속성을 제공하려면 asTool()에 전달해 러너 동작을 사용자 지정할 수 있습니다.
또한 asTool() 옵션을 통해 에이전트 도구에 needsApproval 및 isEnabled를 설정하여 휴먼‑인‑더‑루프 플로우 및 조건부 도구 가용성과 통합할 수 있습니다.
agent.asTool()의 고급 구조적 입력 옵션:
inputBuilder: 구조화된 도구 인수를 중첩 에이전트 입력 페이로드로 매핑includeInputSchema: 더 강력한 스키마 인지 동작을 위해 입력 JSON 스키마를 중첩 실행에 포함resumeState: 중첩된 직렬화RunState재개 시 컨텍스트 조정 전략 제어:'merge'(기본값)는 실시간 승인/컨텍스트 상태를 직렬화 상태에 병합,'replace'는 현재 실행 컨텍스트 사용,'preferSerialized'는 직렬화된 컨텍스트를 변경 없이 재개
에이전트 도구의 스트리밍 이벤트
섹션 제목: “에이전트 도구의 스트리밍 이벤트”에이전트 도구는 모든 중첩 실행 이벤트를 앱으로 스트리밍할 수 있습니다. 도구 구성 방식에 맞는 훅 스타일을 선택하세요:
import { Agent } from '@openai/agents';
const billingAgent = new Agent({ name: 'Billing Agent', instructions: 'Answer billing questions and compute simple charges.',});
const billingTool = billingAgent.asTool({ toolName: 'billing_agent', toolDescription: 'Handles customer billing questions.', // onStream: simplest catch-all when you define the tool inline. onStream: (event) => { console.log(`[onStream] ${event.event.type}`, event); },});
// on(eventName) lets you subscribe selectively (or use '*' for all).billingTool.on('run_item_stream_event', (event) => { console.log('[on run_item_stream_event]', event);});billingTool.on('raw_model_stream_event', (event) => { console.log('[on raw_model_stream_event]', event);});
const orchestrator = new Agent({ name: 'Support Orchestrator', instructions: 'Delegate billing questions to the billing agent tool.', tools: [billingTool],});- 이벤트 유형은
RunStreamEvent['type']과 일치:raw_model_stream_event,run_item_stream_event,agent_updated_stream_event onStream은 가장 단순한 “전체 수신” 방식이며 도구를 인라인으로 선언할 때 잘 작동함(tools: [agent.asTool({ onStream })]). 이벤트별 라우팅이 필요 없다면 이를 사용on(eventName, handler)는 선택적으로 구독(또는'*')할 수 있으며, 더 세밀한 처리가 필요하거나 생성 후 리스너를 부착하고자 할 때 적합onStream또는 어떤on(...)핸들러라도 제공하면 에이전트‑as‑도구는 자동으로 스트리밍 모드로 실행됨. 그렇지 않으면 비스트리밍 경로 유지- 핸들러는 병렬로 호출되므로 느린
onStream콜백이on(...)핸들러를 차단하지 않음(그 반대도 동일) toolCallId는 도구가 모델 도구 호출을 통해 호출되었을 때 제공됨. 직접invoke()호출하거나 공급자 특성에 따라 생략될 수 있음
5. MCP 서버
섹션 제목: “5. MCP 서버”Model Context Protocol (MCP) 서버를 통해 도구를 노출하고 에이전트에 연결할 수 있습니다.
예를 들어 MCPServerStdio를 사용해 stdio MCP 서버를 생성하고 연결할 수 있습니다:
import { Agent, MCPServerStdio } from '@openai/agents';
const server = new MCPServerStdio({ fullCommand: 'npx -y @modelcontextprotocol/server-filesystem ./sample_files',});
await server.connect();
const agent = new Agent({ name: 'Assistant', mcpServers: [server],});완전한 예시는 filesystem-example.ts를 참조하세요. 또한 MCP 서버 도구 통합에 대한 종합적인 가이드를 찾고 있다면, 자세한 내용은 모델 컨텍스트 프로토콜 (MCP) 가이드를 참조하세요.
여러 서버(또는 부분 실패)를 관리할 때는 connectMcpServers와 모델 컨텍스트 프로토콜 (MCP) 가이드의 라이프사이클 지침을 사용하세요.
6. 실험적: Codex 도구
섹션 제목: “6. 실험적: Codex 도구”@openai/agents-extensions/experimental/codex는 codexTool()을 제공하며, 모델 도구 호출을 Codex SDK로 라우팅해 에이전트가 작업공간 범위 작업(shell, 파일 편집, MCP 도구)을 자율적으로 실행할 수 있게 합니다. 이 표면은 실험적이며 변경될 수 있습니다.
먼저 의존성을 설치하세요:
npm install @openai/agents-extensions @openai/codex-sdk빠른 시작:
import { Agent } from '@openai/agents';import { codexTool } from '@openai/agents-extensions/experimental/codex';
export const codexAgent = new Agent({ name: 'Codex Agent', instructions: 'Use the codex tool to inspect the workspace and answer the question. When skill names, which usually start with `$`, are mentioned, you must rely on the codex tool to use the skill and answer the question.', tools: [ codexTool({ sandboxMode: 'workspace-write', workingDirectory: '/path/to/repo', defaultThreadOptions: { model: 'gpt-5.2-codex', networkAccessEnabled: true, webSearchEnabled: false, }, }), ],});알아둘 점:
- 인증:
CODEX_API_KEY(권장) 또는OPENAI_API_KEY를 제공하거나codexOptions.apiKey전달 - 입력: strict 스키마—
inputs에는 최소 하나의{ type: 'text', text }또는{ type: 'local_image', path }가 포함되어야 함 - 안전성:
sandboxMode를workingDirectory와 함께 사용; 디렉터리가 Git 저장소가 아니라면skipGitRepoCheck설정 - 스레딩:
useRunContextThreadId: true는 최신 thread id를runContext.context에서 읽고 저장하며, 앱 상태에서 턴 간 재사용에 유용 - 스레드 ID 우선순위: 도구 호출의
threadId(스키마에 포함된 경우)가 우선, 다음은 실행 컨텍스트의 thread id, 그 다음은codexTool({ threadId }) - 실행 컨텍스트 키:
name: 'codex'일 때 기본codexThreadId,name: 'engineer'와 같은 경우codexThreadId_<suffix>(engineer는 정규화 후codex_engineer) - 변경 가능한 컨텍스트 요구:
useRunContextThreadId가 활성화된 경우run(..., { context })에 변경 가능한 객체 또는Map을 전달 - 네이밍: 도구 이름은
codex네임스페이스로 정규화됨(engineer는codex_engineer가 되며), 하나의 에이전트에서 중복된 Codex 도구 이름은 거부됨 - 스트리밍:
onStream은 Codex 이벤트(추론, 명령 실행, MCP 도구 호출, 파일 변경, 웹 검색)를 미러링하므로 진행 상황을 로깅하거나 트레이싱 가능 - 출력: 도구 결과에는
response,usage,threadId가 포함되며, Codex 토큰 사용량은RunContext에 기록됨 - 구조:
outputSchema는 디스크립터, JSON 스키마 객체 또는 Zod 객체가 될 수 있음. JSON 객체 스키마의 경우additionalProperties는false여야 함
실행 컨텍스트 스레드 재사용 예시:
import { Agent, run } from '@openai/agents';import { codexTool } from '@openai/agents-extensions/experimental/codex';
// Derived from codexTool({ name: 'engineer' }) when runContextThreadIdKey is omitted.type ExampleContext = { codexThreadId_engineer?: string;};
const agent = new Agent<ExampleContext>({ name: 'Codex assistant', instructions: 'Use the codex tool for workspace tasks.', tools: [ codexTool({ // `name` is optional for a single Codex tool. // We set it so the run-context key is tool-specific and to avoid collisions when adding more Codex tools. name: 'engineer', // Reuse the same Codex thread across runs that share this context object. useRunContextThreadId: true, sandboxMode: 'workspace-write', workingDirectory: '/path/to/repo', defaultThreadOptions: { model: 'gpt-5.2-codex', approvalPolicy: 'never', }, }), ],});
// The default key for useRunContextThreadId with name=engineer is codexThreadId_engineer.const context: ExampleContext = {};
// First turn creates (or resumes) a Codex thread and stores the thread ID in context.await run(agent, 'Inspect src/tool.ts and summarize it.', { context });// Second turn reuses the same thread because it shares the same context object.await run(agent, 'Now list refactoring opportunities.', { context });
const threadId = context.codexThreadId_engineer;
void threadId;도구 전략 및 모범 사례
섹션 제목: “도구 전략 및 모범 사례”도구 사용 동작
섹션 제목: “도구 사용 동작”모델이 도구를 언제, 어떻게 사용해야 하는지 제어하려면 에이전트를 참조하세요(modelSettings.toolChoice, toolUseBehavior 등).
모범 사례
섹션 제목: “모범 사례”- 짧고 명시적인 설명 – 도구가 무엇을 하고 언제 사용해야 하는지를 설명
- 입력 유효성 검사 – 가능한 경우 엄격한 JSON 유효성 검사를 위해 Zod 스키마 사용
- 오류 핸들러에서 부작용 회피 –
errorFunction은 예외를 던지지 말고 유용한 문자열을 반환 - 도구당 하나의 책임 – 작고 조합 가능한 도구가 더 나은 모델 추론으로 이어짐