구조화된 출력

구조화된 출력 (Structured Output)

에이전트가 특정 스키마와 일치하는 JSON으로 응답하도록 강제해요.

출처: 문서

본문

개요 (Overview)

구조화된 출력은 에이전트의 응답을 미리 정의된 JSON 스키마와 일치하도록 제약해요. 이것은 다운스트림 처리, API 응답, 다른 시스템과의 통합을 위해 기계 판독 가능한 출력을 생성해야 하는 에이전트를 구축하는 데 유용해요.

Note 언제 쓸까 (When to Use)

  • 일관된 JSON 응답이 필요한 API 엔드포인트 구축
  • 데이터 추출 및 변환 파이프라인
  • 다른 자동화 시스템에 공급되는 에이전트
  • 파싱을 위한 예측 가능한 출력 형식 보장

구성 (Configuration)

agents:
  analyzer:
    model: openai/gpt-4o
    description: Code analyzer that outputs structured results
    instruction: |
      Analyze the provided code and identify issues.
      Return your findings in the structured format.
    structured_output:
      name: analysis_result
      description: Code analysis findings
      strict: true
      schema:
        type: object
        properties:
          issues:
            type: array
            items:
              type: object
              properties:
                severity:
                  type: string
                  enum: ["error", "warning", "info"]
                line:
                  type: integer
                message:
                  type: string
              required: ["severity", "line", "message"]
          summary:
            type: string
        required: ["issues", "summary"]

속성 (Properties)

Property Type Required Description
name string ✓ 출력 스키마용 이름 식별자
description string ✗ 출력이 무엇을 나타내는지에 대한 설명
strict boolean ✗ 엄격한 스키마 준수 강제 — native 모드 전용 (기본값: false)
schema object ✓ 출력 구조를 정의하는 JSON Schema
mode string ✗ 시행 모드: native(기본) 또는 tool (Modes 참고)

모드 (Modes)

native (기본값)

스키마가 제공자의 네이티브 구조화된 출력 지원(OpenAI JSON mode, Gemini JSON mode, ...)에 전달돼요. mode 를 생략하면 이 동작을 유지해요.

tool

structured_output:
  mode: tool
  name: analysis_result
  schema:
    type: object
    properties:
      summary:
        type: string
    required: ["summary"]

tool 모드에서는 제공자의 네이티브 구조화된 출력 API로 아무것도 보내지지 않아요. 대신 런타임이 __structured_output__ 이라는 내부 도구를 노출하는데, 그 파라미터는 정확히 구성된 스키마예요. 모델은 정상적으로 동작하고 — 다른 도구 호출을 포함해서 — 최종 답변을 그 도구를 호출함으로써 전달하며, 응답의 유일한 도구 호출로 그 도구만 호출해요. 런타임은 인자를 스키마에 대해 검증해요:

  • 유효한 호출은 턴을 끝내요; 검증된(압축된) JSON이 최종 어시스턴트 메시지가 돼요.
  • 잘못된 JSON은 모델이 스스로 고치고 재시도할 수 있도록 상세한 도구 에러를 받아요.
  • 모델이 대신 평문으로 답하면, 런타임은 일시적인 시스템 미리 알림을 주입하고 재시도해요(최대 2번), 그다음 structured_output_failed 에러로 실패해요.

