Skip to content

Grok API

Purpose

This page documents the Grok provider class used by Donger.

Responsibilities

The Grok class is responsible for provider-facing workflows, including text generation, image generation and analysis, image editing, embeddings, audio transcription, audio translation, text-to-speech, Grok Files API operations, file-search stores, and Google Cloud bucket workflows.

Import Requirements

This API page imports grok.py. Build the documentation from the repository root after installing both application and documentation dependencies:

pip install -r requirements.txt
mkdocs build --strict

API Reference

Grok


Assembly:                dongr
Filename:                grok.py
Author:                  Terry D. Eppler
Created:                 05-31-2022

Last Modified By:        Terry D. Eppler
Last Modified On:        12-27-2025

       grok.py
       Copyright ©  2024  Terry Eppler

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

You can contact me at: terryeppler@gmail.com or eppler.terry@epa.gov

Grok xAI API for dongr.

Grok

Grok class.

Purpose

Defines the Grok component used by the Boo application. The class groups related provider configuration, runtime state, helper methods, and API-facing behavior so Streamlit workflows can call a consistent interface.

Attributes:

Name Type Description
api_key Optional[str]

Stores api key for the component runtime state.

timeout Optional[float]

Stores timeout for the component runtime state.

base_url Optional[str]

Stores base url for the component runtime state.

model Optional[str]

Stores model for the component runtime state.

store_messages Optional[bool]

Stores store messages for the component runtime state.

response_format Optional[str]

Stores response format for the component runtime state.

temperature Optional[float]

Stores temperature for the component runtime state.

top_percent Optional[float]

Stores top percent for the component runtime state.

frequency_penalty Optional[float]

Stores frequency penalty for the component runtime state.

presence_penalty Optional[float]

Stores presence penalty for the component runtime state.

max_output_tokens Optional[int]

Stores max output tokens for the component runtime state.

tool_choice Optional[str]

Stores tool choice for the component runtime state.

tools Optional[List[str]]

Stores tools for the component runtime state.

stops Optional[List[str]]

Stores stops for the component runtime state.

instructions Optional[str]

Stores instructions for the component runtime state.

content Optional[str]

Stores content for the component runtime state.

messages Optional[List[Dict[str, Any]]]

Stores messages for the component runtime state.

stores Optional[Dict[str, str]]

Stores stores for the component runtime state.

files Optional[Dict[str, str]]

Stores files for the component runtime state.

Chat

Bases: Grok

Provide xAI Grok text-generation workflow support.

Purpose

Provides synchronous and streaming text generation through the xAI Python SDK. The class builds provider-native chat, tool, conversation-history, structured-output, and reasoning configuration from arguments assigned to object members before executing an xAI request.

Attributes:

Name Type Description
client Optional[Client]

xAI SDK client.

chat Any

Provider chat object used by the current request.

model str

Grok model used by the current request.

prompt str

User prompt used by the current request.

temperature float

Sampling temperature.

top_percent float

Nucleus-sampling value.

frequency_penalty float

Frequency penalty.

presence_penalty float

Presence penalty.

max_output_tokens int

Maximum output-token count.

stops List[str]

Stop sequences.

store_messages bool

Indicates whether xAI stores request messages.

stream bool

Indicates whether streaming is enabled.

response_format Any

Provider structured-output configuration.

context List[Dict[str, Any]]

Prior conversation messages.

instructions str

Optional system instruction.

include List[str]

Optional provider response inclusions.

tool_choice str

Provider tool-selection mode.

previous_id str

Previous stored response identifier.

previous_response_id str

Previous stored response identifier.

parallel_tools bool

Indicates whether parallel tool calls are enabled.

max_tools int

Maximum server-side tool turns.

tools List[Any]

Application-selected tool names or tool definitions.

tool_objects List[Any]

Provider-ready tool objects.

reasoning str

Requested reasoning-effort level.

allowed_domains List[str]

Domains permitted for Web Search.

vector_store_ids List[str]

Collection identifiers used by Collections Search.

output_text str

Text extracted from the latest response.

response Any

Latest xAI response.

usage Any

Usage metadata from the latest response.

model_options property

Get model options.

Purpose

Returns Grok text-generation models exposed by the wrapper.

Returns:

Type Description
List[str]

List[str]: Available Grok model identifiers.

include_options property

Get include options.

Purpose

Returns optional xAI SDK response inclusions exposed by the wrapper.

Returns:

Type Description
List[str]

List[str]: Supported include values.

tool_options property

Get tool options.

Purpose

Returns xAI server-side tools implemented by the wrapper.

Returns:

Type Description
List[str]

List[str]: Supported server-side tool names.

choice_options property

Get tool-choice options.

Purpose

Returns xAI tool-selection modes exposed by the wrapper.

Returns:

Type Description
List[str]

List[str]: Supported tool-selection values.

format_options property

Get response-format options.

Purpose

Returns response-format selections supported by the wrapper.

Returns:

Type Description
List[str]

List[str]: Supported response-format values.

reasoning_options property

Get reasoning options.

Purpose

Returns reasoning-effort values exposed by the wrapper.

Returns:

Type Description
List[str]

List[str]: Supported reasoning-effort values.

modality_options property

Get modality options.

Purpose

Returns the response modality supported by the Grok Chat wrapper.

Returns:

Type Description
List[str]

List[str]: Supported response modalities.

media_options property

Get media options.

Purpose

Returns the media-detail selection retained by the application interface.

Returns:

Type Description
List[str]

List[str]: Supported media-detail selections.

supports_reasoning_model

Determine reasoning-model support.

Purpose

Determines whether a required Grok model accepts an explicit reasoning-effort configuration.

Parameters:

Name Type Description Default
model str

Required Grok model identifier.

required

Returns:

Name Type Description
bool bool

True when the model supports explicit reasoning effort.

Raises:

Type Description
Error

Re-raised after the exception is logged.

build_tools

Build provider tools.

Purpose

Builds provider-native Web Search, X Search, Collections Search, and code-execution tools from application selections.

Parameters:

