에이전트 정의

에이전트 정의 (Agent definitions)

에이전트는 SDK 기반 워크플로우의 핵심 단위예요. 모델, 지침, 그리고 도구, 가드레일, MCP 서버, 핸드오프, 구조화된 출력 같은 선택적 런타임 동작을 묶어요. 에이전트를 정의하는 방법을 배워요.

출처: 문서

본문

에이전트는 SDK 기반 워크플로우의 핵심 단위예요. 모델, 지침, 그리고 도구, 가드레일, MCP 서버, 핸드오프, 구조화된 출력 같은 선택적 런타임 동작을 묶어요.

에이전트에 무엇을 넣어야 하는가

해당 전문가(스페셜리스트)에게 본질적인 결정에는 에이전트 설정을 사용하세요:

속성 용도 다음 읽을 것
name 트레이스와 도구/핸드오프 표면에서 사람이 읽을 수 있는 정체성 이 페이지
instructions 그 에이전트의 작업, 제약, 스타일 이 페이지
prompt Responses 기반 실행을 위한 저장된 프롬프트 설정 Models and providers
model 및 모델 설정 모델 선택과 동작 튜닝 Models and providers
tools 에이전트가 직접 호출할 수 있는 능력 Using tools
TypeScript의 handoffDescription 또는 Python의 handoff_description 다른 에이전트가 여기로 위임해야 할 때를 암시 Orchestration and handoffs
handoffs 다른 에이전트로 위임 Orchestration and handoffs
TypeScript의 outputType 또는 Python의 output_type 평문 대신 구조화된 출력 반환 이 페이지
가드레일 및 승인 검증, 차단, 검토 흐름 Guardrails and human review
MCP 서버 및 호스팅 MCP 도구 MCP 기반 능력 연결 Integrations and observability

하나의 집중된 에이전트로 시작하기

명확한 작업을 소유할 수 있는 가장 작은 에이전트를 정의하세요. 별도의 소유권, 다른 지침, 다른 도구 표면, 다른 승인 정책이 필요할 때만 에이전트를 더 추가하세요.

단일 에이전트 정의하기

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-6-astra",
  tools: [getWeather],
});
from agents import Agent, function_tool


@function_tool
def get_weather(city: str) -> str:
    """Return the weather for a given city."""
    return f"The weather in {city} is sunny."


agent = Agent(
    name="Weather bot",
    instructions="You are a helpful weather bot.",
    model="gpt-6-astra",
    tools=[get_weather],
)

지침, 핸드오프, 출력 다듬기

특별히 신경 써야 할 세 가지 설정 선택이 있어요:

  • 정적 instructions로 시작하세요. 지침이 현재 사용자, 테넌트 또는 런타임 컨텍스트에 의존할 때는 호출 지점에서 문자열을 이어 붙이는 대신 동적 지침 콜백(dynamic instructions callback)으로 전환하세요.
  • TypeScript의 handoffDescription 또는 Python의 handoff_description을 짧고 구체적으로 유지해 라우팅 에이전트가 언제 이 전문가를 선택해야 하는지 알게 하세요.
  • 다운스트림 코드가 자유 형식 산문이 아니라 타입이 지정된 데이터를 필요로 할 때는 TypeScript의 outputType 또는 Python의 output_type을 사용하세요.

구조화된 출력 반환하기

import { Agent, run } from "@openai/agents";
import { z } from "zod";

const calendarEvent = z.object({
  name: z.string(),
  date: z.string(),
  participants: z.array(z.string()),
});

const agent = new Agent({
  name: "Calendar extractor",
  instructions: "Extract calendar events from text.",
  outputType: calendarEvent,
});

const result = await run(agent, "Dinner with Priya and Sam on Friday.");

console.log(result.finalOutput);
import asyncio

from pydantic import BaseModel

from agents import Agent, Runner


class CalendarEvent(BaseModel):
    name: str
    date: str
    participants: list[str]


agent = Agent(
    name="Calendar extractor",
    instructions="Extract calendar events from text.",
    output_type=CalendarEvent,
)


