autogen_core.utils#
- schema_to_pydantic_model(schema: Dict[str, Any], model_name: str = 'GeneratedModel') Type[BaseModel] [source]#
Convert a JSON Schema dictionary to a fully-typed Pydantic model.
This function handles schema translation and validation logic to produce a Pydantic model.
Supported JSON Schema Features
Primitive types: string, integer, number, boolean, object, array, null
- String formats:
email, uri, uuid, uuid1, uuid3, uuid4, uuid5
hostname, ipv4, ipv6, ipv4-network, ipv6-network
date, time, date-time, duration
byte, binary, password, path
- String constraints:
minLength, maxLength, pattern
- Numeric constraints:
minimum, maximum, exclusiveMinimum, exclusiveMaximum
- Array constraints:
minItems, maxItems, items
- Object schema support:
properties, required, title, description, default
- Enums:
Converted to Python Literal type
- Union types:
anyOf, oneOf supported with optional discriminator
- Inheritance and composition:
allOf merges multiple schemas into one model
- $ref and $defs resolution:
Supports references to sibling definitions and self-referencing schemas
from autogen_core.utils import schema_to_pydantic_model # Example 1: Simple user model schema = { "title": "User", "type": "object", "properties": { "name": {"type": "string"}, "email": {"type": "string", "format": "email"}, "age": {"type": "integer", "minimum": 0}, }, "required": ["name", "email"], } UserModel = schema_to_pydantic_model(schema) user = UserModel(name="Alice", email="[email protected]", age=30)
from autogen_core.utils import schema_to_pydantic_model # Example 2: Nested model schema = { "title": "BlogPost", "type": "object", "properties": { "title": {"type": "string"}, "tags": {"type": "array", "items": {"type": "string"}}, "author": { "type": "object", "properties": {"name": {"type": "string"}, "email": {"type": "string", "format": "email"}}, "required": ["name"], }, }, "required": ["title", "author"], } BlogPost = schema_to_pydantic_model(schema)
from autogen_core.utils import schema_to_pydantic_model # Example 3: allOf merging with $refs schema = { "title": "EmployeeWithDepartment", "allOf": [{"$ref": "#/$defs/Employee"}, {"$ref": "#/$defs/Department"}], "$defs": { "Employee": { "type": "object", "properties": {"id": {"type": "string"}, "name": {"type": "string"}}, "required": ["id", "name"], }, "Department": { "type": "object", "properties": {"department": {"type": "string"}}, "required": ["department"], }, }, } Model = schema_to_pydantic_model(schema)
from autogen_core.utils import schema_to_pydantic_model # Example 4: Self-referencing (recursive) model schema = { "title": "Category", "type": "object", "properties": { "name": {"type": "string"}, "subcategories": {"type": "array", "items": {"$ref": "#/$defs/Category"}}, }, "required": ["name"], "$defs": { "Category": { "type": "object", "properties": { "name": {"type": "string"}, "subcategories": {"type": "array", "items": {"$ref": "#/$defs/Category"}}, }, "required": ["name"], } }, } Category = schema_to_pydantic_model(schema)
# Example 5: Serializing and deserializing with Pydantic from uuid import uuid4 from pydantic import BaseModel, EmailStr, Field from typing import Optional, List, Dict, Any from autogen_core.utils import schema_to_pydantic_model class Address(BaseModel): street: str city: str zipcode: str class User(BaseModel): id: str name: str email: EmailStr age: int = Field(..., ge=18) address: Address class Employee(BaseModel): id: str name: str manager: Optional["Employee"] = None class Department(BaseModel): name: str employees: List[Employee] class ComplexModel(BaseModel): user: User extra_info: Optional[Dict[str, Any]] = None sub_items: List[Employee] # Convert ComplexModel to JSON schema complex_schema = ComplexModel.model_json_schema() # Rebuild a new Pydantic model from JSON schema ReconstructedModel = schema_to_pydantic_model(complex_schema, "ComplexModel") # Instantiate reconstructed model reconstructed = ReconstructedModel( user={ "id": str(uuid4()), "name": "Alice", "email": "[email protected]", "age": 30, "address": {"street": "123 Main St", "city": "Wonderland", "zipcode": "12345"}, }, sub_items=[{"id": str(uuid4()), "name": "Bob", "manager": {"id": str(uuid4()), "name": "Eve"}}], ) print(reconstructed.model_dump())
- Parameters:
- Returns:
Type[BaseModel] – A dynamically generated Pydantic model class.
- Raises:
ReferenceNotFoundError – If a $ref key references a missing entry.
FormatNotSupportedError – If a format keyword is unknown or unsupported.
UnsupportedKeywordError – If the schema contains an unsupported type.
See also
pydantic.BaseModel
pydantic.create_model()