Name Type Description Default
tools Optional[List[Any]]

Selected tool names or provider tool objects.

None
allowed_domains Optional[List[str]]

Domains permitted for Web Search.

None
vector_store_ids Optional[List[str]]

Collection identifiers used by Collections Search.

None

Returns:

Type Description
List[Any]

List[Any]: Provider-ready xAI tool objects.

Raises:

Type Description
Error

Re-raised after the exception is logged.

build_response_format

Build response format.

Purpose

Builds the provider response-format value for plain text, JSON object, or schema-constrained output.

Parameters:

Name Type Description Default
format Any

Requested response-format selection or provider configuration.

None
response_schema Any

Optional JSON schema or Pydantic model.

None

Returns:

Name Type Description
Any Any

Provider-ready response-format value or None.

Raises:

Type Description
Error

Re-raised after the exception is logged.

build_chat

Build provider chat.

Purpose

Builds the xAI chat object from arguments assigned to object members and provider-native tool and response-format configuration.

Parameters:

Name Type Description Default
model str

Required Grok model identifier.

required
temperature float

Sampling temperature.

0.0
top_p float

Nucleus-sampling value.

0.0
frequency float

Frequency penalty.

0.0
presence float

Presence penalty.

0.0
max_tokens int

Maximum output-token count.

0
stops Optional[List[str]]

Stop sequences.

None
store bool

Indicates whether xAI stores request messages.

False
include Optional[List[str]]

Optional provider response inclusions.

None
tools Optional[List[Any]]

Selected tools.

None
allowed_domains Optional[List[str]]

Domains permitted for Web Search.

None
vector_store_ids Optional[List[str]]

Collection identifiers used by Collections Search.

None
max_tools int

Maximum server-side tool turns.

0
tool_choice str

Tool-selection mode.

''
is_parallel bool

Indicates whether parallel tool calls are enabled.

False
previous_id str

Previous stored response identifier.

''
reasoning str

Reasoning-effort level.

''
format Any

Response-format selection or provider configuration.

None
response_schema Any

Optional structured-output schema.

None

Returns:

Name Type Description
Any Any

Configured xAI chat object.

Raises:

Type Description
Error

Re-raised after the exception is logged.

append_context

Append conversation context.

Purpose

Appends valid system, user, and assistant history messages to the current xAI chat.

Parameters:

Name Type Description Default
context Optional[List[Dict[str, Any]]]

Prior conversation messages.

None

Returns:

Name Type Description
None None

This method updates the current chat.

Raises:

Type Description
Error

Re-raised after the exception is logged.

get_output_text

Get output text.

Purpose

Extracts generated text from the latest xAI response.

Returns:

Name Type Description
str str

Generated response text or an empty string.

Raises:

Type Description
Error

Re-raised after the exception is logged.

generate_text

Generate text.

Purpose

Executes synchronous or streaming Grok text generation using a required prompt, required model, optional conversation history, provider-native server-side tools, stored-response continuation, structured output, and reasoning configuration.

Parameters:

Name Type Description Default
prompt str

Required user prompt.

required
model str

Required Grok model identifier.

required
temperature float

Sampling temperature.

0.0
format Any

Response-format selection or provider configuration.

None
top_p float

Nucleus-sampling value.

0.0
frequency float

Frequency penalty.

0.0
presence float

Presence penalty.

0.0
max_tokens int

Maximum output-token count.

0
stops Optional[List[str]]

Stop sequences.

None
store bool

Indicates whether xAI stores request messages.

False
stream bool

Indicates whether streaming is enabled.

False
instruct str

Optional system instruction.

''
reasoning str

Optional reasoning-effort level.

''
include Optional[List[str]]

Optional provider response inclusions.

None
tools Optional[List[Any]]

Selected server-side tools.

None
allowed_domains Optional[List[str]]

Domains permitted for Web Search.

None
previous_id str

Previous stored response identifier.

''
tool_choice str

Tool-selection mode.

''
is_parallel bool

Indicates whether parallel tool calls are enabled.

False
context Optional[List[Dict[str, Any]]]

Prior conversation messages.

None
vector_store_ids Optional[List[str]]

Collection identifiers used by Collections Search.

None
max_tools int

Maximum server-side tool turns.

0
response_schema Any

Optional structured-output schema.

None
stream_handler Any

Optional callable receiving each streaming text delta.

None

Returns:

Name Type Description
str str

Generated response text.

Raises:

Type Description
Error

Re-raised after the exception is logged.

get_usage

Get usage.

Purpose

Returns usage metadata from the latest xAI response.

Returns:

Name Type Description
Any Any

Provider usage metadata or None when unavailable.

Raises:

Type Description
Error

Re-raised after the exception is logged.

Images

Bases: Grok

Provide Grok image workflow support.

Purpose

Provides image generation, image editing, and image analysis through the xAI Python SDK. The class assigns accepted arguments to object members, constructs provider-native image or multimodal-chat requests, executes the selected operation, and extracts image URLs, decoded image bytes, or analysis text from provider responses.

Attributes:

Name Type Description
client Optional[Client]

xAI SDK client.

chat Any

Multimodal chat used for image analysis.

model str

Grok model used by the current operation.

prompt str

Prompt used by the current operation.

number int

Number of images requested.

aspect_ratio str

Requested output-image aspect ratio.

image_path str

Local source-image path.

image_url str

Provider-ready source-image URL or data URI.

detail str

Image-detail level used for analysis.

response Any

Latest xAI response.

output Any

Extracted image output or collection of outputs.

output_text str

Text extracted from an image-analysis response.

model_options property

Get image-generation model options.

Purpose

Returns Grok models exposed for image generation and editing.

Returns:

Type Description
List[str]

List[str]: Supported Grok image model identifiers.

analysis_model_options property

Get image-analysis model options.

Purpose

Returns Grok multimodal models exposed for image understanding.

Returns:

Type Description
List[str]

List[str]: Supported Grok image-analysis model identifiers.

aspect_options property

Get aspect-ratio options.

Purpose

Returns output-image aspect ratios exposed by the wrapper.

