콘텐츠로 이동

도구

도구는 에이전트가 행동을 수행하도록 합니다. 데이터 가져오기, 외부 API 호출, 코드 실행, 심지어 컴퓨터 사용까지 가능합니다. JavaScript/TypeScript SDK는 네 가지 카테고리를 지원합니다:

  1. 호스티드 툴 – OpenAI 서버에서 모델과 함께 실행됩니다. (웹 검색, 파일 검색, 컴퓨터 사용, code interpreter, 이미지 생성)
  2. 함수 도구 – 로컬 함수를 JSON 스키마로 감싸 LLM이 호출할 수 있게 합니다.
  3. 도구로서의 에이전트 – 전체 에이전트를 호출 가능한 도구로 노출합니다.
  4. 로컬 MCP 서버 – 로컬에서 실행 중인 Model Context Protocol 서버를 연결합니다.

OpenAIResponsesModel을 사용할 때 다음 내장 도구를 추가할 수 있습니다:

ToolType stringPurpose
Web search'web_search'인터넷 검색
File / retrieval search'file_search'OpenAI에 호스팅된 벡터 스토어 질의
Computer use'computer'GUI 상호작용 자동화
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나 의미론적 필터와 같은 고급 옵션은 공식 문서를 참고하세요.


tool() 헬퍼로 어떤 함수든 도구로 변환할 수 있습니다.

Zod 매개변수를 사용하는 함수 도구
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.`;
},
});
FieldRequiredDescription
nameNo기본값은 함수 이름입니다(예: get_weather).
descriptionYesLLM에 표시되는 명확하고 사람이 읽기 쉬운 설명
parametersYesZod 스키마 또는 원문 JSON 스키마 객체 중 하나. Zod 매개변수를 사용하면 자동으로 strict 모드가 활성화됩니다.
strictNotrue(기본값)일 때 인수가 유효성 검사를 통과하지 않으면 SDK가 모델 오류를 반환합니다. 유사 매칭이 필요하면 false로 설정하세요.
executeYes(args, context) => string | Promise<string>– 비즈니스 로직. 두 번째 인수는 선택 사항이며 RunContext입니다.
errorFunctionNo내부 오류를 사용자에게 표시할 문자열로 변환하는 커스텀 핸들러 (context, error) => string

유효하지 않거나 일부만 채워진 입력을 모델이 추론하도록 하려면 원문 JSON 스키마를 사용할 때 strict 모드를 비활성화할 수 있습니다:

비엄격 JSON 스키마 도구
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;
},
});

대화를 완전히 핸드오프하지 않고 에이전트가 다른 에이전트를 보조하도록 하고 싶을 때 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() 메서드에 전달하세요.


Model Context Protocol (MCP) 서버를 통해 도구를 노출하고 에이전트에 연결할 수 있습니다. 예를 들어 MCPServerStdio를 사용하면 stdio MCP 서버를 생성해 연결할 수 있습니다:

로컬 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 등)를 제어하려면 에이전트를 참고하세요.


  • 짧고 명시적인 설명 – 도구가 무엇을 하는지언제 사용하는지를 설명하세요
  • 입력 유효성 검사 – 가능하면 Zod 스키마로 엄격한 JSON 유효성 검사를 수행하세요
  • 에러 핸들러에서 부작용 회피errorFunction은 예외를 던지지 말고 유용한 문자열을 반환해야 합니다
  • 도구당 하나의 책임 – 작고 조합 가능한 도구가 더 나은 모델 추론으로 이어집니다

  • 도구 사용 강제에 대해 학습하세요
  • 도구 입력 또는 출력을 검증하기 위해 가드레일을 추가하세요
  • tool() 및 다양한 호스티드 툴 타입의 TypeDoc 레퍼런스를 확인하세요