콘텐츠로 이동

에이전트

에이전트는 OpenAI Agents SDK의 주요 구성 요소입니다. 에이전트는 다음으로 설정된 대규모 언어 모델 (LLM)입니다.

  • Instructions – 모델에게 자신이 누구인지어떻게 응답해야 하는지 알려주는 시스템 프롬프트입니다.
  • 모델 – 호출할 OpenAI 모델과 선택적 모델 튜닝 매개변수입니다.
  • Tools – LLM이 작업을 수행하기 위해 호출할 수 있는 함수 또는 API 목록입니다.
기본 에이전트 정의
import { Agent } from '@openai/agents';
const agent = new Agent({
name: 'Haiku Agent',
instructions: 'Always respond in haiku form.',
model: 'gpt-5.4', // optional – falls back to the default model
});

단일 Agent를 정의하거나 사용자 지정하려면 이 페이지를 사용하세요. 여러 에이전트가 어떻게 협업해야 할지 결정하는 중이라면 에이전트 오케스트레이션을 읽어보세요.

이 페이지를 에이전트 정의의 허브로 사용하세요. 다음에 내려야 할 결정에 맞는 인접 가이드로 이동하세요.

원하는 작업다음 읽을 문서
모델 선택 또는 저장된 프롬프트 설정모델
에이전트에 기능 추가도구
에이전트에 격리된 파일 시스템 워크스페이스 제공개념
매니저와 핸드오프 중 선택에이전트 오케스트레이션
핸드오프 동작 설정핸드오프
턴 실행, 이벤트 스트리밍 또는 상태 관리에이전트 실행
최종 출력, 실행 항목 또는 재개 검사실행 결과

이 페이지의 나머지 부분에서는 모든 에이전트 기능을 더 자세히 설명합니다.


Agent 생성자는 단일 설정 객체를 받습니다. 가장 자주 사용되는 속성은 아래와 같습니다.

속성필수설명
name사람이 읽을 수 있는 짧은 식별자입니다.
instructions시스템 프롬프트(문자열 또는 함수 – 동적 instructions 참조)입니다.
prompt아니요OpenAI Responses API 프롬프트 설정입니다. 정적 프롬프트 객체 또는 함수를 받습니다. 프롬프트를 참조하세요.
handoffDescription아니요이 에이전트가 핸드오프 도구로 제공될 때 사용되는 짧은 설명입니다.
handoffs아니요대화를 전문 에이전트에게 위임합니다. 구성 패턴핸드오프 가이드를 참조하세요.
model아니요모델 이름 또는 사용자 지정 Model 구현입니다.
modelSettings아니요튜닝 매개변수(temperature, top_p 등)입니다. 모델을 참조하세요. 필요한 속성이 최상위 수준에 없는 경우 providerData 아래에 포함할 수 있습니다.
tools아니요모델이 호출할 수 있는 Tool 인스턴스 배열입니다. 도구를 참조하세요.
mcpServers아니요에이전트를 위한 MCP 기반 도구입니다. 모델 컨텍스트 프로토콜 (MCP)를 참조하세요.
mcpConfig아니요엄격한 스키마, 오류 처리, 서버 접두사가 붙은 도구 이름 등 로컬 MCP 도구 옵션입니다. 에이전트 수준 MCP 설정을 참조하세요.
inputGuardrails아니요이 에이전트 체인의 첫 사용자 입력에 적용되는 가드레일입니다. 가드레일을 참조하세요.
outputGuardrails아니요이 에이전트의 최종 출력에 적용되는 가드레일입니다. 가드레일을 참조하세요.
outputType아니요일반 텍스트 대신 구조화된 출력을 반환합니다. 출력 유형실행 결과를 참조하세요.
toolUseBehavior아니요함수 도구 결과를 모델로 다시 돌려보낼지 또는 실행을 완료할지 제어합니다. 도구 사용 강제를 참조하세요.
resetToolChoice아니요도구 사용 루프를 방지하기 위해 도구 호출 후 toolChoice를 기본값으로 재설정합니다(기본값: true). 도구 사용 강제를 참조하세요.
handoffOutputTypeWarningEnabled아니요핸드오프 출력 유형이 서로 다를 때 경고를 내보냅니다(기본값: true). 실행 결과를 참조하세요.
도구가 있는 에이전트
import { Agent, tool } from '@openai/agents';
import { z } from 'zod';
const getWeather = tool({
name: 'get_weather',
description: 'Return the weather for a given city.',
parameters: z.object({ city: z.string() }),
async execute({ city }) {
return `The weather in ${city} is sunny.`;
},
});
const agent = new Agent({
name: 'Weather bot',
instructions: 'You are a helpful weather bot.',
model: 'gpt-4.1',
tools: [getWeather],
});

