Skip to content

Welcome to Pydantic2

A powerful Python framework for building AI applications with structured responses, powered by Pydantic AI and OpenRouter.

Pydantic2

Core Features

  • Type-safe responses from AI models
  • Automatic validation and parsing
  • Comprehensive usage tracking
  • Budget management
  • Error handling
  • Online search capabilities

For more details, check out our Core Concepts section.

Pydantic2

Documentation PyPI version License: MIT Security Policy PyUp Safety Known Vulnerabilities GitGuardian scan

Introduction

Pydantic2 combines the power of large language models with structured outputs using Pydantic. This framework allows you to:

  • Define structured output formats using Pydantic models
  • Connect to various LLM providers through a unified interface
  • Track usage and costs
  • Enable internet search capabilities
  • Manage response budgets
  • Handle errors gracefully
  • View and analyze usage data through built-in tools

Key Features

  • 🔒 Type-Safe Responses: Built on Pydantic AI for robust type validation
  • 🌐 Online Search: Real-time internet access for up-to-date information
  • 💰 Budget Control: Built-in cost tracking and budget management
  • 📊 Usage Monitoring: Detailed token and cost tracking
  • 🔄 Async Support: Both sync and async interfaces
  • 🛡️ Error Handling: Comprehensive exception system
  • 🎨 Colored Logging: Beautiful console output with detailed logs
  • 🔍 Database Viewer: Built-in CLI tools to inspect models and usage databases

Quick Example

from typing import List
from pydantic import BaseModel, Field
from pydantic2 import PydanticAIClient, ModelSettings

# Define your response model
class ChatResponse(BaseModel):
    message: str = Field(description="The chat response message")
    sources: List[str] = Field(default_factory=list, description="Sources used")
    confidence: float = Field(ge=0, le=1, description="Confidence score")

# Initialize client
client = PydanticAIClient(
    model_name="openai/gpt-4o-mini-2024-07-18",
    client_id="my_app",           # Required for usage tracking
    user_id="user123",           # Required for usage tracking
    verbose=True,
    online=True,                 # Enable internet access
    max_budget=10.0,            # Set $10 budget limit
    model_settings=ModelSettings(
        max_tokens=1000,
        temperature=0.7,
        top_p=1,
        frequency_penalty=0,
    )
)

# Add context
client.message_handler.add_message_system(
    "You are a helpful AI assistant. Be concise but informative."
)

# Add user message
client.message_handler.add_message_user(
    "What is the capital of France?"
)

# Generate response
response: ChatResponse = client.generate(
    result_type=ChatResponse
)

print(f"Message: {response.message}")
print(f"Sources: {response.sources}")
print(f"Confidence: {response.confidence}")

# Get usage statistics
stats = client.get_usage_stats()
print(f"Total cost: ${stats.get('total_cost', 0):.4f}")

Getting Started

Core Concepts

CLI Tools

Examples

Contributing

We welcome contributions! See the project repository on GitHub for more information.