afnio.models.openai#

Classes

AsyncOpenAI([api_key, organization, ...])

OpenAI asynchronous client to perform multiple language model operations.

Omit()

In certain situations you need to be able to represent a case where a default value has to be explicitly removed and None is not an appropriate substitute, for example:

OpenAI([api_key, organization, project, ...])

OpenAI synchronous client to perform multiple language model operations.

class afnio.models.openai.AsyncOpenAI(api_key=None, organization=None, project=None, base_url=None, websocket_base_url=None, timeout=NOT_GIVEN, max_retries=2, default_headers=None, default_query=None, http_client=None)[source]#

Bases: TextCompletionModel, ChatCompletionModel, EmbeddingModel, AsyncOpenAI

OpenAI asynchronous client to perform multiple language model operations.

async achat(*, messages, model, audio=NOT_GIVEN, frequency_penalty=NOT_GIVEN, function_call=NOT_GIVEN, functions=NOT_GIVEN, logit_bias=NOT_GIVEN, logprobs=NOT_GIVEN, max_completion_tokens=NOT_GIVEN, max_tokens=NOT_GIVEN, metadata=NOT_GIVEN, modalities=NOT_GIVEN, n=NOT_GIVEN, parallel_tool_calls=NOT_GIVEN, prediction=NOT_GIVEN, presence_penalty=NOT_GIVEN, prompt_cache_key=NOT_GIVEN, reasoning_effort=NOT_GIVEN, response_format=NOT_GIVEN, safety_identifier=NOT_GIVEN, seed=NOT_GIVEN, service_tier=NOT_GIVEN, stop=NOT_GIVEN, store=NOT_GIVEN, stream=NOT_GIVEN, stream_options=NOT_GIVEN, temperature=NOT_GIVEN, tool_choice=NOT_GIVEN, tools=NOT_GIVEN, top_logprobs=NOT_GIVEN, top_p=NOT_GIVEN, user=NOT_GIVEN, verbosity=NOT_GIVEN, web_search_options=NOT_GIVEN, extra_headers=None, extra_query=None, extra_body=None, timeout=NOT_GIVEN)[source]#

