2025년 인공지능 기술은 단순한 명령 실행을 넘어 복잡한 워크플로우를 자율적으로 처리하는 '에이전틱 AI' 시스템으로 발전하고 있습니다. 이러한 변화의 중심에는 PydanticAI라는 새로운 프레임워크가 있습니다. 이 글에서는 PydanticAI를 활용한 에이전틱 AI 시스템 구축 방법과 그 가능성에 대해 알아보겠습니다.
PydanticAI를 활용한 에이전틱AI 시스템 구축 (에이전틱 AI - 랭체인코리아 밋업 2025Q1)
이 영상은 **PydanticAI**를 활용하여 에이전틱 AI 시스템을 구축하는 방법에 대한 발표 내용을 담고 있습니다. PydanticAI는 데이터 검증 라이브러리인 Pydantic을 기반으로 하며, LM 출력을 코드에 통합
lilys.ai
파이댄틱 AI, 구조화된 데이터 처리의 혁신
파이댄틱 AI는 2024년 말에 공개된 신생 프레임워크로, 강력한 데이터 검증 라이브러리인 파이댄틱(Pydantic)을 기반으로 합니다. 파이댄틱은 이미 FastAPI, LangChain 등 다양한 프레임워크에서 데이터 검증을 위해 널리 사용되고 있는 라이브러리입니다.
데이터 검증의 중요성
데이터 검증이란 외부에서 들어오는 데이터가 우리가 기대하는 타입이나 조건에 부합하는지 확인하는 과정입니다. 파이댄틱은 단순히 검증뿐만 아니라 자동 형변환 기능도 제공합니다. 예를 들어, 문자열로 들어온 숫자를 정수형으로 자동 변환해 주는 기능은 개발 과정에서 매우 유용합니다.
from pydantic import BaseModel
class User(BaseModel):
id: int
name: str
is_active: bool
# 문자열 "123"이 자동으로 정수 123으로 변환됩니다
user = User(id="123", name="홍길동", is_active=True)
파이댄틱의 또 다른 강점은 조건에 맞지 않는 데이터가 입력되거나 필수 필드가 누락되었을 때 명확한 경고 메시지를 표시한다는 점입니다. 이는 개발 단계에서 디버깅을 크게 도와줍니다.
LLM과 코드 통합의 새로운 패러다임
최근 몇 년간 인공지능 기술의 발전, 특히 대규모 언어 모델(LLM)의 등장으로 AI 시스템의 입출력 방식에 큰 변화가 생겼습니다.
구조화되지 않은 출력의 도전과제
과거의 AI 모델들은 대부분 정해진 형식의 입력과 출력을 사용했습니다. 그러나 GPT 같은 현대적 LLM은 자연어 형태의 다양한 입력과 출력을 처리할 수 있습니다. 이는 유연성을 크게 높였지만, 동시에 이러한 비구조화된 출력을 코드에 통합하는 과정을 복잡하게 만들었습니다.
여기서 Pydantic의 역할이 중요해집니다. Pydantic은 자유로운 형태의 LLM 출력을 구조화된 데이터로 변환해 코드에서 안정적으로 사용할 수 있도록 도와줍니다. 이러한 이유로 DSPy, Semantix 등 다양한 AI 프레임워크에서 Pydantic 모델을 활용하고 있습니다1.
에이전트 개발의 핵심 요소
에이전트 개발 시에는 LLM의 출력이 직접 코드에 사용되는 경우가 많습니다. 이때 출력 형식의 일관성이 매우 중요하며, Pydantic은 이러한 구조화된 데이터 처리를 가능하게 합니다. 특히 AI가 동적으로 판단하고 실행하는 복잡한 시스템에서 Pydantic의 중요성은 더욱 커집니다.
파이댄틱 AI의 구조와 기능
파이댄틱 AI는 LLM을 효과적으로 활용하기 위한 다양한 기능을 제공합니다.
자연어 프롬프트의 활용
과거에는 모델별로 개별 태스크에 맞게 학습을 진행해야 했지만, 현재는 자연어 프롬프트를 활용하여 새로운 모델을 쉽게 개발할 수 있게 되었습니다. 이는 AI 시스템 개발의 유연성과 생산성을 크게 향상시켰습니다.
LLM 판단의 활용 방식
LLM의 판단은 주로 두 가지 방식으로 활용됩니다:
- 구조화된 출력 방식: LLM이 직접 구조화된 형태의 데이터를 출력
- 도구 호출 방식: LLM이 적절한 도구(함수)를 선택하고 매개변수를 제공
파이댄틱 AI는 이 두 가지 방식을 모두 지원하며, 에이전트 모델을 통해 유연하게 관리할 수 있습니다.
간편한 에이전트 생성
PydanticAI는 사용자가 간단히 에이전트를 생성할 수 있는 인터페이스를 제공합니다:
from pydanticai import ESAgent
agent = ESAgent(
model="gpt-4",
system_prompt="당신은 도움이 되는 AI 비서입니다."
)
또한 결과 형식 지정, 스트리밍 결과 수신, 의존성 주입 등 다양한 기능을 지원하여 개발자의 생산성을 높입니다.
멀티 에이전트 시스템 구현하기
복잡한 작업을 처리하기 위해서는 여러 에이전트가 협력하는 멀티 에이전트 시스템이 필요합니다. LatteReview와 같은 멀티 에이전트 프레임워크도 Pydantic 기반의 검증을 사용하여 구조화된 입출력을 처리합니다2.
도구 통합 방식
파이댄틱 AI는 데코레이터를 사용하여 에이전트와 도구를 쉽게 연결할 수 있는 구조를 제공합니다:
@agent.tool
def search_web(query: str) -> str:
"""웹에서 정보를 검색합니다."""
# 검색 구현
return search_results
최근에는 검색용 도구도 지원하기 시작했으며, 외부에서 의존성을 주입하여 실행 시점에 관리할 수 있는 특징이 있습니다. 이를 통해 API 키나 클라이언트 등을 유연하게 관리할 수 있으며, 테스트 시에는 가짜 모델을 사용하여 코드 전체가 잘 작동하는지 확인할 수 있습니다.
멀티 에이전트 구현 방법
멀티 에이전트 시스템은 크게 세 가지 방식으로 구현할 수 있습니다:
- 도구 호출 방식: 메인 에이전트가 다른 에이전트를 도구로 호출하여 사용
- 애플리케이션 코드 방식: 개발자가 특정 조건에 따라 에이전트 호출 순서를 결정
- 그래프 방식: 복잡한 워크플로우를 그래프 형태로 관리
도구 호출 방식 예시
# 메인 에이전트 설정
main_agent = ESAgent(model="gpt-4", system_prompt="당신은 메인 조정자입니다.")
# 특화된 에이전트 설정
web_search_agent = ESAgent(model="gpt-4", system_prompt="당신은 웹 검색 전문가입니다.")
weather_agent = ESAgent(model="gpt-4", system_prompt="당신은 날씨 정보 전문가입니다.")
# 메인 에이전트에 도구로 등록
@main_agent.tool
def search_web(query: str) -> str:
return web_search_agent.run(query)
@main_agent.tool
def get_weather(location: str) -> str:
return weather_agent.run(f"{location}의 날씨는 어떻습니까?")
이 방식은 일종의 슈퍼바이저 패턴으로, 메인 에이전트가 작업을 조정하고 필요에 따라 특화된 에이전트를 호출합니다.
애플리케이션 코드 방식 예시
애플리케이션 코드에서는 개발자가 특정 조건에 따라 에이전트 호출 순서를 결정합니다:
# 사용자 쿼리 분석
location_info = location_agent.run(user_query)
# 위치 정보가 있을 경우에만 날씨 에이전트 호출
if location_info.has_city or location_info.has_country:
weather_info = weather_agent.run(f"{location_info.city or location_info.country}의 날씨는?")
return f"{location_info.city or location_info.country}의 현재 날씨: {weather_info}"
else:
return "위치 정보를 찾을 수 없습니다."
그래프 방식의 워크플로우 관리
그래프 기능은
2025년 1월 15일에 처음 추가된 초기 단계의 기능입니다. 파이댄틱 그래프는 복잡한 워크플로우를 시각적으로 표현하고 관리할 수 있게 해줍니다.
from pydanticai.graph import Graph, Node
# 그래프 생성
workflow = Graph()
# 노드 정의
input_node = Node(id="input", fn=lambda x: x)
check_divisible = Node(id="check", fn=lambda x: x % 5 == 0)
increment = Node(id="increment", fn=lambda x: x + 1)
output_node = Node(id="output", fn=lambda x: f"결과: {x}")
# 노드 연결
workflow.add_edge(input_node, check_divisible)
workflow.add_edge(check_divisible, output_node, condition=True)
workflow.add_edge(check_divisible, increment, condition=False)
workflow.add_edge(increment, check_divisible)
# 실행
result = workflow.execute(7) # 7 → 8 → 9 → 10 → "결과: 10"
이 그래프 방식은 LangChain의 그래프와 유사하지만, 아직 초기 단계로 많은 기능이 개발 중입니다.
에이전틱 AI 시스템의 미래와 통합
현재 파이댄틱 그래프는 초기 형태로, 많은 기능이 개발 중에 있습니다. 아직 지원되지 않는 기능으로는:
- 인터럽트 기능: 그래프 실행 중 사용자 입력 받기
- 맨드라 기능: 특정 노드로 직접 이동
- 체크포인트와 메모리 기능: 실행 상태 저장 및 복원
이러한 제한에도 불구하고, 파이댄틱 AI를 LangChain과 같은 다른 프레임워크와 함께 사용하면 더 강력한 시너지를 낼 수 있습니다. 예를 들어, 전체 워크플로우는 LangChain 그래프로 관리하고, 개별 노드에서 파이댄틱 AI 에이전트를 활용하는 방식으로 구현할 수 있습니다.
결론
파이댄틱 AI는 LLM을 활용한 에이전틱 AI 시스템 구축을 위한 강력한 도구입니다. 데이터 검증 기능, 에이전트 통합, 그래프 기반 워크플로우 관리 등 다양한 기능을 제공하여 복잡한 AI 시스템을 더 쉽게 구현할 수 있게 합니다.
비록 아직 초기 단계이지만, 이미 다른 AI 프레임워크들도 Pydantic 모델을 활용하고 있다는 점에서 그 가능성과 확장성을 엿볼 수 있습니다. DSPy, Semantix, LatteReview 등 다양한 프레임워크들도 Pydantic 모델을 사용하여 구조화된 데이터 처리를 지원하고 있습니다12.
앞으로 파이댄틱 AI가 어떻게 발전하고, 에이전틱 AI 시스템의 구축을 더욱 편리하게 만들어 나갈지 기대됩니다. 개발자들은 이러한 도구를 활용하여 더 복잡하고 지능적인 AI 시스템을 구축할 수 있을 것입니다.
여러분은 어떤 에이전틱 AI 시스템을 구축해보고 싶으신가요? 파이댄틱 AI와 같은 최신 도구들을 활용하여 여러분의 아이디어를 실현해보세요!
#AI개발 #파이댄틱AI #에이전틱AI #LLM #인공지능프레임워크 #멀티에이전트 #워크플로우자동화 #파이썬개발 #AI시스템설계 #데이터검증 #Pydantic #AIagent #PydanticAI #LangChain

