Jump to content

Connect Leeroopedia MCP: Equip your AI agents to search best practices, build plans, verify code, diagnose failures, and look up hyperparameter defaults.

Implementation:Groq Groq python BaseModel Construct

From Leeroopedia
Knowledge Sources
Domains SDK_Infrastructure, Data_Modeling
Last Updated 2026-02-15 16:00 GMT

Overview

Concrete tool for constructing and serializing API response models provided by the Groq Python SDK's internal model layer.

Description

The BaseModel class extends Pydantic's BaseModel to provide a unified interface for API response deserialization that works across both Pydantic v1 and v2. It introduces to_dict() and to_json() convenience methods that default to API-friendly serialization (using alias names and excluding unset fields). The companion construct_type() function performs recursive, validation-free construction of nested model hierarchies from raw API response data, handling unions (including discriminated unions), generic types, dates, and primitive coercion.

Usage

All Groq API response types (ChatCompletion, Transcription, Model, ErrorObject, etc.) inherit from BaseModel. Users interact with BaseModel primarily through its to_dict() and to_json() serialization methods on response objects. The construct_type() function is used internally by the SDK to rapidly build response object graphs without expensive Pydantic validation.

Code Reference

Source Location

Signature

class BaseModel(pydantic.BaseModel):
    def to_dict(
        self,
        *,
        mode: Literal["json", "python"] = "python",
        use_api_names: bool = True,
        exclude_unset: bool = True,
        exclude_defaults: bool = False,
        exclude_none: bool = False,
        warnings: bool = True,
    ) -> dict[str, object]: ...

    def to_json(
        self,
        *,
        indent: int | None = 2,
        use_api_names: bool = True,
        exclude_unset: bool = True,
        exclude_defaults: bool = False,
        exclude_none: bool = False,
        warnings: bool = True,
    ) -> str: ...

    @classmethod
    def construct(
        cls,
        _fields_set: set[str] | None = None,
        **values: object,
    ) -> "BaseModel": ...


def construct_type(
    *,
    value: object,
    type_: object,
    metadata: Optional[List[Any]] = None,
) -> object: ...


def validate_type(*, type_: type[_T], value: object) -> _T: ...


def build(
    base_model_cls: Callable[P, _BaseModelT],
    *args: P.args,
    **kwargs: P.kwargs,
) -> _BaseModelT: ...

Import

from groq._models import BaseModel, GenericModel, construct_type, validate_type, build

I/O Contract

Inputs (BaseModel.to_dict)

Name Type Required Description
mode Literal["json", "python"] No Output mode; "json" produces JSON-safe types, "python" allows native types
use_api_names bool No Whether to use API alias keys (default True)
exclude_unset bool No Exclude fields not explicitly set (default True)
exclude_defaults bool No Exclude fields at default values
exclude_none bool No Exclude None-valued fields

Outputs (BaseModel.to_dict)

Name Type Description
return dict[str, object] Dictionary representation of the model

Inputs (construct_type)

Name Type Required Description
value object Yes Raw value from API response
type_ object Yes Target type (may be annotated, generic, union)
metadata Optional[List[Any]] No Annotation metadata for discriminated unions

Outputs (construct_type)

Name Type Description
return object Constructed instance of the target type

Usage Examples

Serializing a Response Object

from groq import Groq

client = Groq()
completion = client.chat.completions.create(
    model="llama-3.3-70b-versatile",
    messages=[{"role": "user", "content": "Hello"}],
)

# Convert response to dictionary with API field names
data = completion.to_dict()

# Convert to JSON string
json_str = completion.to_json(indent=2)

# Use Python field names instead of API names
python_dict = completion.to_dict(use_api_names=False)

# Include all fields, even those not set
full_dict = completion.to_dict(exclude_unset=False)

Related Pages

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment