Structured output을 사용하면 agent가 특정하고 예측 가능한 형식으로 데이터를 반환할 수 있습니다. 자연어 응답을 파싱하는 대신, 애플리케이션에서 직접 사용할 수 있는 JSON 객체, Pydantic model 또는 dataclass 형태의 구조화된 데이터를 얻을 수 있습니다. LangChain의 create_agent는 structured output을 자동으로 처리합니다. 사용자가 원하는 structured output schema를 설정하면, model이 구조화된 데이터를 생성할 때 이를 캡처하고 검증하여 agent state의 'structured_response' key에 반환합니다.
def create_agent(
    ...
    response_format: Union[
        ToolStrategy[StructuredResponseT],
        ProviderStrategy[StructuredResponseT],
        type[StructuredResponseT],
    ]

Response Format

Agent가 구조화된 데이터를 반환하는 방식을 제어합니다:
  • ToolStrategy[StructuredResponseT]: Tool calling을 사용한 structured output
  • ProviderStrategy[StructuredResponseT]: Provider 네이티브 structured output 사용
  • type[StructuredResponseT]: Schema type - model 기능에 따라 자동으로 최적의 전략 선택
  • None: Structured output 없음
Schema type이 직접 제공되면, LangChain은 자동으로 다음을 선택합니다:
  • 네이티브 structured output을 지원하는 model의 경우 ProviderStrategy (예: OpenAI, Grok)
  • 다른 모든 model의 경우 ToolStrategy
Structured response는 agent의 최종 state에서 structured_response key로 반환됩니다.

Provider strategy

일부 model provider는 API를 통해 네이티브로 structured output을 지원합니다(현재 OpenAI와 Grok만 해당). 이는 사용 가능한 경우 가장 신뢰할 수 있는 방법입니다. 이 전략을 사용하려면 ProviderStrategy를 구성하세요:
class ProviderStrategy(Generic[SchemaT]):
    schema: type[SchemaT]
schema
required
Structured output 형식을 정의하는 schema입니다. 지원 형식:
  • Pydantic models: Field 검증이 포함된 BaseModel 하위 클래스
  • Dataclasses: Type annotation이 있는 Python dataclass
  • TypedDict: 타입이 지정된 dictionary 클래스
  • JSON Schema: JSON schema 사양이 포함된 dictionary
LangChain은 schema type을 create_agent.response_format에 직접 전달하고 model이 네이티브 structured output을 지원하는 경우 자동으로 ProviderStrategy를 사용합니다:
from pydantic import BaseModel
from langchain.agents import create_agent


class ContactInfo(BaseModel):
    """Contact information for a person."""
    name: str = Field(description="The name of the person")
    email: str = Field(description="The email address of the person")
    phone: str = Field(description="The phone number of the person")

agent = create_agent(
    model="openai:gpt-5",
    tools=tools,
    response_format=ContactInfo  # Auto-selects ProviderStrategy
)

result = agent.invoke({
    "messages": [{"role": "user", "content": "Extract contact info from: John Doe, [email protected], (555) 123-4567"}]
})

result["structured_response"]
# ContactInfo(name='John Doe', email='[email protected]', phone='(555) 123-4567')
Provider 네이티브 structured output은 model provider가 schema를 강제하기 때문에 높은 신뢰성과 엄격한 검증을 제공합니다. 사용 가능한 경우 이를 사용하세요.
Provider가 선택한 model에 대해 네이티브로 structured output을 지원하는 경우, response_format=ToolStrategy(ProductReview) 대신 response_format=ProductReview로 작성하는 것이 기능적으로 동일합니다. 어느 경우든 structured output이 지원되지 않으면 agent는 tool calling 전략으로 대체됩니다.

Tool calling strategy

네이티브 structured output을 지원하지 않는 model의 경우, LangChain은 tool calling을 사용하여 동일한 결과를 달성합니다. 이는 tool calling을 지원하는 모든 model에서 작동하며, 대부분의 최신 model이 이에 해당합니다. 이 전략을 사용하려면 ToolStrategy를 구성하세요:
class ToolStrategy(Generic[SchemaT]):
    schema: type[SchemaT]
    tool_message_content: str | None
    handle_errors: Union[
        bool,
        str,
        type[Exception],
        tuple[type[Exception], ...],
        Callable[[Exception], str],
    ]
schema
required
Structured output 형식을 정의하는 schema입니다. 지원 형식:
  • Pydantic models: Field 검증이 포함된 BaseModel 하위 클래스
  • Dataclasses: Type annotation이 있는 Python dataclass
  • TypedDict: 타입이 지정된 dictionary 클래스
  • JSON Schema: JSON schema 사양이 포함된 dictionary
  • Union types: 여러 schema 옵션. Model이 컨텍스트에 따라 가장 적절한 schema를 선택합니다.
tool_message_content
Structured output이 생성될 때 반환되는 tool message의 사용자 정의 내용입니다. 제공되지 않으면 structured response 데이터를 표시하는 메시지가 기본값으로 사용됩니다.
handle_errors
Structured output 검증 실패에 대한 오류 처리 전략입니다. 기본값은 True입니다.
  • True: 기본 오류 템플릿으로 모든 오류 포착
  • str: 이 사용자 정의 메시지로 모든 오류 포착
  • type[Exception]: 기본 메시지로 이 예외 타입만 포착
  • tuple[type[Exception], ...]: 기본 메시지로 이러한 예외 타입만 포착
  • Callable[[Exception], str]: 오류 메시지를 반환하는 사용자 정의 함수
  • False: 재시도 없음, 예외 전파
from pydantic import BaseModel, Field
from typing import Literal
from langchain.agents import create_agent
from langchain.agents.structured_output import ToolStrategy


class ProductReview(BaseModel):
    """Analysis of a product review."""
    rating: int | None = Field(description="The rating of the product", ge=1, le=5)
    sentiment: Literal["positive", "negative"] = Field(description="The sentiment of the review")
    key_points: list[str] = Field(description="The key points of the review. Lowercase, 1-3 words each.")

agent = create_agent(
    model="openai:gpt-5",
    tools=tools,
    response_format=ToolStrategy(ProductReview)
)

result = agent.invoke({
    "messages": [{"role": "user", "content": "Analyze this review: 'Great product: 5 out of 5 stars. Fast shipping, but expensive'"}]
})
result["structured_response"]
# ProductReview(rating=5, sentiment='positive', key_points=['fast shipping', 'expensive'])

Custom tool message content

tool_message_content 매개변수를 사용하면 structured output이 생성될 때 대화 기록에 나타나는 메시지를 사용자 정의할 수 있습니다:
from pydantic import BaseModel, Field
from typing import Literal
from langchain.agents import create_agent
from langchain.agents.structured_output import ToolStrategy


class MeetingAction(BaseModel):
    """Action items extracted from a meeting transcript."""
    task: str = Field(description="The specific task to be completed")
    assignee: str = Field(description="Person responsible for the task")
    priority: Literal["low", "medium", "high"] = Field(description="Priority level")

agent = create_agent(
    model="openai:gpt-5",
    tools=[],
    response_format=ToolStrategy(
        schema=MeetingAction,
        tool_message_content="Action item captured and added to meeting notes!"
    )
)

agent.invoke({
    "messages": [{"role": "user", "content": "From our meeting: Sarah needs to update the project timeline as soon as possible"}]
})
================================ Human Message =================================

From our meeting: Sarah needs to update the project timeline as soon as possible
================================== Ai Message ==================================
Tool Calls:
  MeetingAction (call_1)
 Call ID: call_1
  Args:
    task: Update the project timeline
    assignee: Sarah
    priority: high
================================= Tool Message =================================
Name: MeetingAction

Action item captured and added to meeting notes!
tool_message_content 없이는 최종 ToolMessage가 다음과 같이 표시됩니다:
================================= Tool Message =================================
Name: MeetingAction

Returning structured response: {'task': 'update the project timeline', 'assignee': 'Sarah', 'priority': 'high'}

Error handling

Model은 tool calling을 통해 structured output을 생성할 때 실수를 할 수 있습니다. LangChain은 이러한 오류를 자동으로 처리하기 위한 지능형 재시도 메커니즘을 제공합니다.

Multiple structured outputs error

Model이 여러 structured output tool을 잘못 호출하면, agent는 ToolMessage에 오류 피드백을 제공하고 model에 재시도를 요청합니다:
from pydantic import BaseModel, Field
from typing import Union
from langchain.agents import create_agent
from langchain.agents.structured_output import ToolStrategy


class ContactInfo(BaseModel):
    name: str = Field(description="Person's name")
    email: str = Field(description="Email address")

class EventDetails(BaseModel):
    event_name: str = Field(description="Name of the event")
    date: str = Field(description="Event date")

agent = create_agent(
    model="openai:gpt-5",
    tools=[],
    response_format=ToolStrategy(Union[ContactInfo, EventDetails])  # Default: handle_errors=True
)

agent.invoke({
    "messages": [{"role": "user", "content": "Extract info: John Doe ([email protected]) is organizing Tech Conference on March 15th"}]
})
================================ Human Message =================================

Extract info: John Doe ([email protected]) is organizing Tech Conference on March 15th
None
================================== Ai Message ==================================
Tool Calls:
  ContactInfo (call_1)
 Call ID: call_1
  Args:
    name: John Doe
    email: [email protected]
  EventDetails (call_2)
 Call ID: call_2
  Args:
    event_name: Tech Conference
    date: March 15th
================================= Tool Message =================================
Name: ContactInfo

Error: Model incorrectly returned multiple structured responses (ContactInfo, EventDetails) when only one is expected.
 Please fix your mistakes.
================================= Tool Message =================================
Name: EventDetails

Error: Model incorrectly returned multiple structured responses (ContactInfo, EventDetails) when only one is expected.
 Please fix your mistakes.
================================== Ai Message ==================================
Tool Calls:
  ContactInfo (call_3)
 Call ID: call_3
  Args:
    name: John Doe
    email: [email protected]
================================= Tool Message =================================
Name: ContactInfo

Returning structured response: {'name': 'John Doe', 'email': '[email protected]'}

Schema validation error

Structured output이 예상 schema와 일치하지 않으면, agent는 구체적인 오류 피드백을 제공합니다:
from pydantic import BaseModel, Field
from langchain.agents import create_agent
from langchain.agents.structured_output import ToolStrategy


class ProductRating(BaseModel):
    rating: int | None = Field(description="Rating from 1-5", ge=1, le=5)
    comment: str = Field(description="Review comment")

agent = create_agent(
    model="openai:gpt-5",
    tools=[],
    response_format=ToolStrategy(ProductRating),  # Default: handle_errors=True
    system_prompt="You are a helpful assistant that parses product reviews. Do not make any field or value up."
)

agent.invoke({
    "messages": [{"role": "user", "content": "Parse this: Amazing product, 10/10!"}]
})
================================ Human Message =================================

Parse this: Amazing product, 10/10!
================================== Ai Message ==================================
Tool Calls:
  ProductRating (call_1)
 Call ID: call_1
  Args:
    rating: 10
    comment: Amazing product
================================= Tool Message =================================
Name: ProductRating

Error: Failed to parse structured output for tool 'ProductRating': 1 validation error for ProductRating.rating
  Input should be less than or equal to 5 [type=less_than_equal, input_value=10, input_type=int].
 Please fix your mistakes.
================================== Ai Message ==================================
Tool Calls:
  ProductRating (call_2)
 Call ID: call_2
  Args:
    rating: 5
    comment: Amazing product
================================= Tool Message =================================
Name: ProductRating

Returning structured response: {'rating': 5, 'comment': 'Amazing product'}

Error handling strategies

handle_errors 매개변수를 사용하여 오류 처리 방식을 사용자 정의할 수 있습니다: 사용자 정의 오류 메시지:
ToolStrategy(
    schema=ProductRating,
    handle_errors="Please provide a valid rating between 1-5 and include a comment."
)
handle_errors가 문자열인 경우, agent는 고정된 tool message로 항상 model에 재시도를 요청합니다:
================================= Tool Message =================================
Name: ProductRating

Please provide a valid rating between 1-5 and include a comment.
특정 예외만 처리:
ToolStrategy(
    schema=ProductRating,
    handle_errors=ValueError  # Only retry on ValueError, raise others
)
handle_errors가 예외 타입인 경우, agent는 발생한 예외가 지정된 타입인 경우에만 재시도합니다(기본 오류 메시지 사용). 다른 모든 경우에는 예외가 발생합니다. 여러 예외 타입 처리:
ToolStrategy(
    schema=ProductRating,
    handle_errors=(ValueError, TypeError)  # Retry on ValueError and TypeError
)
handle_errors가 예외 튜플인 경우, agent는 발생한 예외가 지정된 타입 중 하나인 경우에만 재시도합니다(기본 오류 메시지 사용). 다른 모든 경우에는 예외가 발생합니다. 사용자 정의 오류 핸들러 함수:
def custom_error_handler(error: Exception) -> str:
    if isinstance(error, StructuredOutputValidationError):
        return "There was an issue with the format. Try again.
    elif isinstance(error, MultipleStructuredOutputsError):
        return "Multiple structured outputs were returned. Pick the most relevant one."
    else:
        return f"Error: {str(error)}"

ToolStrategy(
    schema=ToolStrategy(Union[ContactInfo, EventDetails]),
    handle_errors=custom_error_handler
)
StructuredOutputValidationError의 경우:
================================= Tool Message =================================
Name: ToolStrategy

There was an issue with the format. Try again.
MultipleStructuredOutputsError의 경우:
================================= Tool Message =================================
Name: ToolStrategy

Multiple structured outputs were returned. Pick the most relevant one.
다른 오류의 경우:
================================= Tool Message =================================
Name: ToolStrategy

Error: <error message>
오류 처리 없음:
response_format = ToolStrategy(
    schema=ProductRating,
    handle_errors=False  # All errors raised
)

Connect these docs programmatically to Claude, VSCode, and more via MCP for real-time answers.
I