openapi: 3.2.0 info: title: xAI's REST Chat API description: REST API for xAI compatible with other providers. license: name: '' version: 1.0.0 tags: - name: Chat paths: /v1/chat/completions: post: tags: - Chat summary: Create a chat response from text/image chat prompts. operationId: handle_generic_completion_request requestBody: content: application/json: schema: $ref: '#/components/schemas/ChatRequest' example: messages: - role: system content: You are a helpful assistant that can answer questions and help with tasks. - role: user content: What is 101*3? model: latest required: true responses: '200': description: Success content: application/json: schema: $ref: '#/components/schemas/ChatResponse' example: id: a3d1008e-4544-40d4-d075-11527e794e4a object: chat.completion created: 1752854522 model: latest choices: - index: 0 message: role: assistant content: 101 multiplied by 3 is 303. refusal: null finish_reason: stop usage: prompt_tokens: 32 completion_tokens: 9 total_tokens: 135 prompt_tokens_details: text_tokens: 32 audio_tokens: 0 image_tokens: 0 cached_tokens: 6 completion_tokens_details: reasoning_tokens: 94 audio_tokens: 0 accepted_prediction_tokens: 0 rejected_prediction_tokens: 0 num_sources_used: 0 system_fingerprint: fp_3a7881249c '400': description: Bad request. The request is invalid or an invalid API key is provided. '422': description: Unprocessable Entity. There are missing fields in the request body. security: - bearerAuth: [] /v1/chat/deferred-completion/{request_id}: get: tags: - Chat summary: Tries to fetch a result for a previously-started deferred completion. operationId: handle_get_deferred_completion_request parameters: - name: request_id in: path description: The deferred request id returned by a previous deferred chat request. required: true schema: type: string responses: '200': description: Success content: application/json: schema: $ref: '#/components/schemas/ChatResponse' example: id: 335b92e4-afa5-48e7-b99c-b9a4eabc1c8e object: chat.completion created: 1743770624 model: latest choices: - index: 0 message: role: assistant content: 101 multiplied by 3 is 303. refusal: null finish_reason: stop usage: prompt_tokens: 31 completion_tokens: 11 total_tokens: 42 prompt_tokens_details: text_tokens: 31 audio_tokens: 0 image_tokens: 0 cached_tokens: 0 completion_tokens_details: reasoning_tokens: 0 audio_tokens: 0 accepted_prediction_tokens: 0 rejected_prediction_tokens: 0 system_fingerprint: fp_156d35dcaa '202': description: Accepted. The request is processing, but haven't been completed. You can retry at a later time. '400': description: Bad request. The request is invalid or an invalid API key is provided. '404': description: Not found. No deferred completion could be found with the given request_id. security: - bearerAuth: [] components: schemas: CompletionUsageDetail: type: object description: Details of completion usage. required: - reasoning_tokens - audio_tokens - accepted_prediction_tokens - rejected_prediction_tokens properties: accepted_prediction_tokens: type: integer format: int32 description: The number of tokens in the prediction that appeared in the completion. audio_tokens: type: integer format: int32 description: Audio input tokens generated by the model. reasoning_tokens: type: integer format: int32 description: Tokens generated by the model for reasoning. rejected_prediction_tokens: type: integer format: int32 description: The number of tokens in the prediction that did not appear in the completion. Choice: type: object required: - index - message properties: finish_reason: type: - string - 'null' description: Finish reason. `"stop"` means the inference has reached a model-defined or user-supplied stop sequence in `stop`. `"length"` means the inference result has reached models' maximum allowed token length or user defined value in `max_tokens`. `"end_turn"` or `null` in streaming mode when the chunk is not the last. index: type: integer format: int32 description: Index of the choice within the response choices, starting from 0. logprobs: oneOf: - type: 'null' - $ref: '#/components/schemas/LogProbs' description: The log probabilities of each output token returned in the content of message. message: $ref: '#/components/schemas/ChoiceMessage' description: The generated chat completion message. FunctionDefinition: type: object description: Definition of the tool call made available to the model. required: - name - parameters properties: description: type: - string - 'null' description: A description of the function to indicate to the model when to call it. name: type: string description: 'The name of the function. If the model calls the function, this name is used in the response.' parameters: description: 'A JSON schema describing the function parameters. The model _should_ follow the schema, however, this is not enforced at the moment.' strict: type: - boolean - 'null' description: Not supported. Only maintained for compatibility reasons. ToolCall: type: object required: - id - function properties: function: $ref: '#/components/schemas/Function' description: Function to call for the tool call. id: type: string description: A unique ID of the tool call generated by xAI. After performing tool call's function, user provides this ID with tool call's result in the subsequent request to xAI. xAI can then match the tool call result sent with tool call request. index: type: - integer - 'null' format: int32 description: Index of the tool call. type: type: - string - 'null' description: Type of tool call, should be `"function"` or `"web_search_call"` or `"x_search_call"` or `"code_interpreter_call"` or `"mcp_call"` SearchParameters: type: object description: Parameters to control realtime data. properties: from_date: type: - string - 'null' format: date description: 'Date from which to consider the results in ISO-8601 YYYY-MM-DD. See .' example: '2024-06-24' max_search_results: type: - integer - 'null' format: int32 description: Maximum number of search results to use. default: 15 maximum: 30 minimum: 1 mode: type: - string - 'null' description: 'Choose the mode to query realtime data: * `off`: no search performed and no external will be considered. * `on` (default): the model will search in every sources for relevant data. * `auto`: the model choose whether to search data or not and where to search the data.' default: auto example: auto return_citations: type: - boolean - 'null' description: Whether to return citations in the response or not. default: true sources: type: - array - 'null' items: $ref: '#/components/schemas/SearchSource' description: List of sources to search in. If no sources specified, the model will look over the web and X by default. to_date: type: - string - 'null' format: date description: 'Date up to which to consider the results in ISO-8601 YYYY-MM-DD. See .' example: '2024-12-24' Content: oneOf: - type: string description: Text prompt. - type: array items: $ref: '#/components/schemas/ContentPart' description: An array of content parts of different types, such as image, text or text file. description: Content of each chat message. TokenLogProb: type: object required: - token - logprob - top_logprobs properties: bytes: type: - array - 'null' items: type: integer format: int32 minimum: 0 description: The ASCII encoding of the output character. logprob: type: number format: float description: The log probability of returning this token. token: type: string description: The token. top_logprobs: type: array items: $ref: '#/components/schemas/TopLogProb' description: An array of the most likely tokens to return at this token position. PromptUsageDetail: type: object description: Details of prompt usage. required: - text_tokens - audio_tokens - image_tokens - cached_tokens properties: audio_tokens: type: integer format: int32 description: Audio prompt token used. cached_tokens: type: integer format: int32 description: Token cached by xAI from previous requests and reused for this request. image_tokens: type: integer format: int32 description: Image prompt token used. text_tokens: type: integer format: int32 description: Total text prompt token used (cached + non-cached text tokens). LogProbs: type: object properties: content: type: - array - 'null' items: $ref: '#/components/schemas/TokenLogProb' description: An array the log probabilities of each output token returned. ImageUrl: type: object description: 'Image input for generation and editing requests. Accepts a public URL, a base64-encoded data URL, or a file_id from the xAI Files API.' properties: file_id: type: - string - 'null' description: 'File ID from the xAI Files API. Mutually exclusive with `url`. The file must be an image (JPEG, PNG, or WebP) and fully uploaded.' url: type: string description: 'Public URL or base64-encoded data URL of the image (JPEG, PNG, or WebP). Also accepts `image_url` for compatibility. Required when `file_id` is not set.' ChatResponse: type: object description: The chat response body for `/v1/chat/completions` endpoint. required: - id - object - created - model - choices properties: choices: type: array items: $ref: '#/components/schemas/Choice' description: A list of response choices from the model. The length corresponds to the `n` in request body (default to 1). citations: type: - array - 'null' items: type: string description: List of all the external pages used by the model to answer. created: type: integer format: int64 description: The chat completion creation time in Unix timestamp. id: type: string description: A unique ID for the chat response. model: type: string description: Model ID used to create chat completion. example: latest object: type: string description: The object type, which is always `"chat.completion"`. output_files: type: - array - 'null' items: $ref: '#/components/schemas/OutputFile' description: 'Files generated during the response (e.g., by the code execution tool). Only populated when `code_execution_files_output` is included.' system_fingerprint: type: - string - 'null' description: System fingerprint, used to indicate xAI system configuration changes. usage: oneOf: - type: 'null' - $ref: '#/components/schemas/Usage' description: Token usage information. ChatRequest: type: object description: The chat request body for `/v1/chat/completions` endpoint. properties: deferred: type: - boolean - 'null' description: If set to `true`, the request returns a `request_id`. You can then get the deferred response by GET `/v1/chat/deferred-completion/{request_id}`. default: false frequency_penalty: type: - number - 'null' format: float description: (Not supported by reasoning models) 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. default: 0 maximum: 2 minimum: -2 logit_bias: type: - object - 'null' description: (Unsupported) 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. additionalProperties: type: number format: float propertyNames: type: integer format: int32 logprobs: type: - boolean - 'null' description: Whether to return log probabilities of the output tokens or not. If true, returns the log probabilities of each output token returned in the content of message. default: false max_completion_tokens: type: - integer - 'null' format: int32 description: An upper bound for the number of tokens that can be generated for a completion, only applies to visible output tokens (i.e. does not apply to tokens used for reasoning or function calls). Defaults to None, meaning the model will generate as many tokens as needed up until the model's maximum context length. example: 8192 max_tokens: type: - integer - 'null' format: int32 description: \[DEPRECATED\] The maximum number of tokens that can be generated in the chat completion. Deprecated in favor of `max_completion_tokens`. example: 8192 messages: type: array items: $ref: '#/components/schemas/Message' description: A list of messages that make up the chat conversation. Different models support different message types, such as image and text. model: type: string description: Model name for the model to use. Obtainable from or . example: latest n: type: - integer - 'null' format: int32 description: 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. default: 1 example: 1 minimum: 1 parallel_tool_calls: type: - boolean - 'null' description: If set to false, the model can perform maximum one tool call. default: true example: false presence_penalty: type: - number - 'null' format: float description: (Not supported by `grok-3` and reasoning models) 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. default: 0 maximum: 2 minimum: -2 reasoning_effort: type: - string - 'null' description: Constrains how hard a reasoning model thinks before responding. Not supported by `grok-4` and will result in error if used with `grok-4`. Possible values are `low` (uses fewer reasoning tokens) and `high` (uses more reasoning tokens). response_format: oneOf: - type: 'null' - $ref: '#/components/schemas/ResponseFormat' description: 'An object specifying the format that the model must output. Specify `{ "type": "json_object" }` for JSON output, or `{ "type": "json_schema", "json_schema": {...} }` for structured outputs. If `{ \"type\": \"text\" }`, the model will return a text response.' search_parameters: oneOf: - type: 'null' - $ref: '#/components/schemas/SearchParameters' description: Set the parameters to be used for searched data. If not set, no data will be acquired by the model. seed: type: - integer - 'null' format: int32 description: 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. stop: type: - array - 'null' items: type: string description: (Not supported by reasoning models) Up to 4 sequences where the API will stop generating further tokens. stream: type: - boolean - 'null' description: 'If set, partial message deltas will be sent. Tokens will be sent as data-only server-sent events as they become available, with the stream terminated by a `data: [DONE]` message.' default: false example: true stream_options: oneOf: - type: 'null' - $ref: '#/components/schemas/StreamOptions' description: 'Options for streaming response. Only set this when you set `stream: true`.' temperature: type: - number - 'null' format: float description: What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. default: 1 example: 0.2 maximum: 2 minimum: 0 tool_choice: oneOf: - type: 'null' - $ref: '#/components/schemas/ToolChoice' description: '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: type: - array - 'null' items: $ref: '#/components/schemas/Tool' description: A list of tools the model may call in JSON-schema. Currently, only functions are supported as a tool. Use this to provide a list of functions the model may generate JSON inputs for. A max of 128 functions are supported. maxItems: 128 top_logprobs: type: - integer - 'null' format: int32 description: An integer between 0 and 8 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. maximum: 8 minimum: 0 top_p: type: - number - 'null' format: float description: An alternative to sampling with `temperature`, called nucleus sampling, where the model considers the results of the tokens with `top_p` probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. It is generally recommended to alter this or `temperature` but not both. default: 1 maximum: 1 exclusiveMinimum: 0 user: type: - string - 'null' description: A unique identifier representing your end-user, which can help xAI to monitor and detect abuse. web_search_options: oneOf: - type: 'null' - $ref: '#/components/schemas/WebSearchOptions' description: 'Options to control the web search. This is only included for compatibility reason. Prefer the usage of `realtime_data_parameters` instead.' ContentPart: type: object required: - type properties: file: oneOf: - type: 'null' - $ref: '#/components/schemas/FileRef' description: File reference for file attachments (OpenAI-compatible nesting). image_url: oneOf: - type: 'null' - $ref: '#/components/schemas/ImageUrl' description: A public URL of image prompt, only available for vision models. text: type: - string - 'null' description: Text prompt. type: type: string description: The type of the content part. Can be `text`, `image_url`, `text_file` or `file`. ChoiceMessage: type: object required: - role properties: content: type: - string - 'null' description: The content of the message. reasoning_content: type: - string - 'null' description: The reasoning trace generated by the model. refusal: type: - string - 'null' description: The reason given by model if the model is unable to generate a response. null if model is able to generate. role: type: string description: The role that the message belongs to, the response from model is always `"assistant"`. tool_calls: type: - array - 'null' items: $ref: '#/components/schemas/ToolCall' description: A list of tool calls asked by model for user to perform. Message: oneOf: - type: object description: System message, usually instructions for the model to respond in a certain way. required: - content - role properties: content: $ref: '#/components/schemas/Content' description: System prompt content. name: type: - string - 'null' description: A unique identifier representing your end-user, which can help xAI to monitor and detect abuse. role: type: string enum: - system - type: object description: User message, typically request from user for the model to answer. required: - content - role properties: content: $ref: '#/components/schemas/Content' description: System prompt content. name: type: - string - 'null' description: A unique identifier representing your end-user, which can help xAI to monitor and detect abuse. role: type: string enum: - user - type: object description: Assistant role message, previous chat messages from the model. required: - role properties: content: oneOf: - type: 'null' - $ref: '#/components/schemas/Content' description: Assistant prompt content. name: type: - string - 'null' description: A unique identifier representing your end-user, which can help xAI to monitor and detect abuse. reasoning_content: type: - string - 'null' description: Assistant reasoning content. role: type: string enum: - assistant tool_calls: type: - array - 'null' items: $ref: '#/components/schemas/ToolCall' description: An array of tool calls available to the model on your machine. - type: object description: Tool call role message, used to return function call result to the model. required: - content - role properties: content: $ref: '#/components/schemas/Content' description: Content of the tool call result. role: type: string enum: - tool tool_call_id: type: - string - 'null' description: The ID of the tool call received from assistant message response. - type: object description: 'Function call role message. Deprecated in favor of `{"role": "tool"}`.' required: - content - role properties: content: $ref: '#/components/schemas/Content' description: Content of the tool call result. name: type: - string - 'null' description: A unique identifier representing your end-user, which can help xAI to monitor and detect abuse. role: type: string enum: - function description: Chat message objects. OutputFile: type: object description: A file generated during the model's response (e.g., by the code execution tool). required: - file_id - name properties: file_id: type: string description: The file ID from the Files API. Use this to download the file. name: type: string description: The display name of the file. ResponseFormat: oneOf: - type: object description: Specify text response format, always `"text"`. required: - type properties: type: type: string enum: - text - type: object description: Specify json_object response format, always `json_object`. Used for backward compatibility. Prefer to use `"json_schema"` instead of this. required: - type properties: type: type: string enum: - json_object - type: object description: Specify json_schema response format with a given schema. Type is always `"json_schema"`. required: - json_schema - type properties: json_schema: description: A json schema representing the desired response schema. Includes the schema as a `"schema"` field. type: type: string enum: - json_schema description: Response format parameter for structured outputs. SearchSource: oneOf: - type: object required: - type properties: excluded_x_handles: type: - array - 'null' items: type: string description: 'List of X handles to exclude from the search results. X posts returned will not include any posts authored by these handles.' included_x_handles: type: - array - 'null' items: type: string description: ' NOTE: `included_x_handles` and `x_handles` are the same parameter. `included_x_handles` is the new name but we keep both for backward compatibility. X Handles of the users from whom to consider the posts. Only available if mode is `auto`, `on` or `x`.' post_favorite_count: type: - integer - 'null' format: int32 description: The minimum favorite count of the X posts to consider. post_view_count: type: - integer - 'null' format: int32 description: The minimum view count of the X posts to consider. type: type: string enum: - x x_handles: type: - array - 'null' items: type: string description: 'DEPRECATED in favor of `included_x_handles`. Use `included_x_handles` instead. X Handles of the users from whom to consider the posts. Only available if mode is `auto`, `on` or `x`.' deprecated: true - type: object required: - type properties: allowed_websites: type: - array - 'null' items: type: string description: 'List of website to allow in the search results. This parameter act as a whitelist where only those websites can be selected. A maximum of 5 websites can be selected. Note 1: If no relevant information is found on those websites, the number of results returned might be smaller than `max_search_results`. Note 2: This parameter cannot be set with `excluded_websites`.' example: - wikipedia.com maxItems: 5 country: type: - string - 'null' format: iso3166-1-alpha-2 description: 'ISO alpha-2 code of the country. If the country is set, only data coming from this country will be considered. See .' example: BE excluded_websites: type: - array - 'null' items: type: string description: 'List of website to exclude from the search results without protocol specification or subdomains. A maximum of 5 websites can be excluded. Note 2: This parameter cannot be set with `allowed_websites`' example: - wikipedia.com maxItems: 5 safe_search: type: - boolean - 'null' description: If set to true, mature content won't be considered during the search. Default to `true`. type: type: string enum: - web - type: object required: - type properties: country: type: - string - 'null' format: iso3166-1-alpha-2 description: 'ISO alpha-2 code of the country. If the country is set, only data coming from this country will be considered. See .' example: BE excluded_websites: type: - array - 'null' items: type: string description: 'List of website to exclude from the search results without protocol specification or subdomains. A maximum of 5 websites can be excluded.' example: - foxnews.com maxItems: 5 safe_search: type: - boolean - 'null' description: If set to true, mature content won't be considered during the search. Default to `true`. type: type: string enum: - news - type: object required: - links - type properties: links: type: array items: type: string description: Links of the RSS feeds. example: - https://status.x.ai/feed.xml maxItems: 1 minItems: 1 type: type: string enum: - rss FunctionChoice: type: object description: Function name. required: - name properties: name: type: string ToolChoice: oneOf: - type: string description: Controls tool access by the model. `"none"` makes model ignore tools, `"auto"` let the model automatically decide whether to call a tool, `"required"` forces model to pick a tool to call. - type: object required: - type properties: function: oneOf: - type: 'null' - $ref: '#/components/schemas/FunctionChoice' description: Name of the function to use. type: type: string description: Type is always `"function"`. description: Parameter to control how model chooses the tools. Function: type: object required: - name - arguments properties: arguments: type: string name: type: string Tool: oneOf: - type: object required: - function - type properties: function: $ref: '#/components/schemas/FunctionDefinition' description: Definition of tool call available to the model. type: type: string enum: - function - type: object required: - sources - type properties: sources: type: array items: $ref: '#/components/schemas/SearchSource' type: type: string enum: - live_search description: Definition of one tool that the model can call. FileRef: type: object properties: file_id: type: - string - 'null' description: The file ID from the Files API. url: type: - string - 'null' description: Public URL for a file attachment. WebSearchOptions: type: object properties: filters: description: Only included for compatibility. search_context_size: type: - string - 'null' description: This field included for compatibility reason with OpenAI's API. It is mapped to `max_search`. default: medium example: medium user_location: description: Only included for compatibility. StreamOptions: type: object description: Options available when using streaming response. required: - include_usage properties: include_usage: type: boolean description: 'Set an additional chunk to be streamed before the `data: [DONE]` message. The other chunks will return `null` in `usage` field.' TopLogProb: type: object required: - token - logprob properties: bytes: type: - array - 'null' items: type: integer format: int32 minimum: 0 description: The ASCII encoding of the output character. logprob: type: number format: float description: The log probability of returning this token. token: type: string description: The token. Usage: type: object required: - prompt_tokens - completion_tokens - total_tokens - prompt_tokens_details - completion_tokens_details - num_sources_used - cost_in_usd_ticks properties: completion_tokens: type: integer format: int32 description: Total completion token used. completion_tokens_details: $ref: '#/components/schemas/CompletionUsageDetail' description: Breakdown of completion token usage of different types. cost_in_usd_ticks: type: integer format: int64 description: 'Accurate cost of this request in USD ticks, where "tick" is defined as follows: TICKS_IN_USD_CENT: i64 = 100_000_000 which means there is 10''000''000''000 ticks in one *dollar*.' num_sources_used: type: integer format: int32 description: Number of individual live search source used. prompt_tokens: type: integer format: int32 description: Total prompt token used. prompt_tokens_details: $ref: '#/components/schemas/PromptUsageDetail' description: Breakdown of prompt token usage of different types. total_tokens: type: integer format: int32 description: Total token used, the sum of prompt token and completion token amount. securitySchemes: bearerAuth: type: http scheme: bearer