Returns:

Type Description
List[str]

List[str]: Supported aspect-ratio values.

size_options property

Get image-size options.

Purpose

Returns an automatic size selection because the xAI Python SDK image request does not expose an independent pixel-size parameter.

Returns:

Type Description
List[str]

List[str]: Available image-size selections.

quality_options property

Get image-quality options.

Purpose

Returns model-based quality selections exposed by the application.

Returns:

Type Description
List[str]

List[str]: Available image-quality selections.

style_options property

Get image-style options.

Purpose

Returns an empty collection because xAI image style is controlled through the prompt rather than a separate request argument.

Returns:

Type Description
List[str]

List[str]: Empty style-option collection.

format_options property

Get response-format options.

Purpose

Returns image response representations that may be returned by the xAI SDK.

Returns:

Type Description
List[str]

List[str]: Supported response representations.

mime_options property

Get source-image MIME-type options.

Purpose

Returns MIME types supported for local source images converted to data URIs.

Returns:

Type Description
List[str]

List[str]: Supported source-image MIME types.

detail_options property

Get image-detail options.

Purpose

Returns multimodal image-detail levels exposed for image analysis.

Returns:

Type Description
List[str]

List[str]: Supported image-detail values.

modality_options property

Get response-modality options.

Purpose

Returns image and text modalities represented by the wrapper operations.

Returns:

Type Description
List[str]

List[str]: Supported modality values.

include_options property

Get include options.

Purpose

Returns an empty collection because xAI image operations do not use response include paths.

Returns:

Type Description
List[str]

List[str]: Empty include-option collection.

tool_options property

Get tool options.

Purpose

Returns an empty collection because direct xAI image operations do not use chat server-side tools.

Returns:

Type Description
List[str]

List[str]: Empty tool-option collection.

choice_options property

Get tool-choice options.

Purpose

Returns an empty collection because direct xAI image operations do not use tool selection.

Returns:

Type Description
List[str]

List[str]: Empty tool-choice collection.

reasoning_options property

Get reasoning options.

Purpose

Returns an empty collection because image-generation reasoning is managed by the selected image model.

Returns:

Type Description
List[str]

List[str]: Empty reasoning-option collection.

get_mime_type

Get image MIME type.

Purpose

Determines the MIME type of a required local source image from its file extension.

Parameters:

Name Type Description Default
path str

Required local image path.

required

Returns:

Name Type Description
str str

Source-image MIME type.

Raises:

Type Description
Error

Re-raised after the exception is logged.

build_image_url

Build source-image data URI.

Purpose

Reads a required local source image and converts it into a provider-ready base64 data URI.

Parameters:

Name Type Description Default
path str

Required local image path.

required

Returns:

Name Type Description
str str

Provider-ready image data URI.

Raises:

Type Description
Error

Re-raised after the exception is logged.

extract_image_output

Extract image output.

Purpose

Extracts an image URL or decoded image bytes from a required xAI image response.

Parameters:

Name Type Description Default
response Any

Required xAI image response.

required

Returns:

Name Type Description
Any Any

Image URL, decoded image bytes, or the original provider response.

Raises:

Type Description
Error

Re-raised after the exception is logged.

generate

Generate images.

Purpose

Generates one or more images from a required prompt using a required Grok image model and optional output aspect ratio.

Parameters:

Name Type Description Default
prompt str

Required image-generation prompt.

required
model str

Required Grok image model.

required
number int

Number of images requested.

1
aspect_ratio str

Output-image aspect ratio.

'auto'

Returns:

Name Type Description
Any Any

Generated image output or collection of image outputs.

Raises:

Type Description
Error

Re-raised after the exception is logged.

analyze

Analyze an image.

Purpose

Analyzes a required local image using a required Grok multimodal model and returns the generated textual analysis.

Parameters:

Name Type Description Default
prompt str

Required image-analysis prompt.

required
path str

Required local image path.

required
model str

Required Grok multimodal model.

required
detail str

Image-detail level.

'auto'

Returns:

Name Type Description
str str

Generated image-analysis text.

Raises:

Type Description
Error

Re-raised after the exception is logged.

edit

Edit an image.

Purpose

Edits a required source image using a required prompt and Grok image model. The source may be supplied as a local path or public image URL.

Parameters:

Name Type Description Default
prompt str

Required image-editing instruction.

required
model str

Required Grok image model.

required
path str

Optional local source-image path.

''
image_url str

Optional public source-image URL.

''
aspect_ratio str

Optional output-image aspect ratio.

'auto'
number int

Number of edited images requested.

1

Returns:

Name Type Description
Any Any

Edited image output or collection of edited-image outputs.

Raises:

Type Description
Error

Re-raised after the exception is logged.

Files

Bases: Grok

Provide xAI file-management and file-analysis workflows.

Purpose

Provides file upload, listing, retrieval, content download, deletion, summarization, question answering, and file surveying through the xAI Files and Chat APIs. The class assigns accepted arguments to object members before constructing provider requests and returns stable application-facing metadata, content, and generated text.

Attributes:

Name Type Description
client Optional[Client]

xAI SDK client used for file-enabled chat requests.

api_key str

xAI API key.

base_url str

xAI REST API base URL.

file_path str

Local file path used by the current operation.

file_name str

Filename assigned during upload.

file_id str

xAI file identifier used by the current operation.

file_ids List[str]

File identifiers retained by the wrapper.

purpose str

Compatibility purpose value stored with uploaded files.

expires_after int

Optional file-expiration duration in seconds.

model str

Grok model used for file analysis.

prompt str

Prompt used by the current file-analysis request.

instructions str

Optional system instruction.

temperature float

Sampling temperature.

top_percent float

Nucleus-sampling value.

frequency_penalty float

Frequency penalty.

presence_penalty float

Presence penalty.

max_output_tokens int

Maximum output-token count.

store_messages bool

Indicates whether xAI stores chat messages.

stream bool

Indicates whether response streaming is enabled.

include List[str]

Optional xAI streaming inclusions.

previous_id str

Previous stored response identifier.

