도구
도구는 에이전트가 행동을 수행하도록 합니다. 데이터를 가져오거나 외부 API를 호출하고, 코드를 실행하거나 심지어 컴퓨터를 사용할 수 있습니다. JavaScript/TypeScript SDK는 네 가지 카테고리를 지원합니다:
- 호스티드 툴 – OpenAI 서버에서 모델과 함께 실행됨 (웹 검색, 파일 검색, 컴퓨터 사용, Code Interpreter, 이미지 생성)
- 함수 도구 – 모든 로컬 함수를 JSON 스키마로 감싸 LLM이 호출할 수 있게 함
- 도구로서의 에이전트 – 전체 에이전트를 호출 가능한 도구로 노출
- 로컬 MCP 서버 – 로컬에서 실행되는 Model Context Protocol 서버를 연결
1. 호스티드 툴
섹션 제목: “1. 호스티드 툴”OpenAIResponsesModel을 사용할 때 다음과 같은 내장 도구를 추가할 수 있습니다:
| Tool | Type string | Purpose |
|---|---|---|
| Web search | 'web_search' | Internet search |
| File / retrieval search | 'file_search' | Query vector stores hosted on OpenAI |
| Computer use | 'computer' | Automate GUI interactions |
| Shell | 'shell' | Run shell commands on the host |
| Apply patch | 'apply_patch' | Apply V4A diffs to local files |
| Code Interpreter | 'code_interpreter' | Run code in a sandboxed environment |
| Image generation | 'image_generation' | Generate images based on text |
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 매개변수를 사용하면 자동으로 strict 모드가 활성화됩니다 |
strict | No | true(기본값)일 때 인수가 검증에 실패하면 SDK가 모델 오류를 반환합니다. 퍼지 매칭이 필요하면 false로 설정 |
execute | Yes | (args, context) => string | Promise<string>– 비즈니스 로직을 구현하세요. 두 번째 매개변수는 선택 사항이며 RunContext입니다 |
errorFunction | No | 내부 오류를 사용자에게 보이는 문자열로 변환하는 커스텀 핸들러 (context, error) => string |
비‑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; },});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() 메서드에 전달하여 러너 동작을 사용자 지정할 수 있습니다.
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)를 참조하세요.
도구 사용 동작
섹션 제목: “도구 사용 동작”모델이 도구를 언제 어떻게 사용해야 하는지(tool_choice, toolUseBehavior 등)를 제어하려면 에이전트를 참조하세요.
모범 사례
섹션 제목: “모범 사례”- 짧고 명확한 설명 – 도구가 무엇을 하는지와 언제 사용하는지를 설명
- 입력 검증 – 가능한 경우 엄격한 JSON 검증을 위해 Zod 스키마 사용
- 에러 핸들러에서 부작용 회피 –
errorFunction은 예외를 던지지 말고 유용한 문자열을 반환 - 도구당 하나의 책임 – 작고 조합 가능한 도구가 더 나은 모델 추론으로 이어짐