Asynchronously creates a model response for the given chat conversation. Learn more in the [text generation](https://platform.openai.com/docs/guides/text-generation), [vision](https://platform.openai.com/docs/guides/vision), and [audio](https://platform.openai.com/docs/guides/audio) guides.

Parameter support can differ depending on the model used to generate the response, particularly for newer reasoning models. Parameters that are only supported for reasoning models are noted below. For the current state of unsupported parameters in reasoning models, [refer to the reasoning guide](https://platform.openai.com/docs/guides/reasoning).

Parameters:
  • messages (Iterable[Union[ChatCompletionDeveloperMessageParam, ChatCompletionSystemMessageParam, ChatCompletionUserMessageParam, ChatCompletionAssistantMessageParam, ChatCompletionToolMessageParam, ChatCompletionFunctionMessageParam]]) – A list of messages comprising the conversation so far. Depending on the [model](https://platform.openai.com/docs/models) you use, different message types (modalities) are supported, like [text](https://platform.openai.com/docs/guides/text-generation), [images](https://platform.openai.com/docs/guides/vision), and [audio](https://platform.openai.com/docs/guides/audio).

  • model (Union[str, Literal['gpt-5', 'gpt-5-mini', 'gpt-5-nano', 'gpt-5-2025-08-07', 'gpt-5-mini-2025-08-07', 'gpt-5-nano-2025-08-07', 'gpt-5-chat-latest', 'gpt-4.1', 'gpt-4.1-mini', 'gpt-4.1-nano', 'gpt-4.1-2025-04-14', 'gpt-4.1-mini-2025-04-14', 'gpt-4.1-nano-2025-04-14', 'o4-mini', 'o4-mini-2025-04-16', 'o3', 'o3-2025-04-16', 'o3-mini', 'o3-mini-2025-01-31', 'o1', 'o1-2024-12-17', 'o1-preview', 'o1-preview-2024-09-12', 'o1-mini', 'o1-mini-2024-09-12', 'gpt-4o', 'gpt-4o-2024-11-20', 'gpt-4o-2024-08-06', 'gpt-4o-2024-05-13', 'gpt-4o-audio-preview', 'gpt-4o-audio-preview-2024-10-01', 'gpt-4o-audio-preview-2024-12-17', 'gpt-4o-audio-preview-2025-06-03', 'gpt-4o-mini-audio-preview', 'gpt-4o-mini-audio-preview-2024-12-17', 'gpt-4o-search-preview', 'gpt-4o-mini-search-preview', 'gpt-4o-search-preview-2025-03-11', 'gpt-4o-mini-search-preview-2025-03-11', 'chatgpt-4o-latest', 'codex-mini-latest', 'gpt-4o-mini', 'gpt-4o-mini-2024-07-18', 'gpt-4-turbo', 'gpt-4-turbo-2024-04-09', 'gpt-4-0125-preview', 'gpt-4-turbo-preview', 'gpt-4-1106-preview', 'gpt-4-vision-preview', 'gpt-4', 'gpt-4-0314', 'gpt-4-0613', 'gpt-4-32k', 'gpt-4-32k-0314', 'gpt-4-32k-0613', 'gpt-3.5-turbo', 'gpt-3.5-turbo-16k', 'gpt-3.5-turbo-0301', 'gpt-3.5-turbo-0613', 'gpt-3.5-turbo-1106', 'gpt-3.5-turbo-0125', 'gpt-3.5-turbo-16k-0613']]) – Model ID used to generate the response, like gpt-4o or o3. OpenAI offers a wide range of models with different capabilities, performance characteristics, and price points. Refer to the [model guide](https://platform.openai.com/docs/models) to browse and compare available models.

  • audio (Union[ChatCompletionAudioParam, None, NotGiven]) – Parameters for audio output. Required when audio output is requested with modalities: [“audio”]. [Learn more](https://platform.openai.com/docs/guides/audio).

  • frequency_penalty (Union[float, None, NotGiven]) – 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.

  • function_call (Union[Literal['none', 'auto'], ChatCompletionFunctionCallOptionParam, NotGiven]) –

    Deprecated in favor of tool_choice.

    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.

    Specifying a particular function via {“name”: “my_function”} forces the model to call that function.

    none is the default when no functions are present. auto is the default if functions are present.

  • functions (Union[Iterable[Function], NotGiven]) –

    Deprecated in favor of tools.

    A list of functions the model may generate JSON inputs for.

  • logit_bias (Union[Dict[str, int], None, NotGiven]) –

    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 (Union[bool, None, NotGiven]) – 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_completion_tokens (Union[int, None, NotGiven]) – An upper bound for the number of tokens that can be generated for a completion, including visible output tokens and [reasoning tokens](https://platform.openai.com/docs/guides/reasoning).

  • max_tokens (Union[int, None, NotGiven]) –

    The maximum number of [tokens](/tokenizer) that can be generated in the chat completion. This value can be used to control [costs](https://openai.com/api/pricing/) for text generated via API.

    This value is now deprecated in favor of max_completion_tokens, and is not compatible with [o-series models](https://platform.openai.com/docs/guides/reasoning).

  • metadata (Union[Dict[str, str], None, NotGiven]) –

    Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format, and querying for objects via API or the dashboard.

    Keys are strings with a maximum length of 64 characters. Values are strings with a maximum length of 512 characters.

  • modalities (Union[List[Literal['text', 'audio']], None, NotGiven]) –

    Output types that you would like the model to generate. Most models are capable of generating text, which is the default:

    [“text”]

    The gpt-4o-audio-preview model can also be used to [generate audio](https://platform.openai.com/docs/guides/audio). To request that this model generate both text and audio responses, you can use:

    [“text”, “audio”]

  • n (Union[int, None, NotGiven]) – How many chat completion choices to generate for each input message. Note that you will be charged based on the number of generated tokens across all of the choices. Keep n as 1 to minimize costs.

  • parallel_tool_calls (Union[bool, NotGiven]) – Whether to enable [parallel function calling](https://platform.openai.com/docs/guides/function-calling#configuring-parallel-function-calling) during tool use.

  • prediction (Union[ChatCompletionPredictionContentParam, None, NotGiven]) – Static predicted output content, such as the content of a text file that is being regenerated.

  • presence_penalty (Union[float, None, NotGiven]) – 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.

  • prompt_cache_key (Union[str, NotGiven]) – Used by OpenAI to cache responses for similar requests to optimize your cache hit rates. Replaces the user field. [Learn more](https://platform.openai.com/docs/guides/prompt-caching).

  • reasoning_effort (Union[Literal['minimal', 'low', 'medium', 'high'], None, NotGiven]) – Constrains effort on reasoning for [reasoning models](https://platform.openai.com/docs/guides/reasoning). Currently supported values are minimal, low, medium, and high. Reducing reasoning effort can result in faster responses and fewer tokens used on reasoning in a response.

  • response_format (Union[ResponseFormatText, ResponseFormatJSONSchema, ResponseFormatJSONObject, NotGiven]) –

    An object specifying the format that the model must output.

    Setting to { “type”: “json_schema”, “json_schema”: {…} } enables Structured Outputs which ensures the model will match your supplied JSON schema. Learn more in the [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs).

    Setting to { “type”: “json_object” } enables the older JSON mode, which ensures the message the model generates is valid JSON. Using json_schema is preferred for models that support it.

  • safety_identifier (Union[str, NotGiven]) – A stable identifier used to help detect users of your application that may be violating OpenAI’s usage policies. The IDs should be a string that uniquely identifies each user. We recommend hashing their username or email address, in order to avoid sending us any identifying information. [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#safety-identifiers).

  • seed (Union[int, None, NotGiven]) – 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. Determinism is not guaranteed, and you should refer to the system_fingerprint response parameter to monitor changes in the backend.

  • service_tier (Union[Literal['auto', 'default', 'flex', 'scale', 'priority'], None, NotGiven]) –

    Specifies the processing type used for serving the request.

    • If set to ‘auto’, then the request will be processed with the service tier configured in the Project settings. Unless otherwise configured, the Project will use ‘default’.

    • If set to ‘default’, then the request will be processed with the standard pricing and performance for the selected model.

    • If set to ‘[flex](https://platform.openai.com/docs/guides/flex-processing)’ or ‘[priority](https://openai.com/api-priority-processing/)’, then the request will be processed with the corresponding service tier.

    • When not set, the default behavior is ‘auto’.

    When the service_tier parameter is set, the response body will include the service_tier value based on the processing mode actually used to serve the request. This response value may be different from the value set in the parameter.

  • stop (Union[str, None, Sequence[str], NotGiven]) –

    Not supported with latest reasoning models o3 and o4-mini.

    Up to 4 sequences where the API will stop generating further tokens. The returned text will not contain the stop sequence.

  • store (Union[bool, None, NotGiven]) –

    Whether or not to store the output of this chat completion request for use in our [model distillation](https://platform.openai.com/docs/guides/distillation) or [evals](https://platform.openai.com/docs/guides/evals) products.

    Supports text and image inputs. Note: image inputs over 8MB will be dropped.

  • stream (Union[Literal[False], None, NotGiven]) – If set to true, the model response data will be streamed to the client as it is generated using [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format). See the [Streaming section below](https://platform.openai.com/docs/api-reference/chat/streaming) for more information, along with the [streaming responses](https://platform.openai.com/docs/guides/streaming-responses) guide for more information on how to handle the streaming events.

  • stream_options (Union[ChatCompletionStreamOptionsParam, None, NotGiven]) – Options for streaming response. Only set this when you set stream: true.

  • temperature (Union[float, None, NotGiven]) – 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 (Union[Literal['none', 'auto', 'required'], ChatCompletionAllowedToolChoiceParam, ChatCompletionNamedToolChoiceParam, ChatCompletionNamedToolChoiceCustomParam, NotGiven]) –

    Controls which (if any) tool is called by the model. none means the model will not call any tool and instead generates a message. auto means the model can pick between generating a message or calling one or more tools. required means the model must call one or more tools. Specifying a particular tool via {“type”: “function”, “function”: {“name”: “my_function”}} forces the model to call that tool.

    none is the default when no tools are present. auto is the default if tools are present.

  • tools (Union[Iterable[Union[ChatCompletionFunctionToolParam, ChatCompletionCustomToolParam]], NotGiven]) – A list of tools the model may call. You can provide either [custom tools](https://platform.openai.com/docs/guides/function-calling#custom-tools) or [function tools](https://platform.openai.com/docs/guides/function-calling).

  • top_logprobs (Union[int, None, NotGiven]) – An integer between 0 and 20 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 (Union[float, None, NotGiven]) –

    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 (Union[str, NotGiven]) – This field is being replaced by safety_identifier and prompt_cache_key. Use prompt_cache_key instead to maintain caching optimizations. A stable identifier for your end-users. Used to boost cache hit rates by better bucketing similar requests and to help OpenAI detect and prevent abuse. [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#safety-identifiers).

  • verbosity (Union[Literal['low', 'medium', 'high'], None, NotGiven]) – Constrains the verbosity of the model’s response. Lower values will result in more concise responses, while higher values will result in more verbose responses. Currently supported values are low, medium, and high.

  • web_search_options (Union[WebSearchOptions, NotGiven]) – This tool searches the web for relevant results to use in a response. Learn more about the [web search tool](https://platform.openai.com/docs/guides/tools-web-search?api-mode=chat).

  • extra_headers (Optional[Mapping[str, Union[str, Omit]]]) – Send extra headers

  • extra_query (Optional[Mapping[str, object]]) – Add additional query parameters to the request

  • extra_body (Optional[object]) – Add additional JSON properties to the request

  • timeout (Union[float, Timeout, NotGiven, None]) – Override the client-level default timeout for this request, in seconds

async acomplete(prompt)[source]#

Asynchronous method to generate a completion for the given prompt.

Parameters:

prompt (str) – The input text for which the model should generate a completion.

Returns:

A string containing the generated completion.

Return type:

str

async aembed(input)[source]#

Asynchronous method to generate embeddings for the given input texts.

Parameters:

input (List[str]) – A list of input strings for which embeddings should be generated.

Returns:

A list of embeddings, where each embedding is represented

as a list of floats corresponding to the input strings.

Return type:

List[List[float]]

api_key: Optional[str] = None#
property audio: AsyncAudio#
property auth_headers: dict[str, str]#
property base_url: URL#
property batches: AsyncBatches#
property beta: AsyncBeta#
chat(messages, **kwargs)#

Synchronous method to handle chat-based interactions with the model.

Parameters:
  • messages (List[Dict[str, str]]) – A list of messages, where each message is represented as a dictionary with “role” (e.g., “user”, “system”) and “content” (the text of the message).

  • **kwargs

    Additional parameters to configure the model’s behavior during chat completion. This may include options such as: - model (str): The model to use (e.g., “gpt-4o”). - temperature (float): Amount of randomness injected into the response. - max_completion_tokens (int): Maximum number of tokens to generate. - etc.

    For a complete list of supported parameters for each model, refer to the respective API documentation.

Returns:

A string containing the model’s response to the chat messages.

Return type:

str

clear_usage()#

Clears the token usage statistics.

This resets all numerical values in the usage dictionary to zero (including nested values), while preserving the dictionary structure.

async close()#

Close the underlying HTTPX client.

The client will not be usable after this.

complete(prompt, **kwargs)#

Synchronous method to generate a completion for the given prompt.

Parameters:
  • prompt (str) – The input text for which the model should generate a completion.

  • **kwargs

    Additional parameters to configure the model’s behavior during chat completion. This may include options such as: - model (str): The model to use (e.g., “gpt-4o”). - temperature (float): Amount of randomness injected into the response. - max_completion_tokens (int): Maximum number of tokens to generate. - etc.

    For a complete list of supported parameters for each model, refer to the respective API documentation.

Returns:

A string containing the generated completion.

Return type:

str

property completions: AsyncCompletions#
property containers: AsyncContainers#
property conversations: AsyncConversations#
copy(*, api_key=None, organization=None, project=None, webhook_secret=None, websocket_base_url=None, base_url=None, timeout=NOT_GIVEN, http_client=None, max_retries=NOT_GIVEN, default_headers=None, set_default_headers=None, default_query=None, set_default_query=None, _extra_kwargs={})[source]#

Create a new client instance re-using the same options given to the current client with optional overriding.

property custom_auth: Auth | None#
property default_headers: dict[str, str | Omit]#
property default_query: dict[str, object]#
async delete(path, *, cast_to, body=None, options={})#
embed(input, **kwargs)#

Synchronous method to generate embeddings for the given input texts.

Parameters:
  • input (List[str]) – A list of input strings for which embeddings should be generated.

  • **kwargs

    Additional parameters to configure the model’s behavior during chat completion. This may include options such as: - model (str): The model to use (e.g., “gpt-4o”). - temperature (float): Amount of randomness injected into the response. - max_completion_tokens (int): Maximum number of tokens to generate. - etc.

    For a complete list of supported parameters for each model, refer to the respective API documentation.

Returns:

A list of embeddings, where each embedding is represented

as a list of floats corresponding to the input strings.

Return type:

List[List[float]]

property embeddings: AsyncEmbeddings#
property evals: AsyncEvals#
property files: AsyncFiles#
property fine_tuning: AsyncFineTuning#
async get(path, *, cast_to, options={}, stream=False, stream_cls=None)#
get_api_list(path, *, model, page, body=None, options={}, method='get')#
get_config()#

Returns the model configuration. This includes the model name, temperature, max tokens, and other parameters that are used to configure the model’s behavior.

Returns:

A dictionary containing the model’s configuration parameters.

Return type:

dict

get_provider()#

Returns the model provider name.

get_usage()#

Retrieves the current token usage statistics and cost (in USD).

Returns:

A dictionary containing cumulative token usage

statistics since the model instance was initialized.

Return type:

Dict[str, int]

Example

>>> model.get_usage()
{
    'prompt_tokens': 1500,
    'completion_tokens': 1200,
    'total_tokens': 2700,
    'cost': {'amount': 12.00, 'currency': 'USD'}
}
property images: AsyncImages#
is_closed()#
max_retries: int#
property models: AsyncModels#
property moderations: AsyncModerations#
organization: Optional[str] = None#
async patch(path, *, cast_to, body=None, options={})#
platform_headers()#
async post(path, *, cast_to, body=None, files=None, options={}, stream=False, stream_cls=None)#
project: Optional[str] = None#
async put(path, *, cast_to, body=None, files=None, options={})#
property qs: Querystring#
property realtime: AsyncRealtime#
async request(cast_to, options, *, stream=False, stream_cls=None)#
property responses: AsyncResponses#
timeout: Union[float, Timeout, None]#
update_usage(usage, model_name=None)[source]#

Updates the internal usage counters with values from a new API response.

Parameters:
  • usage (CompletionUsage) – The usage object returned by the OpenAI API.

  • model_name (str, optional) – The name of the model for which the usage is being updated. If None, cost is copied from usage if available.

property uploads: AsyncUploads#
property user_agent: str#
property vector_stores: AsyncVectorStores#
webhook_secret: Optional[str] = None#
property webhooks: AsyncWebhooks#
websocket_base_url: Union[str, URL, None] = None#
with_options(*, api_key=None, organization=None, project=None, webhook_secret=None, websocket_base_url=None, base_url=None, timeout=NOT_GIVEN, http_client=None, max_retries=NOT_GIVEN, default_headers=None, set_default_headers=None, default_query=None, set_default_query=None, _extra_kwargs={})#

Create a new client instance re-using the same options given to the current client with optional overriding.

property with_raw_response: AsyncOpenAIWithRawResponse#
property with_streaming_response: AsyncOpenAIWithStreamedResponse#
class afnio.models.openai.Omit[source]#

Bases: object

In certain situations you need to be able to represent a case where a default value has to be explicitly removed and None is not an appropriate substitute, for example:

# as the default `Content-Type` header is `application/json` that will be sent
client.post("/upload/files", files={"file": b"my raw file content"})

# you can't explicitly override the header as it has to be dynamically generated
# to look something like: 'multipart/form-data; boundary=0d8382fcf5f8c3be01ca2e11002d2983'
client.post(..., headers={"Content-Type": "multipart/form-data"})

# instead you can remove the default `application/json` header by passing Omit
client.post(..., headers={"Content-Type": Omit()})
class afnio.models.openai.OpenAI(api_key=None, organization=None, project=None, base_url=None, websocket_base_url=None, timeout=NOT_GIVEN, max_retries=2, default_headers=None, default_query=None, http_client=None)[source]#

Bases: TextCompletionModel, ChatCompletionModel, EmbeddingModel, OpenAI

OpenAI synchronous client to perform multiple language model operations.

async achat(messages, **kwargs)#

Asynchronous method to handle chat-based interactions with the model.

Parameters:
  • messages (List[Dict[str, str]]) – A list of messages, where each message is represented as a dictionary with “role” (e.g., “user”, “system”) and “content” (the text of the message).

  • **kwargs

    Additional parameters to configure the model’s behavior during chat completion. This may include options such as: - model (str): The model to use (e.g., “gpt-4o”). - temperature (float): Amount of randomness injected into the response. - max_completion_tokens (int): Maximum number of tokens to generate. - etc.

    For a complete list of supported parameters for each model, refer to the respective API documentation.

Returns:

A string containing the model’s response to the chat messages.

Return type:

str

async acomplete(prompt, **kwargs)#

Asynchronous method to generate a completion for the given prompt.

Parameters:
  • prompt (str) – The input text for which the model should generate a completion.

  • **kwargs

    Additional parameters to configure the model’s behavior during chat completion. This may include options such as: - model (str): The model to use (e.g., “gpt-4o”). - temperature (float): Amount of randomness injected into the response. - max_completion_tokens (int): Maximum number of tokens to generate. - etc.

    For a complete list of supported parameters for each model, refer to the respective API documentation.

Returns:

A string containing the generated completion.

Return type:

str

async aembed(input, **kwargs)#

Asynchronous method to generate embeddings for the given input texts.

Parameters:
  • input (List[str]) – A list of input strings for which embeddings should be generated.

  • **kwargs

    Additional parameters to configure the model’s behavior during chat completion. This may include options such as: - model (str): The model to use (e.g., “gpt-4o”). - temperature (float): Amount of randomness injected into the response. - max_completion_tokens (int): Maximum number of tokens to generate. - etc.

    For a complete list of supported parameters for each model, refer to the respective API documentation.

Returns:

A list of embeddings, where each embedding is represented

as a list of floats corresponding to the input strings.

Return type:

List[List[float]]

api_key: Optional[str] = None#
property audio: Audio#
property auth_headers: dict[str, str]#
property base_url: URL#
property batches: Batches#
property beta: Beta#
chat(*, messages, model, audio=NOT_GIVEN, frequency_penalty=NOT_GIVEN, function_call=NOT_GIVEN, functions=NOT_GIVEN, logit_bias=NOT_GIVEN, logprobs=NOT_GIVEN, max_completion_tokens=NOT_GIVEN, max_tokens=NOT_GIVEN, metadata=NOT_GIVEN, modalities=NOT_GIVEN, n=NOT_GIVEN, parallel_tool_calls=NOT_GIVEN, prediction=NOT_GIVEN, presence_penalty=NOT_GIVEN, prompt_cache_key=NOT_GIVEN, reasoning_effort=NOT_GIVEN, response_format=NOT_GIVEN, safety_identifier=NOT_GIVEN, seed=NOT_GIVEN, service_tier=NOT_GIVEN, stop=NOT_GIVEN, store=NOT_GIVEN, stream=NOT_GIVEN, stream_options=NOT_GIVEN, temperature=NOT_GIVEN, tool_choice=NOT_GIVEN, tools=NOT_GIVEN, top_logprobs=NOT_GIVEN, top_p=NOT_GIVEN, user=NOT_GIVEN, verbosity=NOT_GIVEN, web_search_options=NOT_GIVEN, extra_headers=None, extra_query=None, extra_body=None, timeout=NOT_GIVEN)[source]#

Synchronously creates a model response for the given chat conversation. Learn more in the [text generation](https://platform.openai.com/docs/guides/text-generation), [vision](https://platform.openai.com/docs/guides/vision), and [audio](https://platform.openai.com/docs/guides/audio) guides.

Parameter support can differ depending on the model used to generate the response, particularly for newer reasoning models. Parameters that are only supported for reasoning models are noted below. For the current state of unsupported parameters in reasoning models, [refer to the reasoning guide](https://platform.openai.com/docs/guides/reasoning).

Parameters:
  • messages (Iterable[Union[ChatCompletionDeveloperMessageParam, ChatCompletionSystemMessageParam, ChatCompletionUserMessageParam, ChatCompletionAssistantMessageParam, ChatCompletionToolMessageParam, ChatCompletionFunctionMessageParam]]) – A list of messages comprising the conversation so far. Depending on the [model](https://platform.openai.com/docs/models) you use, different message types (modalities) are supported, like [text](https://platform.openai.com/docs/guides/text-generation), [images](https://platform.openai.com/docs/guides/vision), and [audio](https://platform.openai.com/docs/guides/audio).

  • model (Union[str, Literal['gpt-5', 'gpt-5-mini', 'gpt-5-nano', 'gpt-5-2025-08-07', 'gpt-5-mini-2025-08-07', 'gpt-5-nano-2025-08-07', 'gpt-5-chat-latest', 'gpt-4.1', 'gpt-4.1-mini', 'gpt-4.1-nano', 'gpt-4.1-2025-04-14', 'gpt-4.1-mini-2025-04-14', 'gpt-4.1-nano-2025-04-14', 'o4-mini', 'o4-mini-2025-04-16', 'o3', 'o3-2025-04-16', 'o3-mini', 'o3-mini-2025-01-31', 'o1', 'o1-2024-12-17', 'o1-preview', 'o1-preview-2024-09-12', 'o1-mini', 'o1-mini-2024-09-12', 'gpt-4o', 'gpt-4o-2024-11-20', 'gpt-4o-2024-08-06', 'gpt-4o-2024-05-13', 'gpt-4o-audio-preview', 'gpt-4o-audio-preview-2024-10-01', 'gpt-4o-audio-preview-2024-12-17', 'gpt-4o-audio-preview-2025-06-03', 'gpt-4o-mini-audio-preview', 'gpt-4o-mini-audio-preview-2024-12-17', 'gpt-4o-search-preview', 'gpt-4o-mini-search-preview', 'gpt-4o-search-preview-2025-03-11', 'gpt-4o-mini-search-preview-2025-03-11', 'chatgpt-4o-latest', 'codex-mini-latest', 'gpt-4o-mini', 'gpt-4o-mini-2024-07-18', 'gpt-4-turbo', 'gpt-4-turbo-2024-04-09', 'gpt-4-0125-preview', 'gpt-4-turbo-preview', 'gpt-4-1106-preview', 'gpt-4-vision-preview', 'gpt-4', 'gpt-4-0314', 'gpt-4-0613', 'gpt-4-32k', 'gpt-4-32k-0314', 'gpt-4-32k-0613', 'gpt-3.5-turbo', 'gpt-3.5-turbo-16k', 'gpt-3.5-turbo-0301', 'gpt-3.5-turbo-0613', 'gpt-3.5-turbo-1106', 'gpt-3.5-turbo-0125', 'gpt-3.5-turbo-16k-0613']]) – Model ID used to generate the response, like gpt-4o or o3. OpenAI offers a wide range of models with different capabilities, performance characteristics, and price points. Refer to the [model guide](https://platform.openai.com/docs/models) to browse and compare available models.

  • audio (Union[ChatCompletionAudioParam, None, NotGiven]) – Parameters for audio output. Required when audio output is requested with modalities: [“audio”]. [Learn more](https://platform.openai.com/docs/guides/audio).

  • frequency_penalty (Union[float, None, NotGiven]) – 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.

  • function_call (Union[Literal['none', 'auto'], ChatCompletionFunctionCallOptionParam, NotGiven]) –

    Deprecated in favor of tool_choice.

    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.

    Specifying a particular function via {“name”: “my_function”} forces the model to call that function.

    none is the default when no functions are present. auto is the default if functions are present.

  • functions (Union[Iterable[Function], NotGiven]) –

    Deprecated in favor of tools.

    A list of functions the model may generate JSON inputs for.

  • logit_bias (Union[Dict[str, int], None, NotGiven]) –

    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 (Union[bool, None, NotGiven]) – 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_completion_tokens (Union[int, None, NotGiven]) – An upper bound for the number of tokens that can be generated for a completion, including visible output tokens and [reasoning tokens](https://platform.openai.com/docs/guides/reasoning).

  • max_tokens (Union[int, None, NotGiven]) –

    The maximum number of [tokens](/tokenizer) that can be generated in the chat completion. This value can be used to control [costs](https://openai.com/api/pricing/) for text generated via API.

    This value is now deprecated in favor of max_completion_tokens, and is not compatible with [o-series models](https://platform.openai.com/docs/guides/reasoning).

  • metadata (Union[Dict[str, str], None, NotGiven]) –

    Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format, and querying for objects via API or the dashboard.

    Keys are strings with a maximum length of 64 characters. Values are strings with a maximum length of 512 characters.

  • modalities (Union[List[Literal['text', 'audio']], None, NotGiven]) –

    Output types that you would like the model to generate. Most models are capable of generating text, which is the default:

    [“text”]

    The gpt-4o-audio-preview model can also be used to [generate audio](https://platform.openai.com/docs/guides/audio). To request that this model generate both text and audio responses, you can use:

    [“text”, “audio”]

  • n (Union[int, None, NotGiven]) – How many chat completion choices to generate for each input message. Note that you will be charged based on the number of generated tokens across all of the choices. Keep n as 1 to minimize costs.

  • parallel_tool_calls (Union[bool, NotGiven]) – Whether to enable [parallel function calling](https://platform.openai.com/docs/guides/function-calling#configuring-parallel-function-calling) during tool use.

  • prediction (Union[ChatCompletionPredictionContentParam, None, NotGiven]) – Static predicted output content, such as the content of a text file that is being regenerated.

  • presence_penalty (Union[float, None, NotGiven]) – 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.

  • prompt_cache_key (Union[str, NotGiven]) – Used by OpenAI to cache responses for similar requests to optimize your cache hit rates. Replaces the user field. [Learn more](https://platform.openai.com/docs/guides/prompt-caching).

  • reasoning_effort (Union[Literal['minimal', 'low', 'medium', 'high'], None, NotGiven]) – Constrains effort on reasoning for [reasoning models](https://platform.openai.com/docs/guides/reasoning). Currently supported values are minimal, low, medium, and high. Reducing reasoning effort can result in faster responses and fewer tokens used on reasoning in a response.

  • response_format (Union[ResponseFormatText, ResponseFormatJSONSchema, ResponseFormatJSONObject, NotGiven]) –

    An object specifying the format that the model must output.

    Setting to { “type”: “json_schema”, “json_schema”: {…} } enables Structured Outputs which ensures the model will match your supplied JSON schema. Learn more in the [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs).

    Setting to { “type”: “json_object” } enables the older JSON mode, which ensures the message the model generates is valid JSON. Using json_schema is preferred for models that support it.

  • safety_identifier (Union[str, NotGiven]) – A stable identifier used to help detect users of your application that may be violating OpenAI’s usage policies. The IDs should be a string that uniquely identifies each user. We recommend hashing their username or email address, in order to avoid sending us any identifying information. [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#safety-identifiers).

  • seed (Union[int, None, NotGiven]) – 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. Determinism is not guaranteed, and you should refer to the system_fingerprint response parameter to monitor changes in the backend.

  • service_tier (Union[Literal['auto', 'default', 'flex', 'scale', 'priority'], None, NotGiven]) –

    Specifies the processing type used for serving the request.

    • If set to ‘auto’, then the request will be processed with the service tier configured in the Project settings. Unless otherwise configured, the Project will use ‘default’.

    • If set to ‘default’, then the request will be processed with the standard pricing and performance for the selected model.

    • If set to ‘[flex](https://platform.openai.com/docs/guides/flex-processing)’ or ‘[priority](https://openai.com/api-priority-processing/)’, then the request will be processed with the corresponding service tier.

    • When not set, the default behavior is ‘auto’.

    When the service_tier parameter is set, the response body will include the service_tier value based on the processing mode actually used to serve the request. This response value may be different from the value set in the parameter.

  • stop (Union[str, None, Sequence[str], NotGiven]) –

    Not supported with latest reasoning models o3 and o4-mini.

    Up to 4 sequences where the API will stop generating further tokens. The returned text will not contain the stop sequence.

  • store (Union[bool, None, NotGiven]) –

    Whether or not to store the output of this chat completion request for use in our [model distillation](https://platform.openai.com/docs/guides/distillation) or [evals](https://platform.openai.com/docs/guides/evals) products.

    Supports text and image inputs. Note: image inputs over 8MB will be dropped.

  • stream (Union[Literal[False], None, NotGiven]) – If set to true, the model response data will be streamed to the client as it is generated using [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format). See the [Streaming section below](https://platform.openai.com/docs/api-reference/chat/streaming) for more information, along with the [streaming responses](https://platform.openai.com/docs/guides/streaming-responses) guide for more information on how to handle the streaming events.

  • stream_options (Union[ChatCompletionStreamOptionsParam, None, NotGiven]) – Options for streaming response. Only set this when you set stream: true.

  • temperature (Union[float, None, NotGiven]) – 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 (Union[Literal['none', 'auto', 'required'], ChatCompletionAllowedToolChoiceParam, ChatCompletionNamedToolChoiceParam, ChatCompletionNamedToolChoiceCustomParam, NotGiven]) –

    Controls which (if any) tool is called by the model. none means the model will not call any tool and instead generates a message. auto means the model can pick between generating a message or calling one or more tools. required means the model must call one or more tools. Specifying a particular tool via {“type”: “function”, “function”: {“name”: “my_function”}} forces the model to call that tool.

    none is the default when no tools are present. auto is the default if tools are present.

  • tools (Union[Iterable[Union[ChatCompletionFunctionToolParam, ChatCompletionCustomToolParam]], NotGiven]) – A list of tools the model may call. You can provide either [custom tools](https://platform.openai.com/docs/guides/function-calling#custom-tools) or [function tools](https://platform.openai.com/docs/guides/function-calling).

  • top_logprobs (Union[int, None, NotGiven]) – An integer between 0 and 20 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 (Union[float, None, NotGiven]) –

    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 (Union[str, NotGiven]) – This field is being replaced by safety_identifier and prompt_cache_key. Use prompt_cache_key instead to maintain caching optimizations. A stable identifier for your end-users. Used to boost cache hit rates by better bucketing similar requests and to help OpenAI detect and prevent abuse. [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#safety-identifiers).

  • verbosity (Union[Literal['low', 'medium', 'high'], None, NotGiven]) – Constrains the verbosity of the model’s response. Lower values will result in more concise responses, while higher values will result in more verbose responses. Currently supported values are low, medium, and high.

  • web_search_options (Union[WebSearchOptions, NotGiven]) – This tool searches the web for relevant results to use in a response. Learn more about the [web search tool](https://platform.openai.com/docs/guides/tools-web-search?api-mode=chat).

  • extra_headers (Optional[Mapping[str, Union[str, Omit]]]) – Send extra headers

  • extra_query (Optional[Mapping[str, object]]) – Add additional query parameters to the request

  • extra_body (Optional[object]) – Add additional JSON properties to the request

  • timeout (Union[float, Timeout, NotGiven, None]) – Override the client-level default timeout for this request, in seconds

clear_usage()#

Clears the token usage statistics.

This resets all numerical values in the usage dictionary to zero (including nested values), while preserving the dictionary structure.

close()#

Close the underlying HTTPX client.

The client will not be usable after this.

complete(prompt)[source]#

Synchronous method to generate a completion for the given prompt.

Parameters:

prompt (str) – The input text for which the model should generate a completion.

Returns:

A string containing the generated completion.

Return type:

str

property completions: Completions#
property containers: Containers#
property conversations: Conversations#
copy(*, api_key=None, organization=None, project=None, webhook_secret=None, websocket_base_url=None, base_url=None, timeout=NOT_GIVEN, http_client=None, max_retries=NOT_GIVEN, default_headers=None, set_default_headers=None, default_query=None, set_default_query=None, _extra_kwargs={})[source]#

Create a new client instance re-using the same options given to the current client with optional overriding.

property custom_auth: Auth | None#
property default_headers: dict[str, str | Omit]#
property default_query: dict[str, object]#
delete(path, *, cast_to, body=None, options={})#
embed(input)[source]#

Synchronous method to generate embeddings for the given input texts.

Parameters:

input (List[str]) – A list of input strings for which embeddings should be generated.

Returns:

A list of embeddings, where each embedding is represented

as a list of floats corresponding to the input strings.

Return type:

List[List[float]]

property embeddings: Embeddings#
property evals: Evals#
property files: Files#
property fine_tuning: FineTuning#
get(path, *, cast_to, options={}, stream=False, stream_cls=None)#
get_api_list(path, *, model, page, body=None, options={}, method='get')#
get_config()#

Returns the model configuration. This includes the model name, temperature, max tokens, and other parameters that are used to configure the model’s behavior.

Returns:

A dictionary containing the model’s configuration parameters.

Return type:

dict

get_provider()#

Returns the model provider name.

get_usage()#

Retrieves the current token usage statistics and cost (in USD).

Returns:

A dictionary containing cumulative token usage

statistics since the model instance was initialized.

Return type:

Dict[str, int]

Example

>>> model.get_usage()
{
    'prompt_tokens': 1500,
    'completion_tokens': 1200,
    'total_tokens': 2700,
    'cost': {'amount': 12.00, 'currency': 'USD'}
}
property images: Images#
is_closed()#
max_retries: int#
property models: Models#
property moderations: Moderations#
organization: Optional[str] = None#
patch(path, *, cast_to, body=None, options={})#
platform_headers()#
post(path, *, cast_to, body=None, options={}, files=None, stream=False, stream_cls=None)#
project: Optional[str] = None#
put(path, *, cast_to, body=None, files=None, options={})#
property qs: Querystring#
property realtime: Realtime#
request(cast_to, options, *, stream=False, stream_cls=None)#
property responses: Responses#
timeout: Union[float, Timeout, None]#
update_usage(usage, model_name=None)[source]#

Updates the internal usage counters with values from a new API response.

Parameters:
  • usage (CompletionUsage) – The usage object returned by the OpenAI API.

  • model_name (str, optional) – The name of the model for which the usage is being updated. If None, cost is copied from usage if available.

property uploads: Uploads#
property user_agent: str#
property vector_stores: VectorStores#
webhook_secret: Optional[str] = None#
property webhooks: Webhooks#
websocket_base_url: Union[str, URL, None] = None#
with_options(*, api_key=None, organization=None, project=None, webhook_secret=None, websocket_base_url=None, base_url=None, timeout=NOT_GIVEN, http_client=None, max_retries=NOT_GIVEN, default_headers=None, set_default_headers=None, default_query=None, set_default_query=None, _extra_kwargs={})#

Create a new client instance re-using the same options given to the current client with optional overriding.

property with_raw_response: OpenAIWithRawResponse#
property with_streaming_response: OpenAIWithStreamedResponse#