response Any

Latest provider response.

file_content Any

Latest downloaded file content.

output_text str

Text extracted from the latest file-analysis response.

limit int

Maximum number of files requested by a list operation.

pagination_token str

Pagination token supplied to a list operation.

next_token str

Pagination token returned by the latest list operation.

documents Dict[str, str]

Configured document labels mapped to file identifiers.

model_options property

Get file-analysis model options.

Purpose

Returns Grok models exposed for file summarization and question answering.

Returns:

Type Description
List[str]

List[str]: Supported Grok model identifiers.

purpose_options property

Get file-purpose options.

Purpose

Returns compatibility purpose values accepted and stored by the xAI Files API.

Returns:

Type Description
List[str]

List[str]: Available file-purpose values.

format_options property

Get output-format options.

Purpose

Returns the textual output format implemented by file-analysis workflows.

Returns:

Type Description
List[str]

List[str]: Supported output formats.

tool_options property

Get tool options.

Purpose

Returns server-side tools that may be used with file-enabled chat requests.

Returns:

Type Description
List[str]

List[str]: Supported server-side tool names.

include_options property

Get include options.

Purpose

Returns optional xAI streaming response inclusions.

Returns:

Type Description
List[str]

List[str]: Supported include values.

get_headers

Get request headers.

Purpose

Builds authentication headers for xAI Files API requests.

Returns:

Type Description
Dict[str, str]

Dict[str, str]: Provider request headers.

Raises:

Type Description
Error

Re-raised after the exception is logged.

normalize_metadata

Normalize file metadata.

Purpose

Converts a required xAI file response into a stable application-facing metadata record.

Parameters:

Name Type Description Default
file_data Dict[str, Any]

Required provider file metadata.

required

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: Application-facing file metadata.

Raises:

Type Description
Error

Re-raised after the exception is logged.

upload

Upload a file.

Purpose

Uploads a required local file to xAI storage with an optional filename, compatibility purpose, and expiration duration.

Parameters:

Name Type Description Default
file_path str

Required local file path.

required
file_name str

Optional uploaded filename.

''
purpose str

Compatibility purpose value stored with the file.

'assistants'
expires_after int

Optional expiration duration in seconds.

0

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: Uploaded file metadata.

Raises:

Type Description
Error

Re-raised after the exception is logged.

list

List files.

Purpose

Lists uploaded xAI files using an optional result limit and pagination token.

Parameters:

Name Type Description Default
limit int

Maximum number of files requested.

100
pagination_token str

Optional pagination token.

''

Returns:

Type Description
List[Dict[str, Any]]

List[Dict[str, Any]]: Application-facing file metadata records.

Raises:

Type Description
Error

Re-raised after the exception is logged.

list_files

List files.

Purpose

Provides the application-compatible alias for xAI file listing.

Parameters:

Name Type Description Default
limit int

Maximum number of files requested.

100
pagination_token str

Optional pagination token.

''

Returns:

Type Description
List[Dict[str, Any]]

List[Dict[str, Any]]: Application-facing file metadata records.

Raises:

Type Description
Error

Re-raised after the exception is logged.

retrieve

Retrieve file metadata.

Purpose

Retrieves metadata for a required xAI file identifier.

Parameters:

Name Type Description Default
file_id str

Required xAI file identifier.

required

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: Application-facing file metadata.

Raises:

Type Description
Error

Re-raised after the exception is logged.

extract

Download file content.

Purpose

Downloads the original content of a required xAI file.

Parameters:

Name Type Description Default
file_id str

Required xAI file identifier.

required

Returns:

Name Type Description
bytes bytes

Downloaded file content.

Raises:

Type Description
Error

Re-raised after the exception is logged.

download

Download file content.

Purpose

Provides the application-compatible alias for xAI file-content download.

Parameters:

Name Type Description Default
file_id str

Required xAI file identifier.

required

Returns:

Name Type Description
bytes bytes

Downloaded file content.

Raises:

Type Description
Error

Re-raised after the exception is logged.

content

Get file content.

Purpose

Provides the application-compatible alias for xAI file-content retrieval.

Parameters:

Name Type Description Default
file_id str

Required xAI file identifier.

required

Returns:

Name Type Description
bytes bytes

Downloaded file content.

Raises:

Type Description
Error

Re-raised after the exception is logged.

delete

Delete a file.

Purpose

Deletes a required file from xAI storage.

Parameters:

Name Type Description Default
file_id str

Required xAI file identifier.

required

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: File-deletion result.

Raises:

Type Description
Error

Re-raised after the exception is logged.

get_output_text

Get output text.

Purpose

Extracts generated text from the latest xAI file-analysis response.

Returns:

Name Type Description
str str

Generated response text or an empty string.

Raises:

Type Description
Error

Re-raised after the exception is logged.

summarize

Analyze a file.

Purpose

Generates a response to a required prompt using a required xAI file attachment and Grok model.

Parameters:

Name Type Description Default
file_id str

Required xAI file identifier.

required
prompt str

Required file-analysis prompt.

required
model str

Required Grok model identifier.

required
instruct str

Optional system instruction.

''
temperature float

Sampling temperature.

0.0
top_p float

Nucleus-sampling value.

0.0
frequency float

Frequency penalty.

0.0
presence float

Presence penalty.

0.0
max_tokens int

Maximum output-token count.

0
store bool

Indicates whether xAI stores chat messages.

False
stream bool

Indicates whether response streaming is enabled.

False
include Optional[List[str]]

Optional streaming response inclusions.

None
previous_id str

Previous stored response identifier.

''
stream_handler Any

Optional callable receiving each streaming text delta.

None

Returns:

Name Type Description
str str

Generated file-analysis response.

Raises:

Type Description
Error

Re-raised after the exception is logged.

search

Search a file.

Purpose

Answers a required question using a required xAI file attachment.

Parameters:

Name Type Description Default
file_id str

Required xAI file identifier.

required
query str

Required question about the file.

required
model str

Required Grok model identifier.

required
instruct str

Optional system instruction.

''
temperature float

