시작 예제: Pydantic 모델 만들기

시작 예제: Pydantic 모델 만들기

Pydantic AI를 처음 쓸 때 가장 좋은 출발점은 텍스트 입력에서 구조화된 Pydantic 모델을 뽑아내는 짧은 예제예요. 사용자 문장을 모델에 던지면, 에이전트가 그걸 읽고 미리 정의한 output_type에 맞춰 검증된 객체를 돌려줘요. 이 예제가 바로 그 구조화된 출력(Structured Output)을 보여주는 최소 버전이에요.

출처: 공식문서

예제 실행

의존성을 설치하고 환경변수를 설정한 뒤 이렇게 실행해요.

  • pip
python -m pydantic_ai_examples.pydantic_model
  • uv
uv run -m pydantic_ai_examples.pydantic_model

이 예제는 기본적으로 openai:gpt-5를 쓰는데, 다른 모델에서도 잘 동작해요. 예를 들어 Gemini로 실행하려면 이렇게 해요.

  • pip
PYDANTIC_AI_MODEL=gemini-3-pro-preview python -m pydantic_ai_examples.pydantic_model
  • uv
PYDANTIC_AI_MODEL=gemini-3-pro-preview uv run -m pydantic_ai_examples.pydantic_model

(또는 PYDANTIC_AI_MODEL=gemini-3-flash-preview ...)

예제 코드

pydantic_model.py

import os

import logfire
from pydantic import BaseModel

from pydantic_ai import Agent

# 'if-token-present' means nothing will be sent (and the example will work) if you don't have logfire configured
logfire.configure(send_to_logfire='if-token-present')
logfire.instrument_pydantic_ai()


class MyModel(BaseModel):
    city: str
    country: str


model = os.getenv('PYDANTIC_AI_MODEL', 'openai:gpt-5.2')
print(f'Using model: {model}')
agent = Agent(model, output_type=MyModel)

if __name__ == '__main__':
    result = agent.run_sync('The windy city in the US of A.')
    print(result.output)
    print(result.usage)

핵심은 Agent(model, output_type=MyModel) 부분이에요. 에이전트가 "The windy city in the US of A."라는 문장을 해석해서 MyModelcity, country 필드에 맞는 값을 채워 넣어요. result.output은 Pydantic이 검증을 마친 MyModel 인스턴스로, 타입도 그대로 보장돼요. result.usage는 그 실행에서 쓴 토큰 사용량 정보를 담고 있어요.

더 알아보기 (Learn more)