에이전트는 컨텍스트 타입에 대해 제네릭입니다. 즉 Agent<TContext, TOutput>입니다. 컨텍스트는 사용자가 생성해 Runner.run()에 전달하는 의존성 주입 객체입니다. 컨텍스트는 모든 도구, 가드레일, 핸드오프 등에 전달되며 상태를 저장하거나 공유 서비스(데이터베이스 연결, 사용자 메타데이터, 기능 플래그, …)를 제공하는 데 유용합니다.

컨텍스트가 있는 에이전트
import { Agent } from '@openai/agents';
interface Purchase {
id: string;
uid: string;
deliveryStatus: string;
}
interface UserContext {
uid: string;
isProUser: boolean;
// this function can be used within tools
fetchPurchases(): Promise<Purchase[]>;
}
const agent = new Agent<UserContext>({
name: 'Personal shopper',
instructions: 'Recommend products the user will love.',
});
// Later
import { run } from '@openai/agents';
const result = await run(agent, 'Find me a new pair of running shoes', {
context: { uid: 'abc', isProUser: true, fetchPurchases: async () => [] },
});

기본적으로 에이전트는 일반 텍스트(string)를 반환합니다. 모델이 구조화된 객체를 반환하도록 하려면 outputType 속성을 지정할 수 있습니다. SDK는 다음을 받습니다.

  1. Zod 스키마(z.object({...})).
  2. JSON 스키마와 호환되는 모든 객체.
Zod를 사용한 구조화된 출력
import { Agent } from '@openai/agents';
import { z } from 'zod';
const CalendarEvent = z.object({
name: z.string(),
date: z.string(),
participants: z.array(z.string()),
});
const extractor = new Agent({
name: 'Calendar extractor',
instructions: 'Extract calendar events from the supplied text.',
outputType: CalendarEvent,
});

outputType이 제공되면 SDK는 일반 텍스트 대신 자동으로 structured outputs를 사용합니다.


일부 에이전트 개념은 OpenAI 플랫폼 개념에 직접 매핑되지만, 다른 개념은 에이전트를 정의할 때가 아니라 실행할 때 설정됩니다.

SDK 개념OpenAI 가이드필요한 경우
outputTypeStructured Outputs에이전트가 텍스트 대신 타입이 지정된 JSON 또는 Zod로 검증된 객체를 반환해야 할 때
tools / 호스티드 툴도구 가이드모델이 검색, 조회, 코드 실행 또는 함수/도구 호출을 수행해야 할 때
conversationId / previousResponseId대화 상태턴 사이의 대화 상태를 OpenAI가 유지하거나 연결하도록 하려는 경우

conversationIdpreviousResponseIdAgent 생성자 필드가 아니라 런타임 제어 항목입니다. 이러한 SDK 진입점이 필요할 때는 에이전트 실행을 사용하세요.


에이전트가 더 큰 워크플로에 참여할 때 가장 자주 등장하는 SDK 진입점은 두 가지입니다.

  1. 매니저 (agents as tools) – 중앙 에이전트가 대화를 소유하고, 도구로 노출된 전문 에이전트를 호출합니다.
  2. 핸드오프 – 초기 에이전트가 사용자 요청을 식별한 후 전체 대화를 전문 에이전트에게 위임합니다.

이 두 접근 방식은 서로 보완적입니다. 매니저를 사용하면 가드레일이나 속도 제한을 적용할 단일 위치를 확보할 수 있고, 핸드오프를 사용하면 각 에이전트가 대화의 제어권을 유지하지 않고도 하나의 작업에 집중할 수 있습니다. 설계상의 트레이드오프와 각 패턴을 선택해야 하는 시점은 에이전트 오케스트레이션을 참조하세요.

이 패턴에서 매니저는 제어권을 넘기지 않습니다. LLM이 도구를 사용하고 매니저가 최종 답변을 요약합니다. 자세한 내용은 도구 가이드를 참조하세요.

Agents as tools
import { Agent } from '@openai/agents';
const bookingAgent = new Agent({
name: 'Booking expert',
instructions: 'Answer booking questions and modify reservations.',
});
const refundAgent = new Agent({
name: 'Refund expert',
instructions: 'Help customers process refunds and credits.',
});
const customerFacingAgent = new Agent({
name: 'Customer-facing agent',
instructions:
'Talk to the user directly. When they need booking or refund help, call the matching tool.',
tools: [
bookingAgent.asTool({
toolName: 'booking_expert',
toolDescription: 'Handles booking questions and requests.',
}),
refundAgent.asTool({
toolName: 'refund_expert',
toolDescription: 'Handles refund questions and requests.',
}),
],
});