Sampling temperature.

0.0
top_p float

Nucleus-sampling value.

0.0
frequency float

Frequency penalty.

0.0
presence float

Presence penalty.

0.0
max_tokens int

Maximum output-token count.

0
store bool

Indicates whether xAI stores chat messages.

False
stream bool

Indicates whether response streaming is enabled.

False
include Optional[List[str]]

Optional streaming response inclusions.

None
previous_id str

Previous stored response identifier.

''
stream_handler Any

Optional callable receiving each streaming text delta.

None

Returns:

Name Type Description
str str

Generated answer based on the attached file.

Raises:

Type Description
Error

Re-raised after the exception is logged.

survey

Survey a file.

Purpose

Retrieves file metadata and content and returns a bounded textual preview for application inspection.

Parameters:

Name Type Description Default
file_id str

Required xAI file identifier.

required
max_chars int

Maximum number of preview characters.

4000

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: File metadata, preview text, and file identifier.

Raises:

Type Description
Error

Re-raised after the exception is logged.

TTS

Bases: Grok

Provide xAI text-to-speech workflow support.

Purpose

Provides batch speech synthesis through the xAI Text-to-Speech REST API. The class assigns accepted arguments to object members, constructs the provider-native output format and request payload, executes the synthesis request, extracts the returned audio, and optionally writes the audio bytes to a local file.

Attributes:

Name Type Description
api_key str

xAI API key.

base_url str

xAI REST API base URL.

text str

Text converted to speech.

language str

BCP-47 language code used for synthesis.

voice_id str

Built-in or custom xAI voice identifier.

output_format str | Dict[str, Any]

Requested audio-output configuration.

codec str

Requested audio codec.

speed float

Speech-speed multiplier.

optimize_streaming_latency int

Latency-optimization level.

text_normalization bool

Indicates whether written text is normalized before synthesis.

sample_rate int

Requested audio sample rate.

bit_rate int

Requested MP3 bit rate.

with_timestamps bool

Indicates whether character timing metadata is requested.

audio_path str

Optional local output path.

response Any

Latest HTTP response.

audio bytes

Generated audio bytes.

audio_timestamps Any

Character timing metadata returned by the provider.

duration float

Generated audio duration in seconds.

content_type str

MIME type of the generated audio.

params Dict[str, Any]

Provider request payload.

voice_options property

Get voice options.

Purpose

Returns the standard built-in xAI voices exposed by the wrapper. Custom voice identifiers may also be supplied directly to create_speech().

Returns:

Type Description
List[str]

List[str]: Standard built-in xAI voice identifiers.

format_options property

Get audio-format options.

Purpose

Returns audio codecs supported by the xAI Text-to-Speech API.

Returns:

Type Description
List[str]

List[str]: Supported audio-codec values.

language_options property

Get language options.

Purpose

Returns documented language codes exposed by the xAI Text-to-Speech API.

Returns:

Type Description
List[str]

List[str]: Supported language-code values.

sample_rate_options property

Get sample-rate options.

Purpose

Returns documented audio sample rates supported by xAI speech synthesis.

Returns:

Type Description
List[int]

List[int]: Supported sample rates in hertz.

bit_rate_options property

Get bit-rate options.

Purpose

Returns documented MP3 bit rates supported by xAI speech synthesis.

Returns:

Type Description
List[int]

List[int]: Supported MP3 bit rates in bits per second.

build_output_format

Build output-format configuration.

Purpose

Builds the provider-native audio-output configuration from the selected codec, sample rate, and MP3 bit rate.

Parameters:

Name Type Description Default
output_format str | Dict[str, Any]

Audio codec or complete provider output configuration.

'mp3'
sample_rate int

Requested audio sample rate.

24000
bit_rate int

Requested MP3 bit rate.

128000

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: Provider-ready output-format configuration.

Raises:

Type Description
Error

Re-raised after the exception is logged.

extract_audio

Extract generated audio.

Purpose

Extracts audio bytes and available response metadata from the latest xAI Text-to-Speech response. Both direct binary responses and JSON responses containing base64-encoded audio are supported.

Returns:

Name Type Description
bytes bytes

Generated audio bytes.

Raises:

Type Description
Error

Re-raised after the exception is logged.

create_speech

Create speech.

Purpose

Converts required text into speech through the xAI batch Text-to-Speech endpoint using the selected language, built-in or custom voice, output codec, sample rate, MP3 bit rate, speed, normalization, latency, and timestamp controls.

Parameters:

Name Type Description Default
text str

Required text converted to speech.

required
language str

BCP-47 language code or auto.

'en'
voice_id str

Built-in or custom xAI voice identifier.

'eve'
output_format str | Dict[str, Any]

Audio codec or complete provider output configuration.

'mp3'
speed float

Speech-speed multiplier.

1.0
optimize_streaming_latency int

Latency-optimization level.

0
text_normalization bool

Indicates whether written text is normalized before synthesis.

False
sample_rate int

Requested audio sample rate.

24000
bit_rate int

Requested MP3 bit rate.

128000
filepath str

Optional local output path.

''
audio_path str

Compatibility alias for the optional local output path.

''
with_timestamps bool

Indicates whether character timing metadata is requested.

False

Returns:

Name Type Description
bytes bytes

Generated audio bytes.

Raises:

Type Description
Error

Re-raised after the exception is logged.

Translation

Bases: Grok

Provide xAI audio-translation workflow support.

Purpose

Provides spoken-audio translation by transcribing a required audio file through the xAI Speech-to-Text API and translating the resulting transcript through a required Grok text model. The class assigns accepted arguments to object members before constructing either provider request.

Attributes:

Name Type Description
api_key str

xAI API key.

base_url str

xAI REST API base URL.

audio_path str

Local audio-file path used by the current request.

file_name str

Source audio filename.

mime_type str

Source audio MIME type.

source_language str

Optional language code used for transcript formatting.

target_language str

Required translation target language.

text_format bool

Indicates whether inverse text normalization is enabled.

keyterm str

Optional transcription-bias term.

model str