tool 모드 검증은 additionalProperties 를 포함한 전체 JSON Schema를 적용해요 — 스키마가 금지하면 예상치 못한 필드가 거부돼요. 외부 $ref 참조(http(s)://, file://, 교차 문서)는 스키마가 컴파일될 때 거부되고, # 로 시작하는 같은 문서 참조(예: #/definitions/item)만 허용돼요. strict 플래그는 tool 모드에서 효과가 없어요.

Fork 모드 스킬(context: fork)은 면제 하위 세션으로 실행돼요: 스킬은 호출 에이전트를 위해 자체 평문 답변을 만들고 출력 도구를 호출할 필요가 없어요. 부모 에이전트는 여전히 그 도구를 통해 최종 답변을 전달해요.

모델이 스키마 제약이 있는 최종 답변과 도구 사용을 결합해야 할 때, 또는 제공자에 네이티브 구조화된 출력 지원이 없을 때 tool 모드를 사용해요. examples/structured-output-tool-mode.yaml 참고.

스키마 형식 (Schema Format)

스키마는 JSON Schema 사양을 따릅니다. 일반적인 스키마 유형:

단순 객체 (Simple Object)

schema:
  type: object
  properties:
    name:
      type: string
    count:
      type: integer
    active:
      type: boolean
  required: ["name", "count"]

객체 배열 (Array of Objects)

schema:
  type: object
  properties:
    items:
      type: array
      items:
        type: object
        properties:
          id:
            type: string
          value:
            type: number
        required: ["id", "value"]
  required: ["items"]

열거 값 (Enum Values)

schema:
  type: object
  properties:
    status:
      type: string
      enum: ["pending", "approved", "rejected"]
    priority:
      type: string
      enum: ["low", "medium", "high", "critical"]
  required: ["status"]

엄격 모드 (Strict Mode)

strict 는 native 모드에만 적용돼요: 제공자의 구조화된 출력 API에 전달돼요. tool 모드는 무시하고 항상 전체 스키마에 대해 검증해요. strict: true 일 때 모델은 스키마와 정확히 일치하는 출력만 생성하도록 제약돼요. 이것은 더 강한 보증을 제공하지만 모델의 유연성을 제한할 수 있어요.

  • strict: false (기본) — 모델이 스키마에 맞추려 하지만 추가 필드나 약간의 변형을 포함할 수 있어요.
  • strict: true — 모델 출력이 스키마와 정확히 일치하도록 제약. 더 강한 보증.

제공자 지원 (Provider Support)

구조화된 출력 지원은 제공자마다 달라요:

Provider Support Notes
OpenAI ✓ Full 스키마 검증이 있는 네이티브 JSON mode
Anthropic ✓ Full 도구 기반 구조화된 출력
Google Gemini ✓ Full 네이티브 JSON mode
AWS Bedrock ✓ Partial 기본 모델에 따라 다름
DMR ⚠️ Limited 모델 능력에 따라 다름

예제: 데이터 추출 에이전트 (Example: Data Extraction Agent)

agents:
  extractor:
    model: openai/gpt-4o
    description: Extract structured data from text
    instruction: |
      Extract contact information from the provided text.
      Return all found contacts in the structured format.
    structured_output:
      name: contacts
      description: Extracted contact information
      strict: true
      schema:
        type: object
        properties:
          contacts:
            type: array
            items:
              type: object
              properties:
                name:
                  type: string
                  description: Full name of the contact
                email:
                  type: string
                  description: Email address
                phone:
                  type: string
                  description: Phone number
                company:
                  type: string
                  description: Company or organization
              required: ["name"]
          total_found:
            type: integer
            description: Total number of contacts found
        required: ["contacts", "total_found"]

예제: 분류 에이전트 (Example: Classification Agent)

agents:
  classifier:
    model: anthropic/claude-sonnet-4-5
    description: Classify support tickets
    instruction: |
      Classify the support ticket into the appropriate category
      and priority level based on its content.
    structured_output:
      name: ticket_classification
      strict: true
      schema:
        type: object
        properties:
          category:
            type: string
            enum:
              ["billing", "technical", "account", "feature_request", "other"]
          priority:
            type: string
            enum: ["low", "medium", "high", "urgent"]
          confidence:
            type: number
            minimum: 0
            maximum: 1
            description: Confidence score between 0 and 1
          reasoning:
            type: string
            description: Brief explanation for the classification
        required: ["category", "priority", "confidence"]

Warning 도구 한계 (Tool Limitations) 네이티브 구조화된 출력을 사용할 때 에이전트는 응답 형식이 스키마로 제약되므로 일반적으로 도구를 사용할 수 없어요. 그에 맞게 에이전트 워크플로를 설계하세요 — 네이티브 구조화된 출력 에이전트는 단일 턴 분석이나 추출 작업에 가장 잘 동작해요. 에이전트가 스키마 제약 최종 답변을 만들기 전에 도구를 호출해야 한다면 mode: tool 을 사용하세요.

더 알아보기 (Learn more)