Skip to content

openai_protocol

OpenAI API data model

This module defines Pydantic objects that implement an OpenAI compatible data model.

See: https://platform.openai.com/docs/api-reference/chat

Classes

AssistantMessage

Bases: BaseMessage

OpenAI compatible assistant message object

Attributes

role class-attribute instance-attribute
role: str = Field(
    default=assistant.value,
    frozen=True,
    description="The role of the message.",
)
tool_calls class-attribute instance-attribute
tool_calls: Optional[List[ToolCall]] = Field(
    default_factory=list,
    description="The tool calls generated by the model.",
)

Functions

validate_role classmethod
validate_role(role)

BaseChoice

Bases: BaseDataModel

Base OpenAI choice object, note that streaming and non-streaming choices have slight differences

Attributes

finish_reason class-attribute instance-attribute
finish_reason: Optional[
    Literal[
        "stop", "length", "content_filter", "tool_calls"
    ]
] = Field(
    default=None,
    description="The reason the model stopped generating tokens. This will be stop if the model hit a natural stop point or a provided stop sequence, length if the maximum number of tokens specified in the request was reached, content_filter if content was omitted due to a flag from our content filters, tool_calls if the model called a tool.",
)
index class-attribute instance-attribute
index: int = Field(
    ...,
    ge=0,
    description="The index of the choice in the list of choices.",
)
logprobs class-attribute instance-attribute
logprobs: Optional[ChatCompletionLogProbs] = Field(
    default=None,
    description="Log probability information for the choice.",
)

BaseMessage

Bases: BaseDataModel

Attributes

content class-attribute instance-attribute
content: str = Field(
    ..., description="The contents of the message."
)
name class-attribute instance-attribute
name: Optional[str] = Field(
    default=None,
    description="An optional name for the participant. Provides the model information to differentiate between participants of the same role.",
)
role class-attribute instance-attribute
role: str = Field(
    ..., frozen=True, description="The role of the message."
)

ChatCompletionBaseResponse

Bases: BaseDataModel

Attributes

created class-attribute instance-attribute
created: int = Field(
    default_factory=lambda: int(timestamp()),
    description="The Unix timestamp (in seconds) of when the chat completion was created.",
)
field_id class-attribute instance-attribute
field_id: str = Field(
    default_factory=lambda: gen_uuid(prefix="chatcmpl-"),
    alias="id",
    description="A unique identifier for the chat completion.",
)
model class-attribute instance-attribute
model: str = Field(
    ...,
    description="The model used for the chat completion.",
)
system_fingerprint class-attribute instance-attribute
system_fingerprint: Optional[str] = Field(
    default=None,
    description="This fingerprint represents the backend configuration that the model runs with. Can be used in conjunction with the seed request parameter to understand when backend changes have been made that might impact determinism. Ex: fp_44709d6fcb",
)

ChatCompletionChunk

Bases: ChatCompletionBaseResponse

OpenAI compatible chat completion chunk object

Attributes

choices class-attribute instance-attribute
choices: List[StreamingChoice] = Field(
    default_factory=list,
    description="A list of chat completion choices. Can be more than one if n is greater than 1.",
)
field_object class-attribute instance-attribute
field_object: Literal["chat.completion.chunk"] = Field(
    default="chat.completion.chunk",
    alias="object",
    description="The object type, which is always chat.completion.chunk",
)

ChatCompletionLogProbs

Bases: BaseDataModel

OpenAI compatible chat completion logprobs object

Attributes

content class-attribute instance-attribute
content: Optional[List[ChatCompletionLogProbsContent]] = (
    Field(
        default=None,
        description="A list of message content tokens with log probability information.",
    )
)

ChatCompletionLogProbsContent

Bases: ChatCompletionLogprobToken

OpenAI compatible chat completion logprobs content object

Attributes

top_logprobs class-attribute instance-attribute
top_logprobs: List[ChatCompletionLogprobToken] = Field(
    ...,
    description="List of the most likely tokens and their log probability, at this token position. In rare cases, there may be fewer than the number of requested top_logprobs returned",
)

ChatCompletionLogprobToken

Bases: BaseDataModel

OpenAI compatible chat completion logprob token object

Attributes

