Skip to content

App Module

The App module provides functions for initializing and securing apps that interact with the Unique platform.

Overview

The unique_toolkit.app module encompasses functions for: - Initializing the SDK and logging - Handling events from the platform - Verifying webhook signatures - Building FastAPI applications - Running async tasks in parallel

Components

Settings

unique_toolkit.app.unique_settings.UniqueSettings

Source code in unique_toolkit/unique_toolkit/app/unique_settings.py
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
class UniqueSettings:
    def __init__(
        self,
        auth: AuthContextProtocol,
        app: UniqueApp,
        api: UniqueApi,
        *,
        chat_event_filter_options: UniqueChatEventFilterOptions | None = None,
        chat: ChatContextProtocol | None = None,
        env_file: Path | None = None,
    ):
        self._env = UniqueEnvironment(app=app, api=api)
        self._context = UniqueContext(auth=auth, chat=chat)
        self._chat_event_filter_options = chat_event_filter_options
        self._env_file: Path | None = (
            env_file if (env_file and env_file.exists()) else None
        )

    @classmethod
    def _find_env_file(cls, filename: str = "unique.env") -> Path:
        """Find environment file using cross-platform fallback locations.

        Search order:
        1. UNIQUE_ENV_FILE environment variable
        2. Current working directory
        3. User config directory (cross-platform via platformdirs)

        Args:
            filename: Name of the environment file (default: 'unique.env')

        Returns:
            Path to the environment file.

        Raises:
            EnvFileNotFoundError: If no environment file is found in any location.
        """
        locations = [
            # 1. Explicit environment variable
            Path(env_path) if (env_path := os.environ.get("UNIQUE_ENV_FILE")) else None,
            # 2. Current working directory
            Path.cwd() / filename,
            # 3. User config directory (cross-platform)
            Path(user_config_dir("unique", "unique-toolkit")) / filename,
        ]

        for location in locations:
            if location and location.exists() and location.is_file():
                return location

        # If no file found, provide helpful error message
        searched_locations = [str(loc) for loc in locations if loc is not None]
        raise EnvFileNotFoundError(
            f"Environment file '{filename}' not found. Searched locations:\n"
            + "\n".join(f"  - {loc}" for loc in searched_locations)
            + "\n\nTo fix this:\n"
            + f"  1. Create {filename} in one of the above locations, or\n"
            + f"  2. Set UNIQUE_ENV_FILE environment variable to point to your {filename} file"
        )

    @classmethod
    def from_env(
        cls,
        env_file: Path | None = None,
    ) -> UniqueSettings:
        """Initialize settings from environment variables and/or env file.

        Args:
            env_file: Optional path to environment file. If provided, will load variables from this file.

        Returns:
            UniqueSettings instance with values loaded from environment/env file.

        Raises:
            FileNotFoundError: If env_file is provided but does not exist.
            ValidationError: If required environment variables are missing.
        """
        if env_file and not env_file.exists():
            raise FileNotFoundError(f"Environment file not found: {env_file}")

        # Initialize settings with environment file if provided
        env_file_str = str(env_file) if env_file else None
        auth = UniqueAuth(_env_file=env_file_str)  # type: ignore[call-arg]
        app = UniqueApp(_env_file=env_file_str)  # type: ignore[call-arg]
        api = UniqueApi(_env_file=env_file_str)  # type: ignore[call-arg]
        event_filter_options = UniqueChatEventFilterOptions(_env_file=env_file_str)  # type: ignore[call-arg]
        return cls(
            auth=auth,
            app=app,
            api=api,
            chat_event_filter_options=event_filter_options,
            env_file=env_file,
        )

    @classmethod
    def from_env_auto(cls, filename: str = "unique.env") -> UniqueSettings:
        """Initialize settings by automatically finding environment file.

        This method will automatically search for an environment file in standard locations
        and fall back to environment variables only if no file is found.

        Args:
            filename: Name of the environment file to search for (default: '.env')

        Returns:
            UniqueSettings instance with values loaded from found env file or environment variables.
        """
        try:
            env_file = cls._find_env_file(filename)
            logger.info(f"Environment file found at {env_file}")
            return cls.from_env(env_file=env_file)
        except EnvFileNotFoundError:
            logger.warning(
                f"Environment file '{filename}' not found. Falling back to environment variables only."
            )
            # Fall back to environment variables only
            return cls.from_env()

    def init_sdk(self) -> None:
        """Initialize the unique_sdk global configuration with these settings.

        This method configures the global unique_sdk module with the API key,
        app ID, and base URL from these settings.
        """
        unique_sdk.api_key = self.app.key.get_secret_value()
        unique_sdk.app_id = self.app.id.get_secret_value()
        unique_sdk.api_base = self.api.sdk_url()

    @classmethod
    def from_env_auto_with_sdk_init(
        cls, filename: str = "unique.env"
    ) -> UniqueSettings:
        """Initialize settings and SDK in one convenient call.

        This method combines from_env_auto() and init_sdk() for the most common use case.

        Args:
            filename: Name of the environment file to search for (default: '.env')

        Returns:
            UniqueSettings instance with SDK already initialized.
        """
        settings = cls.from_env_auto(filename)
        settings.init_sdk()
        return settings

    @classmethod
    def from_chat_event(cls, event: ChatEvent) -> UniqueSettings:
        """Build a :class:`UniqueSettings` from a :class:`ChatEvent`.

        Auth and chat context are extracted from the event.  App and API
        settings are left at their default values; override them via the
        returned instance's properties if needed.

        Args:
            event: The incoming chat event.

        Returns:
            UniqueSettings with auth + chat context populated from the event.
        """
        return cls(
            auth=AuthContext.from_event(event),
            app=UniqueApp(),
            api=UniqueApi(),
            chat=ChatContext.from_chat_event(event),
        )

    @property
    def context(self) -> UniqueContext:
        """The request-level context (auth + optional chat) for this settings object."""
        return self._context

    def update_from_event(self, event: BaseEvent) -> None:
        # Use UniqueAuth.from_event so the deprecated settings.auth property
        # keeps working for callers that haven't migrated yet.
        self._context = UniqueContext(
            auth=UniqueAuth.from_event(event), chat=self._context.chat
        )

    # utility method to return a copy with new auth context
    def with_auth(self, auth: AuthContextProtocol) -> Self:
        """Return a copy of the settings with the new auth context."""
        return self.__class__(
            auth=auth,
            app=self.app,
            api=self.api,
            chat_event_filter_options=self.chat_event_filter_options,
            chat=self._context.chat,
            env_file=self._env_file,
        )

    @property
    def api(self) -> UniqueApi:
        return self._env.api

    @property
    def app(self) -> UniqueApp:
        return self._env.app

    @property
    @deprecated("Use authcontext instead")
    def auth(self) -> UniqueAuth:
        if not isinstance(self._context.auth, UniqueAuth):
            raise ValueError("Auth context is not a UniqueAuth instance")
        return self._context.auth

    @auth.setter
    @deprecated("Use authcontext instead")
    def auth(self, value: UniqueAuth) -> None:
        self._context.auth = value

    @property
    def authcontext(self) -> AuthContextProtocol:
        return self._context.auth

    @property
    def chat_event_filter_options(self) -> UniqueChatEventFilterOptions | None:
        return self._chat_event_filter_options

context property

The request-level context (auth + optional chat) for this settings object.

from_chat_event(event) classmethod

Build a :class:UniqueSettings from a :class:ChatEvent.

Auth and chat context are extracted from the event. App and API settings are left at their default values; override them via the returned instance's properties if needed.

Parameters:

Name Type Description Default
event ChatEvent

The incoming chat event.

required

Returns:

Type Description
UniqueSettings

UniqueSettings with auth + chat context populated from the event.

Source code in unique_toolkit/unique_toolkit/app/unique_settings.py
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
@classmethod
def from_chat_event(cls, event: ChatEvent) -> UniqueSettings:
    """Build a :class:`UniqueSettings` from a :class:`ChatEvent`.

    Auth and chat context are extracted from the event.  App and API
    settings are left at their default values; override them via the
    returned instance's properties if needed.

    Args:
        event: The incoming chat event.

    Returns:
        UniqueSettings with auth + chat context populated from the event.
    """
    return cls(
        auth=AuthContext.from_event(event),
        app=UniqueApp(),
        api=UniqueApi(),
        chat=ChatContext.from_chat_event(event),
    )

from_env(env_file=None) classmethod

Initialize settings from environment variables and/or env file.

Parameters:

Name Type Description Default
env_file Path | None

Optional path to environment file. If provided, will load variables from this file.

None

Returns:

Type Description
UniqueSettings

UniqueSettings instance with values loaded from environment/env file.

Raises:

Type Description
FileNotFoundError

If env_file is provided but does not exist.

ValidationError

If required environment variables are missing.

Source code in unique_toolkit/unique_toolkit/app/unique_settings.py
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
@classmethod
def from_env(
    cls,
    env_file: Path | None = None,
) -> UniqueSettings:
    """Initialize settings from environment variables and/or env file.

    Args:
        env_file: Optional path to environment file. If provided, will load variables from this file.

    Returns:
        UniqueSettings instance with values loaded from environment/env file.

    Raises:
        FileNotFoundError: If env_file is provided but does not exist.
        ValidationError: If required environment variables are missing.
    """
    if env_file and not env_file.exists():
        raise FileNotFoundError(f"Environment file not found: {env_file}")

    # Initialize settings with environment file if provided
    env_file_str = str(env_file) if env_file else None
    auth = UniqueAuth(_env_file=env_file_str)  # type: ignore[call-arg]
    app = UniqueApp(_env_file=env_file_str)  # type: ignore[call-arg]
    api = UniqueApi(_env_file=env_file_str)  # type: ignore[call-arg]
    event_filter_options = UniqueChatEventFilterOptions(_env_file=env_file_str)  # type: ignore[call-arg]
    return cls(
        auth=auth,
        app=app,
        api=api,
        chat_event_filter_options=event_filter_options,
        env_file=env_file,
    )

from_env_auto(filename='unique.env') classmethod

Initialize settings by automatically finding environment file.

This method will automatically search for an environment file in standard locations and fall back to environment variables only if no file is found.

Parameters:

Name Type Description Default
filename str

Name of the environment file to search for (default: '.env')

'unique.env'

Returns:

Type Description
UniqueSettings

UniqueSettings instance with values loaded from found env file or environment variables.

Source code in unique_toolkit/unique_toolkit/app/unique_settings.py
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
@classmethod
def from_env_auto(cls, filename: str = "unique.env") -> UniqueSettings:
    """Initialize settings by automatically finding environment file.

    This method will automatically search for an environment file in standard locations
    and fall back to environment variables only if no file is found.

    Args:
        filename: Name of the environment file to search for (default: '.env')

    Returns:
        UniqueSettings instance with values loaded from found env file or environment variables.
    """
    try:
        env_file = cls._find_env_file(filename)
        logger.info(f"Environment file found at {env_file}")
        return cls.from_env(env_file=env_file)
    except EnvFileNotFoundError:
        logger.warning(
            f"Environment file '{filename}' not found. Falling back to environment variables only."
        )
        # Fall back to environment variables only
        return cls.from_env()

from_env_auto_with_sdk_init(filename='unique.env') classmethod

Initialize settings and SDK in one convenient call.

This method combines from_env_auto() and init_sdk() for the most common use case.

Parameters:

Name Type Description Default
filename str

Name of the environment file to search for (default: '.env')

'unique.env'

Returns:

Type Description
UniqueSettings

UniqueSettings instance with SDK already initialized.

Source code in unique_toolkit/unique_toolkit/app/unique_settings.py
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
@classmethod
def from_env_auto_with_sdk_init(
    cls, filename: str = "unique.env"
) -> UniqueSettings:
    """Initialize settings and SDK in one convenient call.

    This method combines from_env_auto() and init_sdk() for the most common use case.

    Args:
        filename: Name of the environment file to search for (default: '.env')

    Returns:
        UniqueSettings instance with SDK already initialized.
    """
    settings = cls.from_env_auto(filename)
    settings.init_sdk()
    return settings

init_sdk()

Initialize the unique_sdk global configuration with these settings.

This method configures the global unique_sdk module with the API key, app ID, and base URL from these settings.

Source code in unique_toolkit/unique_toolkit/app/unique_settings.py
576
577
578
579
580
581
582
583
584
def init_sdk(self) -> None:
    """Initialize the unique_sdk global configuration with these settings.

    This method configures the global unique_sdk module with the API key,
    app ID, and base URL from these settings.
    """
    unique_sdk.api_key = self.app.key.get_secret_value()
    unique_sdk.app_id = self.app.id.get_secret_value()
    unique_sdk.api_base = self.api.sdk_url()

with_auth(auth)

Return a copy of the settings with the new auth context.

Source code in unique_toolkit/unique_toolkit/app/unique_settings.py
638
639
640
641
642
643
644
645
646
647
def with_auth(self, auth: AuthContextProtocol) -> Self:
    """Return a copy of the settings with the new auth context."""
    return self.__class__(
        auth=auth,
        app=self.app,
        api=self.api,
        chat_event_filter_options=self.chat_event_filter_options,
        chat=self._context.chat,
        env_file=self._env_file,
    )

Initialization

unique_toolkit.app.init_sdk.init_sdk(strict_all_vars=False)

Initialize the SDK.

Parameters:

Name Type Description Default
strict_all_vars bool

This method raises a ValueError if strict and no value is found in the environment. Defaults to False.

False
Source code in unique_toolkit/unique_toolkit/app/init_sdk.py
54
55
56
57
58
59
60
61
62
63
64
65
66
@deprecated("Use init_unique_sdk instead")
def init_sdk(
    strict_all_vars: bool = False,
):
    """Initialize the SDK.

    Args:
        strict_all_vars (bool, optional): This method raises a ValueError if strict and no value is found in the environment. Defaults to False.
    """

    unique_sdk.api_key = get_env("API_KEY", default="dummy", strict=strict_all_vars)
    unique_sdk.app_id = get_env("APP_ID", default="dummy", strict=strict_all_vars)
    unique_sdk.api_base = get_env("API_BASE", default=None, strict=strict_all_vars)

unique_toolkit.app.init_sdk.init_unique_sdk(*, unique_settings=None, env_file=None)

init_unique_sdk(*, env_file: Path | None = None)
init_unique_sdk(*, unique_settings: UniqueSettings)
Source code in unique_toolkit/unique_toolkit/app/init_sdk.py
40
41
42
43
44
45
46
47
48
49
50
51
def init_unique_sdk(
    *, unique_settings: UniqueSettings | None = None, env_file: Path | None = None
):
    if unique_settings:
        unique_sdk.api_key = unique_settings.app.key.get_secret_value()
        unique_sdk.app_id = unique_settings.app.id.get_secret_value()
        unique_sdk.api_base = unique_settings.api.sdk_url()
    elif env_file:
        unique_settings = UniqueSettings.from_env(env_file=env_file)
        unique_sdk.api_key = unique_settings.app.key.get_secret_value()
        unique_sdk.app_id = unique_settings.app.id.get_secret_value()
        unique_sdk.api_base = unique_settings.api.sdk_url()

unique_toolkit.app.init_logging.init_logging(config=unique_log_config)

Source code in unique_toolkit/unique_toolkit/app/init_logging.py
30
31
def init_logging(config: dict = unique_log_config):
    return dictConfig(config)

Event Schemas

unique_toolkit.app.schemas.ChatEvent

Bases: BaseEvent

Source code in unique_toolkit/unique_toolkit/app/schemas.py
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
class ChatEvent(BaseEvent):
    model_config = model_config

    payload: ChatEventPayload
    created_at: Optional[int] = None
    version: Optional[str] = None

    @classmethod
    def from_json_file(cls, file_path: Path) -> ChatEvent:
        if not file_path.exists():
            raise FileNotFoundError(f"File not found: {file_path}")
        with file_path.open("r", encoding="utf-8") as f:
            data = json.load(f)
        return cls.model_validate(data)

    def get_initial_debug_info(self) -> dict[str, Any]:
        """Get the debug information for the chat event"""

        # TODO: Make sure this coincides with what is shown in the first user message
        return {
            "user_metadata": self.payload.user_metadata,
            "tool_parameters": self.payload.tool_parameters,
            "chosen_module": self.payload.name,
            "assistant": {"id": self.payload.assistant_id},
        }

    @override
    def filter_event(
        self, *, filter_options: UniqueChatEventFilterOptions | None = None
    ) -> bool:
        # Empty string evals to False

        if filter_options is None:
            return False  # Don't filter when no options provided

        if not filter_options.assistant_ids and not filter_options.references_in_code:
            raise ConfigurationException(
                "No filter options provided, all events will be filtered! \n"
                "Please define: \n"
                " - 'UNIQUE_CHAT_EVENT_FILTER_OPTIONS_ASSISTANT_IDS' \n"
                " - 'UNIQUE_CHAT_EVENT_FILTER_OPTIONS_REFERENCES_IN_CODE' \n"
                "in your environment variables."
            )

        # Per reference in code there can be multiple assistants
        if (
            filter_options.assistant_ids
            and self.payload.assistant_id not in filter_options.assistant_ids
        ):
            return True

        if (
            filter_options.references_in_code
            and self.payload.name not in filter_options.references_in_code
        ):
            return True

        return super().filter_event(filter_options=filter_options)

__class_vars__ class-attribute

The names of the class variables defined on the model.

__private_attributes__ class-attribute

Metadata about the private attributes of the model.

__pydantic_complete__ = False class-attribute

Whether model building is completed, or if there are still undefined fields.

__pydantic_computed_fields__ class-attribute

A dictionary of computed field names and their corresponding [ComputedFieldInfo][pydantic.fields.ComputedFieldInfo] objects.

__pydantic_core_schema__ class-attribute

The core schema of the model.

__pydantic_custom_init__ class-attribute

Whether the model has a custom __init__ method.

__pydantic_decorators__ = _decorators.DecoratorInfos() class-attribute

Metadata containing the decorators defined on the model. This replaces Model.__validators__ and Model.__root_validators__ from Pydantic V1.

__pydantic_extra__ = _model_construction.NoInitField(init=False) class-attribute instance-attribute

A dictionary containing extra values, if [extra][pydantic.config.ConfigDict.extra] is set to 'allow'.

__pydantic_fields__ class-attribute

A dictionary of field names and their corresponding [FieldInfo][pydantic.fields.FieldInfo] objects. This replaces Model.__fields__ from Pydantic V1.

__pydantic_fields_set__ = _model_construction.NoInitField(init=False) class-attribute instance-attribute

The names of fields explicitly set during instantiation.

__pydantic_generic_metadata__ class-attribute

Metadata for generic models; contains data used for a similar purpose to args, origin, parameters in typing-module generics. May eventually be replaced by these.

__pydantic_parent_namespace__ = None class-attribute

Parent namespace of the model, used for automatic rebuilding of models.

__pydantic_post_init__ class-attribute

The name of the post-init method for the model, if defined.

__pydantic_private__ = _model_construction.NoInitField(init=False) class-attribute instance-attribute

Values of private attributes set on the model instance.

__pydantic_root_model__ = False class-attribute

Whether the model is a [RootModel][pydantic.root_model.RootModel].

__pydantic_serializer__ class-attribute

The pydantic-core SchemaSerializer used to dump instances of the model.

__pydantic_setattr_handlers__ class-attribute

__setattr__ handlers. Memoizing the handlers leads to a dramatic performance improvement in __setattr__

__pydantic_validator__ class-attribute

The pydantic-core SchemaValidator used to validate instances of the model.

__signature__ class-attribute

The synthesized __init__ [Signature][inspect.Signature] of the model.

model_extra property

Get extra fields set during validation.

Returns:

Type Description
dict[str, Any] | None

A dictionary of extra fields, or None if config.extra is not set to "allow".

model_fields_set property

Returns the set of fields that have been explicitly set on this model instance.

