Skip to content

Chat Completions

src.data_models.chat_completions.MessageBase

Bases: BaseModel

Base class for all message types in the chat completion system.

This class serves as the foundation for all message types, enforcing a common structure and validation rules. It uses Pydantic's strict mode to forbid extra attributes.

Attributes:

Name Type Description
role str

The role of the message sender. Must be implemented by child classes.

Note

This class should not be used directly but rather inherited by specific message types.

Source code in src/data_models/chat_completions.py
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class MessageBase(BaseModel):
    """Base class for all message types in the chat completion system.

    This class serves as the foundation for all message types, enforcing a common structure
    and validation rules. It uses Pydantic's strict mode to forbid extra attributes.

    Attributes:
        role (str): The role of the message sender. Must be implemented by child classes.

    Note:
        This class should not be used directly but rather inherited by specific message types.
    """
    role: str

    model_config = ConfigDict(extra='forbid')

src.data_models.chat_completions.UserTextContent

Bases: BaseModel

Represents the text content structure for user messages.

This model defines the format for text-based content in user messages, ensuring proper typing and validation.

Attributes:

Name Type Description
type Literal['text']

Content type identifier, always set to "text".

text str

The actual text content of the user message.

Source code in src/data_models/chat_completions.py
25
26
27
28
29
30
31
32
33
34
35
36
class UserTextContent(BaseModel):
    """Represents the text content structure for user messages.

    This model defines the format for text-based content in user messages, ensuring
    proper typing and validation.

    Attributes:
        type (Literal["text"]): Content type identifier, always set to "text".
        text (str): The actual text content of the user message.
    """
    type: Literal["text"] = Field(default="text", description="Content type, fixed to 'text' for user messages")
    text: str = Field(..., description="The text content of the user message")

src.data_models.chat_completions.UserImageURLContent

Bases: BaseModel

Represents the image URL content structure for user messages.

This model defines the format for image-based content in user messages, supporting base64 encoded images with configurable processing detail levels.

Attributes:

Name Type Description
type Literal['image_url']

Content type identifier, always set to "image_url".

image_url dict

Dictionary containing a 'url' field with a base64 encoded image string.

detail Optional[Literal['low', 'high', 'auto']]

Processing detail level for the image. Defaults to "auto".

Source code in src/data_models/chat_completions.py
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
class UserImageURLContent(BaseModel):
    """Represents the image URL content structure for user messages.

    This model defines the format for image-based content in user messages, supporting
    base64 encoded images with configurable processing detail levels.

    Attributes:
        type (Literal["image_url"]): Content type identifier, always set to "image_url".
        image_url (dict): Dictionary containing a 'url' field with a base64 encoded image string.
        detail (Optional[Literal["low", "high", "auto"]]): Processing detail level for the image.
            Defaults to "auto".
    """
    type: Literal["image_url"] = Field(
        default="image_url",
        description="Content type, fixed to 'image_url' for user messages"
    )
    image_url: dict = Field(
        ...,
        description="The image URL as a dictionary containing a 'url' field with a base64 encoded string"
    )
    detail: Optional[Literal["low", "high", "auto"]] = Field(
        default="auto",
        description="Detail level for image processing"
    )

src.data_models.chat_completions.UserMessage

Bases: MessageBase

Represents a message from the user in the chat completion system.

This model handles both simple text messages and complex content types including images. It supports single string content or a list of mixed content types.

Attributes:

Name Type Description
role Literal['user']

Role identifier, always set to "user".

content Union[str, List[Union[UserTextContent, UserImageURLContent]]]

The message content, either as a simple string or a list of content objects.

Source code in src/data_models/chat_completions.py
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
class UserMessage(MessageBase):
    """Represents a message from the user in the chat completion system.

    This model handles both simple text messages and complex content types including
    images. It supports single string content or a list of mixed content types.

    Attributes:
        role (Literal["user"]): Role identifier, always set to "user".
        content (Union[str, List[Union[UserTextContent, UserImageURLContent]]]):
            The message content, either as a simple string or a list of content objects.
    """
    role: Literal["user"] = Field(default="user", description="Role is fixed to 'user' for user messages")
    content: Union[str, List[Union[UserTextContent, UserImageURLContent]]] = Field(
        ..., description="String or detailed content of the user message"
    )

src.data_models.chat_completions.FunctionDetail

Bases: BaseModel

Defines the structure for function call details in tool calls.

This model contains the essential information needed to execute a function through the tool calling system.

Attributes:

Name Type Description
name str

The name of the function to be called.

arguments Dict

Dictionary of arguments to be passed to the function.

Source code in src/data_models/chat_completions.py
82
83
84
85
86
87
88
89
90
91
92
93
class FunctionDetail(BaseModel):
    """Defines the structure for function call details in tool calls.

    This model contains the essential information needed to execute a function
    through the tool calling system.

    Attributes:
        name (str): The name of the function to be called.
        arguments (Dict): Dictionary of arguments to be passed to the function.
    """
    name: str = Field(..., description="Name of the function")
    arguments: str = Field(..., description="Arguments for the function")

src.data_models.chat_completions.ToolCall

Bases: BaseModel

Represents a tool call made by the assistant.

This model handles the structure and formatting of tool calls, including custom serialization of function arguments to JSON.

Attributes:

Name Type Description
id str

Unique identifier for the tool call.

type Literal['function']

Type of tool call, currently only supports "function".

function FunctionDetail

Detailed information about the function to be called.

Methods:

Name Description
model_dump

Custom serialization method that converts function arguments to JSON string.

format_tool_calls

Formats the tool call as a JSON array string for API compatibility.

Source code in src/data_models/chat_completions.py
 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
