구조화된 출력을 사용하면 에이전트가 특정하고 예측 가능한 형식으로 데이터를 반환할 수 있습니다. 자연어 응답을 파싱하는 대신, 애플리케이션에서 직접 사용할 수 있는 JSON 객체, Pydantic 모델 또는 데이터클래스 형태의 구조화된 데이터를 얻을 수 있습니다.LangChain의 create_agent는 구조화된 출력을 자동으로 처리합니다. 사용자가 원하는 구조화된 출력 스키마를 설정하면, 모델이 구조화된 데이터를 생성할 때 이를 캡처하고 검증한 후 에이전트 상태의 'structured_response' 키에 반환합니다.
제공자 네이티브 구조화된 출력은 모델 제공자가 스키마를 강제하기 때문에 높은 신뢰성과 엄격한 검증을 제공합니다. 사용 가능한 경우 이를 사용하세요.
제공자가 선택한 모델에 대해 네이티브로 구조화된 출력을 지원하는 경우, response_format=ProductReview 대신 response_format=ToolStrategy(ProductReview)로 작성하는 것과 기능적으로 동일합니다. 두 경우 모두 구조화된 출력이 지원되지 않으면 에이전트가 도구 호출 전략으로 폴백합니다.
tool_message_content 매개변수를 사용하면 구조화된 출력이 생성될 때 대화 기록에 나타나는 메시지를 커스터마이즈할 수 있습니다:
Copy
from pydantic import BaseModel, Fieldfrom typing import Literalfrom langchain.agents import create_agentfrom langchain.agents.structured_output import ToolStrategyclass MeetingAction(BaseModel): """회의록에서 추출한 액션 아이템입니다.""" task: str = Field(description="완료해야 할 구체적인 작업") assignee: str = Field(description="작업 담당자") priority: Literal["low", "medium", "high"] = Field(description="우선순위 레벨")agent = create_agent( model="openai:gpt-5", tools=[], response_format=ToolStrategy( schema=MeetingAction, tool_message_content="액션 아이템이 캡처되어 회의록에 추가되었습니다!" ))agent.invoke({ "messages": [{"role": "user", "content": "From our meeting: Sarah needs to update the project timeline as soon as possible"}]})
Copy
================================ 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액션 아이템이 캡처되어 회의록에 추가되었습니다!
tool_message_content 없이는 최종 ToolMessage가 다음과 같이 표시됩니다:
================================ Human Message =================================Extract info: John Doe ([email protected]) is organizing Tech Conference on March 15thNone================================== 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: ContactInfoError: Model incorrectly returned multiple structured responses (ContactInfo, EventDetails) when only one is expected. Please fix your mistakes.================================= Tool Message =================================Name: EventDetailsError: 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: ContactInfoReturning structured response: {'name': 'John Doe', 'email': '[email protected]'}
구조화된 출력이 예상 스키마와 일치하지 않으면, 에이전트가 구체적인 오류 피드백을 제공합니다:
Copy
from pydantic import BaseModel, Fieldfrom langchain.agents import create_agentfrom langchain.agents.structured_output import ToolStrategyclass ProductRating(BaseModel): rating: int | None = Field(description="1-5 사이의 평점", ge=1, le=5) comment: str = Field(description="리뷰 코멘트")agent = create_agent( model="openai:gpt-5", tools=[], response_format=ToolStrategy(ProductRating), # 기본값: 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!"}]})
Copy
================================ 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: ProductRatingError: 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: ProductRatingReturning structured response: {'rating': 5, 'comment': 'Amazing product'}
handle_errors가 예외 튜플인 경우, 발생한 예외가 지정된 타입 중 하나인 경우에만 에이전트가 재시도합니다(기본 오류 메시지 사용). 다른 모든 경우에는 예외가 발생합니다.커스텀 오류 핸들러 함수:
Copy
def custom_error_handler(error: Exception) -> str: if isinstance(error, StructuredOutputValidationError): return "형식에 문제가 있습니다. 다시 시도해주세요." elif isinstance(error, MultipleStructuredOutputsError): return "여러 구조화된 출력이 반환되었습니다. 가장 관련성 높은 것을 선택하세요." else: return f"오류: {str(error)}"ToolStrategy( schema=ToolStrategy(Union[ContactInfo, EventDetails]), handle_errors=custom_error_handler)
StructuredOutputValidationError 발생 시:
Copy
================================= Tool Message =================================Name: ToolStrategy형식에 문제가 있습니다. 다시 시도해주세요.
MultipleStructuredOutputsError 발생 시:
Copy
================================= Tool Message =================================Name: ToolStrategy여러 구조화된 출력이 반환되었습니다. 가장 관련성 높은 것을 선택하세요.