Building Next-Generation Agentic AI Systems with PydanticAI: A New Horizon for Structured Data Processing
In 2025, artificial intelligence technology has evolved beyond simple command execution to "agentic AI" systems that autonomously handle complex workflows. At the center of this transformation is a new framework called PydanticAI. In this article, we'll explore how to build agentic AI systems using PydanticAI and its potential.
PydanticAI: Innovation in Structured Data Processing
PydanticAI is a new framework released at the end of 2024, based on the powerful data validation library Pydantic. Pydantic is already widely used for data validation in various frameworks such as FastAPI and LangChain.
The Importance of Data Validation
Data validation is the process of verifying that data coming from external sources meets our expected types or conditions. Pydantic not only validates but also provides automatic type conversion. For example, the ability to automatically convert a numeric string to an integer is very useful during development.
from pydantic import BaseModel
class User(BaseModel):
id: int
name: str
is_active: bool
# The string "123" is automatically converted to the integer 123
user = User(id="123", name="John Doe", is_active=True)
Another strength of Pydantic is displaying clear warning messages when non-compliant data is entered or required fields are missing. This greatly assists with debugging during development.
A New Paradigm for LLM and Code Integration
In recent years, advancements in AI technology, particularly the emergence of Large Language Models (LLMs), have brought significant changes to how AI systems handle inputs and outputs.
Challenges of Unstructured Outputs
Most AI models in the past used predetermined input and output formats. However, modern LLMs like GPT can process various inputs and outputs in natural language form. This has greatly increased flexibility but has also complicated the process of integrating such unstructured outputs into code.
This is where Pydantic's role becomes important. Pydantic helps convert free-form LLM outputs into structured data for reliable use in code. For this reason, various AI frameworks such as DSPy and Semantix utilize Pydantic models1.
Core Elements of Agent Development
When developing agents, LLM outputs are often used directly in code. Consistency in output format is very important in these cases, and Pydantic enables such structured data processing. The importance of Pydantic becomes even greater in complex systems where AI dynamically makes decisions and executes actions.
Structure and Functions of PydanticAI
PydanticAI provides various features for effectively utilizing LLMs.
Utilization of Natural Language Prompts
In the past, models had to be trained specifically for individual tasks, but now it's possible to easily develop new models using natural language prompts. This has greatly improved the flexibility and productivity of AI system development.
Ways to Utilize LLM Judgments
LLM judgments are primarily utilized in two ways:
- Structured Output Method: The LLM directly outputs data in a structured format
- Tool Calling Method: The LLM selects appropriate tools (functions) and provides parameters
PydanticAI supports both of these methods and can flexibly manage them through agent models.
Simple Agent Creation
PydanticAI provides an interface for users to create agents simply:
from pydanticai import ESAgent
agent = ESAgent(
model="gpt-4",
system_prompt="You are a helpful AI assistant."
)
It also supports various features such as result format specification, streaming result reception, and dependency injection, enhancing developer productivity.
Implementing Multi-Agent Systems
To handle complex tasks, multi-agent systems where multiple agents collaborate are necessary. Multi-agent frameworks like LatteReview also use Pydantic-based validation to handle structured inputs and outputs2.
Tool Integration Method
PydanticAI provides a structure that easily connects agents and tools using decorators:
@agent.tool
def search_web(query: str) -> str:
"""Search for information on the web."""
# Search implementation
return search_results
It has recently started supporting tools for searching and has the characteristic of being able to manage dependencies by injecting them from outside at runtime. This allows for flexible management of API keys and clients, and during testing, the entire code can be verified by using mock models.
Methods for Implementing Multi-Agent Systems
Multi-agent systems can be implemented in three main ways:
- Tool Calling Method: The main agent calls other agents as tools
- Application Code Method: The developer determines the order of agent calls based on specific conditions
- Graph Method: Complex workflows are managed in graph form
Tool Calling Method Example
# Set up the main agent
main_agent = ESAgent(model="gpt-4", system_prompt="You are the main coordinator.")
# Set up specialized agents
web_search_agent = ESAgent(model="gpt-4", system_prompt="You are a web search expert.")
weather_agent = ESAgent(model="gpt-4", system_prompt="You are a weather information expert.")
# Register as tools to the main agent
@main_agent.tool
def search_web(query: str) -> str:
return web_search_agent.run(query)
@main_agent.tool
def get_weather(location: str) -> str:
return weather_agent.run(f"What is the weather in {location}?")
This method is a kind of supervisor pattern where the main agent coordinates tasks and calls specialized agents as needed.
Application Code Method Example
In the application code, the developer determines the order of agent calls based on specific conditions:
# Analyze user query
location_info = location_agent.run(user_query)
# Call weather agent only if location information exists
if location_info.has_city or location_info.has_country:
weather_info = weather_agent.run(f"What's the weather in {location_info.city or location_info.country}?")
return f"Current weather in {location_info.city or location_info.country}: {weather_info}"
else:
return "Location information not found."
Graph-Based Workflow Management
The graph feature was first added on January 15, 2025, and is in its early stages. Pydantic graphs allow complex workflows to be visually represented and managed.
from pydanticai.graph import Graph, Node
# Create a graph
workflow = Graph()
# Define nodes
input_node = Node(id="input", fn=lambda x: x)
check_divisible = Node(id="check", fn=lambda x: x % 5 == 0)
increment = Node(id="increment", fn=lambda x: x + 1)
output_node = Node(id="output", fn=lambda x: f"Result: {x}")
# Connect nodes
workflow.add_edge(input_node, check_divisible)
workflow.add_edge(check_divisible, output_node, condition=True)
workflow.add_edge(check_divisible, increment, condition=False)
workflow.add_edge(increment, check_divisible)
# Execute
result = workflow.execute(7) # 7 → 8 → 9 → 10 → "Result: 10"
This graph method is similar to LangChain's graph but is still in the early stages with many features under development.
The Future of Agentic AI Systems and Integration
Currently, Pydantic graphs are in their early form with many features under development. Features not yet supported include:
- Interrupt feature: Receiving user input during graph execution
- Mandra feature: Direct movement to specific nodes
- Checkpoint and memory features: Saving and restoring execution states
Despite these limitations, using PydanticAI together with other frameworks like LangChain can create a powerful synergy. For example, the overall workflow can be managed with a LangChain graph, and PydanticAI agents can be utilized in individual nodes.
Conclusion
PydanticAI is a powerful tool for building agentic AI systems utilizing LLMs. It provides various features such as data validation, agent integration, and graph-based workflow management, making it easier to implement complex AI systems.
Although still in its early stages, the fact that other AI frameworks are also utilizing Pydantic models shows its potential and scalability. Various frameworks such as DSPy, Semantix, and LatteReview use Pydantic models to support structured data processing12.
We look forward to seeing how PydanticAI develops and makes building agentic AI systems more convenient. Developers can use these tools to build more complex and intelligent AI systems.
What kind of agentic AI system would you like to build? Use the latest tools like PydanticAI to bring your ideas to life!
#AIDevelopment #PydanticAI #AgenticAI #LLM #AIFramework #MultiAgent #WorkflowAutomation #PythonDevelopment #AISystemDesign #DataValidation #Pydantic #AIagent #PydanticAI #LangChain
Citations:
- https://arxiv.org/pdf/2410.18146.pdf
- https://arxiv.org/abs/2501.05468
- https://www.semanticscholar.org/paper/b0cca9021f02308409374e14081550e80d57b1fd
- https://www.semanticscholar.org/paper/5bf39d952cd94bf71e6b5fd04170b9d9b79ec0f4
- https://www.semanticscholar.org/paper/1a4c6856292b8c64d19a812a77f0aa6fd47cb96c
- https://arxiv.org/abs/2302.06590
- https://www.semanticscholar.org/paper/117e0e417f8d513945cc0f22f107f5a4baa04732
- https://www.semanticscholar.org/paper/5bac0ce06b139041b7aba4715494431f458379fc
- https://www.semanticscholar.org/paper/a1f3a5f16faf9670f948f1e4e84d12f08dfe353b
- https://www.semanticscholar.org/paper/bdadef060e6603962ae26a63d8c4611f676b441a
'Agentic AI' 카테고리의 다른 글
에이전트 AI 혁명: 여러 LLM을 조합한 스마트 솔루션 개발의 비밀 (0) | 2025.03.23 |
---|---|
AI 에이전트와 사용자 경험(UX): 성공적인 상호작용을 위한 디자인의 중요성 (0) | 2025.03.23 |
실질적 임팩트 없는 AI 도입은 의미 없다: 조직의 성공적인 AI 전환을 위한 핵심 전략 (0) | 2025.03.22 |
AI와 UX의 완벽한 조화: 기술이 아닌 사용자 중심 혁신을 말하다 (1) | 2025.03.22 |
미래를 바꿀 AI 에이전트 기술, 어디까지 왔나? (Anthropic의 Claude와 Manus AI 협업 사례) (1) | 2025.03.22 |