class ToolCall(BaseModel):
    """Represents a tool call made by the assistant.

    This model handles the structure and formatting of tool calls, including
    custom serialization of function arguments to JSON.

    Attributes:
        id (str): Unique identifier for the tool call.
        type (Literal["function"]): Type of tool call, currently only supports "function".
        function (FunctionDetail): Detailed information about the function to be called.

    Methods:
        model_dump(*args, **kwargs) -> dict:
            Custom serialization method that converts function arguments to JSON string.

        format_tool_calls() -> str:
            Formats the tool call as a JSON array string for API compatibility.
    """
    id: str = Field(..., description="ID of the tool call")
    type: Literal["function"] = Field(default="function", description="Tool type, currently only 'function' is allowed")
    function: FunctionDetail = Field(..., description="Details of the function call, including name and arguments")

    def model_dump(self, *args, **kwargs) -> dict:
        """Custom model_dump to convert 'arguments' in function to a JSON string."""
        # Call the original model_dump
        data = super().model_dump(*args, **kwargs)

        # Convert 'arguments' to a JSON string within 'function'
        if "function" in data:
            data["function"]["arguments"] = json.dumps(data["function"]["arguments"])

        return data

    def format_tool_calls(self) -> str:
        """Format tool call as a JSON array string."""
        formatted_call = {
            "name": self.function.name,
            "arguments": self.function.arguments
        }
        return json.dumps(formatted_call)

format_tool_calls()

Format tool call as a JSON array string.

Source code in src/data_models/chat_completions.py
129
130
131
132
133
134
135
def format_tool_calls(self) -> str:
    """Format tool call as a JSON array string."""
    formatted_call = {
        "name": self.function.name,
        "arguments": self.function.arguments
    }
    return json.dumps(formatted_call)

model_dump(*args, **kwargs)

Custom model_dump to convert 'arguments' in function to a JSON string.

Source code in src/data_models/chat_completions.py
118
119
120
121
122
123
124
125
126
127
def model_dump(self, *args, **kwargs) -> dict:
    """Custom model_dump to convert 'arguments' in function to a JSON string."""
    # Call the original model_dump
    data = super().model_dump(*args, **kwargs)

    # Convert 'arguments' to a JSON string within 'function'
    if "function" in data:
        data["function"]["arguments"] = json.dumps(data["function"]["arguments"])

    return data

src.data_models.chat_completions.AssistantMessage

Bases: MessageBase

Represents a message from the assistant in the chat completion system.

This model handles various types of assistant responses, including regular messages, tool calls, and refusals. It includes custom serialization logic to handle None values.

Attributes:

Name Type Description
role Literal['assistant']

Role identifier, always set to "assistant".

content Optional[Union[str, List[dict]]]

The content of the assistant's message.

refusal Optional[str]

Optional refusal message if the assistant declines to respond.

tool_calls Optional[List[ToolCall]]

List of tool calls made by the assistant.

Methods:

Name Description
model_dump

Custom serialization method that excludes None values and properly formats tool calls.

Source code in src/data_models/chat_completions.py
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
class AssistantMessage(MessageBase):
    """Represents a message from the assistant in the chat completion system.

    This model handles various types of assistant responses, including regular messages,
    tool calls, and refusals. It includes custom serialization logic to handle None values.

    Attributes:
        role (Literal["assistant"]): Role identifier, always set to "assistant".
        content (Optional[Union[str, List[dict]]]): The content of the assistant's message.
        refusal (Optional[str]): Optional refusal message if the assistant declines to respond.
        tool_calls (Optional[List[ToolCall]]): List of tool calls made by the assistant.

    Methods:
        model_dump(*args, **kwargs) -> dict:
            Custom serialization method that excludes None values and properly formats tool calls.
    """
    role: Literal["assistant"] = Field(
        default="assistant", description="Role is fixed to 'assistant' for assistant messages"
    )
    content: Optional[Union[str, List[dict]]] = Field(None, description="The content of the assistant message")
    refusal: Optional[str] = Field(None, description="The refusal message by the assistant")
    tool_calls: Optional[List[ToolCall]] = Field(None, description="List of tool calls made by the assistant")

    def model_dump(self, *args, **kwargs) -> dict:
        """Custom model_dump that excludes fields with None values and calls model_dump on nested ToolCall models."""
        data = super().model_dump(*args, **kwargs)
        if self.tool_calls:
            data["tool_calls"] = [call.model_dump() for call in self.tool_calls]
        return {key: value for key, value in data.items() if value is not None}

model_dump(*args, **kwargs)

Custom model_dump that excludes fields with None values and calls model_dump on nested ToolCall models.

Source code in src/data_models/chat_completions.py
161
162
163
164
165
166
def model_dump(self, *args, **kwargs) -> dict:
    """Custom model_dump that excludes fields with None values and calls model_dump on nested ToolCall models."""
    data = super().model_dump(*args, **kwargs)
    if self.tool_calls:
        data["tool_calls"] = [call.model_dump() for call in self.tool_calls]
    return {key: value for key, value in data.items() if value is not None}

src.data_models.chat_completions.SystemMessage

Bases: MessageBase

Represents a system message in the chat completion system.

This model handles system-level instructions and context that guide the conversation behavior.

Attributes:

Name Type Description
role Literal['system']

Role identifier, always set to "system".

content str

The content of the system message.

Source code in src/data_models/chat_completions.py
169
170
171
172
173
174
175
176
177
178
179
180
class SystemMessage(MessageBase):
    """Represents a system message in the chat completion system.

    This model handles system-level instructions and context that guide the
    conversation behavior.

    Attributes:
        role (Literal["system"]): Role identifier, always set to "system".
        content (str): The content of the system message.
    """
    role: Literal["system"] = Field(default="system", description="Role is fixed to 'system' for system messages")
    content: str = Field(..., description="The content of the system message")