Grok text model used for translation.

prompt str

Translation prompt sent to the Grok model.

response Any

Latest provider response.

transcript str

Text returned by the Speech-to-Text API.

translation str

Text returned by the Grok translation request.

result Dict[str, Any]

Parsed Speech-to-Text response.

params List[Tuple[str, str]]

Speech-to-Text multipart parameters.

chat Any

xAI chat used for translation.

client Optional[Client]

xAI SDK client.

duration float

Source audio duration returned by Speech-to-Text.

words List[Dict[str, Any]]

Word-level transcription segments.

model_options property

Get translation-model options.

Purpose

Returns Grok text models exposed for transcript translation.

Returns:

Type Description
List[str]

List[str]: Supported Grok text model identifiers.

language_options property

Get language options.

Purpose

Returns language codes supported for xAI Speech-to-Text formatting and transcript translation selection.

Returns:

Type Description
List[str]

List[str]: Supported language-code values.

mime_options property

Get audio MIME-type options.

Purpose

Returns common container MIME types accepted by the xAI Speech-to-Text endpoint.

Returns:

Type Description
List[str]

List[str]: Supported audio MIME-type values.

format_options property

Get text-formatting options.

Purpose

Returns the Boolean values supported by the Speech-to-Text inverse text normalization argument.

Returns:

Type Description
List[bool]

List[bool]: Available text-formatting values.

get_mime_type

Get audio MIME type.

Purpose

Determines the MIME type of a required local audio file from its extension.

Parameters:

Name Type Description Default
path str

Required local audio-file path.

required

Returns:

Name Type Description
str str

Audio MIME type.

Raises:

Type Description
Error

Re-raised after the exception is logged.

transcribe

Transcribe source audio.

Purpose

Transcribes a required local audio file through the xAI Speech-to-Text endpoint using optional language-formatting and keyterm controls.

Parameters:

Name Type Description Default
path str

Required local audio-file path.

required
source_language str

Optional language code used with text formatting.

''
text_format bool

Indicates whether inverse text normalization is enabled.

False
mime_type str

Optional source-audio MIME type.

''
keyterm str

Optional term used to bias transcription.

''

Returns:

Name Type Description
str str

Generated source transcript.

Raises:

Type Description
Error

Re-raised after the exception is logged.

get_output_text

Get translated text.

Purpose

Extracts translated text from the latest Grok chat response.

Returns:

Name Type Description
str str

Generated translated text or an empty string.

Raises:

Type Description
Error

Re-raised after the exception is logged.

translate

Translate spoken audio.

Purpose

Transcribes a required local audio file through xAI Speech-to-Text and translates the transcript into a required target language through a required Grok text model.

Parameters:

Name Type Description Default
path str

Required local audio-file path.

required
target_language str

Required target language or language code.

required
model str

Required Grok text model identifier.

required
source_language str

Optional source-language formatting code.

''
text_format bool

Indicates whether inverse text normalization is enabled.

False
mime_type str

Optional source-audio MIME type.

''
keyterm str

Optional term used to bias transcription.

''
instruct str

Optional translation system instruction.

''

Returns:

Name Type Description
str str

Generated translated text.

Raises:

Type Description
Error

Re-raised after the exception is logged.

Transcription

Bases: Grok

Provide xAI speech-to-text workflow support.

Purpose

Provides batch audio transcription through the xAI Speech-to-Text REST API. The class assigns accepted arguments to object members, constructs the provider multipart request, uploads the required local audio file, and extracts transcript text, duration, detected language, word-level timestamps, and channel-level results from the provider response.

Attributes:

Name Type Description
api_key str

xAI API key.

base_url str

xAI REST API base URL.

audio_path str

Local audio-file path used by the current request.

file_name str

Source audio filename.

mime_type str

Source audio MIME type.

language str

Optional source-language hint.

text_format bool

Indicates whether inverse text normalization is enabled.

keyterm str

Optional transcription-bias term.

response Any

Latest provider response.

transcript str

Transcript extracted from the latest response.

result Dict[str, Any]

Parsed Speech-to-Text response.

words List[Dict[str, Any]]

Word-level transcription results.

channels List[Dict[str, Any]]

Channel-level transcription results.

duration float

Audio duration returned by the provider.

params List[Tuple[str, str]]

Multipart Speech-to-Text parameters.

format_options property

Get text-formatting options.

Purpose

Returns the Boolean values accepted by the xAI inverse text-normalization argument.

Returns:

Type Description
List[bool]

List[bool]: Available text-formatting values.

language_options property

Get language options.

Purpose

Returns language codes supported by the xAI Speech-to-Text workflow.

Returns:

Type Description
List[str]

List[str]: Supported language-code values.

mime_options property

Get audio MIME-type options.

Purpose

Returns common audio MIME types accepted by the xAI Speech-to-Text endpoint.

Returns:

Type Description
List[str]

List[str]: Supported audio MIME-type values.

get_mime_type

Get audio MIME type.

Purpose

Determines the MIME type of a required local audio file from its extension.

Parameters:

Name Type Description Default
path str

Required local audio-file path.

required

Returns:

Name Type Description
str str

Audio MIME type.

Raises:

Type Description
Error

Re-raised after the exception is logged.

transcribe

Transcribe audio.

Purpose

Uploads a required local audio file to the xAI batch Speech-to-Text endpoint and returns the generated transcript. Optional language, inverse text normalization, MIME type, and keyterm-bias settings are included when supplied.

Parameters:

Name Type Description Default
path str

Required local audio-file path.

required
language str

Optional source-language hint.

''
format bool

Indicates whether inverse text normalization is enabled.

False
mime_type str

Optional source-audio MIME type.

''
keyterm str

Optional term used to bias transcription.

''

Returns:

Name Type Description
str str

Generated transcript text.

Raises:

Type Description
Error

Re-raised after the exception is logged.

get_result

Get transcription result.

Purpose

Returns the complete parsed response from the latest xAI Speech-to-Text request.

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: Parsed transcription response.

Raises:

Type Description
Error

Re-raised after the exception is logged.

