I’ll attempt to answer your questions about the .parse() version of chat completions, found in ‘beta’. The new beta method, when used with a BaseModel, enforces and passes strict:true without regard to your desires otherwise when you use a pydantic BaseModel as the response_format. For example, le… Answer from arata on community.openai.com
🌐
Pydantic
docs.pydantic.dev › latest › concepts › json_schema
JSON Schema - Pydantic Validation
Here's an example of generating JSON schema from a BaseModel: ... import json from enum import Enum from typing import Annotated, Union from pydantic import BaseModel, Field from pydantic.config import ConfigDict class FooBar(BaseModel): count: int size: Union[float, None] = None class Gender(str, Enum): male = 'male' female = 'female' other = 'other' not_given = 'not_given' class MainModel(BaseModel): """ This is the description of the main model """ model_config = ConfigDict(title='Main') foo_bar: FooBar gender: Annotated[Union[Gender, None], Field(alias='Gender')] = None snap: int = Field( default=42, title='The Snap', description='this is the value of snap', gt=30, lt=50, ) main_model_schema = MainModel.model_json_schema() # (1)!
Discussions

dynamic - Dynamically Generating Pydantic Model from a Schema JSON File - Stack Overflow
I want to dynamically generate a Pydantic model at runtime. I can do this by calling create_model. For example, from pydantic import create_model create_model("MyModel", i=(int,...), s=(str...)) ... I want to serialize these Pydantic schemas as JSON. It's easy to write code to parse JSON into ... More on stackoverflow.com
🌐 stackoverflow.com
Take 2: create model from JSON schema aka model_load_json_schema()
In short, there is a method for ... from JSON to a Model. The use case is simple: I want to give my users the capability to store arbitrary artifacts. An artifact can be anything, any object: a car, a travel trip, a database cluster, a toilet, you name it. But it has to conform to a predefined schema for that object. So an admin user would say, fine, we create the model schema (using the pydantic ... More on github.com
🌐 github.com
5
11
python - Pydantic model for JSON Meta Schema - Stack Overflow
I have a use case where user needs to define some JSON Schema for later usage. Right know I am using Pydantic parse user configs and check if they are ok. Does any one know if there exist an librar... More on stackoverflow.com
🌐 stackoverflow.com
jsonschema - Pydantic v2 to JSON Schema translation: How to suppress autogeneration of "title" annotation in v2? - Stack Overflow
I am using Pydantic 2.6.4 to generate JSON schemas. If I write an attribute in a Pydantic model that has no value for "title" in its FieldInfo, Pydantic will always autogenerate one from ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Pydantic
docs.pydantic.dev › 1.10 › usage › schema
Schema - Pydantic
On the contrary, JSON Schema validators treat the pattern keyword as implicitly unanchored, more like what re.search does. For interoperability, depending on your desired behavior, either explicitly anchor your regular expressions with ^ (e.g. ^foo to match any string starting with foo), or explicitly allow an arbitrary prefix with .*? (e.g. .*?foo to match any string containing the substring foo). See #1631 for a discussion of possible changes to pydantic ...
🌐
Medium
medium.com › @kishanbabariya101 › episode-8-json-schema-generation-in-pydantic-9a4c4fee02c8
Episode 8: JSON Schema Generation in Pydantic | by Kishan Babariya | Medium
December 17, 2024 - Sometimes, you may need to tweak the default JSON Schema to better describe your data. You can use the Field function to add metadata like descriptions and examples to your schema. from pydantic import BaseModel, Field class Product(BaseModel): id: int = Field(..., description="The unique identifier for the product") name: str = Field(..., description="The name of the product", example="Laptop") price: float = Field(..., ge=0, description="The price of the product", example=999.99) print(Product.model_json_schema())
Top answer
1 of 5
11

This has been discussed some time ago and Samuel Colvin said he didn't want to pursue this as a feature for Pydantic.

If you are fine with code generation instead of actual runtime creation of models, you can use the datamodel-code-generator.

To be honest, I struggle to see the use case for generating complex models at runtime, seeing as their main purpose is validation, implying that you think about correct schema before running your program. But that is just my view.

For simple models I guess you can throw together your own logic for this fairly quickly.

If do you need something more sophisticated, the aforementioned library does offer some extensibility. You should be able to import and inherit from some of their classes like the JsonSchemaParser. Maybe that will get you somewhere.

Ultimately I think this becomes non-trivial very quickly, which is why Pydantic's maintainer didn't want to deal with it and why there is a whole separate project for this.

2 of 5
7

Updated @Alon's answer to handle nested modals:

from typing import Any, Type, Optional
from enum import Enum

from pydantic import BaseModel, Field, create_model


def json_schema_to_base_model(schema: dict[str, Any]) -> Type[BaseModel]:
    type_mapping: dict[str, type] = {
        "string": str,
        "integer": int,
        "number": float,
        "boolean": bool,
        "array": list,
        "object": dict,
    }

    properties = schema.get("properties", {})
    required_fields = schema.get("required", [])
    model_fields = {}

    def process_field(field_name: str, field_props: dict[str, Any]) -> tuple:
        """Recursively processes a field and returns its type and Field instance."""
        json_type = field_props.get("type", "string")
        enum_values = field_props.get("enum")

        # Handle Enums
        if enum_values:
            enum_name: str = f"{field_name.capitalize()}Enum"
            field_type = Enum(enum_name, {v: v for v in enum_values})
        # Handle Nested Objects
        elif json_type == "object" and "properties" in field_props:
            field_type = json_schema_to_base_model(
                field_props
            )  # Recursively create submodel
        # Handle Arrays with Nested Objects
        elif json_type == "array" and "items" in field_props:
            item_props = field_props["items"]
            if item_props.get("type") == "object":
                item_type: type[BaseModel] = json_schema_to_base_model(item_props)
            else:
                item_type: type = type_mapping.get(item_props.get("type"), Any)
            field_type = list[item_type]
        else:
            field_type = type_mapping.get(json_type, Any)

        # Handle default values and optionality
        default_value = field_props.get("default", ...)
        nullable = field_props.get("nullable", False)
        description = field_props.get("title", "")

        if nullable:
            field_type = Optional[field_type]

        if field_name not in required_fields:
            default_value = field_props.get("default", None)

        return field_type, Field(default_value, description=description)

    # Process each field
    for field_name, field_props in properties.items():
        model_fields[field_name] = process_field(field_name, field_props)

    return create_model(schema.get("title", "DynamicModel"), **model_fields)

Example Schema

schema = {
    "title": "User",
    "type": "object",
    "properties": {
        "name": {"type": "string"},
        "age": {"type": "integer"},
        "is_active": {"type": "boolean"},
        "address": {
            "type": "object",
            "properties": {
                "street": {"type": "string"},
                "city": {"type": "string"},
                "zipcode": {"type": "integer"},
            },
        },
        "roles": {
            "type": "array",
            "items": {
                "type": "string",
                "enum": ["admin", "user", "guest"]
            }
        }
    },
    "required": ["name", "age"]
}

Generate the Pydantic model

DynamicModel = json_schema_to_base_model(schema)

Example usage

print(DynamicModel.schema_json(indent=2))
🌐
Pydantic
docs.pydantic.dev › 2.4 › concepts › json_schema
JSON Schema - Pydantic
The generated JSON schemas are compliant with the following specifications: ... OpenAPI extensions. import json from enum import Enum from typing import Union from typing_extensions import Annotated from pydantic import BaseModel, Field from pydantic.config import ConfigDict class FooBar(BaseModel): count: int size: Union[float, None] = None class Gender(str, Enum): male = 'male' female = 'female' other = 'other' not_given = 'not_given' class MainModel(BaseModel): """ This is the description of the main model """ model_config = ConfigDict(title='Main') foo_bar: FooBar gender: Annotated[Union[Gender, None], Field(alias='Gender')] = None snap: int = Field( 42, title='The Snap', description='this is the value of snap', gt=30, lt=50, ) print(json.dumps(MainModel.model_json_schema(), indent=2))
Find elsewhere
🌐
Pydantic
docs.pydantic.dev › latest › integrations › datamodel_code_generator
datamodel-code-generator - Pydantic Validation
# generated by datamodel-codegen: # filename: person.json # timestamp: 2020-05-19T15:07:31+00:00 from __future__ import annotations from typing import Any from pydantic import BaseModel, Field, conint class Pet(BaseModel): name: str | None = None age: int | None = None class Person(BaseModel): first_name: str = Field(description="The person's first name.") last_name: str = Field(description="The person's last name.") age: conint(ge=0) | None = Field(None, description='Age in years.') pets: list[Pet] | None = None comment: Any | None = None
🌐
GitHub
github.com › pydantic › pydantic › blob › main › docs › concepts › json_schema.md
pydantic/docs/concepts/json_schema.md at main · pydantic/pydantic
The [WithJsonSchema][pydantic.... __get_pydantic_core_schema__ or __get_pydantic_json_schema__ on the type itself. Note that this overrides the whole JSON Schema generation process for the field (in the following example, the 'type' also needs to be provided...
Author   pydantic
🌐
Orchestra
getorchestra.io › guides › pydantic-json-schema-a-comprehensive-guide-for-fastapi-users
Pydantic JSON Schema: A Comprehensive Guide for FastAPI Users | Orchestra
April 8, 2024 - First, let's define a basic Pydantic model and see how we can generate its JSON Schema. from pydantic import BaseModel class User(BaseModel): name: str age: int is_active: bool = True user_schema = User.schema() print(user_schema) In this example, ...
🌐
PyPI
pypi.org › project › json-schema-to-pydantic
json-schema-to-pydantic · PyPI
2 weeks ago - from json_schema_to_pydantic import ( SchemaError, # Base class for all schema errors TypeError, # Invalid or unsupported type CombinerError, # Error in schema combiners ReferenceError, # Error in schema references ) try: model = create_model(schema) except TypeError as e: print(f"Invalid type in schema: {e}") except ReferenceError as e: print(f"Invalid reference: {e}")
      » pip install json-schema-to-pydantic
    
Published   Mar 09, 2026
Version   0.4.11
Top answer
1 of 3
2

One solution is to hack the utils out of datamodel-code-generator, specifically their JsonSchemaParser. This generates an intermediate text representation of all pydantic models which you can then dynamically import. You might reasonably balk at this, but it does allow for self-referencing and multi-model setups at least:

import importlib.util
import json
import re
import sys
from contextlib import contextmanager
from pathlib import Path
from tempfile import NamedTemporaryFile
from types import ModuleType

from datamodel_code_generator.parser.jsonschema import JsonSchemaParser
from pydantic import BaseModel


NON_ALPHANUMERIC = re.compile(r"[^a-zA-Z0-9]+")
UPPER_CAMEL_CASE = re.compile(r"[A-Z][a-zA-Z0-9]+")
LOWER_CAMEL_CASE = re.compile(r"[a-z][a-zA-Z0-9]+")

class BadJsonSchema(Exception):
    pass


def _to_camel_case(name: str) -> str:
    if any(NON_ALPHANUMERIC.finditer(name)):
        return "".join(term.lower().title() for term in NON_ALPHANUMERIC.split(name))
    if UPPER_CAMEL_CASE.match(name):
        return name
    if LOWER_CAMEL_CASE.match(name):
        return name[0].upper() + name[1:]
    raise BadJsonSchema(f"Unknown case used for {name}")


def _load_module_from_file(file_path: Path) -> ModuleType:
    spec = importlib.util.spec_from_file_location(
        name=file_path.stem, location=str(file_path)
    )
    module = importlib.util.module_from_spec(spec)
    sys.modules[file_path.stem] = module
    spec.loader.exec_module(module)
    return module


@contextmanager
def _delete_file_on_completion(file_path: Path):
    try:
        yield
    finally:
        file_path.unlink(missing_ok=True)


def json_schema_to_pydantic_model(json_schema: dict, name_override: str) -> BaseModel:
    json_schema_as_str = json.dumps(json_schema)
    pydantic_models_as_str: str = JsonSchemaParser(json_schema_as_str).parse()

    with NamedTemporaryFile(suffix=".py", delete=False) as temp_file:
        temp_file_path = Path(temp_file.name).resolve()
        temp_file.write(pydantic_models_as_str.encode())

    with _delete_file_on_completion(file_path=temp_file_path):
        module = _load_module_from_file(file_path=temp_file_path)

    main_model_name = _to_camel_case(name=json_schema["title"])
    pydantic_model: BaseModel = module.__dict__[main_model_name]
    # Override the pydantic model/parser name for nicer ValidationError messaging and logging
    pydantic_model.__name__ = name_override
    pydantic_model.parse_obj.__func__.__name__ = name_override
    return pydantic_model

Main drawback as I see it- datamodel-code-generator has non-dev dependencies isort and black- not ideal to have in your deployments.

2 of 3
2

If I understand correctly, you are looking for a way to generate Pydantic models from JSON schemas. Here is an implementation of a code generator - meaning you feed it a JSON schema and it outputs a Python file with the Model definition(s). It is not "at runtime" though. For this, an approach that utilizes the create_model function was also discussed in this issue thread a while back, but as far as I know there is no such feature in Pydantic yet.

If you know that your models will not be too complex, it might be fairly easy to implement a crude version of this yourself. Essentially the properties in a JSON schema are reflected fairly nicely by the __fields__ attribute of a model. You could write a function that takes a parsed JSON schema (i.e. a dictionary) and generates the Field definitions to pass to create_model.

🌐
Pydantic
docs.pydantic.dev › latest › concepts › json
JSON - Pydantic Validation
The JSON list is incomplete - it's missing a closing "] When allow_partial is set to False (the default), a parsing error occurs. When allow_partial is set to True, part of the input is deserialized successfully. This also works for deserializing partial dictionaries. For example: from pydantic_core import from_json partial_dog_json = '{"breed": "lab", "name": "fluffy", "friends": ["buddy", "spot", "rufus"], "age' dog_dict = from_json(partial_dog_json, allow_partial=True) print(dog_dict) #> {'breed': 'lab', 'name': 'fluffy', 'friends': ['buddy', 'spot', 'rufus']}
🌐
LangChain
python.langchain.com › docs › modules › model_io › output_parsers › pydantic
Pydantic (JSON) parser
Validation: Pydantic models provide automatic validation. TypedDict and JSON Schema require manual validation. See your provider’s integration page for supported methods and configuration options. Example: Message output alongside parsed structure
🌐
Pydantic
pydantic.com.cn › en › api › json_schema
JSON Schema - Pydantic documentation (en)
Generates a JSON schema that matches None. ... Generates a JSON schema that matches a bool value.
🌐
Pydantic
pydantic.dev › articles › llm-intro
How to Use Pydantic for LLMs: Schema, Validation & Prompts
January 4, 2024 - resp = client.chat.completions.create( model="gpt-3.5-turbo", messages=[ { "role": "user", "content": "Pydantic and FastAPI?", }, ], tools=[ { "type": "function", "function": { "name": "Requirements", "description": "A list of packages and their first authors.", "parameters": { "$defs": { "Package": { "properties": { "name": {"title": "Name", "type": "string"}, "author": {"title": "Author", "type": "string"}, }, "required": ["name", "author"], "title": "Package", "type": "object", } }, "properties": { "packages": { "items": {"$ref": "#/$defs/Package"}, "title": "Packages", "type": "array", } }
🌐
PyPI
pypi.org › project › jsonschema-pydantic
jsonschema-pydantic · PyPI
jsonschema_pydantic-0.6.tar.gz (6.2 kB view details)
      » pip install jsonschema-pydantic
    
Published   Feb 03, 2024
Version   0.6
🌐
Couchbase
couchbase.com › home › validate json documents in python using pydantic
JSON Validation Against Pydantic Schema Tutorial | Couchbase
June 14, 2025 - In the above example, we validate the mobile and home fields to check for extensions. If they contain an extension, we do not support it and throw a custom error. These schema errors are then shown to the users doing the pydantic validation. You can view the schema definition by specifying the Model.schema_json() method as shown here:
🌐
FastAPI
fastapi.tiangolo.com › tutorial › schema-extra-example
Declare Request Example Data - FastAPI
Even after OpenAPI 3.1.0 was released ... examples inside a Pydantic model, using schema_extra or Field(examples=["something"]) that example is added to the JSON Schema for that Pydantic model....