field_bytes class-attribute instance-attribute
field_bytes: Optional[List[int]] = Field(
    default=None,
    alias="bytes",
    description="A list of integers representing the UTF-8 bytes representation of the token. Useful in instances where characters are represented by multiple tokens and their byte representations must be combined to generate the correct text representation. Can be null if there is no bytes representation for the token.",
)
logprob class-attribute instance-attribute
logprob: float = Field(
    ..., description="The log probability of this token."
)
token class-attribute instance-attribute
token: str = Field(..., description='The token.')

Functions

populate_field_bytes
populate_field_bytes() -> ChatCompletionLogprobToken
token_to_field_bytes staticmethod
token_to_field_bytes(token_string: str) -> List[int]

Converts a string to a list of integers representing the UTF-8 byte values.

Intended use case is to convert tokens returned in the OpenAI API logits response to a list of integer suitable to populate the field_bytes field

Parameters:

  • token_string (str) –

    The input string to be converted.

Returns:

  • list ( List[int] ) –

    A list of integers representing the UTF-8 byte values of the input string.

ChatCompletionMessage

Bases: BaseDataModel

OpenAI compatible chat completion message object

Attributes

content class-attribute instance-attribute
content: Optional[str] = Field(
    default=None, description="The content of the message."
)
role class-attribute instance-attribute
role: Optional[Literal["user", "assistant", "tool"]] = (
    Field(
        default=None,
        description="The role of the author of this message.",
    )
)
tool_calls class-attribute instance-attribute
tool_calls: List[ToolCall] = Field(
    default_factory=list,
    description="The tool calls generated by the model, such as function calls.",
)

ChatCompletionRequest

Bases: BaseModel

OpenAI compatible chat completion request object

Attributes

frequency_penalty class-attribute instance-attribute
frequency_penalty: float = Field(
    default=0.0,
    ge=-2.0,
    le=2.0,
    description="Number between -2.0 and 2.0. Positive values penalize new tokens based on their existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim.",
)
logit_bias class-attribute instance-attribute
logit_bias: Optional[Dict[str, float]] = Field(
    default=None,
    description="Modify the likelihood of specified tokens appearing in the completion. Accepts a JSON object that maps tokens (specified by their token ID in the tokenizer) to an associated bias value from -100 to 100. Mathematically, the bias is added to the logits generated by the model prior to sampling. The exact effect will vary per model, but values between -1 and 1 should decrease or increase likelihood of selection; values like -100 or 100 should result in a ban or exclusive selection of the relevant token.",
)
logprobs class-attribute instance-attribute
logprobs: bool = Field(
    default=False,
    description="Whether to return log probabilities of the output tokens or not. If true, returns the log probabilities of each output token returned in the content of message",
)
max_tokens class-attribute instance-attribute
max_tokens: Optional[int] = Field(
    default=None,
    description="The maximum number of tokens that can be generated in the chat completion.",
)
messages class-attribute instance-attribute
messages: List[
    Union[
        SystemMessage,
        UserMessage,
        AssistantMessage,
        ToolMessage,
    ]
] = Field(
    ...,
    description="A list of messages comprising the conversation so far.",
)
model class-attribute instance-attribute
model: str = Field(
    ..., description="The model to use for the completion."
)
n class-attribute instance-attribute
n: int = Field(
    default=1,
    description="How many chat completion choices to generate for each input message.",
)
presence_penalty class-attribute instance-attribute
presence_penalty: float = Field(
    default=0.0,
    ge=-2.0,
    le=2.0,
    description="Number between -2.0 and 2.0. Positive values penalize new tokens based on whether they appear in the text so far, increasing the model's likelihood to talk about new topics.",
)
response_format class-attribute instance-attribute
response_format: Optional[Dict[str, str]] = Field(
    default=None,
    description="An object specifying the format that the model must output",
)
seed class-attribute instance-attribute
seed: int = Field(
    default=-1,
    description="This feature is in Beta. If specified, our system will make a best effort to sample deterministically, such that repeated requests with the same seed and parameters should return the same result.",
)
stop class-attribute instance-attribute
stop: Union[str, List[str]] = Field(
    default_factory=list,
    description="Up to 4 sequences where the API will stop generating further tokens.",
)
stream class-attribute instance-attribute
stream: bool = Field(
    default=False,
    description="If set, partial message deltas will be sent",
)
temperature class-attribute instance-attribute
temperature: float = Field(
    default=1.0,
    ge=0.0,
    le=2.0,
    description="What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. We generally recommend altering this or top_p but not both.",
)
tool_choice class-attribute instance-attribute
tool_choice: Union[str, ToolChoice] = Field(
    default="none",
    description="Controls which (if any) function is called by the model. none means the model will not call a function and instead generates a message. auto means the model can pick between generating a message or calling a function.",
)
tools class-attribute instance-attribute
tools: List[Tool] = Field(
    default_factory=list,
    description="A list of tools the model may call. Currently, only functions are supported as a tool. Use this to provide a list of functions the model may generate JSON inputs for.",
)
top_logprobs class-attribute instance-attribute
top_logprobs: Optional[int] = Field(
    default=None,
    ge=0,
    le=5,
    description="An integer between 0 and 5 specifying the number of most likely tokens to return at each token position, each with an associated log probability. logprobs must be set to true if this parameter is used.",
)
top_p class-attribute instance-attribute
top_p: float = Field(
    default=1.0,
    description="An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. We generally recommend altering this or temperature but not both.",
)
user class-attribute instance-attribute
user: Optional[str] = Field(
    default=None, description="The user id of the user."
)