get_words

Get word-level results.

Purpose

Returns word-level transcription timestamps from the latest xAI response.

Returns:

Type Description
List[Dict[str, Any]]

List[Dict[str, Any]]: Word-level transcription results.

Raises:

Type Description
Error

Re-raised after the exception is logged.

get_channels

Get channel-level results.

Purpose

Returns channel-level transcription results from the latest xAI response.

Returns:

Type Description
List[Dict[str, Any]]

List[Dict[str, Any]]: Channel-level transcription results.

Raises:

Type Description
Error

Re-raised after the exception is logged.

Collections

Bases: Grok

Provide xAI Collections workflow support.

Purpose

Provides xAI collection creation, listing, retrieval, updating, deletion, document management, and semantic search. The class uses the xAI Management API key for collection and indexed-document administration and the standard xAI API key for semantic collection searches.

Attributes:

Name Type Description
client Optional[Client]

xAI SDK client used for collection searches.

api_key str

Standard xAI API key.

management_key str

xAI Management API key.

base_url str

Standard xAI REST API base URL.

management_base_url str

xAI Management API base URL.

model str

Grok model retained by search workflows.

prompt str

Semantic-search query.

name str

Collection name used by the current operation.

description str

Collection description used by the current operation.

file_path str

Local document path used by an upload operation.

file_name str

Document filename used by the current operation.

file_id str

xAI file identifier used by the current operation.

file_ids List[str]

File identifiers used by a batch operation.

store_id str

Application-facing collection identifier.

store_ids List[str]

Application-facing collection identifiers.

collection_id str

Provider collection identifier.

collection_ids List[str]

Provider collection identifiers.

request Dict[str, Any]

Latest request data.

response Any

Latest provider response.

result Any

Normalized result from the latest operation.

params Dict[str, Any]

Query-string parameters.

payload Dict[str, Any]

JSON request body.

headers Dict[str, str]

HTTP request headers.

team_id str

Optional xAI team identifier.

limit int

Maximum number of resources requested.

order str

Result ordering.

sort_by str

Result sort field.

pagination_token str

Pagination token.

next_token str

Pagination token returned by the provider.

filter str

Provider filter expression.

collections Dict[str, str]

Configured collection labels and identifiers.

documents Dict[str, str]

Configured document labels and identifiers.

model_options property

Get model options.

Purpose

Returns Grok models exposed for collection-grounded generation workflows.

Returns:

Type Description
List[str]

List[str]: Supported Grok model identifiers.

order_options property

Get ordering options.

Purpose

Returns ordering values supported by xAI collection and document list operations.

Returns:

Type Description
List[str]

List[str]: Supported ordering values.

collection_sort_options property

Get collection sort options.

Purpose

Returns fields supported for sorting collection-list results.

Returns:

Type Description
List[str]

List[str]: Supported collection sort fields.

document_sort_options property

Get document sort options.

Purpose

Returns fields supported for sorting collection-document results.

Returns:

Type Description
List[str]

List[str]: Supported document sort fields.

get_collection_id

Get provider collection identifier.

Purpose

Resolves a required application-facing store identifier or configured collection label to the corresponding xAI collection identifier.

Parameters:

Name Type Description Default
store_id str

Required store identifier or configured collection label.

required

Returns:

Name Type Description
str str

Provider collection identifier.

Raises:

Type Description
Error

Re-raised after the exception is logged.

get_collection_name

Get configured collection name.

Purpose

Resolves a required provider collection identifier to its configured application-facing label when one is available.

Parameters:

Name Type Description Default
collection_id str

Required provider collection identifier.

required

Returns:

Name Type Description
str str

Configured collection label or the original identifier.

Raises:

Type Description
Error

Re-raised after the exception is logged.

build_management_headers

Build Management API headers.

Purpose

Builds authenticated JSON headers for xAI collection-management requests.

Returns:

Type Description
Dict[str, str]

Dict[str, str]: Management API request headers.

Raises:

Type Description
Error

Re-raised after the exception is logged.

execute_management_request

Execute Management API request.

Purpose

Executes an authenticated xAI collection-management request and returns its decoded JSON body when present.

Parameters:

Name Type Description Default
method str

Required HTTP method.

required
path str

Required Management API resource path.

required
params Optional[Dict[str, Any]]

Optional query-string parameters.

None
payload Optional[Dict[str, Any]]

Optional JSON request body.

None

Returns:

Name Type Description
Any Any

Decoded JSON response or an empty dictionary.

Raises:

Type Description
Error

Re-raised after the exception is logged.

normalize_collection

Normalize collection metadata.

Purpose

Converts required xAI collection metadata into a stable application-facing record.

Parameters:

Name Type Description Default
collection Dict[str, Any]

Required provider collection metadata.

required

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: Application-facing collection metadata.

Raises:

Type Description
Error

Re-raised after the exception is logged.

normalize_collection_list

Normalize collection list.

Purpose

Converts a required xAI collection-list response into application-facing records and updates the configured name-to-identifier mapping.

Parameters:

Name Type Description Default
payload Dict[str, Any]

Required provider collection-list response.

required

Returns:

Type Description
List[Dict[str, Any]]

List[Dict[str, Any]]: Application-facing collection metadata records.

Raises:

Type Description
Error

Re-raised after the exception is logged.

get_text_output

Get collection-search output.

Purpose

Extracts textual content or semantic-search matches from a required xAI collection search response.

Parameters:

Name Type Description Default
response Any

Required xAI collection-search response.

required

Returns:

Name Type Description
Any Any

Search text, semantic matches, or the original provider response.

Raises:

Type Description
Error

Re-raised after the exception is logged.

create

Create a collection.

Purpose

Creates an xAI collection with a required name and optional description.

Parameters:

Name Type Description Default
name str

Required collection name.

required
description str

Optional collection description.

''

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: Created collection metadata.

Raises:

Type Description
Error

Re-raised after the exception is logged.

list

List collections.

Purpose

Lists xAI collections using pagination, ordering, sorting, filtering, and optional team scope.

Parameters:

