도구
도구를 사용하면 에이전트가 데이터를 가져오고, 외부 API를 호출하고, 코드를 실행하고, 심지어 컴퓨터를 사용하는 등 행동을 수행할 수 있습니다. JavaScript/TypeScript SDK는 네 가지 카테고리를 지원합니다:
- 호스티드 툴 – OpenAI 서버에서 모델과 함께 실행됩니다. (웹 검색, 파일 검색, 컴퓨터 사용, code interpreter, 이미지 생성)
- 함수 도구 – 임의의 로컬 함수를 JSON 스키마로 감싸 LLM이 호출할 수 있게 합니다.
- 도구로서의 에이전트 – 전체 에이전트를 호출 가능한 도구로 노출합니다.
- 로컬 MCP 서버 – 머신에서 실행 중인 Model Context Protocol 서버를 연결합니다.
1. 호스티드 툴
섹션 제목: “1. 호스티드 툴”OpenAIResponsesModel을 사용할 때 다음과 같은 내장 도구를 추가할 수 있습니다:
| Tool | Type string | Purpose |
|---|---|---|
| Web search | 'web_search' | 인터넷 검색 |
| File / retrieval search | 'file_search' | OpenAI에 호스팅된 벡터 스토어 질의 |
| Computer use | 'computer' | GUI 상호작용 자동화 |
| Shell | 'shell' | 호스트에서 셸 명령 실행 |
| Apply patch | 'apply_patch' | V4A diff를 로컬 파일에 적용 |
| Code Interpreter | 'code_interpreter' | 샌드박스 환경에서 코드 실행 |
| Image generation | 'image_generation' | 텍스트 기반 이미지 생성 |
import { Agent, webSearchTool, fileSearchTool } from '@openai/agents';
const agent = new Agent({ name: 'Travel assistant', tools: [webSearchTool(), fileSearchTool('VS_ID')],});정확한 매개변수 세트는 OpenAI Responses API와 일치합니다. rankingOptions나 의미 기반 필터와 같은 고급 옵션은 공식 문서를 참조하세요.
2. 함수 도구
섹션 제목: “2. 함수 도구”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 parameters는 자동으로 strict 모드를 활성화합니다. |
strict | No | true(기본값)일 때 인수가 유효성 검사를 통과하지 않으면 SDK가 모델 오류를 반환합니다. 유사 매칭이 필요하면 false로 설정하세요. |
execute | Yes | (args, context) => string | Promise<string>– 비즈니스 로직입니다. 두 번째 매개변수는 선택 사항이며 RunContext입니다. |
errorFunction | No | 내부 오류를 사용자에게 표시할 문자열로 변환하는 커스텀 핸들러 (context, error) => string입니다. |
비엄격 JSON 스키마 도구
섹션 제목: “비엄격 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; },});3. 도구로서의 에이전트
섹션 제목: “3. 도구로서의 에이전트”대화를 완전히 핸드오프하지 않고도 한 에이전트가 다른 에이전트를 보조하도록 하고 싶을 때 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() 메서드에 전달하여 러너 동작을 커스터마이즈할 수 있습니다.
에이전트 도구의 스트리밍 이벤트
섹션 제목: “에이전트 도구의 스트리밍 이벤트”에이전트 도구는 모든 중첩 실행 이벤트를 앱으로 스트리밍할 수 있습니다. 도구 구성 방식에 맞는 훅 스타일을 선택하세요:
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(...)핸들러라도 제공하면 에이전트-도구는 자동으로 스트리밍 모드에서 실행됩니다. 그렇지 않으면 비스트리밍 경로로 유지됩니다- 핸들러는 병렬로 호출되므로 느린
onStream콜백이on(...)핸들러를 차단하지 않습니다(그리고 그 반대도 마찬가지) toolCallId는 도구가 모델의 도구 호출을 통해 호출되었을 때 제공됩니다. 직접적인invoke()호출 또는 공급자 특성에 따라 생략될 수 있습니다
4. MCP 서버
섹션 제목: “4. 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 guide를 참조하세요.
도구 사용 동작
섹션 제목: “도구 사용 동작”모델이 언제, 어떻게 도구를 사용해야 하는지(tool_choice, toolUseBehavior 등)를 제어하려면 에이전트 가이드를 참조하세요.
모범 사례
섹션 제목: “모범 사례”- 짧고 명시적인 설명 – 도구가 무엇을 하고 언제 사용하는지를 설명하세요.
- 입력 검증 – 가능하면 Zod 스키마로 엄격한 JSON 검증을 사용하세요.
- 에러 핸들러에서 부작용 회피 –
errorFunction은 도움이 되는 문자열을 반환해야 하며, 예외를 던지지 마세요. - 도구별 단일 책임 – 작고 조합 가능한 도구가 더 나은 모델 추론으로 이어집니다.