Returns:

Type Description
set[str]

A set of strings representing the fields that have been set, i.e. that were not filled from defaults.

__copy__()

Returns a shallow copy of the model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
def __copy__(self) -> Self:
    """Returns a shallow copy of the model."""
    cls = type(self)
    m = cls.__new__(cls)
    _object_setattr(m, '__dict__', copy(self.__dict__))
    _object_setattr(m, '__pydantic_extra__', copy(self.__pydantic_extra__))
    _object_setattr(m, '__pydantic_fields_set__', copy(self.__pydantic_fields_set__))

    if not hasattr(self, '__pydantic_private__') or self.__pydantic_private__ is None:
        _object_setattr(m, '__pydantic_private__', None)
    else:
        _object_setattr(
            m,
            '__pydantic_private__',
            {k: v for k, v in self.__pydantic_private__.items() if v is not PydanticUndefined},
        )

    return m

__deepcopy__(memo=None)

Returns a deep copy of the model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
def __deepcopy__(self, memo: dict[int, Any] | None = None) -> Self:
    """Returns a deep copy of the model."""
    cls = type(self)
    m = cls.__new__(cls)
    _object_setattr(m, '__dict__', deepcopy(self.__dict__, memo=memo))
    _object_setattr(m, '__pydantic_extra__', deepcopy(self.__pydantic_extra__, memo=memo))
    # This next line doesn't need a deepcopy because __pydantic_fields_set__ is a set[str],
    # and attempting a deepcopy would be marginally slower.
    _object_setattr(m, '__pydantic_fields_set__', copy(self.__pydantic_fields_set__))

    if not hasattr(self, '__pydantic_private__') or self.__pydantic_private__ is None:
        _object_setattr(m, '__pydantic_private__', None)
    else:
        _object_setattr(
            m,
            '__pydantic_private__',
            deepcopy({k: v for k, v in self.__pydantic_private__.items() if v is not PydanticUndefined}, memo=memo),
        )

    return m

__get_pydantic_json_schema__(core_schema, handler) classmethod

Hook into generating the model's JSON schema.

Parameters:

Name Type Description Default
core_schema CoreSchema

A pydantic-core CoreSchema. You can ignore this argument and call the handler with a new CoreSchema, wrap this CoreSchema ({'type': 'nullable', 'schema': current_schema}), or just call the handler with the original schema.

required
handler GetJsonSchemaHandler

Call into Pydantic's internal JSON schema generation. This will raise a pydantic.errors.PydanticInvalidForJsonSchema if JSON schema generation fails. Since this gets called by BaseModel.model_json_schema you can override the schema_generator argument to that function to change JSON schema generation globally for a type.

required

Returns:

Type Description
JsonSchemaValue

A JSON schema, as a Python object.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
@classmethod
def __get_pydantic_json_schema__(
    cls,
    core_schema: CoreSchema,
    handler: GetJsonSchemaHandler,
    /,
) -> JsonSchemaValue:
    """Hook into generating the model's JSON schema.

    Args:
        core_schema: A `pydantic-core` CoreSchema.
            You can ignore this argument and call the handler with a new CoreSchema,
            wrap this CoreSchema (`{'type': 'nullable', 'schema': current_schema}`),
            or just call the handler with the original schema.
        handler: Call into Pydantic's internal JSON schema generation.
            This will raise a `pydantic.errors.PydanticInvalidForJsonSchema` if JSON schema
            generation fails.
            Since this gets called by `BaseModel.model_json_schema` you can override the
            `schema_generator` argument to that function to change JSON schema generation globally
            for a type.

    Returns:
        A JSON schema, as a Python object.
    """
    return handler(core_schema)

__init__(**data)

Create a new model by parsing and validating input data from keyword arguments.

Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.