async def main() -> None:
    result = await Runner.run(
        agent,
        "Dinner with Priya and Sam on Friday.",
    )
    print(result.final_output)


if __name__ == "__main__":
    asyncio.run(main())

전체 시스템 프롬프트를 코드에 내장하는 대신 Responses API의 저장된 프롬프트 설정을 참조하고 싶을 때는 prompt를 사용하세요.

로컬 컨텍스트를 모델 컨텍스트와 분리하기

SDK는 모델로 보내지 않고 애플리케이션 상태와 의존성을 실행에 전달할 수 있게 해줘요. 인증된 사용자 정보, 데이터베이스 클라이언트, 로거, 헬퍼 함수 같은 데이터에 사용하세요.

도구에 로컬 컨텍스트 전달하기

import { Agent, run, tool } from "@openai/agents";
import { z } from "zod";

const fetchUserAge = tool({
  name: "fetch_user_age",
  description: "Return the age of the current user.",
  parameters: z.object({}),
  // TypeScript users can type this as RunContext<{ name: string; uid: number }>.
  async execute(_args, runContext) {
    return `User ${runContext?.context.name} is 47 years old`;
  },
});

const agent = new Agent({
  name: "Assistant",
  tools: [fetchUserAge],
});

const result = await run(agent, "What is the age of the user?", {
  context: { name: "John", uid: 123 },
});

console.log(result.finalOutput);
import asyncio
from dataclasses import dataclass

from agents import Agent, RunContextWrapper, Runner, function_tool


@dataclass
class UserInfo:
    name: str
    uid: int


@function_tool
async def fetch_user_age(wrapper: RunContextWrapper[UserInfo]) -> str:
    """Fetch the age of the current user."""
    return f"The user {wrapper.context.name} is 47 years old."


agent = Agent[UserInfo](
    name="Assistant",
    tools=[fetch_user_age],
)


async def main() -> None:
    result = await Runner.run(
        agent,
        "What is the age of the user?",
        context=UserInfo(name="John", uid=123),
    )
    print(result.final_output)


if __name__ == "__main__":
    asyncio.run(main())

중요한 경계는 다음과 같아요:

  • 대화 히스토리는 모델이 보는 것이에요.
  • 실행 컨텍스트(run context)는 여러분의 코드가 보는 것이에요.

모델이 사실이 필요하다면 지침, 입력, 검색 또는 도구에 넣으세요. 여러분의 런타임만 필요하다면 로컬 컨텍스트에 두세요.

하나의 에이전트를 여러 개로 나눌 때

한 전문가가 전체 답변을 소유해서는 안 될 때, 또는 별도의 능력이 실질적으로 다를 때 에이전트를 나누세요. 일반적인 이유는:

  • 전문가가 다른 도구나 MCP 표면이 필요할 때.
  • 전문가가 다른 승인 정책이나 가드레일이 필요할 때.
  • 워크플로우의 한 분기가 다른 모델이나 출력 스타일을 필요로 할 때.
  • 하나의 큰 프롬프트 대신 트레이스에서 명시적 라우팅을 원할 때.

다음 단계

한 전문가가 깔끔하게 정의되면, 다음 설계 질문에 맞는 가이드로 이동하세요.

[Models and providers

    Choose models, defaults, and transport strategy for this agent.](https://developers.openai.com/api/docs/guides/agents/models)

[Using tools

    Add capabilities the agent can call directly.](https://developers.openai.com/api/docs/guides/tools#usage-in-the-agents-sdk)

[Orchestration and handoffs

    Choose how specialists collaborate once one agent is no longer enough.](https://developers.openai.com/api/docs/guides/agents/orchestration)

[Running agents

    Understand the runtime loop, state, and streaming behavior.](https://developers.openai.com/api/docs/guides/agents/running-agents)

더 알아보기 (Learn more)

관련 문서: 에이전트 모델과 제공자와 오케스트레이션 및 핸드오프를 참고하세요.