ChatCompletionResponse

Bases: ChatCompletionBaseResponse

OpenAI compatible chat completion response object

Attributes

choices class-attribute instance-attribute
choices: List[Choice] = Field(
    ...,
    description="A list of chat completion choices. Can be more than one if n is greater than 1.",
)
field_object class-attribute instance-attribute
field_object: Optional[Literal["chat.completion"]] = Field(
    default="chat.completion",
    alias="object",
    description="The object type, which is always chat.completion",
)
usage class-attribute instance-attribute
usage: Optional[ChatCompletionUsage] = Field(
    default=None,
    description="Usage statistics for the chat completion.",
)

ChatCompletionUsage

Bases: BaseDataModel

OpenAI compatible chat completion usage object

Attributes

completion_tokens class-attribute instance-attribute
completion_tokens: int = Field(
    ...,
    description="Number of tokens in the generated completion.",
)
prompt_tokens class-attribute instance-attribute
prompt_tokens: int = Field(
    ..., description="Number of tokens in the prompt."
)
total_tokens class-attribute instance-attribute
total_tokens: int = Field(
    ...,
    description="Total number of tokens used in the request (prompt + completion).",
)

Choice

Bases: BaseChoice

OpenAI compatible non-streaming choice object

Attributes

message class-attribute instance-attribute
message: Optional[ChatCompletionMessage] = Field(
    default=None,
    description="A chat completion message generated by the model.",
)

Model

Bases: BaseDataModel

OpenAI compatible model object

Attributes

created class-attribute instance-attribute
created: int = Field(
    default_factory=lambda: int(timestamp()),
    description="The Unix timestamp (in seconds) when the model was created.",
)
field_id class-attribute instance-attribute
field_id: str = Field(
    ...,
    serialization_alias="id",
    description="The model identifier, which can be referenced in the API endpoints.",
)
field_object class-attribute instance-attribute
field_object: Literal["model"] = Field(
    default="model",
    alias="object",
    description="The object type, which is always model",
)
owned_by class-attribute instance-attribute
owned_by: str = Field(..., description='Model owner')

ModelsListResponse

Bases: BaseDataModel

OpenAI compatible model list response object

Attributes

data class-attribute instance-attribute
data: List[Model] = Field(
    ..., description="A list of models."
)
field_object class-attribute instance-attribute
field_object: Literal["list"] = Field(
    default="list",
    alias="object",
    description="The object type, which is always 'list'",
)

OpenAIRole

Bases: Enum

Attributes

assistant class-attribute instance-attribute
assistant = 'assistant'
system class-attribute instance-attribute
system = 'system'
tool class-attribute instance-attribute
tool = 'tool'
user class-attribute instance-attribute
user = 'user'

StreamingChoice

Bases: BaseChoice

OpenAI compatible streaming choice object

Attributes