self is explicitly positional-only to allow self as a field name.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
def __init__(self, /, **data: Any) -> None:
    """Create a new model by parsing and validating input data from keyword arguments.

    Raises [`ValidationError`][pydantic_core.ValidationError] if the input data cannot be
    validated to form a valid model.

    `self` is explicitly positional-only to allow `self` as a field name.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True
    validated_self = self.__pydantic_validator__.validate_python(data, self_instance=self)
    if self is not validated_self:
        warnings.warn(
            'A custom validator is returning a value other than `self`.\n'
            "Returning anything other than `self` from a top level model validator isn't supported when validating via `__init__`.\n"
            'See the `model_validator` docs (https://docs.pydantic.dev/latest/concepts/validators/#model-validators) for more details.',
            stacklevel=2,
        )

__init_subclass__(**kwargs)

This signature is included purely to help type-checkers check arguments to class declaration, which provides a way to conveniently set model_config key/value pairs.

from pydantic import BaseModel

class MyModel(BaseModel, extra='allow'): ...

However, this may be deceiving, since the actual calls to __init_subclass__ will not receive any of the config arguments, and will only receive any keyword arguments passed during class initialization that are not expected keys in ConfigDict. (This is due to the way ModelMetaclass.__new__ works.)

Parameters:

Name Type Description Default
**kwargs Unpack[ConfigDict]

Keyword arguments passed to the class definition, which set model_config

{}
Note

You may want to override __pydantic_init_subclass__ instead, which behaves similarly but is called after the class is fully initialized.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
def __init_subclass__(cls, **kwargs: Unpack[ConfigDict]):
    """This signature is included purely to help type-checkers check arguments to class declaration, which
    provides a way to conveniently set model_config key/value pairs.

    ```python
    from pydantic import BaseModel

    class MyModel(BaseModel, extra='allow'): ...
    ```

    However, this may be deceiving, since the _actual_ calls to `__init_subclass__` will not receive any
    of the config arguments, and will only receive any keyword arguments passed during class initialization
    that are _not_ expected keys in ConfigDict. (This is due to the way `ModelMetaclass.__new__` works.)

    Args:
        **kwargs: Keyword arguments passed to the class definition, which set model_config

    Note:
        You may want to override `__pydantic_init_subclass__` instead, which behaves similarly but is called
        *after* the class is fully initialized.
    """

__iter__()

So dict(model) works.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
1229
1230
1231
1232
1233
1234
def __iter__(self) -> TupleGenerator:
    """So `dict(model)` works."""
    yield from [(k, v) for (k, v) in self.__dict__.items() if not k.startswith('_')]
    extra = self.__pydantic_extra__
    if extra:
        yield from extra.items()

__pydantic_init_subclass__(**kwargs) classmethod

This is intended to behave just like __init_subclass__, but is called by ModelMetaclass only after basic class initialization is complete. In particular, attributes like model_fields will be present when this is called, but forward annotations are not guaranteed to be resolved yet, meaning that creating an instance of the class may fail.

This is necessary because __init_subclass__ will always be called by type.__new__, and it would require a prohibitively large refactor to the ModelMetaclass to ensure that type.__new__ was called in such a manner that the class would already be sufficiently initialized.

This will receive the same kwargs that would be passed to the standard __init_subclass__, namely, any kwargs passed to the class definition that aren't used internally by Pydantic.

Parameters:

Name Type Description Default
**kwargs Any

Any keyword arguments passed to the class definition that aren't used internally by Pydantic.

{}
Note

You may want to override __pydantic_on_complete__() instead, which is called once the class and its fields are fully initialized and ready for validation.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
@classmethod
def __pydantic_init_subclass__(cls, **kwargs: Any) -> None:
    """This is intended to behave just like `__init_subclass__`, but is called by `ModelMetaclass`
    only after basic class initialization is complete. In particular, attributes like `model_fields` will
    be present when this is called, but forward annotations are not guaranteed to be resolved yet,
    meaning that creating an instance of the class may fail.

    This is necessary because `__init_subclass__` will always be called by `type.__new__`,
    and it would require a prohibitively large refactor to the `ModelMetaclass` to ensure that
    `type.__new__` was called in such a manner that the class would already be sufficiently initialized.

    This will receive the same `kwargs` that would be passed to the standard `__init_subclass__`, namely,
    any kwargs passed to the class definition that aren't used internally by Pydantic.

    Args:
        **kwargs: Any keyword arguments passed to the class definition that aren't used internally
            by Pydantic.

    Note:
        You may want to override [`__pydantic_on_complete__()`][pydantic.main.BaseModel.__pydantic_on_complete__]
        instead, which is called once the class and its fields are fully initialized and ready for validation.
    """

__pydantic_on_complete__() classmethod

This is called once the class and its fields are fully initialized and ready to be used.

This typically happens when the class is created (just before __pydantic_init_subclass__() is called on the superclass), except when forward annotations are used that could not immediately be resolved. In that case, it will be called later, when the model is rebuilt automatically or explicitly using model_rebuild().

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
877
878
879
880
881
882
883
884
885
886
@classmethod
def __pydantic_on_complete__(cls) -> None:
    """This is called once the class and its fields are fully initialized and ready to be used.

    This typically happens when the class is created (just before
    [`__pydantic_init_subclass__()`][pydantic.main.BaseModel.__pydantic_init_subclass__] is called on the superclass),
    except when forward annotations are used that could not immediately be resolved.
    In that case, it will be called later, when the model is rebuilt automatically or explicitly using
    [`model_rebuild()`][pydantic.main.BaseModel.model_rebuild].
    """

copy(*, include=None, exclude=None, update=None, deep=False)

Returns a copy of the model.

Deprecated

This method is now deprecated; use model_copy instead.

If you need include or exclude, use:

data = self.model_dump(include=include, exclude=exclude, round_trip=True)
data = {**data, **(update or {})}
copied = self.model_validate(data)

Parameters:

Name Type Description Default
include AbstractSetIntStr | MappingIntStrAny | None

Optional set or mapping specifying which fields to include in the copied model.

None
exclude AbstractSetIntStr | MappingIntStrAny | None

Optional set or mapping specifying which fields to exclude in the copied model.

None
update Dict[str, Any] | None

Optional dictionary of field-value pairs to override field values in the copied model.

None
deep bool

If True, the values of fields that are Pydantic models will be deep-copied.

False

Returns:

Type Description
Self

A copy of the model with included, excluded and updated fields as specified.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
@typing_extensions.deprecated(
    'The `copy` method is deprecated; use `model_copy` instead. '
    'See the docstring of `BaseModel.copy` for details about how to handle `include` and `exclude`.',
    category=None,
)
def copy(
    self,
    *,
    include: AbstractSetIntStr | MappingIntStrAny | None = None,
    exclude: AbstractSetIntStr | MappingIntStrAny | None = None,
    update: Dict[str, Any] | None = None,  # noqa UP006
    deep: bool = False,
) -> Self:  # pragma: no cover
    """Returns a copy of the model.

    !!! warning "Deprecated"
        This method is now deprecated; use `model_copy` instead.

    If you need `include` or `exclude`, use:

    ```python {test="skip" lint="skip"}
    data = self.model_dump(include=include, exclude=exclude, round_trip=True)
    data = {**data, **(update or {})}
    copied = self.model_validate(data)
    ```

    Args:
        include: Optional set or mapping specifying which fields to include in the copied model.
        exclude: Optional set or mapping specifying which fields to exclude in the copied model.
        update: Optional dictionary of field-value pairs to override field values in the copied model.
        deep: If True, the values of fields that are Pydantic models will be deep-copied.

    Returns:
        A copy of the model with included, excluded and updated fields as specified.
    """
    warnings.warn(
        'The `copy` method is deprecated; use `model_copy` instead. '
        'See the docstring of `BaseModel.copy` for details about how to handle `include` and `exclude`.',
        category=PydanticDeprecatedSince20,
        stacklevel=2,
    )
    from .deprecated import copy_internals

    values = dict(
        copy_internals._iter(
            self, to_dict=False, by_alias=False, include=include, exclude=exclude, exclude_unset=False
        ),
        **(update or {}),
    )
    if self.__pydantic_private__ is None:
        private = None
    else:
        private = {k: v for k, v in self.__pydantic_private__.items() if v is not PydanticUndefined}

    if self.__pydantic_extra__ is None:
        extra: dict[str, Any] | None = None
    else:
        extra = self.__pydantic_extra__.copy()
        for k in list(self.__pydantic_extra__):
            if k not in values:  # k was in the exclude
                extra.pop(k)
        for k in list(values):
            if k in self.__pydantic_extra__:  # k must have come from extra
                extra[k] = values.pop(k)

    # new `__pydantic_fields_set__` can have unset optional fields with a set value in `update` kwarg
    if update:
        fields_set = self.__pydantic_fields_set__ | update.keys()
    else:
        fields_set = set(self.__pydantic_fields_set__)

    # removing excluded fields from `__pydantic_fields_set__`
    if exclude:
        fields_set -= set(exclude)

    return copy_internals._copy_and_set_values(self, values, fields_set, extra, private, deep=deep)

get_initial_debug_info()

Get the debug information for the chat event

Source code in unique_toolkit/unique_toolkit/app/schemas.py
295
296
297
298
299
300
301
302
303
304
def get_initial_debug_info(self) -> dict[str, Any]:
    """Get the debug information for the chat event"""

    # TODO: Make sure this coincides with what is shown in the first user message
    return {
        "user_metadata": self.payload.user_metadata,
        "tool_parameters": self.payload.tool_parameters,
        "chosen_module": self.payload.name,
        "assistant": {"id": self.payload.assistant_id},
    }

model_computed_fields() classmethod

A mapping of computed field names to their respective [ComputedFieldInfo][pydantic.fields.ComputedFieldInfo] instances.

Warning

Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3. Instead, you should access this attribute from the model class.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
273
274
275
276
277
278
279
280
281
282
@_utils.deprecated_instance_property
@classmethod
def model_computed_fields(cls) -> dict[str, ComputedFieldInfo]:
    """A mapping of computed field names to their respective [`ComputedFieldInfo`][pydantic.fields.ComputedFieldInfo] instances.

    !!! warning
        Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3.
        Instead, you should access this attribute from the model class.
    """
    return getattr(cls, '__pydantic_computed_fields__', {})

model_construct(_fields_set=None, **values) classmethod

Creates a new instance of the Model class with validated data.

Creates a new model setting __dict__ and __pydantic_fields_set__ from trusted or pre-validated data. Default values are respected, but no other validation is performed.

Note

model_construct() generally respects the model_config.extra setting on the provided model. That is, if model_config.extra == 'allow', then all extra passed values are added to the model instance's __dict__ and __pydantic_extra__ fields. If model_config.extra == 'ignore' (the default), then all extra passed values are ignored. Because no validation is performed with a call to model_construct(), having model_config.extra == 'forbid' does not result in an error if extra values are passed, but they will be ignored.

Parameters:

Name Type Description Default
_fields_set set[str] | None

A set of field names that were originally explicitly set during instantiation. If provided, this is directly used for the [model_fields_set][pydantic.BaseModel.model_fields_set] attribute. Otherwise, the field names from the values argument will be used.

None
values Any

Trusted or pre-validated data dictionary.

{}

Returns:

Type Description
Self

A new instance of the Model class with validated data.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
@classmethod
def model_construct(cls, _fields_set: set[str] | None = None, **values: Any) -> Self:  # noqa: C901
    """Creates a new instance of the `Model` class with validated data.

    Creates a new model setting `__dict__` and `__pydantic_fields_set__` from trusted or pre-validated data.
    Default values are respected, but no other validation is performed.

    !!! note
        `model_construct()` generally respects the `model_config.extra` setting on the provided model.
        That is, if `model_config.extra == 'allow'`, then all extra passed values are added to the model instance's `__dict__`
        and `__pydantic_extra__` fields. If `model_config.extra == 'ignore'` (the default), then all extra passed values are ignored.
        Because no validation is performed with a call to `model_construct()`, having `model_config.extra == 'forbid'` does not result in
        an error if extra values are passed, but they will be ignored.

    Args:
        _fields_set: A set of field names that were originally explicitly set during instantiation. If provided,
            this is directly used for the [`model_fields_set`][pydantic.BaseModel.model_fields_set] attribute.
            Otherwise, the field names from the `values` argument will be used.
        values: Trusted or pre-validated data dictionary.

    Returns:
        A new instance of the `Model` class with validated data.
    """
    m = cls.__new__(cls)
    fields_values: dict[str, Any] = {}
    fields_set = set()

    for name, field in cls.__pydantic_fields__.items():
        if field.alias is not None and field.alias in values:
            fields_values[name] = values.pop(field.alias)
            fields_set.add(name)

        if (name not in fields_set) and (field.validation_alias is not None):
            validation_aliases: list[str | AliasPath] = (
                field.validation_alias.choices
                if isinstance(field.validation_alias, AliasChoices)
                else [field.validation_alias]
            )

            for alias in validation_aliases:
                if isinstance(alias, str) and alias in values:
                    fields_values[name] = values.pop(alias)
                    fields_set.add(name)
                    break
                elif isinstance(alias, AliasPath):
                    value = alias.search_dict_for_path(values)
                    if value is not PydanticUndefined:
                        fields_values[name] = value
                        fields_set.add(name)
                        break

        if name not in fields_set:
            if name in values:
                fields_values[name] = values.pop(name)
                fields_set.add(name)
            elif not field.is_required():
                fields_values[name] = field.get_default(call_default_factory=True, validated_data=fields_values)
    if _fields_set is None:
        _fields_set = fields_set

    _extra: dict[str, Any] | None = values if cls.model_config.get('extra') == 'allow' else None
    _object_setattr(m, '__dict__', fields_values)
    _object_setattr(m, '__pydantic_fields_set__', _fields_set)
    if not cls.__pydantic_root_model__:
        _object_setattr(m, '__pydantic_extra__', _extra)

    if cls.__pydantic_post_init__:
        m.model_post_init(None)
        # update private attributes with values set
        if hasattr(m, '__pydantic_private__') and m.__pydantic_private__ is not None:
            for k, v in values.items():
                if k in m.__private_attributes__:
                    m.__pydantic_private__[k] = v

    elif not cls.__pydantic_root_model__:
        # Note: if there are any private attributes, cls.__pydantic_post_init__ would exist
        # Since it doesn't, that means that `__pydantic_private__` should be set to None
        _object_setattr(m, '__pydantic_private__', None)

    return m

model_copy(*, update=None, deep=False)

Usage Documentation

model_copy

Returns a copy of the model.

Note

The underlying instance's [__dict__][object.__dict__] attribute is copied. This might have unexpected side effects if you store anything in it, on top of the model fields (e.g. the value of [cached properties][functools.cached_property]).

Parameters:

Name Type Description Default
update Mapping[str, Any] | None

Values to change/add in the new model. Note: the data is not validated before creating the new model. You should trust this data.

None
deep bool

Set to True to make a deep copy of the model.

False

Returns:

Type Description
Self

New model instance.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
def model_copy(self, *, update: Mapping[str, Any] | None = None, deep: bool = False) -> Self:
    """!!! abstract "Usage Documentation"
        [`model_copy`](../concepts/models.md#model-copy)

    Returns a copy of the model.

    !!! note
        The underlying instance's [`__dict__`][object.__dict__] attribute is copied. This
        might have unexpected side effects if you store anything in it, on top of the model
        fields (e.g. the value of [cached properties][functools.cached_property]).

    Args:
        update: Values to change/add in the new model. Note: the data is not validated
            before creating the new model. You should trust this data.
        deep: Set to `True` to make a deep copy of the model.

    Returns:
        New model instance.
    """
    copied = self.__deepcopy__() if deep else self.__copy__()
    if update:
        if self.model_config.get('extra') == 'allow':
            for k, v in update.items():
                if k in self.__pydantic_fields__:
                    copied.__dict__[k] = v
                else:
                    if copied.__pydantic_extra__ is None:
                        copied.__pydantic_extra__ = {}
                    copied.__pydantic_extra__[k] = v
        else:
            copied.__dict__.update(update)
        copied.__pydantic_fields_set__.update(update.keys())
    return copied

model_dump(*, mode='python', include=None, exclude=None, context=None, by_alias=None, exclude_unset=False, exclude_defaults=False, exclude_none=False, exclude_computed_fields=False, round_trip=False, warnings=True, fallback=None, serialize_as_any=False)

Usage Documentation

model_dump

Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.

Parameters:

Name Type Description Default
mode Literal['json', 'python'] | str

The mode in which to_python should run. If mode is 'json', the output will only contain JSON serializable types. If mode is 'python', the output may contain non-JSON-serializable Python objects.

'python'
include IncEx | None

A set of fields to include in the output.

None
exclude IncEx | None

A set of fields to exclude from the output.

None
context Any | None

Additional context to pass to the serializer.

None
by_alias bool | None

Whether to use the field's alias in the dictionary key if defined.

None
exclude_unset bool

Whether to exclude fields that have not been explicitly set.

False
exclude_defaults bool

Whether to exclude fields that are set to their default value.

False
exclude_none bool

Whether to exclude fields that have a value of None.

False
exclude_computed_fields bool

Whether to exclude computed fields. While this can be useful for round-tripping, it is usually recommended to use the dedicated round_trip parameter instead.

False
round_trip bool

If True, dumped values should be valid as input for non-idempotent types such as Json[T].

False
warnings bool | Literal['none', 'warn', 'error']

How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors, "error" raises a [PydanticSerializationError][pydantic_core.PydanticSerializationError].

True
fallback Callable[[Any], Any] | None

A function to call when an unknown value is encountered. If not provided, a [PydanticSerializationError][pydantic_core.PydanticSerializationError] error is raised.

None
serialize_as_any bool

Whether to serialize fields with duck-typing serialization behavior.

False

Returns:

Type Description
dict[str, Any]

A dictionary representation of the model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
def model_dump(
    self,
    *,
    mode: Literal['json', 'python'] | str = 'python',
    include: IncEx | None = None,
    exclude: IncEx | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    exclude_unset: bool = False,
    exclude_defaults: bool = False,
    exclude_none: bool = False,
    exclude_computed_fields: bool = False,
    round_trip: bool = False,
    warnings: bool | Literal['none', 'warn', 'error'] = True,
    fallback: Callable[[Any], Any] | None = None,
    serialize_as_any: bool = False,
) -> dict[str, Any]:
    """!!! abstract "Usage Documentation"
        [`model_dump`](../concepts/serialization.md#python-mode)

    Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.

    Args:
        mode: The mode in which `to_python` should run.
            If mode is 'json', the output will only contain JSON serializable types.
            If mode is 'python', the output may contain non-JSON-serializable Python objects.
        include: A set of fields to include in the output.
        exclude: A set of fields to exclude from the output.
        context: Additional context to pass to the serializer.
        by_alias: Whether to use the field's alias in the dictionary key if defined.
        exclude_unset: Whether to exclude fields that have not been explicitly set.
        exclude_defaults: Whether to exclude fields that are set to their default value.
        exclude_none: Whether to exclude fields that have a value of `None`.
        exclude_computed_fields: Whether to exclude computed fields.
            While this can be useful for round-tripping, it is usually recommended to use the dedicated
            `round_trip` parameter instead.
        round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
        warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
            "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
        fallback: A function to call when an unknown value is encountered. If not provided,
            a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
        serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.

    Returns:
        A dictionary representation of the model.
    """
    return self.__pydantic_serializer__.to_python(
        self,
        mode=mode,
        by_alias=by_alias,
        include=include,
        exclude=exclude,
        context=context,
        exclude_unset=exclude_unset,
        exclude_defaults=exclude_defaults,
        exclude_none=exclude_none,
        exclude_computed_fields=exclude_computed_fields,
        round_trip=round_trip,
        warnings=warnings,
        fallback=fallback,
        serialize_as_any=serialize_as_any,
    )

model_dump_json(*, indent=None, ensure_ascii=False, include=None, exclude=None, context=None, by_alias=None, exclude_unset=False, exclude_defaults=False, exclude_none=False, exclude_computed_fields=False, round_trip=False, warnings=True, fallback=None, serialize_as_any=False)

Usage Documentation

model_dump_json

Generates a JSON representation of the model using Pydantic's to_json method.

Parameters:

Name Type Description Default
indent int | None

Indentation to use in the JSON output. If None is passed, the output will be compact.

None
ensure_ascii bool

If True, the output is guaranteed to have all incoming non-ASCII characters escaped. If False (the default), these characters will be output as-is.

False
include IncEx | None

Field(s) to include in the JSON output.

None
exclude IncEx | None

Field(s) to exclude from the JSON output.

None
context Any | None

Additional context to pass to the serializer.

None
by_alias bool | None

Whether to serialize using field aliases.

None
exclude_unset bool

Whether to exclude fields that have not been explicitly set.

False
exclude_defaults bool

Whether to exclude fields that are set to their default value.

False
exclude_none bool

Whether to exclude fields that have a value of None.

False
exclude_computed_fields bool

Whether to exclude computed fields. While this can be useful for round-tripping, it is usually recommended to use the dedicated round_trip parameter instead.

False
round_trip bool

If True, dumped values should be valid as input for non-idempotent types such as Json[T].

False
warnings bool | Literal['none', 'warn', 'error']

How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors, "error" raises a [PydanticSerializationError][pydantic_core.PydanticSerializationError].

True
fallback Callable[[Any], Any] | None

A function to call when an unknown value is encountered. If not provided, a [PydanticSerializationError][pydantic_core.PydanticSerializationError] error is raised.

None
serialize_as_any bool

Whether to serialize fields with duck-typing serialization behavior.

False

Returns:

Type Description
str

A JSON string representation of the model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
def model_dump_json(
    self,
    *,
    indent: int | None = None,
    ensure_ascii: bool = False,
    include: IncEx | None = None,
    exclude: IncEx | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    exclude_unset: bool = False,
    exclude_defaults: bool = False,
    exclude_none: bool = False,
    exclude_computed_fields: bool = False,
    round_trip: bool = False,
    warnings: bool | Literal['none', 'warn', 'error'] = True,
    fallback: Callable[[Any], Any] | None = None,
    serialize_as_any: bool = False,
) -> str:
    """!!! abstract "Usage Documentation"
        [`model_dump_json`](../concepts/serialization.md#json-mode)

    Generates a JSON representation of the model using Pydantic's `to_json` method.

    Args:
        indent: Indentation to use in the JSON output. If None is passed, the output will be compact.
        ensure_ascii: If `True`, the output is guaranteed to have all incoming non-ASCII characters escaped.
            If `False` (the default), these characters will be output as-is.
        include: Field(s) to include in the JSON output.
        exclude: Field(s) to exclude from the JSON output.
        context: Additional context to pass to the serializer.
        by_alias: Whether to serialize using field aliases.
        exclude_unset: Whether to exclude fields that have not been explicitly set.
        exclude_defaults: Whether to exclude fields that are set to their default value.
        exclude_none: Whether to exclude fields that have a value of `None`.
        exclude_computed_fields: Whether to exclude computed fields.
            While this can be useful for round-tripping, it is usually recommended to use the dedicated
            `round_trip` parameter instead.
        round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
        warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
            "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
        fallback: A function to call when an unknown value is encountered. If not provided,
            a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
        serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.

    Returns:
        A JSON string representation of the model.
    """
    return self.__pydantic_serializer__.to_json(
        self,
        indent=indent,
        ensure_ascii=ensure_ascii,
        include=include,
        exclude=exclude,
        context=context,
        by_alias=by_alias,
        exclude_unset=exclude_unset,
        exclude_defaults=exclude_defaults,
        exclude_none=exclude_none,
        exclude_computed_fields=exclude_computed_fields,
        round_trip=round_trip,
        warnings=warnings,
        fallback=fallback,
        serialize_as_any=serialize_as_any,
    ).decode()

model_fields() classmethod

A mapping of field names to their respective [FieldInfo][pydantic.fields.FieldInfo] instances.

Warning

Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3. Instead, you should access this attribute from the model class.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
262
263
264
265
266
267
268
269
270
271
@_utils.deprecated_instance_property
@classmethod
def model_fields(cls) -> dict[str, FieldInfo]:
    """A mapping of field names to their respective [`FieldInfo`][pydantic.fields.FieldInfo] instances.

    !!! warning
        Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3.
        Instead, you should access this attribute from the model class.
    """
    return getattr(cls, '__pydantic_fields__', {})

model_json_schema(by_alias=True, ref_template=DEFAULT_REF_TEMPLATE, schema_generator=GenerateJsonSchema, mode='validation', *, union_format='any_of') classmethod

Generates a JSON schema for a model class.

Parameters:

Name Type Description Default
by_alias bool

Whether to use attribute aliases or not.

True
ref_template str

The reference template.

DEFAULT_REF_TEMPLATE
union_format Literal['any_of', 'primitive_type_array']

The format to use when combining schemas from unions together. Can be one of:

  • 'any_of': Use the anyOf keyword to combine schemas (the default).
  • 'primitive_type_array': Use the type keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive type (string, boolean, null, integer or number) or contains constraints/metadata, falls back to any_of.
'any_of'
schema_generator type[GenerateJsonSchema]

To override the logic used to generate the JSON schema, as a subclass of GenerateJsonSchema with your desired modifications

GenerateJsonSchema
mode JsonSchemaMode

The mode in which to generate the schema.

'validation'

Returns:

Type Description
dict[str, Any]

The JSON schema for the given model class.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
@classmethod
def model_json_schema(
    cls,
    by_alias: bool = True,
    ref_template: str = DEFAULT_REF_TEMPLATE,
    schema_generator: type[GenerateJsonSchema] = GenerateJsonSchema,
    mode: JsonSchemaMode = 'validation',
    *,
    union_format: Literal['any_of', 'primitive_type_array'] = 'any_of',
) -> dict[str, Any]:
    """Generates a JSON schema for a model class.

    Args:
        by_alias: Whether to use attribute aliases or not.
        ref_template: The reference template.
        union_format: The format to use when combining schemas from unions together. Can be one of:

            - `'any_of'`: Use the [`anyOf`](https://json-schema.org/understanding-json-schema/reference/combining#anyOf)
            keyword to combine schemas (the default).
            - `'primitive_type_array'`: Use the [`type`](https://json-schema.org/understanding-json-schema/reference/type)
            keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive
            type (`string`, `boolean`, `null`, `integer` or `number`) or contains constraints/metadata, falls back to
            `any_of`.
        schema_generator: To override the logic used to generate the JSON schema, as a subclass of
            `GenerateJsonSchema` with your desired modifications
        mode: The mode in which to generate the schema.

    Returns:
        The JSON schema for the given model class.
    """
    return model_json_schema(
        cls,
        by_alias=by_alias,
        ref_template=ref_template,
        union_format=union_format,
        schema_generator=schema_generator,
        mode=mode,
    )

model_parametrized_name(params) classmethod

Compute the class name for parametrizations of generic classes.

This method can be overridden to achieve a custom naming scheme for generic BaseModels.

Parameters:

Name Type Description Default
params tuple[type[Any], ...]

Tuple of types of the class. Given a generic class Model with 2 type variables and a concrete model Model[str, int], the value (str, int) would be passed to params.

required

Returns:

Type Description
str

String representing the new class where params are passed to cls as type variables.

Raises:

Type Description
TypeError

Raised when trying to generate concrete names for non-generic models.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
@classmethod
def model_parametrized_name(cls, params: tuple[type[Any], ...]) -> str:
    """Compute the class name for parametrizations of generic classes.

    This method can be overridden to achieve a custom naming scheme for generic BaseModels.

    Args:
        params: Tuple of types of the class. Given a generic class
            `Model` with 2 type variables and a concrete model `Model[str, int]`,
            the value `(str, int)` would be passed to `params`.

    Returns:
        String representing the new class where `params` are passed to `cls` as type variables.

    Raises:
        TypeError: Raised when trying to generate concrete names for non-generic models.
    """
    if not issubclass(cls, Generic):
        raise TypeError('Concrete names should only be generated for generic models.')

    # Any strings received should represent forward references, so we handle them specially below.
    # If we eventually move toward wrapping them in a ForwardRef in __class_getitem__ in the future,
    # we may be able to remove this special case.
    param_names = [param if isinstance(param, str) else _repr.display_as_type(param) for param in params]
    params_component = ', '.join(param_names)
    return f'{cls.__name__}[{params_component}]'

model_post_init(context)

Override this method to perform additional initialization after __init__ and model_construct. This is useful if you want to do some validation that requires the entire model to be initialized.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
612
613
614
615
def model_post_init(self, context: Any, /) -> None:
    """Override this method to perform additional initialization after `__init__` and `model_construct`.
    This is useful if you want to do some validation that requires the entire model to be initialized.
    """

model_rebuild(*, force=False, raise_errors=True, _parent_namespace_depth=2, _types_namespace=None) classmethod

Try to rebuild the pydantic-core schema for the model.

This may be necessary when one of the annotations is a ForwardRef which could not be resolved during the initial attempt to build the schema, and automatic rebuilding fails.

Parameters:

Name Type Description Default
force bool

Whether to force the rebuilding of the model schema, defaults to False.

False
raise_errors bool

Whether to raise errors, defaults to True.

True
_parent_namespace_depth int

The depth level of the parent namespace, defaults to 2.

2
_types_namespace MappingNamespace | None

The types namespace, defaults to None.

None

Returns:

Type Description
bool | None

Returns None if the schema is already "complete" and rebuilding was not required.

bool | None

If rebuilding was required, returns True if rebuilding was successful, otherwise False.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
@classmethod
def model_rebuild(
    cls,
    *,
    force: bool = False,
    raise_errors: bool = True,
    _parent_namespace_depth: int = 2,
    _types_namespace: MappingNamespace | None = None,
) -> bool | None:
    """Try to rebuild the pydantic-core schema for the model.

    This may be necessary when one of the annotations is a ForwardRef which could not be resolved during
    the initial attempt to build the schema, and automatic rebuilding fails.

    Args:
        force: Whether to force the rebuilding of the model schema, defaults to `False`.
        raise_errors: Whether to raise errors, defaults to `True`.
        _parent_namespace_depth: The depth level of the parent namespace, defaults to 2.
        _types_namespace: The types namespace, defaults to `None`.

    Returns:
        Returns `None` if the schema is already "complete" and rebuilding was not required.
        If rebuilding _was_ required, returns `True` if rebuilding was successful, otherwise `False`.
    """
    already_complete = cls.__pydantic_complete__
    if already_complete and not force:
        return None

    cls.__pydantic_complete__ = False

    for attr in ('__pydantic_core_schema__', '__pydantic_validator__', '__pydantic_serializer__'):
        if attr in cls.__dict__ and not isinstance(getattr(cls, attr), _mock_val_ser.MockValSer):
            # Deleting the validator/serializer is necessary as otherwise they can get reused in
            # pydantic-core. We do so only if they aren't mock instances, otherwise — as `model_rebuild()`
            # isn't thread-safe — concurrent model instantiations can lead to the parent validator being used.
            # Same applies for the core schema that can be reused in schema generation.
            delattr(cls, attr)

    if _types_namespace is not None:
        rebuild_ns = _types_namespace
    elif _parent_namespace_depth > 0:
        rebuild_ns = _typing_extra.parent_frame_namespace(parent_depth=_parent_namespace_depth, force=True) or {}
    else:
        rebuild_ns = {}

    parent_ns = _model_construction.unpack_lenient_weakvaluedict(cls.__pydantic_parent_namespace__) or {}

    ns_resolver = _namespace_utils.NsResolver(
        parent_namespace={**rebuild_ns, **parent_ns},
    )

    return _model_construction.complete_model_class(
        cls,
        _config.ConfigWrapper(cls.model_config, check=False),
        ns_resolver,
        raise_errors=raise_errors,
        # If the model was already complete, we don't need to call the hook again.
        call_on_complete_hook=not already_complete,
    )

model_validate(obj, *, strict=None, extra=None, from_attributes=None, context=None, by_alias=None, by_name=None) classmethod

Validate a pydantic model instance.

Parameters:

Name Type Description Default
obj Any

The object to validate.

required
strict bool | None

Whether to enforce types strictly.

None
extra ExtraValues | None

Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.

None
from_attributes bool | None

Whether to extract data from object attributes.

None
context Any | None

Additional context to pass to the validator.

None
by_alias bool | None

Whether to use the field's alias when validating against the provided input data.

None
by_name bool | None

Whether to use the field's name when validating against the provided input data.

None

Raises:

Type Description
ValidationError

If the object could not be validated.

Returns:

Type Description
Self

The validated model instance.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
@classmethod
def model_validate(
    cls,
    obj: Any,
    *,
    strict: bool | None = None,
    extra: ExtraValues | None = None,
    from_attributes: bool | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    by_name: bool | None = None,
) -> Self:
    """Validate a pydantic model instance.

    Args:
        obj: The object to validate.
        strict: Whether to enforce types strictly.
        extra: Whether to ignore, allow, or forbid extra data during model validation.
            See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
        from_attributes: Whether to extract data from object attributes.
        context: Additional context to pass to the validator.
        by_alias: Whether to use the field's alias when validating against the provided input data.
        by_name: Whether to use the field's name when validating against the provided input data.

    Raises:
        ValidationError: If the object could not be validated.

    Returns:
        The validated model instance.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True

    if by_alias is False and by_name is not True:
        raise PydanticUserError(
            'At least one of `by_alias` or `by_name` must be set to True.',
            code='validate-by-alias-and-name-false',
        )

    return cls.__pydantic_validator__.validate_python(
        obj,
        strict=strict,
        extra=extra,
        from_attributes=from_attributes,
        context=context,
        by_alias=by_alias,
        by_name=by_name,
    )

model_validate_json(json_data, *, strict=None, extra=None, context=None, by_alias=None, by_name=None) classmethod

Usage Documentation

JSON Parsing

Validate the given JSON data against the Pydantic model.

Parameters:

Name Type Description Default
json_data str | bytes | bytearray

The JSON data to validate.

required
strict bool | None

Whether to enforce types strictly.

None
extra ExtraValues | None

Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.

None
context Any | None

Extra variables to pass to the validator.

None
by_alias bool | None

Whether to use the field's alias when validating against the provided input data.

None
by_name bool | None

Whether to use the field's name when validating against the provided input data.

None

Returns:

Type Description
Self

The validated Pydantic model.

Raises:

Type Description
ValidationError

If json_data is not a JSON string or the object could not be validated.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
@classmethod
def model_validate_json(
    cls,
    json_data: str | bytes | bytearray,
    *,
    strict: bool | None = None,
    extra: ExtraValues | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    by_name: bool | None = None,
) -> Self:
    """!!! abstract "Usage Documentation"
        [JSON Parsing](../concepts/json.md#json-parsing)

    Validate the given JSON data against the Pydantic model.

    Args:
        json_data: The JSON data to validate.
        strict: Whether to enforce types strictly.
        extra: Whether to ignore, allow, or forbid extra data during model validation.
            See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
        context: Extra variables to pass to the validator.
        by_alias: Whether to use the field's alias when validating against the provided input data.
        by_name: Whether to use the field's name when validating against the provided input data.

    Returns:
        The validated Pydantic model.

    Raises:
        ValidationError: If `json_data` is not a JSON string or the object could not be validated.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True

    if by_alias is False and by_name is not True:
        raise PydanticUserError(
            'At least one of `by_alias` or `by_name` must be set to True.',
            code='validate-by-alias-and-name-false',
        )

    return cls.__pydantic_validator__.validate_json(
        json_data, strict=strict, extra=extra, context=context, by_alias=by_alias, by_name=by_name
    )

model_validate_strings(obj, *, strict=None, extra=None, context=None, by_alias=None, by_name=None) classmethod

Validate the given object with string data against the Pydantic model.

Parameters:

Name Type Description Default
obj Any

The object containing string data to validate.

required
strict bool | None

Whether to enforce types strictly.

None
extra ExtraValues | None

Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.

None
context Any | None

Extra variables to pass to the validator.

None
by_alias bool | None

Whether to use the field's alias when validating against the provided input data.

None
by_name bool | None

Whether to use the field's name when validating against the provided input data.

None

Returns:

Type Description
Self

The validated Pydantic model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
@classmethod
def model_validate_strings(
    cls,
    obj: Any,
    *,
    strict: bool | None = None,
    extra: ExtraValues | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    by_name: bool | None = None,
) -> Self:
    """Validate the given object with string data against the Pydantic model.

    Args:
        obj: The object containing string data to validate.
        strict: Whether to enforce types strictly.
        extra: Whether to ignore, allow, or forbid extra data during model validation.
            See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
        context: Extra variables to pass to the validator.
        by_alias: Whether to use the field's alias when validating against the provided input data.
        by_name: Whether to use the field's name when validating against the provided input data.

    Returns:
        The validated Pydantic model.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True

    if by_alias is False and by_name is not True:
        raise PydanticUserError(
            'At least one of `by_alias` or `by_name` must be set to True.',
            code='validate-by-alias-and-name-false',
        )

    return cls.__pydantic_validator__.validate_strings(
        obj, strict=strict, extra=extra, context=context, by_alias=by_alias, by_name=by_name
    )

unique_toolkit.app.schemas.Event

Bases: ChatEvent

Source code in unique_toolkit/unique_toolkit/app/schemas.py
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
@deprecated(
    """Use the more specific `ChatEvent` instead that has the same properties. \
This class will be removed in the next major version."""
)
class Event(ChatEvent):
    pass
    # The below should only affect type hints
    # event: EventName T
    # payload: EventPayload

    @classmethod
    def from_json_file(cls, file_path: Path) -> Event:
        if not file_path.exists():
            raise FileNotFoundError(f"File not found: {file_path}")
        with file_path.open("r", encoding="utf-8") as f:
            data = json.load(f)
        return cls.model_validate(data)

__class_vars__ class-attribute

The names of the class variables defined on the model.

__private_attributes__ class-attribute

Metadata about the private attributes of the model.

__pydantic_complete__ = False class-attribute

Whether model building is completed, or if there are still undefined fields.

__pydantic_computed_fields__ class-attribute

A dictionary of computed field names and their corresponding [ComputedFieldInfo][pydantic.fields.ComputedFieldInfo] objects.

__pydantic_core_schema__ class-attribute

The core schema of the model.

__pydantic_custom_init__ class-attribute

Whether the model has a custom __init__ method.

__pydantic_decorators__ = _decorators.DecoratorInfos() class-attribute

Metadata containing the decorators defined on the model. This replaces Model.__validators__ and Model.__root_validators__ from Pydantic V1.

__pydantic_extra__ = _model_construction.NoInitField(init=False) class-attribute instance-attribute

A dictionary containing extra values, if [extra][pydantic.config.ConfigDict.extra] is set to 'allow'.

__pydantic_fields__ class-attribute

A dictionary of field names and their corresponding [FieldInfo][pydantic.fields.FieldInfo] objects. This replaces Model.__fields__ from Pydantic V1.

__pydantic_fields_set__ = _model_construction.NoInitField(init=False) class-attribute instance-attribute

The names of fields explicitly set during instantiation.

__pydantic_generic_metadata__ class-attribute

Metadata for generic models; contains data used for a similar purpose to args, origin, parameters in typing-module generics. May eventually be replaced by these.

__pydantic_parent_namespace__ = None class-attribute

Parent namespace of the model, used for automatic rebuilding of models.

__pydantic_post_init__ class-attribute

The name of the post-init method for the model, if defined.

__pydantic_private__ = _model_construction.NoInitField(init=False) class-attribute instance-attribute

Values of private attributes set on the model instance.

__pydantic_root_model__ = False class-attribute

Whether the model is a [RootModel][pydantic.root_model.RootModel].

__pydantic_serializer__ class-attribute

The pydantic-core SchemaSerializer used to dump instances of the model.

__pydantic_setattr_handlers__ class-attribute

__setattr__ handlers. Memoizing the handlers leads to a dramatic performance improvement in __setattr__

__pydantic_validator__ class-attribute

The pydantic-core SchemaValidator used to validate instances of the model.

__signature__ class-attribute

The synthesized __init__ [Signature][inspect.Signature] of the model.

model_extra property

Get extra fields set during validation.

Returns:

Type Description
dict[str, Any] | None

A dictionary of extra fields, or None if config.extra is not set to "allow".

model_fields_set property

Returns the set of fields that have been explicitly set on this model instance.

Returns:

Type Description
set[str]

A set of strings representing the fields that have been set, i.e. that were not filled from defaults.

__copy__()

Returns a shallow copy of the model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
def __copy__(self) -> Self:
    """Returns a shallow copy of the model."""
    cls = type(self)
    m = cls.__new__(cls)
    _object_setattr(m, '__dict__', copy(self.__dict__))
    _object_setattr(m, '__pydantic_extra__', copy(self.__pydantic_extra__))
    _object_setattr(m, '__pydantic_fields_set__', copy(self.__pydantic_fields_set__))

    if not hasattr(self, '__pydantic_private__') or self.__pydantic_private__ is None:
        _object_setattr(m, '__pydantic_private__', None)
    else:
        _object_setattr(
            m,
            '__pydantic_private__',
            {k: v for k, v in self.__pydantic_private__.items() if v is not PydanticUndefined},
        )

    return m

__deepcopy__(memo=None)

Returns a deep copy of the model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
def __deepcopy__(self, memo: dict[int, Any] | None = None) -> Self:
    """Returns a deep copy of the model."""
    cls = type(self)
    m = cls.__new__(cls)
    _object_setattr(m, '__dict__', deepcopy(self.__dict__, memo=memo))
    _object_setattr(m, '__pydantic_extra__', deepcopy(self.__pydantic_extra__, memo=memo))
    # This next line doesn't need a deepcopy because __pydantic_fields_set__ is a set[str],
    # and attempting a deepcopy would be marginally slower.
    _object_setattr(m, '__pydantic_fields_set__', copy(self.__pydantic_fields_set__))

    if not hasattr(self, '__pydantic_private__') or self.__pydantic_private__ is None:
        _object_setattr(m, '__pydantic_private__', None)
    else:
        _object_setattr(
            m,
            '__pydantic_private__',
            deepcopy({k: v for k, v in self.__pydantic_private__.items() if v is not PydanticUndefined}, memo=memo),
        )

    return m

__get_pydantic_json_schema__(core_schema, handler) classmethod

Hook into generating the model's JSON schema.

Parameters:

Name Type Description Default
core_schema CoreSchema

A pydantic-core CoreSchema. You can ignore this argument and call the handler with a new CoreSchema, wrap this CoreSchema ({'type': 'nullable', 'schema': current_schema}), or just call the handler with the original schema.

required
handler GetJsonSchemaHandler

Call into Pydantic's internal JSON schema generation. This will raise a pydantic.errors.PydanticInvalidForJsonSchema if JSON schema generation fails. Since this gets called by BaseModel.model_json_schema you can override the schema_generator argument to that function to change JSON schema generation globally for a type.

required

Returns:

Type Description
JsonSchemaValue

A JSON schema, as a Python object.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
@classmethod
def __get_pydantic_json_schema__(
    cls,
    core_schema: CoreSchema,
    handler: GetJsonSchemaHandler,
    /,
) -> JsonSchemaValue:
    """Hook into generating the model's JSON schema.

    Args:
        core_schema: A `pydantic-core` CoreSchema.
            You can ignore this argument and call the handler with a new CoreSchema,
            wrap this CoreSchema (`{'type': 'nullable', 'schema': current_schema}`),
            or just call the handler with the original schema.
        handler: Call into Pydantic's internal JSON schema generation.
            This will raise a `pydantic.errors.PydanticInvalidForJsonSchema` if JSON schema
            generation fails.
            Since this gets called by `BaseModel.model_json_schema` you can override the
            `schema_generator` argument to that function to change JSON schema generation globally
            for a type.

    Returns:
        A JSON schema, as a Python object.
    """
    return handler(core_schema)

__init__(**data)

Create a new model by parsing and validating input data from keyword arguments.

Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.

self is explicitly positional-only to allow self as a field name.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
def __init__(self, /, **data: Any) -> None:
    """Create a new model by parsing and validating input data from keyword arguments.

    Raises [`ValidationError`][pydantic_core.ValidationError] if the input data cannot be
    validated to form a valid model.

    `self` is explicitly positional-only to allow `self` as a field name.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True
    validated_self = self.__pydantic_validator__.validate_python(data, self_instance=self)
    if self is not validated_self:
        warnings.warn(
            'A custom validator is returning a value other than `self`.\n'
            "Returning anything other than `self` from a top level model validator isn't supported when validating via `__init__`.\n"
            'See the `model_validator` docs (https://docs.pydantic.dev/latest/concepts/validators/#model-validators) for more details.',
            stacklevel=2,
        )

__init_subclass__(**kwargs)

This signature is included purely to help type-checkers check arguments to class declaration, which provides a way to conveniently set model_config key/value pairs.

from pydantic import BaseModel

class MyModel(BaseModel, extra='allow'): ...

However, this may be deceiving, since the actual calls to __init_subclass__ will not receive any of the config arguments, and will only receive any keyword arguments passed during class initialization that are not expected keys in ConfigDict. (This is due to the way ModelMetaclass.__new__ works.)

Parameters:

Name Type Description Default
**kwargs Unpack[ConfigDict]

Keyword arguments passed to the class definition, which set model_config

{}
Note

You may want to override __pydantic_init_subclass__ instead, which behaves similarly but is called after the class is fully initialized.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
def __init_subclass__(cls, **kwargs: Unpack[ConfigDict]):
    """This signature is included purely to help type-checkers check arguments to class declaration, which
    provides a way to conveniently set model_config key/value pairs.

    ```python
    from pydantic import BaseModel

    class MyModel(BaseModel, extra='allow'): ...
    ```

    However, this may be deceiving, since the _actual_ calls to `__init_subclass__` will not receive any
    of the config arguments, and will only receive any keyword arguments passed during class initialization
    that are _not_ expected keys in ConfigDict. (This is due to the way `ModelMetaclass.__new__` works.)

    Args:
        **kwargs: Keyword arguments passed to the class definition, which set model_config

    Note:
        You may want to override `__pydantic_init_subclass__` instead, which behaves similarly but is called
        *after* the class is fully initialized.
    """

__iter__()

So dict(model) works.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
1229
1230
1231
1232
1233
1234
def __iter__(self) -> TupleGenerator:
    """So `dict(model)` works."""
    yield from [(k, v) for (k, v) in self.__dict__.items() if not k.startswith('_')]
    extra = self.__pydantic_extra__
    if extra:
        yield from extra.items()

__pydantic_init_subclass__(**kwargs) classmethod

This is intended to behave just like __init_subclass__, but is called by ModelMetaclass only after basic class initialization is complete. In particular, attributes like model_fields will be present when this is called, but forward annotations are not guaranteed to be resolved yet, meaning that creating an instance of the class may fail.

This is necessary because __init_subclass__ will always be called by type.__new__, and it would require a prohibitively large refactor to the ModelMetaclass to ensure that type.__new__ was called in such a manner that the class would already be sufficiently initialized.

This will receive the same kwargs that would be passed to the standard __init_subclass__, namely, any kwargs passed to the class definition that aren't used internally by Pydantic.

Parameters:

Name Type Description Default
**kwargs Any

Any keyword arguments passed to the class definition that aren't used internally by Pydantic.

{}
Note

You may want to override __pydantic_on_complete__() instead, which is called once the class and its fields are fully initialized and ready for validation.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
@classmethod
def __pydantic_init_subclass__(cls, **kwargs: Any) -> None:
    """This is intended to behave just like `__init_subclass__`, but is called by `ModelMetaclass`
    only after basic class initialization is complete. In particular, attributes like `model_fields` will
    be present when this is called, but forward annotations are not guaranteed to be resolved yet,
    meaning that creating an instance of the class may fail.

    This is necessary because `__init_subclass__` will always be called by `type.__new__`,
    and it would require a prohibitively large refactor to the `ModelMetaclass` to ensure that
    `type.__new__` was called in such a manner that the class would already be sufficiently initialized.

    This will receive the same `kwargs` that would be passed to the standard `__init_subclass__`, namely,
    any kwargs passed to the class definition that aren't used internally by Pydantic.

    Args:
        **kwargs: Any keyword arguments passed to the class definition that aren't used internally
            by Pydantic.

    Note:
        You may want to override [`__pydantic_on_complete__()`][pydantic.main.BaseModel.__pydantic_on_complete__]
        instead, which is called once the class and its fields are fully initialized and ready for validation.
    """

__pydantic_on_complete__() classmethod

This is called once the class and its fields are fully initialized and ready to be used.

This typically happens when the class is created (just before __pydantic_init_subclass__() is called on the superclass), except when forward annotations are used that could not immediately be resolved. In that case, it will be called later, when the model is rebuilt automatically or explicitly using model_rebuild().

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
877
878
879
880
881
882
883
884
885
886
@classmethod
def __pydantic_on_complete__(cls) -> None:
    """This is called once the class and its fields are fully initialized and ready to be used.

    This typically happens when the class is created (just before
    [`__pydantic_init_subclass__()`][pydantic.main.BaseModel.__pydantic_init_subclass__] is called on the superclass),
    except when forward annotations are used that could not immediately be resolved.
    In that case, it will be called later, when the model is rebuilt automatically or explicitly using
    [`model_rebuild()`][pydantic.main.BaseModel.model_rebuild].
    """

copy(*, include=None, exclude=None, update=None, deep=False)

Returns a copy of the model.

Deprecated

This method is now deprecated; use model_copy instead.

If you need include or exclude, use:

data = self.model_dump(include=include, exclude=exclude, round_trip=True)
data = {**data, **(update or {})}
copied = self.model_validate(data)

Parameters:

Name Type Description Default
include AbstractSetIntStr | MappingIntStrAny | None

Optional set or mapping specifying which fields to include in the copied model.

None
exclude AbstractSetIntStr | MappingIntStrAny | None

Optional set or mapping specifying which fields to exclude in the copied model.

None
update Dict[str, Any] | None

Optional dictionary of field-value pairs to override field values in the copied model.

None
deep bool

If True, the values of fields that are Pydantic models will be deep-copied.

False

Returns:

Type Description
Self

A copy of the model with included, excluded and updated fields as specified.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
@typing_extensions.deprecated(
    'The `copy` method is deprecated; use `model_copy` instead. '
    'See the docstring of `BaseModel.copy` for details about how to handle `include` and `exclude`.',
    category=None,
)
def copy(
    self,
    *,
    include: AbstractSetIntStr | MappingIntStrAny | None = None,
    exclude: AbstractSetIntStr | MappingIntStrAny | None = None,
    update: Dict[str, Any] | None = None,  # noqa UP006
    deep: bool = False,
) -> Self:  # pragma: no cover
    """Returns a copy of the model.

    !!! warning "Deprecated"
        This method is now deprecated; use `model_copy` instead.

    If you need `include` or `exclude`, use:

    ```python {test="skip" lint="skip"}
    data = self.model_dump(include=include, exclude=exclude, round_trip=True)
    data = {**data, **(update or {})}
    copied = self.model_validate(data)
    ```

    Args:
        include: Optional set or mapping specifying which fields to include in the copied model.
        exclude: Optional set or mapping specifying which fields to exclude in the copied model.
        update: Optional dictionary of field-value pairs to override field values in the copied model.
        deep: If True, the values of fields that are Pydantic models will be deep-copied.

    Returns:
        A copy of the model with included, excluded and updated fields as specified.
    """
    warnings.warn(
        'The `copy` method is deprecated; use `model_copy` instead. '
        'See the docstring of `BaseModel.copy` for details about how to handle `include` and `exclude`.',
        category=PydanticDeprecatedSince20,
        stacklevel=2,
    )
    from .deprecated import copy_internals

    values = dict(
        copy_internals._iter(
            self, to_dict=False, by_alias=False, include=include, exclude=exclude, exclude_unset=False
        ),
        **(update or {}),
    )
    if self.__pydantic_private__ is None:
        private = None
    else:
        private = {k: v for k, v in self.__pydantic_private__.items() if v is not PydanticUndefined}

    if self.__pydantic_extra__ is None:
        extra: dict[str, Any] | None = None
    else:
        extra = self.__pydantic_extra__.copy()
        for k in list(self.__pydantic_extra__):
            if k not in values:  # k was in the exclude
                extra.pop(k)
        for k in list(values):
            if k in self.__pydantic_extra__:  # k must have come from extra
                extra[k] = values.pop(k)

    # new `__pydantic_fields_set__` can have unset optional fields with a set value in `update` kwarg
    if update:
        fields_set = self.__pydantic_fields_set__ | update.keys()
    else:
        fields_set = set(self.__pydantic_fields_set__)

    # removing excluded fields from `__pydantic_fields_set__`
    if exclude:
        fields_set -= set(exclude)

    return copy_internals._copy_and_set_values(self, values, fields_set, extra, private, deep=deep)

get_initial_debug_info()

Get the debug information for the chat event

Source code in unique_toolkit/unique_toolkit/app/schemas.py
295
296
297
298
299
300
301
302
303
304
def get_initial_debug_info(self) -> dict[str, Any]:
    """Get the debug information for the chat event"""

    # TODO: Make sure this coincides with what is shown in the first user message
    return {
        "user_metadata": self.payload.user_metadata,
        "tool_parameters": self.payload.tool_parameters,
        "chosen_module": self.payload.name,
        "assistant": {"id": self.payload.assistant_id},
    }

model_computed_fields() classmethod

A mapping of computed field names to their respective [ComputedFieldInfo][pydantic.fields.ComputedFieldInfo] instances.

Warning

Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3. Instead, you should access this attribute from the model class.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
273
274
275
276
277
278
279
280
281
282
@_utils.deprecated_instance_property
@classmethod
def model_computed_fields(cls) -> dict[str, ComputedFieldInfo]:
    """A mapping of computed field names to their respective [`ComputedFieldInfo`][pydantic.fields.ComputedFieldInfo] instances.

    !!! warning
        Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3.
        Instead, you should access this attribute from the model class.
    """
    return getattr(cls, '__pydantic_computed_fields__', {})

model_construct(_fields_set=None, **values) classmethod

Creates a new instance of the Model class with validated data.

Creates a new model setting __dict__ and __pydantic_fields_set__ from trusted or pre-validated data. Default values are respected, but no other validation is performed.

Note

model_construct() generally respects the model_config.extra setting on the provided model. That is, if model_config.extra == 'allow', then all extra passed values are added to the model instance's __dict__ and __pydantic_extra__ fields. If model_config.extra == 'ignore' (the default), then all extra passed values are ignored. Because no validation is performed with a call to model_construct(), having model_config.extra == 'forbid' does not result in an error if extra values are passed, but they will be ignored.

Parameters:

Name Type Description Default
_fields_set set[str] | None

A set of field names that were originally explicitly set during instantiation. If provided, this is directly used for the [model_fields_set][pydantic.BaseModel.model_fields_set] attribute. Otherwise, the field names from the values argument will be used.

None
values Any

Trusted or pre-validated data dictionary.

{}

Returns:

Type Description
Self

A new instance of the Model class with validated data.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
@classmethod
def model_construct(cls, _fields_set: set[str] | None = None, **values: Any) -> Self:  # noqa: C901
    """Creates a new instance of the `Model` class with validated data.

    Creates a new model setting `__dict__` and `__pydantic_fields_set__` from trusted or pre-validated data.
    Default values are respected, but no other validation is performed.

    !!! note
        `model_construct()` generally respects the `model_config.extra` setting on the provided model.
        That is, if `model_config.extra == 'allow'`, then all extra passed values are added to the model instance's `__dict__`
        and `__pydantic_extra__` fields. If `model_config.extra == 'ignore'` (the default), then all extra passed values are ignored.
        Because no validation is performed with a call to `model_construct()`, having `model_config.extra == 'forbid'` does not result in
        an error if extra values are passed, but they will be ignored.

    Args:
        _fields_set: A set of field names that were originally explicitly set during instantiation. If provided,
            this is directly used for the [`model_fields_set`][pydantic.BaseModel.model_fields_set] attribute.
            Otherwise, the field names from the `values` argument will be used.
        values: Trusted or pre-validated data dictionary.

    Returns:
        A new instance of the `Model` class with validated data.
    """
    m = cls.__new__(cls)
    fields_values: dict[str, Any] = {}
    fields_set = set()

    for name, field in cls.__pydantic_fields__.items():
        if field.alias is not None and field.alias in values:
            fields_values[name] = values.pop(field.alias)
            fields_set.add(name)

        if (name not in fields_set) and (field.validation_alias is not None):
            validation_aliases: list[str | AliasPath] = (
                field.validation_alias.choices
                if isinstance(field.validation_alias, AliasChoices)
                else [field.validation_alias]
            )

            for alias in validation_aliases:
                if isinstance(alias, str) and alias in values:
                    fields_values[name] = values.pop(alias)
                    fields_set.add(name)
                    break
                elif isinstance(alias, AliasPath):
                    value = alias.search_dict_for_path(values)
                    if value is not PydanticUndefined:
                        fields_values[name] = value
                        fields_set.add(name)
                        break

        if name not in fields_set:
            if name in values:
                fields_values[name] = values.pop(name)
                fields_set.add(name)
            elif not field.is_required():
                fields_values[name] = field.get_default(call_default_factory=True, validated_data=fields_values)
    if _fields_set is None:
        _fields_set = fields_set

    _extra: dict[str, Any] | None = values if cls.model_config.get('extra') == 'allow' else None
    _object_setattr(m, '__dict__', fields_values)
    _object_setattr(m, '__pydantic_fields_set__', _fields_set)
    if not cls.__pydantic_root_model__:
        _object_setattr(m, '__pydantic_extra__', _extra)

    if cls.__pydantic_post_init__:
        m.model_post_init(None)
        # update private attributes with values set
        if hasattr(m, '__pydantic_private__') and m.__pydantic_private__ is not None:
            for k, v in values.items():
                if k in m.__private_attributes__:
                    m.__pydantic_private__[k] = v

    elif not cls.__pydantic_root_model__:
        # Note: if there are any private attributes, cls.__pydantic_post_init__ would exist
        # Since it doesn't, that means that `__pydantic_private__` should be set to None
        _object_setattr(m, '__pydantic_private__', None)

    return m

model_copy(*, update=None, deep=False)

Usage Documentation

model_copy

Returns a copy of the model.

Note

The underlying instance's [__dict__][object.__dict__] attribute is copied. This might have unexpected side effects if you store anything in it, on top of the model fields (e.g. the value of [cached properties][functools.cached_property]).

Parameters:

Name Type Description Default
update Mapping[str, Any] | None

Values to change/add in the new model. Note: the data is not validated before creating the new model. You should trust this data.

None
deep bool

Set to True to make a deep copy of the model.

False

Returns:

Type Description
Self

New model instance.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
def model_copy(self, *, update: Mapping[str, Any] | None = None, deep: bool = False) -> Self:
    """!!! abstract "Usage Documentation"
        [`model_copy`](../concepts/models.md#model-copy)

    Returns a copy of the model.

    !!! note
        The underlying instance's [`__dict__`][object.__dict__] attribute is copied. This
        might have unexpected side effects if you store anything in it, on top of the model
        fields (e.g. the value of [cached properties][functools.cached_property]).

    Args:
        update: Values to change/add in the new model. Note: the data is not validated
            before creating the new model. You should trust this data.
        deep: Set to `True` to make a deep copy of the model.

    Returns:
        New model instance.
    """
    copied = self.__deepcopy__() if deep else self.__copy__()
    if update:
        if self.model_config.get('extra') == 'allow':
            for k, v in update.items():
                if k in self.__pydantic_fields__:
                    copied.__dict__[k] = v
                else:
                    if copied.__pydantic_extra__ is None:
                        copied.__pydantic_extra__ = {}
                    copied.__pydantic_extra__[k] = v
        else:
            copied.__dict__.update(update)
        copied.__pydantic_fields_set__.update(update.keys())
    return copied

model_dump(*, mode='python', include=None, exclude=None, context=None, by_alias=None, exclude_unset=False, exclude_defaults=False, exclude_none=False, exclude_computed_fields=False, round_trip=False, warnings=True, fallback=None, serialize_as_any=False)

Usage Documentation

model_dump

Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.

Parameters:

Name Type Description Default
mode Literal['json', 'python'] | str

The mode in which to_python should run. If mode is 'json', the output will only contain JSON serializable types. If mode is 'python', the output may contain non-JSON-serializable Python objects.

'python'
include IncEx | None

A set of fields to include in the output.

None
exclude IncEx | None

A set of fields to exclude from the output.

None
context Any | None

Additional context to pass to the serializer.

None
by_alias bool | None

Whether to use the field's alias in the dictionary key if defined.

None
exclude_unset bool

Whether to exclude fields that have not been explicitly set.

False
exclude_defaults bool

Whether to exclude fields that are set to their default value.

False
exclude_none bool

Whether to exclude fields that have a value of None.

False
exclude_computed_fields bool

Whether to exclude computed fields. While this can be useful for round-tripping, it is usually recommended to use the dedicated round_trip parameter instead.

False
round_trip bool

If True, dumped values should be valid as input for non-idempotent types such as Json[T].

False
warnings bool | Literal['none', 'warn', 'error']

How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors, "error" raises a [PydanticSerializationError][pydantic_core.PydanticSerializationError].

True
fallback Callable[[Any], Any] | None

A function to call when an unknown value is encountered. If not provided, a [PydanticSerializationError][pydantic_core.PydanticSerializationError] error is raised.

None
serialize_as_any bool

Whether to serialize fields with duck-typing serialization behavior.

False

Returns:

Type Description
dict[str, Any]

A dictionary representation of the model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
def model_dump(
    self,
    *,
    mode: Literal['json', 'python'] | str = 'python',
    include: IncEx | None = None,
    exclude: IncEx | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    exclude_unset: bool = False,
    exclude_defaults: bool = False,
    exclude_none: bool = False,
    exclude_computed_fields: bool = False,
    round_trip: bool = False,
    warnings: bool | Literal['none', 'warn', 'error'] = True,
    fallback: Callable[[Any], Any] | None = None,
    serialize_as_any: bool = False,
) -> dict[str, Any]:
    """!!! abstract "Usage Documentation"
        [`model_dump`](../concepts/serialization.md#python-mode)

    Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.

    Args:
        mode: The mode in which `to_python` should run.
            If mode is 'json', the output will only contain JSON serializable types.
            If mode is 'python', the output may contain non-JSON-serializable Python objects.
        include: A set of fields to include in the output.
        exclude: A set of fields to exclude from the output.
        context: Additional context to pass to the serializer.
        by_alias: Whether to use the field's alias in the dictionary key if defined.
        exclude_unset: Whether to exclude fields that have not been explicitly set.
        exclude_defaults: Whether to exclude fields that are set to their default value.
        exclude_none: Whether to exclude fields that have a value of `None`.
        exclude_computed_fields: Whether to exclude computed fields.
            While this can be useful for round-tripping, it is usually recommended to use the dedicated
            `round_trip` parameter instead.
        round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
        warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
            "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
        fallback: A function to call when an unknown value is encountered. If not provided,
            a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
        serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.

    Returns:
        A dictionary representation of the model.
    """
    return self.__pydantic_serializer__.to_python(
        self,
        mode=mode,
        by_alias=by_alias,
        include=include,
        exclude=exclude,
        context=context,
        exclude_unset=exclude_unset,
        exclude_defaults=exclude_defaults,
        exclude_none=exclude_none,
        exclude_computed_fields=exclude_computed_fields,
        round_trip=round_trip,
        warnings=warnings,
        fallback=fallback,
        serialize_as_any=serialize_as_any,
    )

model_dump_json(*, indent=None, ensure_ascii=False, include=None, exclude=None, context=None, by_alias=None, exclude_unset=False, exclude_defaults=False, exclude_none=False, exclude_computed_fields=False, round_trip=False, warnings=True, fallback=None, serialize_as_any=False)

Usage Documentation

model_dump_json

Generates a JSON representation of the model using Pydantic's to_json method.

Parameters:

Name Type Description Default
indent int | None

Indentation to use in the JSON output. If None is passed, the output will be compact.

None
ensure_ascii bool

If True, the output is guaranteed to have all incoming non-ASCII characters escaped. If False (the default), these characters will be output as-is.

False
include IncEx | None

Field(s) to include in the JSON output.

None
exclude IncEx | None

Field(s) to exclude from the JSON output.

None
context Any | None

Additional context to pass to the serializer.

None
by_alias bool | None

Whether to serialize using field aliases.

None
exclude_unset bool

Whether to exclude fields that have not been explicitly set.

False
exclude_defaults bool

Whether to exclude fields that are set to their default value.

False
exclude_none bool

Whether to exclude fields that have a value of None.

False
exclude_computed_fields bool

Whether to exclude computed fields. While this can be useful for round-tripping, it is usually recommended to use the dedicated round_trip parameter instead.

False
round_trip bool

If True, dumped values should be valid as input for non-idempotent types such as Json[T].

False
warnings bool | Literal['none', 'warn', 'error']

How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors, "error" raises a [PydanticSerializationError][pydantic_core.PydanticSerializationError].

True
fallback Callable[[Any], Any] | None

A function to call when an unknown value is encountered. If not provided, a [PydanticSerializationError][pydantic_core.PydanticSerializationError] error is raised.

None
serialize_as_any bool

Whether to serialize fields with duck-typing serialization behavior.

False

Returns:

Type Description
str

A JSON string representation of the model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
def model_dump_json(
    self,
    *,
    indent: int | None = None,
    ensure_ascii: bool = False,
    include: IncEx | None = None,
    exclude: IncEx | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    exclude_unset: bool = False,
    exclude_defaults: bool = False,
    exclude_none: bool = False,
    exclude_computed_fields: bool = False,
    round_trip: bool = False,
    warnings: bool | Literal['none', 'warn', 'error'] = True,
    fallback: Callable[[Any], Any] | None = None,
    serialize_as_any: bool = False,
) -> str:
    """!!! abstract "Usage Documentation"
        [`model_dump_json`](../concepts/serialization.md#json-mode)

    Generates a JSON representation of the model using Pydantic's `to_json` method.

    Args:
        indent: Indentation to use in the JSON output. If None is passed, the output will be compact.
        ensure_ascii: If `True`, the output is guaranteed to have all incoming non-ASCII characters escaped.
            If `False` (the default), these characters will be output as-is.
        include: Field(s) to include in the JSON output.
        exclude: Field(s) to exclude from the JSON output.
        context: Additional context to pass to the serializer.
        by_alias: Whether to serialize using field aliases.
        exclude_unset: Whether to exclude fields that have not been explicitly set.
        exclude_defaults: Whether to exclude fields that are set to their default value.
        exclude_none: Whether to exclude fields that have a value of `None`.
        exclude_computed_fields: Whether to exclude computed fields.
            While this can be useful for round-tripping, it is usually recommended to use the dedicated
            `round_trip` parameter instead.
        round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
        warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
            "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
        fallback: A function to call when an unknown value is encountered. If not provided,
            a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
        serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.

    Returns:
        A JSON string representation of the model.
    """
    return self.__pydantic_serializer__.to_json(
        self,
        indent=indent,
        ensure_ascii=ensure_ascii,
        include=include,
        exclude=exclude,
        context=context,
        by_alias=by_alias,
        exclude_unset=exclude_unset,
        exclude_defaults=exclude_defaults,
        exclude_none=exclude_none,
        exclude_computed_fields=exclude_computed_fields,
        round_trip=round_trip,
        warnings=warnings,
        fallback=fallback,
        serialize_as_any=serialize_as_any,
    ).decode()

model_fields() classmethod

A mapping of field names to their respective [FieldInfo][pydantic.fields.FieldInfo] instances.

Warning

Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3. Instead, you should access this attribute from the model class.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
262
263
264
265
266
267
268
269
270
271
@_utils.deprecated_instance_property
@classmethod
def model_fields(cls) -> dict[str, FieldInfo]:
    """A mapping of field names to their respective [`FieldInfo`][pydantic.fields.FieldInfo] instances.

    !!! warning
        Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3.
        Instead, you should access this attribute from the model class.
    """
    return getattr(cls, '__pydantic_fields__', {})

model_json_schema(by_alias=True, ref_template=DEFAULT_REF_TEMPLATE, schema_generator=GenerateJsonSchema, mode='validation', *, union_format='any_of') classmethod

Generates a JSON schema for a model class.

Parameters:

Name Type Description Default
by_alias bool

Whether to use attribute aliases or not.

True
ref_template str

The reference template.

DEFAULT_REF_TEMPLATE
union_format Literal['any_of', 'primitive_type_array']

The format to use when combining schemas from unions together. Can be one of:

  • 'any_of': Use the anyOf keyword to combine schemas (the default).
  • 'primitive_type_array': Use the type keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive type (string, boolean, null, integer or number) or contains constraints/metadata, falls back to any_of.
'any_of'
schema_generator type[GenerateJsonSchema]

To override the logic used to generate the JSON schema, as a subclass of GenerateJsonSchema with your desired modifications

GenerateJsonSchema
mode JsonSchemaMode

The mode in which to generate the schema.

'validation'

Returns:

Type Description
dict[str, Any]

The JSON schema for the given model class.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
@classmethod
def model_json_schema(
    cls,
    by_alias: bool = True,
    ref_template: str = DEFAULT_REF_TEMPLATE,
    schema_generator: type[GenerateJsonSchema] = GenerateJsonSchema,
    mode: JsonSchemaMode = 'validation',
    *,
    union_format: Literal['any_of', 'primitive_type_array'] = 'any_of',
) -> dict[str, Any]:
    """Generates a JSON schema for a model class.

    Args:
        by_alias: Whether to use attribute aliases or not.
        ref_template: The reference template.
        union_format: The format to use when combining schemas from unions together. Can be one of:

            - `'any_of'`: Use the [`anyOf`](https://json-schema.org/understanding-json-schema/reference/combining#anyOf)
            keyword to combine schemas (the default).
            - `'primitive_type_array'`: Use the [`type`](https://json-schema.org/understanding-json-schema/reference/type)
            keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive
            type (`string`, `boolean`, `null`, `integer` or `number`) or contains constraints/metadata, falls back to
            `any_of`.
        schema_generator: To override the logic used to generate the JSON schema, as a subclass of
            `GenerateJsonSchema` with your desired modifications
        mode: The mode in which to generate the schema.

    Returns:
        The JSON schema for the given model class.
    """
    return model_json_schema(
        cls,
        by_alias=by_alias,
        ref_template=ref_template,
        union_format=union_format,
        schema_generator=schema_generator,
        mode=mode,
    )

model_parametrized_name(params) classmethod

Compute the class name for parametrizations of generic classes.

This method can be overridden to achieve a custom naming scheme for generic BaseModels.

Parameters:

Name Type Description Default
params tuple[type[Any], ...]

Tuple of types of the class. Given a generic class Model with 2 type variables and a concrete model Model[str, int], the value (str, int) would be passed to params.

required

Returns:

Type Description
str

String representing the new class where params are passed to cls as type variables.

Raises:

Type Description
TypeError

Raised when trying to generate concrete names for non-generic models.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
@classmethod
def model_parametrized_name(cls, params: tuple[type[Any], ...]) -> str:
    """Compute the class name for parametrizations of generic classes.

    This method can be overridden to achieve a custom naming scheme for generic BaseModels.

    Args:
        params: Tuple of types of the class. Given a generic class
            `Model` with 2 type variables and a concrete model `Model[str, int]`,
            the value `(str, int)` would be passed to `params`.

    Returns:
        String representing the new class where `params` are passed to `cls` as type variables.

    Raises:
        TypeError: Raised when trying to generate concrete names for non-generic models.
    """
    if not issubclass(cls, Generic):
        raise TypeError('Concrete names should only be generated for generic models.')

    # Any strings received should represent forward references, so we handle them specially below.
    # If we eventually move toward wrapping them in a ForwardRef in __class_getitem__ in the future,
    # we may be able to remove this special case.
    param_names = [param if isinstance(param, str) else _repr.display_as_type(param) for param in params]
    params_component = ', '.join(param_names)
    return f'{cls.__name__}[{params_component}]'

model_post_init(context)

Override this method to perform additional initialization after __init__ and model_construct. This is useful if you want to do some validation that requires the entire model to be initialized.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
612
613
614
615
def model_post_init(self, context: Any, /) -> None:
    """Override this method to perform additional initialization after `__init__` and `model_construct`.
    This is useful if you want to do some validation that requires the entire model to be initialized.
    """

model_rebuild(*, force=False, raise_errors=True, _parent_namespace_depth=2, _types_namespace=None) classmethod

Try to rebuild the pydantic-core schema for the model.

This may be necessary when one of the annotations is a ForwardRef which could not be resolved during the initial attempt to build the schema, and automatic rebuilding fails.

Parameters:

Name Type Description Default
force bool

Whether to force the rebuilding of the model schema, defaults to False.

False
raise_errors bool

Whether to raise errors, defaults to True.

True
_parent_namespace_depth int

The depth level of the parent namespace, defaults to 2.

2
_types_namespace MappingNamespace | None

The types namespace, defaults to None.

None

Returns:

Type Description
bool | None

Returns None if the schema is already "complete" and rebuilding was not required.

bool | None

If rebuilding was required, returns True if rebuilding was successful, otherwise False.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
@classmethod
def model_rebuild(
    cls,
    *,
    force: bool = False,
    raise_errors: bool = True,
    _parent_namespace_depth: int = 2,
    _types_namespace: MappingNamespace | None = None,
) -> bool | None:
    """Try to rebuild the pydantic-core schema for the model.

    This may be necessary when one of the annotations is a ForwardRef which could not be resolved during
    the initial attempt to build the schema, and automatic rebuilding fails.

    Args:
        force: Whether to force the rebuilding of the model schema, defaults to `False`.
        raise_errors: Whether to raise errors, defaults to `True`.
        _parent_namespace_depth: The depth level of the parent namespace, defaults to 2.
        _types_namespace: The types namespace, defaults to `None`.

    Returns:
        Returns `None` if the schema is already "complete" and rebuilding was not required.
        If rebuilding _was_ required, returns `True` if rebuilding was successful, otherwise `False`.
    """
    already_complete = cls.__pydantic_complete__
    if already_complete and not force:
        return None

    cls.__pydantic_complete__ = False

    for attr in ('__pydantic_core_schema__', '__pydantic_validator__', '__pydantic_serializer__'):
        if attr in cls.__dict__ and not isinstance(getattr(cls, attr), _mock_val_ser.MockValSer):
            # Deleting the validator/serializer is necessary as otherwise they can get reused in
            # pydantic-core. We do so only if they aren't mock instances, otherwise — as `model_rebuild()`
            # isn't thread-safe — concurrent model instantiations can lead to the parent validator being used.
            # Same applies for the core schema that can be reused in schema generation.
            delattr(cls, attr)

    if _types_namespace is not None:
        rebuild_ns = _types_namespace
    elif _parent_namespace_depth > 0:
        rebuild_ns = _typing_extra.parent_frame_namespace(parent_depth=_parent_namespace_depth, force=True) or {}
    else:
        rebuild_ns = {}

    parent_ns = _model_construction.unpack_lenient_weakvaluedict(cls.__pydantic_parent_namespace__) or {}

    ns_resolver = _namespace_utils.NsResolver(
        parent_namespace={**rebuild_ns, **parent_ns},
    )

    return _model_construction.complete_model_class(
        cls,
        _config.ConfigWrapper(cls.model_config, check=False),
        ns_resolver,
        raise_errors=raise_errors,
        # If the model was already complete, we don't need to call the hook again.
        call_on_complete_hook=not already_complete,
    )

model_validate(obj, *, strict=None, extra=None, from_attributes=None, context=None, by_alias=None, by_name=None) classmethod

Validate a pydantic model instance.

Parameters:

Name Type Description Default
obj Any

The object to validate.

required
strict bool | None

Whether to enforce types strictly.

None
extra ExtraValues | None

Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.

None
from_attributes bool | None

Whether to extract data from object attributes.

None
context Any | None

Additional context to pass to the validator.

None
by_alias bool | None

Whether to use the field's alias when validating against the provided input data.

None
by_name bool | None

Whether to use the field's name when validating against the provided input data.

None

Raises:

Type Description
ValidationError

If the object could not be validated.

Returns:

Type Description
Self

The validated model instance.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
@classmethod
def model_validate(
    cls,
    obj: Any,
    *,
    strict: bool | None = None,
    extra: ExtraValues | None = None,
    from_attributes: bool | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    by_name: bool | None = None,
) -> Self:
    """Validate a pydantic model instance.

    Args:
        obj: The object to validate.
        strict: Whether to enforce types strictly.
        extra: Whether to ignore, allow, or forbid extra data during model validation.
            See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
        from_attributes: Whether to extract data from object attributes.
        context: Additional context to pass to the validator.
        by_alias: Whether to use the field's alias when validating against the provided input data.
        by_name: Whether to use the field's name when validating against the provided input data.

    Raises:
        ValidationError: If the object could not be validated.

    Returns:
        The validated model instance.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True

    if by_alias is False and by_name is not True:
        raise PydanticUserError(
            'At least one of `by_alias` or `by_name` must be set to True.',
            code='validate-by-alias-and-name-false',
        )

    return cls.__pydantic_validator__.validate_python(
        obj,
        strict=strict,
        extra=extra,
        from_attributes=from_attributes,
        context=context,
        by_alias=by_alias,
        by_name=by_name,
    )

model_validate_json(json_data, *, strict=None, extra=None, context=None, by_alias=None, by_name=None) classmethod

Usage Documentation

JSON Parsing

Validate the given JSON data against the Pydantic model.

Parameters:

Name Type Description Default
json_data str | bytes | bytearray

The JSON data to validate.

required
strict bool | None

Whether to enforce types strictly.

None
extra ExtraValues | None

Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.

None
context Any | None

Extra variables to pass to the validator.

None
by_alias bool | None

Whether to use the field's alias when validating against the provided input data.

None
by_name bool | None

Whether to use the field's name when validating against the provided input data.

None

Returns:

Type Description
Self

The validated Pydantic model.

Raises:

Type Description
ValidationError

If json_data is not a JSON string or the object could not be validated.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
@classmethod
def model_validate_json(
    cls,
    json_data: str | bytes | bytearray,
    *,
    strict: bool | None = None,
    extra: ExtraValues | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    by_name: bool | None = None,
) -> Self:
    """!!! abstract "Usage Documentation"
        [JSON Parsing](../concepts/json.md#json-parsing)

    Validate the given JSON data against the Pydantic model.

    Args:
        json_data: The JSON data to validate.
        strict: Whether to enforce types strictly.
        extra: Whether to ignore, allow, or forbid extra data during model validation.
            See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
        context: Extra variables to pass to the validator.
        by_alias: Whether to use the field's alias when validating against the provided input data.
        by_name: Whether to use the field's name when validating against the provided input data.

    Returns:
        The validated Pydantic model.

    Raises:
        ValidationError: If `json_data` is not a JSON string or the object could not be validated.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True

    if by_alias is False and by_name is not True:
        raise PydanticUserError(
            'At least one of `by_alias` or `by_name` must be set to True.',
            code='validate-by-alias-and-name-false',
        )

    return cls.__pydantic_validator__.validate_json(
        json_data, strict=strict, extra=extra, context=context, by_alias=by_alias, by_name=by_name
    )

model_validate_strings(obj, *, strict=None, extra=None, context=None, by_alias=None, by_name=None) classmethod

Validate the given object with string data against the Pydantic model.

Parameters:

Name Type Description Default
obj Any

The object containing string data to validate.

required
strict bool | None

Whether to enforce types strictly.

None
extra ExtraValues | None

Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.

None
context Any | None

Extra variables to pass to the validator.

None
by_alias bool | None

Whether to use the field's alias when validating against the provided input data.

None
by_name bool | None

Whether to use the field's name when validating against the provided input data.

None

Returns:

Type Description
Self

The validated Pydantic model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
@classmethod
def model_validate_strings(
    cls,
    obj: Any,
    *,
    strict: bool | None = None,
    extra: ExtraValues | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    by_name: bool | None = None,
) -> Self:
    """Validate the given object with string data against the Pydantic model.

    Args:
        obj: The object containing string data to validate.
        strict: Whether to enforce types strictly.
        extra: Whether to ignore, allow, or forbid extra data during model validation.
            See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
        context: Extra variables to pass to the validator.
        by_alias: Whether to use the field's alias when validating against the provided input data.
        by_name: Whether to use the field's name when validating against the provided input data.

    Returns:
        The validated Pydantic model.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True

    if by_alias is False and by_name is not True:
        raise PydanticUserError(
            'At least one of `by_alias` or `by_name` must be set to True.',
            code='validate-by-alias-and-name-false',
        )

    return cls.__pydantic_validator__.validate_strings(
        obj, strict=strict, extra=extra, context=context, by_alias=by_alias, by_name=by_name
    )

unique_toolkit.app.schemas.BaseEvent

Bases: BaseModel, Generic[FilterOptionsT]

Source code in unique_toolkit/unique_toolkit/app/schemas.py
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
class BaseEvent(BaseModel, Generic[FilterOptionsT]):
    model_config = model_config

    id: str
    event: str
    user_id: str
    company_id: str

    @classmethod
    def from_json_file(cls, file_path: Path) -> BaseEvent:
        if not file_path.exists():
            raise FileNotFoundError(f"File not found: {file_path}")
        with file_path.open("r", encoding="utf-8") as f:
            data = json.load(f)
        return cls.model_validate(data)

    def filter_event(self, *, filter_options: FilterOptionsT | None = None) -> bool:
        """Determine if event should be filtered out and be neglected."""
        return False

__class_vars__ class-attribute

The names of the class variables defined on the model.

__private_attributes__ class-attribute

Metadata about the private attributes of the model.

__pydantic_complete__ = False class-attribute

Whether model building is completed, or if there are still undefined fields.

__pydantic_computed_fields__ class-attribute

A dictionary of computed field names and their corresponding [ComputedFieldInfo][pydantic.fields.ComputedFieldInfo] objects.

__pydantic_core_schema__ class-attribute

The core schema of the model.

__pydantic_custom_init__ class-attribute

Whether the model has a custom __init__ method.

__pydantic_decorators__ = _decorators.DecoratorInfos() class-attribute

Metadata containing the decorators defined on the model. This replaces Model.__validators__ and Model.__root_validators__ from Pydantic V1.

__pydantic_extra__ = _model_construction.NoInitField(init=False) class-attribute instance-attribute

A dictionary containing extra values, if [extra][pydantic.config.ConfigDict.extra] is set to 'allow'.

__pydantic_fields__ class-attribute

A dictionary of field names and their corresponding [FieldInfo][pydantic.fields.FieldInfo] objects. This replaces Model.__fields__ from Pydantic V1.

__pydantic_fields_set__ = _model_construction.NoInitField(init=False) class-attribute instance-attribute

The names of fields explicitly set during instantiation.

__pydantic_generic_metadata__ class-attribute

Metadata for generic models; contains data used for a similar purpose to args, origin, parameters in typing-module generics. May eventually be replaced by these.

__pydantic_parent_namespace__ = None class-attribute

Parent namespace of the model, used for automatic rebuilding of models.

__pydantic_post_init__ class-attribute

The name of the post-init method for the model, if defined.

__pydantic_private__ = _model_construction.NoInitField(init=False) class-attribute instance-attribute

Values of private attributes set on the model instance.

__pydantic_root_model__ = False class-attribute

Whether the model is a [RootModel][pydantic.root_model.RootModel].

__pydantic_serializer__ class-attribute

The pydantic-core SchemaSerializer used to dump instances of the model.

__pydantic_setattr_handlers__ class-attribute

__setattr__ handlers. Memoizing the handlers leads to a dramatic performance improvement in __setattr__

__pydantic_validator__ class-attribute

The pydantic-core SchemaValidator used to validate instances of the model.

__signature__ class-attribute

The synthesized __init__ [Signature][inspect.Signature] of the model.

model_extra property

Get extra fields set during validation.

Returns:

Type Description
dict[str, Any] | None

A dictionary of extra fields, or None if config.extra is not set to "allow".

model_fields_set property

Returns the set of fields that have been explicitly set on this model instance.

Returns:

Type Description
set[str]

A set of strings representing the fields that have been set, i.e. that were not filled from defaults.

__copy__()

Returns a shallow copy of the model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
def __copy__(self) -> Self:
    """Returns a shallow copy of the model."""
    cls = type(self)
    m = cls.__new__(cls)
    _object_setattr(m, '__dict__', copy(self.__dict__))
    _object_setattr(m, '__pydantic_extra__', copy(self.__pydantic_extra__))
    _object_setattr(m, '__pydantic_fields_set__', copy(self.__pydantic_fields_set__))

    if not hasattr(self, '__pydantic_private__') or self.__pydantic_private__ is None:
        _object_setattr(m, '__pydantic_private__', None)
    else:
        _object_setattr(
            m,
            '__pydantic_private__',
            {k: v for k, v in self.__pydantic_private__.items() if v is not PydanticUndefined},
        )

    return m

__deepcopy__(memo=None)

Returns a deep copy of the model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
def __deepcopy__(self, memo: dict[int, Any] | None = None) -> Self:
    """Returns a deep copy of the model."""
    cls = type(self)
    m = cls.__new__(cls)
    _object_setattr(m, '__dict__', deepcopy(self.__dict__, memo=memo))
    _object_setattr(m, '__pydantic_extra__', deepcopy(self.__pydantic_extra__, memo=memo))
    # This next line doesn't need a deepcopy because __pydantic_fields_set__ is a set[str],
    # and attempting a deepcopy would be marginally slower.
    _object_setattr(m, '__pydantic_fields_set__', copy(self.__pydantic_fields_set__))

    if not hasattr(self, '__pydantic_private__') or self.__pydantic_private__ is None:
        _object_setattr(m, '__pydantic_private__', None)
    else:
        _object_setattr(
            m,
            '__pydantic_private__',
            deepcopy({k: v for k, v in self.__pydantic_private__.items() if v is not PydanticUndefined}, memo=memo),
        )

    return m

__get_pydantic_json_schema__(core_schema, handler) classmethod

Hook into generating the model's JSON schema.

Parameters:

Name Type Description Default
core_schema CoreSchema

A pydantic-core CoreSchema. You can ignore this argument and call the handler with a new CoreSchema, wrap this CoreSchema ({'type': 'nullable', 'schema': current_schema}), or just call the handler with the original schema.

required
handler GetJsonSchemaHandler

Call into Pydantic's internal JSON schema generation. This will raise a pydantic.errors.PydanticInvalidForJsonSchema if JSON schema generation fails. Since this gets called by BaseModel.model_json_schema you can override the schema_generator argument to that function to change JSON schema generation globally for a type.

required

Returns:

Type Description
JsonSchemaValue

A JSON schema, as a Python object.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
@classmethod
def __get_pydantic_json_schema__(
    cls,
    core_schema: CoreSchema,
    handler: GetJsonSchemaHandler,
    /,
) -> JsonSchemaValue:
    """Hook into generating the model's JSON schema.

    Args:
        core_schema: A `pydantic-core` CoreSchema.
            You can ignore this argument and call the handler with a new CoreSchema,
            wrap this CoreSchema (`{'type': 'nullable', 'schema': current_schema}`),
            or just call the handler with the original schema.
        handler: Call into Pydantic's internal JSON schema generation.
            This will raise a `pydantic.errors.PydanticInvalidForJsonSchema` if JSON schema
            generation fails.
            Since this gets called by `BaseModel.model_json_schema` you can override the
            `schema_generator` argument to that function to change JSON schema generation globally
            for a type.

    Returns:
        A JSON schema, as a Python object.
    """
    return handler(core_schema)

__init__(**data)

Create a new model by parsing and validating input data from keyword arguments.

Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.

self is explicitly positional-only to allow self as a field name.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
def __init__(self, /, **data: Any) -> None:
    """Create a new model by parsing and validating input data from keyword arguments.

    Raises [`ValidationError`][pydantic_core.ValidationError] if the input data cannot be
    validated to form a valid model.

    `self` is explicitly positional-only to allow `self` as a field name.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True
    validated_self = self.__pydantic_validator__.validate_python(data, self_instance=self)
    if self is not validated_self:
        warnings.warn(
            'A custom validator is returning a value other than `self`.\n'
            "Returning anything other than `self` from a top level model validator isn't supported when validating via `__init__`.\n"
            'See the `model_validator` docs (https://docs.pydantic.dev/latest/concepts/validators/#model-validators) for more details.',
            stacklevel=2,
        )

__init_subclass__(**kwargs)

This signature is included purely to help type-checkers check arguments to class declaration, which provides a way to conveniently set model_config key/value pairs.

from pydantic import BaseModel

class MyModel(BaseModel, extra='allow'): ...

However, this may be deceiving, since the actual calls to __init_subclass__ will not receive any of the config arguments, and will only receive any keyword arguments passed during class initialization that are not expected keys in ConfigDict. (This is due to the way ModelMetaclass.__new__ works.)

Parameters:

Name Type Description Default
**kwargs Unpack[ConfigDict]

Keyword arguments passed to the class definition, which set model_config

{}
Note

You may want to override __pydantic_init_subclass__ instead, which behaves similarly but is called after the class is fully initialized.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
def __init_subclass__(cls, **kwargs: Unpack[ConfigDict]):
    """This signature is included purely to help type-checkers check arguments to class declaration, which
    provides a way to conveniently set model_config key/value pairs.

    ```python
    from pydantic import BaseModel

    class MyModel(BaseModel, extra='allow'): ...
    ```

    However, this may be deceiving, since the _actual_ calls to `__init_subclass__` will not receive any
    of the config arguments, and will only receive any keyword arguments passed during class initialization
    that are _not_ expected keys in ConfigDict. (This is due to the way `ModelMetaclass.__new__` works.)

    Args:
        **kwargs: Keyword arguments passed to the class definition, which set model_config

    Note:
        You may want to override `__pydantic_init_subclass__` instead, which behaves similarly but is called
        *after* the class is fully initialized.
    """

__iter__()

So dict(model) works.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
1229
1230
1231
1232
1233
1234
def __iter__(self) -> TupleGenerator:
    """So `dict(model)` works."""
    yield from [(k, v) for (k, v) in self.__dict__.items() if not k.startswith('_')]
    extra = self.__pydantic_extra__
    if extra:
        yield from extra.items()

__pydantic_init_subclass__(**kwargs) classmethod

This is intended to behave just like __init_subclass__, but is called by ModelMetaclass only after basic class initialization is complete. In particular, attributes like model_fields will be present when this is called, but forward annotations are not guaranteed to be resolved yet, meaning that creating an instance of the class may fail.

This is necessary because __init_subclass__ will always be called by type.__new__, and it would require a prohibitively large refactor to the ModelMetaclass to ensure that type.__new__ was called in such a manner that the class would already be sufficiently initialized.

This will receive the same kwargs that would be passed to the standard __init_subclass__, namely, any kwargs passed to the class definition that aren't used internally by Pydantic.

Parameters:

Name Type Description Default
**kwargs Any

Any keyword arguments passed to the class definition that aren't used internally by Pydantic.

{}
Note

You may want to override __pydantic_on_complete__() instead, which is called once the class and its fields are fully initialized and ready for validation.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
@classmethod
def __pydantic_init_subclass__(cls, **kwargs: Any) -> None:
    """This is intended to behave just like `__init_subclass__`, but is called by `ModelMetaclass`
    only after basic class initialization is complete. In particular, attributes like `model_fields` will
    be present when this is called, but forward annotations are not guaranteed to be resolved yet,
    meaning that creating an instance of the class may fail.

    This is necessary because `__init_subclass__` will always be called by `type.__new__`,
    and it would require a prohibitively large refactor to the `ModelMetaclass` to ensure that
    `type.__new__` was called in such a manner that the class would already be sufficiently initialized.

    This will receive the same `kwargs` that would be passed to the standard `__init_subclass__`, namely,
    any kwargs passed to the class definition that aren't used internally by Pydantic.

    Args:
        **kwargs: Any keyword arguments passed to the class definition that aren't used internally
            by Pydantic.

    Note:
        You may want to override [`__pydantic_on_complete__()`][pydantic.main.BaseModel.__pydantic_on_complete__]
        instead, which is called once the class and its fields are fully initialized and ready for validation.
    """

__pydantic_on_complete__() classmethod

This is called once the class and its fields are fully initialized and ready to be used.

This typically happens when the class is created (just before __pydantic_init_subclass__() is called on the superclass), except when forward annotations are used that could not immediately be resolved. In that case, it will be called later, when the model is rebuilt automatically or explicitly using model_rebuild().

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
877
878
879
880
881
882
883
884
885
886
@classmethod
def __pydantic_on_complete__(cls) -> None:
    """This is called once the class and its fields are fully initialized and ready to be used.

    This typically happens when the class is created (just before
    [`__pydantic_init_subclass__()`][pydantic.main.BaseModel.__pydantic_init_subclass__] is called on the superclass),
    except when forward annotations are used that could not immediately be resolved.
    In that case, it will be called later, when the model is rebuilt automatically or explicitly using
    [`model_rebuild()`][pydantic.main.BaseModel.model_rebuild].
    """

copy(*, include=None, exclude=None, update=None, deep=False)

Returns a copy of the model.

Deprecated

This method is now deprecated; use model_copy instead.

If you need include or exclude, use:

data = self.model_dump(include=include, exclude=exclude, round_trip=True)
data = {**data, **(update or {})}
copied = self.model_validate(data)

Parameters:

Name Type Description Default
include AbstractSetIntStr | MappingIntStrAny | None

Optional set or mapping specifying which fields to include in the copied model.

None
exclude AbstractSetIntStr | MappingIntStrAny | None

Optional set or mapping specifying which fields to exclude in the copied model.

None
update Dict[str, Any] | None

Optional dictionary of field-value pairs to override field values in the copied model.

None
deep bool

If True, the values of fields that are Pydantic models will be deep-copied.

False

Returns:

Type Description
Self

A copy of the model with included, excluded and updated fields as specified.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
@typing_extensions.deprecated(
    'The `copy` method is deprecated; use `model_copy` instead. '
    'See the docstring of `BaseModel.copy` for details about how to handle `include` and `exclude`.',
    category=None,
)
def copy(
    self,
    *,
    include: AbstractSetIntStr | MappingIntStrAny | None = None,
    exclude: AbstractSetIntStr | MappingIntStrAny | None = None,
    update: Dict[str, Any] | None = None,  # noqa UP006
    deep: bool = False,
) -> Self:  # pragma: no cover
    """Returns a copy of the model.

    !!! warning "Deprecated"
        This method is now deprecated; use `model_copy` instead.

    If you need `include` or `exclude`, use:

    ```python {test="skip" lint="skip"}
    data = self.model_dump(include=include, exclude=exclude, round_trip=True)
    data = {**data, **(update or {})}
    copied = self.model_validate(data)
    ```

    Args:
        include: Optional set or mapping specifying which fields to include in the copied model.
        exclude: Optional set or mapping specifying which fields to exclude in the copied model.
        update: Optional dictionary of field-value pairs to override field values in the copied model.
        deep: If True, the values of fields that are Pydantic models will be deep-copied.

    Returns:
        A copy of the model with included, excluded and updated fields as specified.
    """
    warnings.warn(
        'The `copy` method is deprecated; use `model_copy` instead. '
        'See the docstring of `BaseModel.copy` for details about how to handle `include` and `exclude`.',
        category=PydanticDeprecatedSince20,
        stacklevel=2,
    )
    from .deprecated import copy_internals

    values = dict(
        copy_internals._iter(
            self, to_dict=False, by_alias=False, include=include, exclude=exclude, exclude_unset=False
        ),
        **(update or {}),
    )
    if self.__pydantic_private__ is None:
        private = None
    else:
        private = {k: v for k, v in self.__pydantic_private__.items() if v is not PydanticUndefined}

    if self.__pydantic_extra__ is None:
        extra: dict[str, Any] | None = None
    else:
        extra = self.__pydantic_extra__.copy()
        for k in list(self.__pydantic_extra__):
            if k not in values:  # k was in the exclude
                extra.pop(k)
        for k in list(values):
            if k in self.__pydantic_extra__:  # k must have come from extra
                extra[k] = values.pop(k)

    # new `__pydantic_fields_set__` can have unset optional fields with a set value in `update` kwarg
    if update:
        fields_set = self.__pydantic_fields_set__ | update.keys()
    else:
        fields_set = set(self.__pydantic_fields_set__)

    # removing excluded fields from `__pydantic_fields_set__`
    if exclude:
        fields_set -= set(exclude)

    return copy_internals._copy_and_set_values(self, values, fields_set, extra, private, deep=deep)

filter_event(*, filter_options=None)

Determine if event should be filtered out and be neglected.

Source code in unique_toolkit/unique_toolkit/app/schemas.py
58
59
60
def filter_event(self, *, filter_options: FilterOptionsT | None = None) -> bool:
    """Determine if event should be filtered out and be neglected."""
    return False

model_computed_fields() classmethod

A mapping of computed field names to their respective [ComputedFieldInfo][pydantic.fields.ComputedFieldInfo] instances.

Warning

Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3. Instead, you should access this attribute from the model class.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
273
274
275
276
277
278
279
280
281
282
@_utils.deprecated_instance_property
@classmethod
def model_computed_fields(cls) -> dict[str, ComputedFieldInfo]:
    """A mapping of computed field names to their respective [`ComputedFieldInfo`][pydantic.fields.ComputedFieldInfo] instances.

    !!! warning
        Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3.
        Instead, you should access this attribute from the model class.
    """
    return getattr(cls, '__pydantic_computed_fields__', {})

model_construct(_fields_set=None, **values) classmethod

Creates a new instance of the Model class with validated data.

Creates a new model setting __dict__ and __pydantic_fields_set__ from trusted or pre-validated data. Default values are respected, but no other validation is performed.

Note

model_construct() generally respects the model_config.extra setting on the provided model. That is, if model_config.extra == 'allow', then all extra passed values are added to the model instance's __dict__ and __pydantic_extra__ fields. If model_config.extra == 'ignore' (the default), then all extra passed values are ignored. Because no validation is performed with a call to model_construct(), having model_config.extra == 'forbid' does not result in an error if extra values are passed, but they will be ignored.

Parameters:

Name Type Description Default
_fields_set set[str] | None

A set of field names that were originally explicitly set during instantiation. If provided, this is directly used for the [model_fields_set][pydantic.BaseModel.model_fields_set] attribute. Otherwise, the field names from the values argument will be used.

None
values Any

Trusted or pre-validated data dictionary.

{}

Returns:

Type Description
Self

A new instance of the Model class with validated data.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
@classmethod
def model_construct(cls, _fields_set: set[str] | None = None, **values: Any) -> Self:  # noqa: C901
    """Creates a new instance of the `Model` class with validated data.

    Creates a new model setting `__dict__` and `__pydantic_fields_set__` from trusted or pre-validated data.
    Default values are respected, but no other validation is performed.

    !!! note
        `model_construct()` generally respects the `model_config.extra` setting on the provided model.
        That is, if `model_config.extra == 'allow'`, then all extra passed values are added to the model instance's `__dict__`
        and `__pydantic_extra__` fields. If `model_config.extra == 'ignore'` (the default), then all extra passed values are ignored.
        Because no validation is performed with a call to `model_construct()`, having `model_config.extra == 'forbid'` does not result in
        an error if extra values are passed, but they will be ignored.

    Args:
        _fields_set: A set of field names that were originally explicitly set during instantiation. If provided,
            this is directly used for the [`model_fields_set`][pydantic.BaseModel.model_fields_set] attribute.
            Otherwise, the field names from the `values` argument will be used.
        values: Trusted or pre-validated data dictionary.

    Returns:
        A new instance of the `Model` class with validated data.
    """
    m = cls.__new__(cls)
    fields_values: dict[str, Any] = {}
    fields_set = set()

    for name, field in cls.__pydantic_fields__.items():
        if field.alias is not None and field.alias in values:
            fields_values[name] = values.pop(field.alias)
            fields_set.add(name)

        if (name not in fields_set) and (field.validation_alias is not None):
            validation_aliases: list[str | AliasPath] = (
                field.validation_alias.choices
                if isinstance(field.validation_alias, AliasChoices)
                else [field.validation_alias]
            )

            for alias in validation_aliases:
                if isinstance(alias, str) and alias in values:
                    fields_values[name] = values.pop(alias)
                    fields_set.add(name)
                    break
                elif isinstance(alias, AliasPath):
                    value = alias.search_dict_for_path(values)
                    if value is not PydanticUndefined:
                        fields_values[name] = value
                        fields_set.add(name)
                        break

        if name not in fields_set:
            if name in values:
                fields_values[name] = values.pop(name)
                fields_set.add(name)
            elif not field.is_required():
                fields_values[name] = field.get_default(call_default_factory=True, validated_data=fields_values)
    if _fields_set is None:
        _fields_set = fields_set

    _extra: dict[str, Any] | None = values if cls.model_config.get('extra') == 'allow' else None
    _object_setattr(m, '__dict__', fields_values)
    _object_setattr(m, '__pydantic_fields_set__', _fields_set)
    if not cls.__pydantic_root_model__:
        _object_setattr(m, '__pydantic_extra__', _extra)

    if cls.__pydantic_post_init__:
        m.model_post_init(None)
        # update private attributes with values set
        if hasattr(m, '__pydantic_private__') and m.__pydantic_private__ is not None:
            for k, v in values.items():
                if k in m.__private_attributes__:
                    m.__pydantic_private__[k] = v

    elif not cls.__pydantic_root_model__:
        # Note: if there are any private attributes, cls.__pydantic_post_init__ would exist
        # Since it doesn't, that means that `__pydantic_private__` should be set to None
        _object_setattr(m, '__pydantic_private__', None)

    return m

model_copy(*, update=None, deep=False)

Usage Documentation

model_copy

Returns a copy of the model.

Note

The underlying instance's [__dict__][object.__dict__] attribute is copied. This might have unexpected side effects if you store anything in it, on top of the model fields (e.g. the value of [cached properties][functools.cached_property]).

Parameters:

Name Type Description Default
update Mapping[str, Any] | None

Values to change/add in the new model. Note: the data is not validated before creating the new model. You should trust this data.

None
deep bool

Set to True to make a deep copy of the model.

False

Returns:

Type Description
Self

New model instance.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
def model_copy(self, *, update: Mapping[str, Any] | None = None, deep: bool = False) -> Self:
    """!!! abstract "Usage Documentation"
        [`model_copy`](../concepts/models.md#model-copy)

    Returns a copy of the model.

    !!! note
        The underlying instance's [`__dict__`][object.__dict__] attribute is copied. This
        might have unexpected side effects if you store anything in it, on top of the model
        fields (e.g. the value of [cached properties][functools.cached_property]).

    Args:
        update: Values to change/add in the new model. Note: the data is not validated
            before creating the new model. You should trust this data.
        deep: Set to `True` to make a deep copy of the model.

    Returns:
        New model instance.
    """
    copied = self.__deepcopy__() if deep else self.__copy__()
    if update:
        if self.model_config.get('extra') == 'allow':
            for k, v in update.items():
                if k in self.__pydantic_fields__:
                    copied.__dict__[k] = v
                else:
                    if copied.__pydantic_extra__ is None:
                        copied.__pydantic_extra__ = {}
                    copied.__pydantic_extra__[k] = v
        else:
            copied.__dict__.update(update)
        copied.__pydantic_fields_set__.update(update.keys())
    return copied

model_dump(*, mode='python', include=None, exclude=None, context=None, by_alias=None, exclude_unset=False, exclude_defaults=False, exclude_none=False, exclude_computed_fields=False, round_trip=False, warnings=True, fallback=None, serialize_as_any=False)

Usage Documentation

model_dump

Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.

Parameters:

Name Type Description Default
mode Literal['json', 'python'] | str

The mode in which to_python should run. If mode is 'json', the output will only contain JSON serializable types. If mode is 'python', the output may contain non-JSON-serializable Python objects.

'python'
include IncEx | None

A set of fields to include in the output.

None
exclude IncEx | None

A set of fields to exclude from the output.

None
context Any | None

Additional context to pass to the serializer.

None
by_alias bool | None

Whether to use the field's alias in the dictionary key if defined.

None
exclude_unset bool

Whether to exclude fields that have not been explicitly set.

False
exclude_defaults bool

Whether to exclude fields that are set to their default value.

False
exclude_none bool

Whether to exclude fields that have a value of None.

False
exclude_computed_fields bool

Whether to exclude computed fields. While this can be useful for round-tripping, it is usually recommended to use the dedicated round_trip parameter instead.

False
round_trip bool

If True, dumped values should be valid as input for non-idempotent types such as Json[T].

False
warnings bool | Literal['none', 'warn', 'error']

How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors, "error" raises a [PydanticSerializationError][pydantic_core.PydanticSerializationError].

True
fallback Callable[[Any], Any] | None

A function to call when an unknown value is encountered. If not provided, a [PydanticSerializationError][pydantic_core.PydanticSerializationError] error is raised.

None
serialize_as_any bool

Whether to serialize fields with duck-typing serialization behavior.

False

Returns:

Type Description
dict[str, Any]

A dictionary representation of the model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
def model_dump(
    self,
    *,
    mode: Literal['json', 'python'] | str = 'python',
    include: IncEx | None = None,
    exclude: IncEx | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    exclude_unset: bool = False,
    exclude_defaults: bool = False,
    exclude_none: bool = False,
    exclude_computed_fields: bool = False,
    round_trip: bool = False,
    warnings: bool | Literal['none', 'warn', 'error'] = True,
    fallback: Callable[[Any], Any] | None = None,
    serialize_as_any: bool = False,
) -> dict[str, Any]:
    """!!! abstract "Usage Documentation"
        [`model_dump`](../concepts/serialization.md#python-mode)

    Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.

    Args:
        mode: The mode in which `to_python` should run.
            If mode is 'json', the output will only contain JSON serializable types.
            If mode is 'python', the output may contain non-JSON-serializable Python objects.
        include: A set of fields to include in the output.
        exclude: A set of fields to exclude from the output.
        context: Additional context to pass to the serializer.
        by_alias: Whether to use the field's alias in the dictionary key if defined.
        exclude_unset: Whether to exclude fields that have not been explicitly set.
        exclude_defaults: Whether to exclude fields that are set to their default value.
        exclude_none: Whether to exclude fields that have a value of `None`.
        exclude_computed_fields: Whether to exclude computed fields.
            While this can be useful for round-tripping, it is usually recommended to use the dedicated
            `round_trip` parameter instead.
        round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
        warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
            "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
        fallback: A function to call when an unknown value is encountered. If not provided,
            a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
        serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.

    Returns:
        A dictionary representation of the model.
    """
    return self.__pydantic_serializer__.to_python(
        self,
        mode=mode,
        by_alias=by_alias,
        include=include,
        exclude=exclude,
        context=context,
        exclude_unset=exclude_unset,
        exclude_defaults=exclude_defaults,
        exclude_none=exclude_none,
        exclude_computed_fields=exclude_computed_fields,
        round_trip=round_trip,
        warnings=warnings,
        fallback=fallback,
        serialize_as_any=serialize_as_any,
    )

model_dump_json(*, indent=None, ensure_ascii=False, include=None, exclude=None, context=None, by_alias=None, exclude_unset=False, exclude_defaults=False, exclude_none=False, exclude_computed_fields=False, round_trip=False, warnings=True, fallback=None, serialize_as_any=False)

Usage Documentation

model_dump_json

Generates a JSON representation of the model using Pydantic's to_json method.

Parameters:

Name Type Description Default
indent int | None

Indentation to use in the JSON output. If None is passed, the output will be compact.

None
ensure_ascii bool

If True, the output is guaranteed to have all incoming non-ASCII characters escaped. If False (the default), these characters will be output as-is.

False
include IncEx | None

Field(s) to include in the JSON output.

None
exclude IncEx | None

Field(s) to exclude from the JSON output.

None
context Any | None

Additional context to pass to the serializer.

None
by_alias bool | None

Whether to serialize using field aliases.

None
exclude_unset bool

Whether to exclude fields that have not been explicitly set.

False
exclude_defaults bool

Whether to exclude fields that are set to their default value.

False
exclude_none bool

Whether to exclude fields that have a value of None.

False
exclude_computed_fields bool

Whether to exclude computed fields. While this can be useful for round-tripping, it is usually recommended to use the dedicated round_trip parameter instead.

False
round_trip bool

If True, dumped values should be valid as input for non-idempotent types such as Json[T].

False
warnings bool | Literal['none', 'warn', 'error']

How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors, "error" raises a [PydanticSerializationError][pydantic_core.PydanticSerializationError].

True
fallback Callable[[Any], Any] | None

A function to call when an unknown value is encountered. If not provided, a [PydanticSerializationError][pydantic_core.PydanticSerializationError] error is raised.

None
serialize_as_any bool

Whether to serialize fields with duck-typing serialization behavior.

False

Returns:

Type Description
str

A JSON string representation of the model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
def model_dump_json(
    self,
    *,
    indent: int | None = None,
    ensure_ascii: bool = False,
    include: IncEx | None = None,
    exclude: IncEx | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    exclude_unset: bool = False,
    exclude_defaults: bool = False,
    exclude_none: bool = False,
    exclude_computed_fields: bool = False,
    round_trip: bool = False,
    warnings: bool | Literal['none', 'warn', 'error'] = True,
    fallback: Callable[[Any], Any] | None = None,
    serialize_as_any: bool = False,
) -> str:
    """!!! abstract "Usage Documentation"
        [`model_dump_json`](../concepts/serialization.md#json-mode)

    Generates a JSON representation of the model using Pydantic's `to_json` method.

    Args:
        indent: Indentation to use in the JSON output. If None is passed, the output will be compact.
        ensure_ascii: If `True`, the output is guaranteed to have all incoming non-ASCII characters escaped.
            If `False` (the default), these characters will be output as-is.
        include: Field(s) to include in the JSON output.
        exclude: Field(s) to exclude from the JSON output.
        context: Additional context to pass to the serializer.
        by_alias: Whether to serialize using field aliases.
        exclude_unset: Whether to exclude fields that have not been explicitly set.
        exclude_defaults: Whether to exclude fields that are set to their default value.
        exclude_none: Whether to exclude fields that have a value of `None`.
        exclude_computed_fields: Whether to exclude computed fields.
            While this can be useful for round-tripping, it is usually recommended to use the dedicated
            `round_trip` parameter instead.
        round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T].
        warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
            "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
        fallback: A function to call when an unknown value is encountered. If not provided,
            a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
        serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.

    Returns:
        A JSON string representation of the model.
    """
    return self.__pydantic_serializer__.to_json(
        self,
        indent=indent,
        ensure_ascii=ensure_ascii,
        include=include,
        exclude=exclude,
        context=context,
        by_alias=by_alias,
        exclude_unset=exclude_unset,
        exclude_defaults=exclude_defaults,
        exclude_none=exclude_none,
        exclude_computed_fields=exclude_computed_fields,
        round_trip=round_trip,
        warnings=warnings,
        fallback=fallback,
        serialize_as_any=serialize_as_any,
    ).decode()

model_fields() classmethod

A mapping of field names to their respective [FieldInfo][pydantic.fields.FieldInfo] instances.

Warning

Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3. Instead, you should access this attribute from the model class.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
262
263
264
265
266
267
268
269
270
271
@_utils.deprecated_instance_property
@classmethod
def model_fields(cls) -> dict[str, FieldInfo]:
    """A mapping of field names to their respective [`FieldInfo`][pydantic.fields.FieldInfo] instances.

    !!! warning
        Accessing this attribute from a model instance is deprecated, and will not work in Pydantic V3.
        Instead, you should access this attribute from the model class.
    """
    return getattr(cls, '__pydantic_fields__', {})

model_json_schema(by_alias=True, ref_template=DEFAULT_REF_TEMPLATE, schema_generator=GenerateJsonSchema, mode='validation', *, union_format='any_of') classmethod

Generates a JSON schema for a model class.

Parameters:

Name Type Description Default
by_alias bool

Whether to use attribute aliases or not.

True
ref_template str

The reference template.

DEFAULT_REF_TEMPLATE
union_format Literal['any_of', 'primitive_type_array']

The format to use when combining schemas from unions together. Can be one of:

  • 'any_of': Use the anyOf keyword to combine schemas (the default).
  • 'primitive_type_array': Use the type keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive type (string, boolean, null, integer or number) or contains constraints/metadata, falls back to any_of.
'any_of'
schema_generator type[GenerateJsonSchema]

To override the logic used to generate the JSON schema, as a subclass of GenerateJsonSchema with your desired modifications

GenerateJsonSchema
mode JsonSchemaMode

The mode in which to generate the schema.

'validation'

Returns:

Type Description
dict[str, Any]

The JSON schema for the given model class.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
@classmethod
def model_json_schema(
    cls,
    by_alias: bool = True,
    ref_template: str = DEFAULT_REF_TEMPLATE,
    schema_generator: type[GenerateJsonSchema] = GenerateJsonSchema,
    mode: JsonSchemaMode = 'validation',
    *,
    union_format: Literal['any_of', 'primitive_type_array'] = 'any_of',
) -> dict[str, Any]:
    """Generates a JSON schema for a model class.

    Args:
        by_alias: Whether to use attribute aliases or not.
        ref_template: The reference template.
        union_format: The format to use when combining schemas from unions together. Can be one of:

            - `'any_of'`: Use the [`anyOf`](https://json-schema.org/understanding-json-schema/reference/combining#anyOf)
            keyword to combine schemas (the default).
            - `'primitive_type_array'`: Use the [`type`](https://json-schema.org/understanding-json-schema/reference/type)
            keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive
            type (`string`, `boolean`, `null`, `integer` or `number`) or contains constraints/metadata, falls back to
            `any_of`.
        schema_generator: To override the logic used to generate the JSON schema, as a subclass of
            `GenerateJsonSchema` with your desired modifications
        mode: The mode in which to generate the schema.

    Returns:
        The JSON schema for the given model class.
    """
    return model_json_schema(
        cls,
        by_alias=by_alias,
        ref_template=ref_template,
        union_format=union_format,
        schema_generator=schema_generator,
        mode=mode,
    )

model_parametrized_name(params) classmethod

Compute the class name for parametrizations of generic classes.

This method can be overridden to achieve a custom naming scheme for generic BaseModels.

Parameters:

Name Type Description Default
params tuple[type[Any], ...]

Tuple of types of the class. Given a generic class Model with 2 type variables and a concrete model Model[str, int], the value (str, int) would be passed to params.

required

Returns:

Type Description
str

String representing the new class where params are passed to cls as type variables.

Raises:

Type Description
TypeError

Raised when trying to generate concrete names for non-generic models.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
@classmethod
def model_parametrized_name(cls, params: tuple[type[Any], ...]) -> str:
    """Compute the class name for parametrizations of generic classes.

    This method can be overridden to achieve a custom naming scheme for generic BaseModels.

    Args:
        params: Tuple of types of the class. Given a generic class
            `Model` with 2 type variables and a concrete model `Model[str, int]`,
            the value `(str, int)` would be passed to `params`.

    Returns:
        String representing the new class where `params` are passed to `cls` as type variables.

    Raises:
        TypeError: Raised when trying to generate concrete names for non-generic models.
    """
    if not issubclass(cls, Generic):
        raise TypeError('Concrete names should only be generated for generic models.')

    # Any strings received should represent forward references, so we handle them specially below.
    # If we eventually move toward wrapping them in a ForwardRef in __class_getitem__ in the future,
    # we may be able to remove this special case.
    param_names = [param if isinstance(param, str) else _repr.display_as_type(param) for param in params]
    params_component = ', '.join(param_names)
    return f'{cls.__name__}[{params_component}]'

model_post_init(context)

Override this method to perform additional initialization after __init__ and model_construct. This is useful if you want to do some validation that requires the entire model to be initialized.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
612
613
614
615
def model_post_init(self, context: Any, /) -> None:
    """Override this method to perform additional initialization after `__init__` and `model_construct`.
    This is useful if you want to do some validation that requires the entire model to be initialized.
    """

model_rebuild(*, force=False, raise_errors=True, _parent_namespace_depth=2, _types_namespace=None) classmethod

Try to rebuild the pydantic-core schema for the model.

This may be necessary when one of the annotations is a ForwardRef which could not be resolved during the initial attempt to build the schema, and automatic rebuilding fails.

Parameters:

Name Type Description Default
force bool

Whether to force the rebuilding of the model schema, defaults to False.

False
raise_errors bool

Whether to raise errors, defaults to True.

True
_parent_namespace_depth int

The depth level of the parent namespace, defaults to 2.

2
_types_namespace MappingNamespace | None

The types namespace, defaults to None.

None

Returns:

Type Description
bool | None

Returns None if the schema is already "complete" and rebuilding was not required.

bool | None

If rebuilding was required, returns True if rebuilding was successful, otherwise False.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
@classmethod
def model_rebuild(
    cls,
    *,
    force: bool = False,
    raise_errors: bool = True,
    _parent_namespace_depth: int = 2,
    _types_namespace: MappingNamespace | None = None,
) -> bool | None:
    """Try to rebuild the pydantic-core schema for the model.

    This may be necessary when one of the annotations is a ForwardRef which could not be resolved during
    the initial attempt to build the schema, and automatic rebuilding fails.

    Args:
        force: Whether to force the rebuilding of the model schema, defaults to `False`.
        raise_errors: Whether to raise errors, defaults to `True`.
        _parent_namespace_depth: The depth level of the parent namespace, defaults to 2.
        _types_namespace: The types namespace, defaults to `None`.

    Returns:
        Returns `None` if the schema is already "complete" and rebuilding was not required.
        If rebuilding _was_ required, returns `True` if rebuilding was successful, otherwise `False`.
    """
    already_complete = cls.__pydantic_complete__
    if already_complete and not force:
        return None

    cls.__pydantic_complete__ = False

    for attr in ('__pydantic_core_schema__', '__pydantic_validator__', '__pydantic_serializer__'):
        if attr in cls.__dict__ and not isinstance(getattr(cls, attr), _mock_val_ser.MockValSer):
            # Deleting the validator/serializer is necessary as otherwise they can get reused in
            # pydantic-core. We do so only if they aren't mock instances, otherwise — as `model_rebuild()`
            # isn't thread-safe — concurrent model instantiations can lead to the parent validator being used.
            # Same applies for the core schema that can be reused in schema generation.
            delattr(cls, attr)

    if _types_namespace is not None:
        rebuild_ns = _types_namespace
    elif _parent_namespace_depth > 0:
        rebuild_ns = _typing_extra.parent_frame_namespace(parent_depth=_parent_namespace_depth, force=True) or {}
    else:
        rebuild_ns = {}

    parent_ns = _model_construction.unpack_lenient_weakvaluedict(cls.__pydantic_parent_namespace__) or {}

    ns_resolver = _namespace_utils.NsResolver(
        parent_namespace={**rebuild_ns, **parent_ns},
    )

    return _model_construction.complete_model_class(
        cls,
        _config.ConfigWrapper(cls.model_config, check=False),
        ns_resolver,
        raise_errors=raise_errors,
        # If the model was already complete, we don't need to call the hook again.
        call_on_complete_hook=not already_complete,
    )

model_validate(obj, *, strict=None, extra=None, from_attributes=None, context=None, by_alias=None, by_name=None) classmethod

Validate a pydantic model instance.

Parameters:

Name Type Description Default
obj Any

The object to validate.

required
strict bool | None

Whether to enforce types strictly.

None
extra ExtraValues | None

Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.

None
from_attributes bool | None

Whether to extract data from object attributes.

None
context Any | None

Additional context to pass to the validator.

None
by_alias bool | None

Whether to use the field's alias when validating against the provided input data.

None
by_name bool | None

Whether to use the field's name when validating against the provided input data.

None

Raises:

Type Description
ValidationError

If the object could not be validated.

Returns:

Type Description
Self

The validated model instance.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
@classmethod
def model_validate(
    cls,
    obj: Any,
    *,
    strict: bool | None = None,
    extra: ExtraValues | None = None,
    from_attributes: bool | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    by_name: bool | None = None,
) -> Self:
    """Validate a pydantic model instance.

    Args:
        obj: The object to validate.
        strict: Whether to enforce types strictly.
        extra: Whether to ignore, allow, or forbid extra data during model validation.
            See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
        from_attributes: Whether to extract data from object attributes.
        context: Additional context to pass to the validator.
        by_alias: Whether to use the field's alias when validating against the provided input data.
        by_name: Whether to use the field's name when validating against the provided input data.

    Raises:
        ValidationError: If the object could not be validated.

    Returns:
        The validated model instance.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True

    if by_alias is False and by_name is not True:
        raise PydanticUserError(
            'At least one of `by_alias` or `by_name` must be set to True.',
            code='validate-by-alias-and-name-false',
        )

    return cls.__pydantic_validator__.validate_python(
        obj,
        strict=strict,
        extra=extra,
        from_attributes=from_attributes,
        context=context,
        by_alias=by_alias,
        by_name=by_name,
    )

model_validate_json(json_data, *, strict=None, extra=None, context=None, by_alias=None, by_name=None) classmethod

Usage Documentation

JSON Parsing

Validate the given JSON data against the Pydantic model.

Parameters:

Name Type Description Default
json_data str | bytes | bytearray

The JSON data to validate.

required
strict bool | None

Whether to enforce types strictly.

None
extra ExtraValues | None

Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.

None
context Any | None

Extra variables to pass to the validator.

None
by_alias bool | None

Whether to use the field's alias when validating against the provided input data.

None
by_name bool | None

Whether to use the field's name when validating against the provided input data.

None

Returns:

Type Description
Self

The validated Pydantic model.

Raises:

Type Description
ValidationError

If json_data is not a JSON string or the object could not be validated.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
@classmethod
def model_validate_json(
    cls,
    json_data: str | bytes | bytearray,
    *,
    strict: bool | None = None,
    extra: ExtraValues | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    by_name: bool | None = None,
) -> Self:
    """!!! abstract "Usage Documentation"
        [JSON Parsing](../concepts/json.md#json-parsing)

    Validate the given JSON data against the Pydantic model.

    Args:
        json_data: The JSON data to validate.
        strict: Whether to enforce types strictly.
        extra: Whether to ignore, allow, or forbid extra data during model validation.
            See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
        context: Extra variables to pass to the validator.
        by_alias: Whether to use the field's alias when validating against the provided input data.
        by_name: Whether to use the field's name when validating against the provided input data.

    Returns:
        The validated Pydantic model.

    Raises:
        ValidationError: If `json_data` is not a JSON string or the object could not be validated.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True

    if by_alias is False and by_name is not True:
        raise PydanticUserError(
            'At least one of `by_alias` or `by_name` must be set to True.',
            code='validate-by-alias-and-name-false',
        )

    return cls.__pydantic_validator__.validate_json(
        json_data, strict=strict, extra=extra, context=context, by_alias=by_alias, by_name=by_name
    )

model_validate_strings(obj, *, strict=None, extra=None, context=None, by_alias=None, by_name=None) classmethod

Validate the given object with string data against the Pydantic model.

Parameters:

Name Type Description Default
obj Any

The object containing string data to validate.

required
strict bool | None

Whether to enforce types strictly.

None
extra ExtraValues | None

Whether to ignore, allow, or forbid extra data during model validation. See the [extra configuration value][pydantic.ConfigDict.extra] for details.

None
context Any | None

Extra variables to pass to the validator.

None
by_alias bool | None

Whether to use the field's alias when validating against the provided input data.

None
by_name bool | None

Whether to use the field's name when validating against the provided input data.

None

Returns:

Type Description
Self

The validated Pydantic model.

Source code in .venv/lib/python3.12/site-packages/pydantic/main.py
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
@classmethod
def model_validate_strings(
    cls,
    obj: Any,
    *,
    strict: bool | None = None,
    extra: ExtraValues | None = None,
    context: Any | None = None,
    by_alias: bool | None = None,
    by_name: bool | None = None,
) -> Self:
    """Validate the given object with string data against the Pydantic model.

    Args:
        obj: The object containing string data to validate.
        strict: Whether to enforce types strictly.
        extra: Whether to ignore, allow, or forbid extra data during model validation.
            See the [`extra` configuration value][pydantic.ConfigDict.extra] for details.
        context: Extra variables to pass to the validator.
        by_alias: Whether to use the field's alias when validating against the provided input data.
        by_name: Whether to use the field's name when validating against the provided input data.

    Returns:
        The validated Pydantic model.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True

    if by_alias is False and by_name is not True:
        raise PydanticUserError(
            'At least one of `by_alias` or `by_name` must be set to True.',
            code='validate-by-alias-and-name-false',
        )

    return cls.__pydantic_validator__.validate_strings(
        obj, strict=strict, extra=extra, context=context, by_alias=by_alias, by_name=by_name
    )

unique_toolkit.app.schemas.EventName

Bases: StrEnum

Source code in unique_toolkit/unique_toolkit/app/schemas.py
29
30
31
32
33
34
35
36
37
38
39
class EventName(StrEnum):
    EXTERNAL_MODULE_CHOSEN = "unique.chat.external-module.chosen"
    USER_MESSAGE_CREATED = "unique.chat.user-message.created"
    INGESTION_CONTENT_UPLOADED = "unique.ingestion.content.uploaded"
    INGESTION_CONTENT_FINISHED = "unique.ingestion.content.finished"
    MAGIC_TABLE_IMPORT_COLUMNS = "unique.magic-table.import-columns"
    MAGIC_TABLE_ADD_META_DATA = "unique.magic-table.add-meta-data"
    MAGIC_TABLE_ADD_DOCUMENT = "unique.magic-table.add-document"
    MAGIC_TABLE_DELETE_ROW = "unique.magic-table.delete-row"
    MAGIC_TABLE_DELETE_COLUMN = "unique.magic-table.delete-column"
    MAGIC_TABLE_UPDATE_CELL = "unique.magic-table.update-cell"

Verification

unique_toolkit.app.verification.verify_signature_and_construct_event(headers, payload, endpoint_secret, logger=logger, event_constructor=Event)

Verify the signature of a webhook and construct an event object.

Parameters:

Name Type Description Default
headers Dict[str, str]

The headers of the webhook request.

required
payload bytes

The raw payload of the webhook request.

required
endpoint_secret str

The secret used to verify the webhook signature.

required
logger Logger

A logger instance for logging messages.

logger
event_constructor Callable[..., T]

A callable that constructs an event object.

Event

Raises:

Type Description
WebhookVerificationError

If there's an error during verification or event construction.

Source code in unique_toolkit/unique_toolkit/app/verification.py
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
def verify_signature_and_construct_event(
    headers: dict[str, str],
    payload: bytes,
    endpoint_secret: str,
    logger: logging.Logger = logger,
    event_constructor: Callable[..., T] = Event,
) -> T:
    """
    Verify the signature of a webhook and construct an event object.

    Args:
        headers (Dict[str, str]): The headers of the webhook request.
        payload (bytes): The raw payload of the webhook request.
        endpoint_secret (str): The secret used to verify the webhook signature.
        logger (logging.Logger): A logger instance for logging messages.
        event_constructor (Callable[..., T]): A callable that constructs an event object.
    Returns:
        T: The constructed event object.

    Raises:
        WebhookVerificationError: If there's an error during verification or event construction.
    """

    sig_header = headers.get("X-Unique-Signature")
    timestamp = headers.get("X-Unique-Created-At")

    if not sig_header or not timestamp:
        logger.error("⚠️  Webhook signature or timestamp headers missing.")
        raise WebhookVerificationError("Signature or timestamp headers missing")

    try:
        event = unique_sdk.Webhook.construct_event(
            payload,
            sig_header,
            timestamp,
            endpoint_secret,
        )
        logger.info("✅  Webhook signature verification successful.")
        return event_constructor(**event)
    except unique_sdk.SignatureVerificationError as e:
        logger.error("⚠️  Webhook signature verification failed. " + str(e))
        raise WebhookVerificationError(f"Signature verification failed: {str(e)}")

unique_toolkit.app.webhook.is_webhook_signature_valid(headers, payload, endpoint_secret, tolerance=300)

Verify webhook signature from Unique platform.

Parameters:

Name Type Description Default
headers dict[str, str]

Request headers with X-Unique-Signature and X-Unique-Created-At

required
payload bytes

Raw request body bytes

required
endpoint_secret str

App endpoint secret from Unique platform

required
tolerance int

Max seconds between timestamp and now (default: 300)

300

Returns:

Type Description
bool

True if signature is valid, False otherwise

Source code in unique_toolkit/unique_toolkit/app/webhook.py
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
def is_webhook_signature_valid(
    headers: dict[str, str],
    payload: bytes,
    endpoint_secret: str,
    tolerance: int = 300,
) -> bool:
    """
    Verify webhook signature from Unique platform.

    Args:
        headers: Request headers with X-Unique-Signature and X-Unique-Created-At
        payload: Raw request body bytes
        endpoint_secret: App endpoint secret from Unique platform
        tolerance: Max seconds between timestamp and now (default: 300)

    Returns:
        True if signature is valid, False otherwise
    """
    # Extract headers
    signature = headers.get("X-Unique-Signature") or headers.get("x-unique-signature")
    timestamp_str = headers.get("X-Unique-Created-At") or headers.get(
        "x-unique-created-at"
    )

    if not signature:
        _LOGGER.error("Missing X-Unique-Signature header")
        return False

    if not timestamp_str:
        _LOGGER.error("Missing X-Unique-Created-At header")
        return False

    # Convert timestamp to int
    try:
        timestamp = int(timestamp_str)
    except ValueError:
        _LOGGER.error(f"Invalid timestamp: {timestamp_str}")
        return False

    # Decode payload if bytes
    message = payload.decode("utf-8") if isinstance(payload, bytes) else payload

    # Compute expected signature: HMAC-SHA256(message, secret)
    expected_signature = hmac.new(
        endpoint_secret.encode("utf-8"),
        msg=message.encode("utf-8"),
        digestmod=hashlib.sha256,
    ).hexdigest()

    # Compare signatures (constant-time to prevent timing attacks)
    if not hmac.compare_digest(expected_signature, signature):
        _LOGGER.error("Signature mismatch. Ensure you're using the raw request body.")
        return False

    # Check timestamp tolerance (prevent replay attacks)
    if tolerance and timestamp < time.time() - tolerance:
        _LOGGER.error(
            f"Timestamp outside tolerance ({tolerance}s). Possible replay attack."
        )
        return False

    _LOGGER.debug("✅ Webhook signature verified successfully")
    return True

FastAPI Factory

unique_toolkit.app.fast_api_factory.build_unique_custom_app(*, title='Unique Chat App', webhook_path='/webhook', settings, event_handler=default_event_handler, event_constructor=ChatEvent, subscribed_event_names=None)

Factory class for creating FastAPI apps with Unique webhook handling.

Source code in unique_toolkit/unique_toolkit/app/fast_api_factory.py
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
def build_unique_custom_app(
    *,
    title: str = "Unique Chat App",
    webhook_path: str = "/webhook",
    settings: UniqueSettings,
    event_handler: EventHandlerType = default_event_handler,
    event_constructor: Callable[..., T] = ChatEvent,
    subscribed_event_names: list[str] | None = None,
) -> "FastAPI":
    """Factory class for creating FastAPI apps with Unique webhook handling."""
    if FastAPI is None:
        raise ImportError(
            "FastAPI is not installed. Install it with: poetry install --with fastapi"
        )

    app = FastAPI(title=title)

    if subscribed_event_names is None:
        subscribed_event_names = [EventName.EXTERNAL_MODULE_CHOSEN]

    @app.get(path="/")
    async def health_check() -> JSONResponse:
        """Health check endpoint."""
        return JSONResponse(content={"status": "healthy", "service": title})

    @app.post(path=webhook_path)
    async def webhook_handler(
        request: Request, background_tasks: BackgroundTasks
    ) -> JSONResponse:
        """
        Webhook endpoint for receiving events from Unique platform.

        This endpoint:
        1. Verifies the webhook signature
        2. Constructs an event from the payload
        3. Calls the configured event handler
        """
        # Get raw body and headers
        body = await request.body()
        headers = dict(request.headers)

        from unique_toolkit.app.webhook import is_webhook_signature_valid

        if not is_webhook_signature_valid(
            headers=headers,
            payload=body,
            endpoint_secret=settings.app.endpoint_secret.get_secret_value(),
        ):
            return JSONResponse(
                status_code=status.HTTP_401_UNAUTHORIZED,
                content={"error": "Invalid webhook signature"},
            )

        try:
            event_data = json.loads(body.decode(encoding="utf-8"))
        except json.JSONDecodeError as e:
            logger.error(f"Error parsing event: {e}", exc_info=True)
            return JSONResponse(
                status_code=status.HTTP_400_BAD_REQUEST,
                content={"error": f"Invalid event format: {e.msg}"},
            )

        if event_data["event"] not in subscribed_event_names:
            return JSONResponse(
                status_code=status.HTTP_400_BAD_REQUEST,
                content={"error": "Not subscribed event"},
            )

        try:
            event = event_constructor(**event_data)
            if (
                settings.chat_event_filter_options
                and settings.chat_event_filter_options.assistant_ids
            ):
                if event.filter_event(
                    filter_options=settings.chat_event_filter_options
                ):
                    return JSONResponse(
                        status_code=status.HTTP_200_OK,
                        content={"error": "Event filtered out"},
                    )
        except ValidationError as e:
            # pydantic errors https://docs.pydantic.dev/2.10/errors/errors/
            logger.error(f"Validation error with model: {e.json()}", exc_info=True)
            raise e
        except ValueError as e:
            logger.error(f"Error deserializing event: {e}", exc_info=True)
            return JSONResponse(
                status_code=status.HTTP_400_BAD_REQUEST,
                content={"error": "Invalid event"},
            )

        # Run the task in background so that we don't block for long running tasks
        background_tasks.add_task(event_handler, event)
        return JSONResponse(
            status_code=status.HTTP_200_OK, content={"message": "Event received"}
        )

    return app