핸드오프에서는 분류 에이전트가 요청을 라우팅하지만, 핸드오프가 발생하면 전문 에이전트가 최종 출력을 생성할 때까지 대화를 소유합니다. 이렇게 하면 프롬프트를 짧게 유지하고 각 에이전트를 독립적으로 추론할 수 있습니다. 자세한 내용은 핸드오프 가이드를 참조하세요.

핸드오프가 있는 에이전트
import { Agent } from '@openai/agents';
const bookingAgent = new Agent({
name: 'Booking Agent',
instructions: 'Help users with booking requests.',
});
const refundAgent = new Agent({
name: 'Refund Agent',
instructions: 'Process refund requests politely and efficiently.',
});
// Use Agent.create method to ensure the finalOutput type considers handoffs
const triageAgent = Agent.create({
name: 'Triage Agent',
instructions: `Help the user with their questions.
If the user asks about booking, hand off to the booking agent.
If the user asks about refunds, hand off to the refund agent.`.trimStart(),
handoffs: [bookingAgent, refundAgent],
});

핸드오프 대상이 서로 다른 출력 유형을 반환할 수 있다면 new Agent(...)보다 Agent.create(...)를 사용하는 것이 좋습니다. 이렇게 하면 TypeScript가 핸드오프 그래프 전반에서 가능한 finalOutput 형태의 유니온을 추론할 수 있고, handoffOutputTypeWarningEnabled로 제어되는 런타임 경고를 피할 수 있습니다. 종단 간 예제는 실행 결과 가이드를 참조하세요.


instructions는 문자열 대신 함수일 수 있습니다. 이 함수는 현재 RunContext와 에이전트 인스턴스를 받고, 문자열 또는 Promise<string>을 반환할 수 있습니다.

동적 instructions가 있는 에이전트
import { Agent, RunContext } from '@openai/agents';
interface UserContext {
name: string;
}
function buildInstructions(runContext: RunContext<UserContext>) {
return `The user's name is ${runContext.context.name}. Be extra friendly!`;
}
const agent = new Agent<UserContext>({
name: 'Personalized helper',
instructions: buildInstructions,
});

동기 함수와 async 함수가 모두 지원됩니다.


promptinstructions와 동일한 콜백 형태를 지원하지만, 문자열 대신 프롬프트 설정 객체를 반환합니다. 이는 프롬프트 ID, 버전 또는 변수가 현재 실행 컨텍스트에 따라 달라질 때 유용합니다.

동적 프롬프트가 있는 에이전트
import { Agent, RunContext } from '@openai/agents';
interface PromptContext {
customerTier: 'free' | 'pro';
}
function buildPrompt(runContext: RunContext<PromptContext>) {
return {
promptId: 'pmpt_support_agent',
version: '7',
variables: {
customer_tier: runContext.context.customerTier,
},
};
}
const agent = new Agent<PromptContext>({
name: 'Prompt-backed helper',
prompt: buildPrompt,
});

이는 OpenAI Responses API를 사용할 때만 지원됩니다. 동기 함수와 async 함수가 모두 지원됩니다.


고급 사용 사례에서는 이벤트를 수신하여 에이전트 라이프사이클을 관찰할 수 있습니다.

Agent 인스턴스는 해당 특정 에이전트 인스턴스의 라이프사이클 이벤트를 내보내는 반면, Runner는 전체 실행에 걸친 단일 스트림으로 동일한 이벤트 이름을 내보냅니다. 이는 핸드오프와 도구 호출을 한곳에서 관찰하려는 멀티 에이전트 워크플로에 유용합니다.

공유 이벤트 이름은 다음과 같습니다.

이벤트에이전트 훅 인수Runner 훅 인수
agent_start(context, agent, turnInput?)(context, agent, turnInput?)
agent_end(context, output)(context, agent, output)
agent_handoff(context, nextAgent)(context, fromAgent, toAgent)
agent_tool_start(context, tool, { toolCall })(context, agent, tool, { toolCall })
agent_tool_end(context, tool, result, { toolCall })(context, agent, tool, result, { toolCall })
라이프사이클 훅이 있는 에이전트
import { Agent } from '@openai/agents';
const agent = new Agent({
name: 'Verbose agent',
instructions: 'Explain things thoroughly.',
});
agent.on('agent_start', (ctx, agent) => {
console.log(`[${agent.name}] started`);
});
agent.on('agent_end', (ctx, output) => {
console.log(`[agent] produced:`, output);
});

가드레일을 사용하면 사용자 입력과 에이전트 출력을 검증하거나 변환할 수 있습니다. 가드레일은 inputGuardrailsoutputGuardrails 배열을 통해 설정됩니다. 자세한 내용은 가드레일 가이드를 참조하세요.