Name Type Description Default
limit int

Maximum number of collections requested.

100
order str

Result ordering.

'desc'
sort_by str

Collection sort field.

'collection_name'
pagination_token str

Optional pagination token.

''
filter str

Optional provider filter expression.

''
team_id str

Optional team identifier.

''

Returns:

Type Description
List[Dict[str, Any]]

List[Dict[str, Any]]: Application-facing collection metadata records.

Raises:

Type Description
Error

Re-raised after the exception is logged.

retrieve

Retrieve a collection.

Purpose

Retrieves metadata for a required xAI collection.

Parameters:

Name Type Description Default
store_id str

Required collection identifier or configured label.

required
team_id str

Optional team identifier.

''

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: Application-facing collection metadata.

Raises:

Type Description
Error

Re-raised after the exception is logged.

update

Update a collection.

Purpose

Updates the name or description of a required xAI collection.

Parameters:

Name Type Description Default
store_id str

Required collection identifier or configured label.

required
name str

Optional replacement collection name.

''
description str

Optional replacement collection description.

''

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: Updated collection metadata.

Raises:

Type Description
Error

Re-raised after the exception is logged.

delete

Delete a collection.

Purpose

Deletes a required xAI collection.

Parameters:

Name Type Description Default
store_id str

Required collection identifier or configured label.

required
team_id str

Optional team identifier.

''

Returns:

Name Type Description
bool bool

True when the deletion request completes.

Raises:

Type Description
Error

Re-raised after the exception is logged.

add_document

Add a document to a collection.

Purpose

Adds a required existing xAI file to a required collection and optionally assigns document metadata fields.

Parameters:

Name Type Description Default
store_id str

Required collection identifier or configured label.

required
file_id str

Required xAI file identifier.

required
fields Optional[Dict[str, Any]]

Optional collection document fields.

None

Returns:

Name Type Description
Any Any

Provider document-addition result.

Raises:

Type Description
Error

Re-raised after the exception is logged.

list_documents

List collection documents.

Purpose

Lists documents in a required xAI collection using pagination, ordering, sorting, filtering, and optional team scope.

Parameters:

Name Type Description Default
store_id str

Required collection identifier or configured label.

required
limit int

Maximum number of documents requested.

100
order str

Result ordering.

'desc'
sort_by str

Document sort field.

'name'
pagination_token str

Optional pagination token.

''
filter str

Optional document filter expression.

''
team_id str

Optional team identifier.

''

Returns:

Type Description
List[Dict[str, Any]]

List[Dict[str, Any]]: Collection document metadata.

Raises:

Type Description
Error

Re-raised after the exception is logged.

retrieve_document

Retrieve collection document.

Purpose

Retrieves metadata for a required document in a required xAI collection.

Parameters:

Name Type Description Default
store_id str

Required collection identifier or configured label.

required
file_id str

Required xAI file identifier.

required
team_id str

Optional team identifier.

''

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: Collection document metadata.

Raises:

Type Description
Error

Re-raised after the exception is logged.

regenerate_document

Regenerate document index.

Purpose

Regenerates semantic indices for a required document in a required xAI collection.

Parameters:

Name Type Description Default
store_id str

Required collection identifier or configured label.

required
file_id str

Required xAI file identifier.

required
team_id str

Optional team identifier.

''

Returns:

Name Type Description
Any Any

Provider regeneration result.

Raises:

Type Description
Error

Re-raised after the exception is logged.

remove_document

Remove a collection document.

Purpose

Removes a required document from a required xAI collection without deleting the underlying xAI file.

Parameters:

Name Type Description Default
store_id str

Required collection identifier or configured label.

required
file_id str

Required xAI file identifier.

required
team_id str

Optional team identifier.

''

Returns:

Name Type Description
bool bool

True when the removal request completes.

Raises:

Type Description
Error

Re-raised after the exception is logged.

batch_get_documents

Retrieve document metadata in a batch.

Purpose

Retrieves metadata for required file identifiers in a required xAI collection.

Parameters:

Name Type Description Default
store_id str

Required collection identifier or configured label.

required
file_ids List[str]

Required xAI file identifiers.

required
team_id str

Optional team identifier.

''

Returns:

Type Description
List[Dict[str, Any]]

List[Dict[str, Any]]: Requested collection document metadata.

Raises:

Type Description
Error

Re-raised after the exception is logged.

search

Search a collection.

Purpose

Performs semantic retrieval for a required query against a required xAI collection.

Parameters:

Name Type Description Default
prompt str

Required semantic-search query.

required
store_id str

Required collection identifier or configured label.

required
model str

Required Grok model retained by the operation.

required
filter str

Optional document metadata filter.

''

Returns:

Name Type Description
Any Any

Semantic-search matches returned by xAI.

Raises:

Type Description
Error

Re-raised after the exception is logged.

survey

Search multiple collections.

Purpose

Performs semantic retrieval for a required query across multiple required xAI collections.

Parameters:

Name Type Description Default
prompt str

Required semantic-search query.

required
store_ids List[str]

Required collection identifiers or configured labels.

required
model str

Required Grok model retained by the operation.

required
filter str

Optional document metadata filter.

''

Returns:

Name Type Description
Any Any

Semantic-search matches returned by xAI.

Raises:

Type Description
Error

Re-raised after the exception is logged.

encode_image

Encode image.

Purpose

Performs the encode_image workflow using the inputs supplied by the caller and the current runtime configuration. The function keeps this behavior isolated so related UI, provider, and data-processing paths can call it consistently.

Parameters:

Name Type Description Default
image_path str

Image path value used by the operation.

required

Returns:

Name Type Description
str str

Return value produced by the operation.

throw_if

Throw if.

Purpose

Validates that a required argument contains a usable value before the surrounding workflow continues. This guard centralizes early validation so provider wrappers and UI routines fail with consistent, readable error messages.

Parameters:

Name Type Description Default
name str

Name value used by the operation.

required
value object

Value value used by the operation.

required

Returns:

Name Type Description
None None

This function performs its work through side effects and does not return a value.