delta class-attribute instance-attribute
delta: Optional[ChatCompletionMessage] = Field(
    default=None,
    description="A chat completion delta generated by streamed model responses.",
)

StreamingErrorResponse

Bases: BaseDataModel

OpenAI compatible streaming error response object

Attributes

error class-attribute instance-attribute
error: StreamingErrorResponseRecord = Field(
    ..., description=__doc__
)

StreamingErrorResponseRecord

Bases: BaseDataModel

OpenAI compatible streaming error response record object

Attributes

code class-attribute instance-attribute
code: int | None = Field(
    default=None, description="Numeric error code"
)
field_type class-attribute instance-attribute
field_type: str | None = Field(
    default=None, alias="type", description="Error type"
)
message class-attribute instance-attribute
message: str = Field(..., description='The error message')
param class-attribute instance-attribute
param: str | None = Field(
    default=None,
    description="Parameter field, currently unused",
)

SystemMessage

Bases: BaseMessage

OpenAI compatible system message object

Attributes

role class-attribute instance-attribute
role: str = Field(
    default=system.value,
    frozen=True,
    description="The role of the message.",
)

Functions

validate_role classmethod
validate_role(role)

Tool

Bases: BaseDataModel

OpenAI compatible tool object

Attributes

field_function class-attribute instance-attribute
field_function: ToolFunction = Field(
    ...,
    alias="function",
    description="The function that the model called.",
)
field_type class-attribute instance-attribute
field_type: Literal["function"] = Field(
    ...,
    alias="type",
    description="The type of the tool call.",
)

ToolCall

Bases: BaseDataModel

The tool call generated by the model

Attributes

field_function class-attribute instance-attribute
field_function: ToolCallFunction = Field(
    ...,
    alias="function",
    description="The function that the model called.",
)
field_id class-attribute instance-attribute
field_id: str = Field(
    ..., alias="id", description="The id of the tool call."
)
field_type class-attribute instance-attribute
field_type: Literal["function"] = Field(
    ...,
    alias="type",
    description="The type of the tool call.",
)

ToolCallFunction

Bases: BaseDataModel

The function that the model called

Attributes

arguments class-attribute instance-attribute
arguments: str = Field(
    ...,
    description="The arguments to pass to the function.",
)
name class-attribute instance-attribute
name: str = Field(
    ..., description="The name of the function to call."
)

ToolChoice

Bases: BaseDataModel

OpenAI compatible tool choice object

Attributes

field_function class-attribute instance-attribute
field_function: ToolChoiceFunction = Field(
    ...,
    alias="function",
    description="The function that the model called.",
)
field_type class-attribute instance-attribute
field_type: Literal["function"] = Field(
    ...,
    alias="type",
    description="The type of the tool choice.",
)

ToolChoiceFunction

Bases: BaseDataModel

OpenAI compatible tool choice function object

Attributes

name class-attribute instance-attribute
name: str = Field(
    ..., description="The name of the function to call."
)

ToolFunction

Bases: BaseDataModel

OpenAI compatible tool function object

Attributes

description class-attribute instance-attribute
description: Optional[str] = Field(
    default=None,
    description="A description of what the function does, used by the model to choose when and how to call the function.",
)
name class-attribute instance-attribute
name: str = Field(
    ...,
    description="The name of the function to be called. Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length of 64.",
)
parameters class-attribute instance-attribute
parameters: Dict = Field(
    default_factory=dict,
    description="The parameters the functions accepts, described as a JSON Schema object",
)

ToolMessage

Bases: BaseMessage

OpenAI compatible tool message object

Attributes

content class-attribute instance-attribute
content: str = Field(
    ..., description="The contents of the tool message."
)
role class-attribute instance-attribute
role: str = Field(
    default=tool.value,
    frozen=True,
    description="The role of the messages author, in this case tool",
)
tool_call_id class-attribute instance-attribute
tool_call_id: str = Field(
    ...,
    description="Tool call that this message is responding to.",
)

Functions

validate_role classmethod
validate_role(role)

UserMessage

Bases: BaseMessage

OpenAI compatible user message object

Attributes

role class-attribute instance-attribute
role: str = Field(
    default=user.value,
    frozen=True,
    description="The role of the message.",
)

Functions

validate_role classmethod
validate_role(role)

Functions