기존 에이전트를 약간 수정한 버전이 필요하신가요? 완전히 새로운 Agent 인스턴스를 반환하는 clone() 메서드를 사용하세요.

에이전트 복제
import { Agent } from '@openai/agents';
const pirateAgent = new Agent({
name: 'Pirate',
instructions: 'Respond like a pirate – lots of “Arrr!”',
model: 'gpt-5.4',
});
const robotAgent = pirateAgent.clone({
name: 'Robot',
instructions: 'Respond like a robot – be precise and factual.',
});

도구를 제공한다고 해서 LLM이 반드시 도구를 호출하는 것은 아닙니다. modelSettings.toolChoice로 도구 사용을 강제할 수 있습니다.

  1. 'auto'(기본값) – LLM이 도구를 사용할지 여부를 결정합니다.
  2. 'required' – LLM이 도구를 반드시 호출해야 합니다(어떤 도구를 호출할지는 선택할 수 있음).
  3. 'none' – LLM이 도구를 호출하지 않아야 합니다.
  4. 특정 도구 이름(예: 'calculator') – LLM이 해당 특정 도구를 호출해야 합니다.

사용 가능한 도구가 OpenAI Responses의 computerTool()인 경우 toolChoice: 'computer'는 특별합니다. 이는 'computer'를 일반 함수 이름으로 취급하는 대신 GA 내장 컴퓨터 도구를 강제합니다. SDK는 이전 연동을 위해 프리뷰 호환 컴퓨터 선택자도 허용하지만, 새 코드는 'computer'를 사용하는 것이 좋습니다. 사용 가능한 컴퓨터 도구가 없으면 해당 문자열은 다른 함수 도구 이름처럼 동작합니다.

도구 사용 강제
import { Agent, tool } from '@openai/agents';
import { z } from 'zod';
const calculatorTool = tool({
name: 'Calculator',
description: 'Use this tool to answer questions about math problems.',
parameters: z.object({ question: z.string() }),
execute: async (input) => {
throw new Error('TODO: implement this');
},
});
const agent = new Agent({
name: 'Strict tool user',
instructions: 'Always answer using the calculator tool.',
tools: [calculatorTool],
modelSettings: { toolChoice: 'required' },
});

toolNamespace() 같은 지연 로딩 Responses 도구, deferLoading: true가 설정된 함수 도구, 또는 deferLoading: true가 설정된 호스티드 MCP 도구를 사용할 때는 modelSettings.toolChoice'auto'로 유지하세요. 모델이 이러한 정의를 언제 로드할지 결정해야 하므로, SDK는 지연 도구나 내장 tool_search 헬퍼를 이름으로 강제하는 것을 거부합니다. 전체 tool-search 설정은 도구 가이드를 참조하세요.

도구 호출 후 SDK는 자동으로 toolChoice를 다시 'auto'로 재설정합니다. 이렇게 하면 모델이 같은 도구를 반복해서 호출하려는 무한 루프에 빠지는 것을 방지할 수 있습니다. resetToolChoice 플래그를 사용하거나 toolUseBehavior를 설정하여 이 동작을 재정의할 수 있습니다.

  • 'run_llm_again'(기본값) – 도구 결과와 함께 LLM을 다시 실행합니다.
  • 'stop_on_first_tool' – 첫 번째 도구 결과를 최종 답변으로 처리합니다.
  • { stopAtToolNames: ['my_tool'] } – 나열된 도구 중 하나가 호출되면 중지합니다.
  • (context, toolResults) => ... – 실행을 완료해야 하는지 여부를 반환하는 사용자 지정 함수입니다.
const agent = new Agent({
...,
toolUseBehavior: 'stop_on_first_tool',
});

참고: toolUseBehavior함수 도구에만 적용됩니다. 호스티드 툴은 항상 처리를 위해 모델로 반환됩니다.


  • 모델 선택, 저장된 프롬프트, 공급자 설정은 모델를 참조하세요.
  • 함수 도구, 호스티드 툴, MCP, agent.asTool()도구를 참조하세요.
  • 매니저, 핸드오프, 코드 기반 오케스트레이션 중 선택하려면 에이전트 오케스트레이션을 참조하세요.
  • 전문 에이전트 위임 설정은 핸드오프를 참조하세요.
  • 턴 실행, 스트리밍, 대화 상태는 에이전트 실행을 참조하세요.
  • finalOutput, 실행 항목, 재개 상태는 실행 결과를 참조하세요.
  • 사이드바의 @openai/agents 아래에서 전체 TypeDoc 참조를 살펴보세요.