### Configure 4-Agent Setup with OpenAI SDK Source: https://docs.x.ai/developers/model-capabilities/text/multi-agent.md This example demonstrates setting up a 4-agent configuration using the OpenAI SDK, specifying a 'low' reasoning effort. It requires the XAI_API_KEY to be set in your environment. ```python import os from openai import OpenAI client = OpenAI( api_key=os.getenv("XAI_API_KEY"), base_url="https://api.x.ai/v1", ) response = client.responses.create( model="grok-4.20-multi-agent", reasoning={"effort": "low"}, input=[ { "role": "user", "content": "What are the key differences between TCP and UDP?", }, ], ) print(response.output_text) ``` -------------------------------- ### Define Client-Side Tool and SDK Setup Source: https://docs.x.ai/developers/tools/advanced-usage.md Imports necessary libraries and defines a client-side tool for getting weather information. This setup is required before initiating a chat. ```pythonXAI import os import json from xai_sdk import Client from xai_sdk.chat import user, tool, tool_result from xai_sdk.tools import web_search, get_tool_call_type client = Client(api_key=os.getenv("XAI_API_KEY")) # Define client-side tool def get_weather(city: str) -> str: """Get the weather for a given city.""" # In a real app, this would query your database return f"The weather in {city} is sunny." # Tools array with both server-side and client-side tools tools = [ web_search(), tool( name="get_weather", description="Get the weather for a given city.", parameters={ "type": "object", "properties": { "city": { "type": "string", "description": "The name of the city", } }, "required": ["city"] }, ), ] model = "grok-4.3" ``` -------------------------------- ### Example Output of All Citations Source: https://docs.x.ai/developers/tools/citations.md An example of the list format for all citations, showing URLs of sources the agent encountered. ```output [ 'https://x.com/i/user/1912644073896206336', 'https://x.com/i/status/1975607901571199086', 'https://x.ai/news', 'https://docs.x.ai/developers/release-notes', ... ] ``` -------------------------------- ### Install Grok Build CLI Source: https://docs.x.ai/developers/release-notes.md Install the Grok Build command-line interface using a curl command. This script fetches and executes the installation. ```bash curl -fsSL https://x.ai/cli/install.sh | bash ``` -------------------------------- ### Response Example Source: https://docs.x.ai/developers/rest-api-reference/collections/collection.md An example of the JSON response when listing collections. ```APIDOC ## Response Example ```json { "collections": [ { "collection_id": "collection_80100614-300c-4609-959b-a138fa90f542", "collection_name": "SEC Filings", "created_at": "2025-09-16T18:36:09.790629Z", "index_configuration": { "model_name": "grok-embedding-small" }, "chunk_configuration": { "tokens_configuration": { "max_chunk_size_tokens": 1024, "chunk_overlap_tokens": 200, "encoding_name": "o200k_base" }, "strip_whitespace": true, "inject_name_into_chunks": false }, "documents_count": 0, "collection_type": "text", "collection_description": "Filings from the SEC for financial analysis" } ] } ``` ``` -------------------------------- ### Example Response Body Source: https://docs.x.ai/developers/rest-api-reference/inference/videos.md This is an example of a successful response when a video generation task is completed. ```json { "status": "done", "video": { "url": "https://vidgen.x.ai/xai-vidgen-bucket/xai-video-{request_id}.mp4", "duration": 6, "respect_moderation": true }, "model": "grok-imagine-video" } ``` -------------------------------- ### Create Collection Response Example Source: https://docs.x.ai/developers/rest-api-reference/collections/collection.md This is an example of a successful response when creating a collection. It includes the collection ID, name, creation timestamp, and configuration details. ```json { "collection_id": "collection_80100614-300c-4609-959b-a138fa90f542", "collection_name": "SEC Filings", "created_at": "2025-09-16T18:36:09.790629Z", "index_configuration": { "model_name": "grok-embedding-small" }, "chunk_configuration": { "tokens_configuration": { "max_chunk_size_tokens": 1024, "chunk_overlap_tokens": 200, "encoding_name": "o200k_base" }, "strip_whitespace": true, "inject_name_into_chunks": false }, "documents_count": 0, "collection_description": "Filings from the SEC for financial analysis" } ``` -------------------------------- ### Streaming Example with Python Source: https://docs.x.ai/developers/tools/streaming-and-sync.md Use streaming mode for real-time observability of tool calls and immediate feedback during potentially long-running requests. This example shows how to process tool calls and content chunks as they arrive. ```pythonXAI import os from xai_sdk import Client from xai_sdk.chat import user from xai_sdk.tools import code_execution, web_search, x_search client = Client(api_key=os.getenv("XAI_API_KEY")) chat = client.chat.create( model="grok-4.3", tools=[ web_search(), x_search(), code_execution(), ], include=["verbose_streaming"], ) chat.append(user("What are the latest updates from xAI?")) is_thinking = True for response, chunk in chat.stream(): # View server-side tool calls in real-time for tool_call in chunk.tool_calls: print(f"\nCalling tool: {tool_call.function.name}") if response.usage.reasoning_tokens and is_thinking: print(f"\rThinking... ({response.usage.reasoning_tokens} tokens)", end="", flush=True) if chunk.content and is_thinking: print("\n\nFinal Response:") is_thinking = False if chunk.content and not is_thinking: print(chunk.content, end="", flush=True) print("\nCitations:", response.citations) ``` -------------------------------- ### Complete Batch Workflow Example Source: https://docs.x.ai/developers/advanced-api-usage/batch-api.md This example shows a full workflow for analyzing customer feedback using the Batch API. It covers creating a batch, adding requests, monitoring processing, and retrieving results. For large batches, refer to pagination details in the results retrieval step. ```python import time from xai_sdk import Client from xai_sdk.chat import system, user client = Client() # Sample dataset: customer feedback to analyze feedback_data = [ {"id": "fb_001", "text": "Absolutely love this product! Best purchase ever."}, {"id": "fb_002", "text": "Delivery was late and the packaging was damaged."}, {"id": "fb_003", "text": "Works fine, nothing special to report."}, {"id": "fb_004", "text": "Customer support was incredibly helpful!"}, {"id": "fb_005", "text": "The app keeps crashing on my phone."}, ] # Step 1: Create a batch print("Creating batch...") batch = client.batch.create(batch_name="feedback_sentiment_analysis") print(f"Batch created: {batch.batch_id}") # Step 2: Build and add requests print("\nAdding requests...") batch_requests = [] for item in feedback_data: chat = client.chat.create( model="grok-4.3", batch_request_id=item["id"], ) chat.append(system( "Analyze the sentiment of the customer feedback. " "Respond with exactly one word: positive, negative, or neutral." )) chat.append(user(item["text"])) batch_requests.append(chat) client.batch.add(batch_id=batch.batch_id, batch_requests=batch_requests) print(f"Added {len(batch_requests)} requests") # Step 3: Wait for completion print("\nProcessing...") while True: batch = client.batch.get(batch_id=batch.batch_id) pending = batch.state.num_pending completed = batch.state.num_success + batch.state.num_error print(f" {completed}/{batch.state.num_requests} complete") if pending == 0: break time.sleep(2) # Step 4: Retrieve and display results print("\n--- Results ---") results = client.batch.list_batch_results(batch_id=batch.batch_id) # Create a lookup for original feedback text feedback_lookup = {item["id"]: item["text"] for item in feedback_data} for result in results.succeeded: original_text = feedback_lookup.get(result.batch_request_id, "") sentiment = result.response.content.strip().lower() print(f"[{sentiment.upper()}] {original_text[:50]}...") # Report any failures if results.failed: print("\n--- Errors ---") for result in results.failed: print(f"[{result.batch_request_id}] {result.error_message}") # Display cost cost_usd = batch.cost_breakdown.total_cost_usd_ticks / 1e10 print("\nTotal cost: $%.4f" % cost_usd) ``` -------------------------------- ### Configure 4-Agent Setup with xAI SDK Source: https://docs.x.ai/developers/model-capabilities/text/multi-agent.md Use this snippet to initiate a chat with 4 agents using the xAI SDK. Ensure your XAI_API_KEY is set as an environment variable. This setup is best for quick research and focused queries. ```python import os from xai_sdk import Client from xai_sdk.chat import user client = Client(api_key=os.getenv("XAI_API_KEY")) chat = client.chat.create( model="grok-4.20-multi-agent", agent_count=4, ) chat.append(user("What are the key differences between TCP and UDP?")) for response, chunk in chat.stream(): if chunk.content: print(chunk.content, end="", flush=True) ``` -------------------------------- ### Install OpenAI Python SDK Source: https://docs.x.ai/developers/quickstart.md Install the OpenAI SDK for Python, which can be configured to work with the xAI API by setting the base URL. ```python pip install openai ``` -------------------------------- ### Configure 4-Agent Setup with Requests Library Source: https://docs.x.ai/developers/model-capabilities/text/multi-agent.md Use the Requests library to make a POST request for a 4-agent setup with 'low' reasoning effort. Ensure your XAI_API_KEY is available as an environment variable for authorization. ```python import os import requests url = "https://api.x.ai/v1/responses" headers = { "Content-Type": "application/json", "Authorization": f"Bearer {os.getenv('XAI_API_KEY')}" } payload = { "model": "grok-4.20-multi-agent", "reasoning": {"effort": "low"}, "input": [ { "role": "user", "content": "What are the key differences between TCP and UDP?" } ] } response = requests.post(url, headers=headers, json=payload) print(response.json()) ``` -------------------------------- ### Streaming Example with JavaScript Source: https://docs.x.ai/developers/tools/streaming-and-sync.md Use streaming mode for real-time observability of tool calls and immediate feedback during potentially long-running requests. This example shows how to process tool calls and content chunks as they arrive. ```javascriptAISDK import { xai } from '@ai-sdk/xai'; import { streamText } from 'ai'; const { fullStream } = streamText({ model: xai.responses('grok-4.3'), prompt: 'What are the latest updates from xAI?', tools: { web_search: xai.tools.webSearch(), x_search: xai.tools.xSearch(), code_execution: xai.tools.codeExecution(), }, }); for await (const part of fullStream) { if (part.type === 'tool-call') { console.log(`Calling tool: ${part.toolName}`); } else if (part.type === 'text-delta') { process.stdout.write(part.text); } else if (part.type === 'source' && part.sourceType === 'url') { console.log(`Citation: ${part.url}`); } } ``` -------------------------------- ### Configure 4-Agent Setup with Vercel AI SDK Source: https://docs.x.ai/developers/model-capabilities/text/multi-agent.md Initiate a text generation with a 4-agent setup using the Vercel AI SDK, setting reasoning effort to 'low'. This requires the '@ai-sdk/xai' and 'ai' packages. ```javascript import { xai } from "@ai-sdk/xai"; import { generateText } from "ai"; const { text } = await generateText({ model: xai.responses("grok-4.20-multi-agent"), prompt: "What are the key differences between TCP and UDP?", providerOptions: { xai: { reasoningEffort: "low" }, }, }); console.log(text); ``` -------------------------------- ### Get Voice Details (Python) Source: https://docs.x.ai/developers/rest-api-reference/inference/voice.md Obtain voice details using Python. This example demonstrates making an HTTP GET request and handling the JSON response. ```python import json import os import requests voice_id = "eve" response = requests.get( f"https://api.x.ai/v1/tts/voices/{voice_id}", headers={ "Authorization": f"Bearer {os.environ['XAI_API_KEY']}", }, ) print(json.dumps(response.json(), indent=2)) ``` -------------------------------- ### Define Client-Side Tool and SDK Setup Source: https://docs.x.ai/developers/tools/advanced-usage.md Set up the OpenAI client and define a client-side tool function. This includes importing necessary libraries, configuring the API key and base URL, and defining the tool's signature and parameters. ```python import os import json from openai import OpenAI client = OpenAI( api_key=os.getenv("XAI_API_KEY"), base_url="https://api.x.ai/v1", ) # Define client-side tool def get_weather(city: str) -> str: """Get the weather for a given city.""" # In a real app, this would query your database return f"The weather in {city} is sunny." model = "grok-4.3" tools = [ { "type": "function", "name": "get_weather", "description": "Get the weather for a given city.", "parameters": { "type": "object", "properties": { "city": { "type": "string", "description": "The name of the city", }, }, "required": ["city"], }, }, { "type": "web_search", }, ] ``` -------------------------------- ### Generate Image with ai SDK Source: https://docs.x.ai/developers/model-capabilities/images Generate images using the ai SDK for JavaScript. This example shows how to get the image data in base64 format. ```JavaScript import { xai } from "@ai-sdk/xai"; import { generateImage } from "ai"; const { image } = await generateImage({ model: xai.image("grok-imagine-image-quality"), prompt: "A collage of London landmarks in a stenciled street‑art style", }); console.log(image.base64); ``` -------------------------------- ### Initialize OpenAI SDK with xAI API Source: https://docs.x.ai/developers/tools/collections-search.md Shows how to initialize the OpenAI SDK to interact with the xAI API. Note that collections must be created and documents uploaded beforehand. ```python import os from openai import OpenAI # Using OpenAI SDK with xAI API (requires pre-created collection) api_key = os.getenv("XAI_API_KEY") client = OpenAI( api_key=api_key, base_url="https://api.x.ai/v1", ) # Note: You must create the collection and upload documents first using either the xAI console (console.x.ai) or the xAI SDK ``` -------------------------------- ### Basic X Search with xAI SDK Source: https://docs.x.ai/developers/tools/x-search.md Demonstrates how to use the xAI SDK to perform a search on X and stream the response. Ensure the XAI_API_KEY environment variable is set. ```pythonXAI import os from xai_sdk import Client from xai_sdk.chat import user from xai_sdk.tools import x_search client = Client(api_key=os.getenv("XAI_API_KEY")) chat = client.chat.create( model="grok-4.3", # reasoning model tools=[x_search()], include=["verbose_streaming"], ) chat.append(user("What are people saying about xAI on X?")) is_thinking = True for response, chunk in chat.stream(): for tool_call in chunk.tool_calls: print(f"\nCalling tool: {tool_call.function.name} with arguments: {tool_call.function.arguments}") if response.usage.reasoning_tokens and is_thinking: print(f"\rThinking... ({response.usage.reasoning_tokens} tokens)", end="", flush=True) if chunk.content and is_thinking: print("\n\nFinal Response:") is_thinking = False if chunk.content and not is_thinking: print(chunk.content, end="", flush=True) print("\n\nCitations:") print(response.citations) ``` -------------------------------- ### Create Response with Tools Source: https://docs.x.ai/developers/tools/streaming-and-sync.md This example demonstrates how to create a response using the OpenAI SDK, specifying a model, input, and available tools for processing. ```APIDOC ## POST /responses ### Description Creates a new response from the AI model, optionally using specified tools. ### Method POST ### Endpoint /v1/responses ### Parameters #### Request Body - **model** (string) - Required - The AI model to use for generating the response. - **input** (array) - Required - An array of message objects representing the conversation history. - **tools** (array) - Optional - A list of tools the model can use to generate the response. ### Request Example { "model": "grok-4.3", "input": [ { "role": "user", "content": "what is the latest update from xAI?" } ], "tools": [ { "type": "web_search" }, { "type": "x_search" } ] } ### Response #### Success Response (200) - **id** (string) - The unique identifier for the response. - **model** (string) - The model that generated the response. - **choices** (array) - An array of response choices. #### Response Example { "id": "resp_abc123", "model": "grok-4.3", "choices": [ { "message": { "role": "assistant", "content": "The latest update from xAI is..." } } ] } ``` -------------------------------- ### Get Custom Voice Details with JavaScript (Node.js) Source: https://docs.x.ai/developers/rest-api-reference/inference/voice.md Fetch a custom voice's details using JavaScript. This example assumes you are using Node.js and have your API key stored in environment variables. ```javascript const response = await fetch('https://api.x.ai/v1/custom-voices/nlbqfwie', { headers: { Authorization: `Bearer ${process.env.XAI_API_KEY}` }, }); console.log(JSON.stringify(await response.json(), null, 2)); ``` -------------------------------- ### Sample or Stream Response with OpenAI SDK Source: https://docs.x.ai/developers/tools/advanced-usage.md Use the OpenAI SDK to send a request to the API and receive a response. This example demonstrates setting up the client with an API key and base URL, and includes research tools like web search and code interpreter. ```python import os from openai import OpenAI api_key = os.getenv("XAI_API_KEY") client = OpenAI( api_key=api_key, base_url="https://api.x.ai/v1", ) response = client.responses.create( model="grok-4.3", input=[ { "role": "user", "content": "What is the average market cap of the companies with the top 5 market cap in the US stock market today?", }, ], # research_tools tools=[ { "type": "web_search", }, { "type": "code_interpreter", }, ], ) print(response) ``` -------------------------------- ### Connect to WebSocket with Ephemeral Token (Node.js) Source: https://docs.x.ai/developers/model-capabilities/audio/ephemeral-tokens.md This Node.js example shows how to connect to the xAI WebSocket API using an ephemeral token. The token is included in the 'Authorization' header during the WebSocket connection setup. ```javascript import WebSocket from "ws"; const baseUrl = "wss://api.x.ai/v1/realtime?model=grok-voice-latest"; // Connect with API key in Authorization header const ws = new WebSocket(baseUrl, { headers: { Authorization: "Bearer " + OBTAINED_EPHEMERAL_TOKEN, "Content-Type": "application/json", }, }); ws.on("open", () => { console.log("Connected with ephemeral token authentication"); }); ``` -------------------------------- ### JSON Response with Inline Citations Source: https://docs.x.ai/developers/tools/citations.md This JSON structure shows an example of response text containing an 'annotations' array with structured citation metadata. Each annotation includes type, URL, start and end indices, and a title. ```json { "created_at": 1781829888, "completed_at": 1781829888, "id": "5808284d-ae14-9981-9289-73515f67ebda", "max_output_tokens": null, "model": "grok-4.3", "object": "response", "output": [ ... { "content": [ { "type": "output_text", "text": "**xAI is an artificial intelligence company founded by Elon Musk in March 2023.** Its stated mission is to \"understand the universe\" by building advanced AI systems that accelerate human scientific discovery.[[1]](https://x.ai/company)\n\n### Key Details\n- **Flagship product**: Grok, a family of frontier AI models focused on reasoning, code, voice, image generation, and video. These are trained on massive infrastructure, including what the company describes as the world's largest supercluster (Colossus). Grok powers chatbots, APIs, and multimodal tools available via a unified API.[[2]](https://x.ai/)\n- **Current status (as of mid-2026)**: xAI operates as a subsidiary of SpaceX following an acquisition in February 2026. It is also connected to the X social platform (formerly Twitter), which xAI effectively became the parent of in 2025. The company has expanded into data centers and enterprise AI offerings (e.g., integrations with Amazon Bedrock and Databricks).[[3]](https://en.wikipedia.org/wiki/XAI_(company))\n- **Headquarters and team**: Based in the Stanford Research Park in Palo Alto, California. It was initially founded with a team of AI researchers and is led by Elon Musk as CEO.\n\nxAI positions itself as building maximally truth-seeking AI, distinct from other labs in its approach. Its official website (x.ai) highlights developer tools, API access, and ongoing model releases. Note that there is an unrelated blockchain/gaming project called Xai (xai.games), but the primary reference to \"xAI\" in this context is Musk's AI venture.[[4]](https://xai.games/)\n\nFor the latest updates, check x.ai or @xai on X.", "logprobs": [], "annotations": [ { "type": "url_citation", "url": "https://x.ai/company", "start_index": 208, "end_index": 235, "title": "1" }, { "type": "url_citation", "url": "https://x.ai/", "start_index": 585, "end_index": 605, "title": "2" }, { "type": "url_citation", "url": "https://en.wikipedia.org/wiki/XAI_(company)", "start_index": 972, "end_index": 1022, "title": "3" }, { "type": "url_citation", "url": "https://xai.games/", "start_index": 1555, "end_index": 1580, "title": "4" } ] } ], "id": "msg_5808284d-ae14-9981-9289-73515f67ebda", "role": "assistant", "type": "message", "status": "completed" } ], "parallel_tool_calls": true, "previous_response_id": null, "reasoning": { "effort": "low", "summary": "detailed" }, ... } ``` -------------------------------- ### Basic MCP Tool Usage with xAI SDK Source: https://docs.x.ai/developers/tools/remote-mcp.md Demonstrates how to use the xAI native SDK to connect to an MCP server and stream responses, including real-time tool call information. ```pythonXAI import os from xai_sdk import Client from xai_sdk.chat import user from xai_sdk.tools import mcp client = Client(api_key=os.getenv("XAI_API_KEY")) chat = client.chat.create( model="grok-4.3", tools=[ mcp(server_url="https://mcp.deepwiki.com/mcp"), ], include=["verbose_streaming"], ) chat.append(user("What can you do with https://github.com/xai-org/xai-sdk-python?")) is_thinking = True for response, chunk in chat.stream(): # View the server-side tool calls as they are being made in real-time for tool_call in chunk.tool_calls: print(f"\nCalling tool: {tool_call.function.name} with arguments: {tool_call.function.arguments}") if response.usage.reasoning_tokens and is_thinking: print(f"\rThinking... ({response.usage.reasoning_tokens} tokens)", end="", flush=True) if chunk.content and is_thinking: print("\n\nFinal Response:") is_thinking = False if chunk.content and not is_thinking: print(chunk.content, end="", flush=True) print("\n\nUsage:") print(response.usage) print(response.server_side_tool_usage) print("\n\nServer Side Tool Calls:") print(response.tool_calls) ``` -------------------------------- ### Make a Text Generation Request with cURL Source: https://docs.x.ai/developers/quickstart.md Send a POST request to the xAI API endpoint using cURL to get a text response from the grok-4.3 model. This example demonstrates how to set headers and provide the request payload. ```bash curl https://api.x.ai/v1/responses \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $XAI_API_KEY" \ -d '{ "model": "grok-4.3", "input": [ {"role": "system", "content": "You are Grok, a highly intelligent, helpful AI assistant."}, {"role": "user", "content": "What is the meaning of life, the universe, and everything?"} ] }' ``` -------------------------------- ### Processing TTS Response with Timestamps (JavaScript) Source: https://docs.x.ai/developers/model-capabilities/audio/text-to-speech.md This JavaScript example shows how to request text-to-speech with character timestamps, save the decoded audio, and log each character's start and end times. It requires Node.js and the `fetch` API. ```javascript import fs from "fs"; const response = await fetch("https://api.x.ai/v1/tts", { method: "POST", headers: { Authorization: `Bearer ${process.env.XAI_API_KEY}`, "Content-Type": "application/json", }, body: JSON.stringify({ text: "Hello world.", voice_id: "eve", language: "en", with_timestamps: true, }), }); if (!response.ok) throw new Error(`TTS error ${response.status}`); const payload = await response.json(); // The audio is base64-encoded — decode it exactly like a normal response fs.writeFileSync("hello.mp3", Buffer.from(payload.audio, "base64")); const { graph_chars, graph_times } = payload.audio_timestamps; graph_chars.forEach((char, i) => { const [start, end] = graph_times[i]; console.log(`${JSON.stringify(char).padStart(5)} ${start.toFixed(2)}s – ${end.toFixed(2)}s`); }); console.log(`duration: ${payload.duration.toFixed(2)}s`); ``` -------------------------------- ### Compute Collatz Steps with XAI SDK and Structured Output (Python) Source: https://docs.x.ai/developers/model-capabilities/text/structured-outputs.md This example demonstrates using the XAI SDK to define a tool for computing Collatz sequence steps and handling structured output. It includes setting up the client, defining the tool, and parsing the final response into a Pydantic model. ```python import os import json from pydantic import BaseModel, Field from xai_sdk import Client from xai_sdk.chat import tool, tool_result, user # CollatzResult schema defined above def collatz_steps(n: int) -> int: """Returns the number of steps for n to reach 1 in the Collatz sequence.""" steps = 0 while n != 1: n = n // 2 if n % 2 == 0 else 3 * n + 1 steps += 1 return steps collatz_tool = tool( name="collatz_steps", description="Compute the number of steps for a number to reach 1 in the Collatz sequence", parameters={ "type": "object", "properties": { "n": {"type": "integer", "description": "The starting number"}, }, "required": ["n"], }, ) client = Client(api_key=os.getenv("XAI_API_KEY")) chat = client.chat.create( model="grok-4.3", tools=[collatz_tool], ) chat.append(user("Use the collatz_steps tool to find how many steps it takes for 20250709 to reach 1.")) # Handle tool calls until we get a final response while True: response = chat.sample() if not response.tool_calls: break chat.append(response) for tc in response.tool_calls: args = json.loads(tc.function.arguments) result = collatz_steps(args["n"]) chat.append(tool_result(str(result))) # Parse the final response into structured output response, result = chat.parse(CollatzResult) print(f"Starting number: {result.starting_number}") print(f"Steps to reach 1: {result.steps}") ``` -------------------------------- ### Generate Video with Reference Images Source: https://docs.x.ai/developers/model-capabilities/video/reference-to-video.md This example demonstrates how to initiate a video generation request using a text prompt and reference images, and then poll for the result. ```APIDOC ## POST /v1/videos/generations ### Description Initiates a video generation request using a text prompt and reference images. Returns a request ID to poll for the video status and URL. ### Method POST ### Endpoint https://api.x.ai/v1/videos/generations ### Request Body - **model** (string) - Required - The model to use for generation (e.g., "grok-imagine-video"). - **prompt** (string) - Required - The text prompt describing the desired video content. - **reference_images** (array) - Required - A list of objects, each containing a URL to a reference image. - **url** (string) - Required - The URL of the reference image. - **duration** (integer) - Optional - The desired duration of the video in seconds. - **aspect_ratio** (string) - Optional - The desired aspect ratio of the video (e.g., "16:9"). - **resolution** (string) - Optional - The desired resolution of the video (e.g., "720p"). ### Request Example ```json { "model": "grok-imagine-video", "prompt": "slow zoom in on the white fashion runway stage. then, the model from walks in from the back of the shot from the white opening, and gracefully walk out onto the front of the white stage platform. they wear the shirt from and black flared jeans. they look dramatically at the camera. high quality slow motion shot. fun, playful. skin pores. highly detailed faces. perfect shot. they reach the end of the runway and look at the camera as the camera slowly zooms. subtle smile.", "reference_images": [ {"url": ""}, {"url": ""}, {"url": ""} ], "duration": 10, "aspect_ratio": "16:9", "resolution": "720p" } ``` ## GET /v1/videos/{request_id} ### Description Polls for the status and result of a video generation request using the provided request ID. ### Method GET ### Endpoint https://api.x.ai/v1/videos/{request_id} ### Parameters #### Path Parameters - **request_id** (string) - Required - The ID of the video generation request. ### Response #### Success Response (200) - **status** (string) - The current status of the request (e.g., "done", "failed", "expired"). - **video** (object) - Present if status is "done". - **url** (string) - The URL of the generated video. ### Response Example ```json { "status": "done", "video": { "url": "https://cdn.x.ai/videos/generated/example.mp4" } } ``` ``` -------------------------------- ### GET /v1/batches/{batch_id} Source: https://docs.x.ai/developers/rest-api-reference/inference/batches.md Get information about a specific batch. ```APIDOC ## GET /v1/batches/{batch_id} ### Description Get information about a specific batch. ### Method GET ### Endpoint /v1/batches/{batch_id} ### Parameters #### Path Parameters - **batch_id** (string) - Required - The unique identifier of the batch ``` -------------------------------- ### AIP-160 Filter String Examples: Complex Examples Source: https://docs.x.ai/developers/files/collections/metadata.md Provides examples of complex filter strings combining multiple conditions, logical operators, and nested logic using parentheses for precise filtering. ```bash # Multiple conditions author="Sandra Kim" AND year>=2020 AND status!="draft" # Nested logic with parentheses (author="Sandra Kim" OR author="John Doe") AND year>=2020 # Multiple fields with mixed operators category="finance" AND (year=2023 OR year=2024) AND status!="archived" ``` -------------------------------- ### Generate Video via API with Storage Options Source: https://docs.x.ai/developers/model-capabilities/imagine/files/outputs.md Initiate video generation using a direct API call and poll for the result. This example demonstrates how to set the filename and request a public URL for the output video. ```bash # Start the generation REQUEST_ID=$(curl -s -X POST https://api.x.ai/v1/videos/generations \ -H "Authorization: Bearer $XAI_API_KEY" \ -H "Content-Type: application/json" \ -d '{ \ "model": "grok-imagine-video", \ "prompt": "A ball bouncing slowly on a flat surface", \ "duration": 5, \ "storage_options": {"filename": "bouncing-ball.mp4", "public_url": true} \ }' | jq -r '.request_id') # Poll until done while true; do RESULT=$(curl -s "https://api.x.ai/v1/videos/$REQUEST_ID" \ -H "Authorization: Bearer $XAI_API_KEY") STATUS=$(echo "$RESULT" | jq -r '.status') if [ "$STATUS" = "done" ]; then echo "$RESULT" | jq '.video.file_output' break fi sleep 5 done ``` -------------------------------- ### Create a Batch with JavaScript (No SDK) Source: https://docs.x.ai/developers/advanced-api-usage/batch-api.md This JavaScript example demonstrates creating a batch using the fetch API without relying on an SDK. Ensure your API key is securely managed. ```javascript // Create a batch with a descriptive name const response = await fetch("https://api.x.ai/v1/batches", { method: "POST", headers: { "Content-Type": "application/json", Authorization: `Bearer ${process.env.XAI_API_KEY}`, }, body: JSON.stringify({ name: "customer_feedback_analysis" }), }); const batch = await response.json(); console.log(`Created batch: ${batch.batch_id}`); // Store the batch_id for later use const batchId = batch.batch_id; ``` -------------------------------- ### Example JSON Output Source: https://docs.x.ai/developers/model-capabilities/text/structured-outputs.md This is an example of a structured JSON output that respects an input schema. ```json { "vendor_name": "Acme Corp", "vendor_address": { "street": "123 Main St", "city": "Springfield", "postal_code": "62704", "country": "IL" }, "invoice_number": "INV-2025-001", "invoice_date": "2025-02-10", "line_items": [ { "description": "Widget A", "quantity": 5, "unit_price": 10.0 }, { "description": "Widget B", "quantity": 2, "unit_price": 15.0 } ], "total_amount": 80.0, "currency": "USD" } ``` -------------------------------- ### Python SDK Example Source: https://docs.x.ai/developers/quickstart.md Generate an image using the xai_sdk Python library. ```APIDOC ## Generate an image with Python SDK ### Description Use the `xai_sdk` to generate an image from a text prompt. ### Method ```python client.image.sample( prompt="A futuristic city skyline at sunset", model="grok-imagine-image-quality", ) ``` ### Parameters * **prompt** (string) - Required - The text description for the image. * **model** (string) - Required - The image generation model to use. ``` -------------------------------- ### Chat Completion Response Example Source: https://docs.x.ai/developers/rest-api-reference/inference/chat.md Example of a chat completion response, showing the generated message, usage statistics, and other metadata. ```json { "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" } ``` -------------------------------- ### Basic Python Code Execution Setup Source: https://docs.x.ai/developers/tools/code-execution.md Set up the code execution tool for basic Python calculations using the xAI SDK. Ensure your XAI_API_KEY is set as an environment variable. ```pythonXAI import os from xai_sdk import Client from xai_sdk.chat import user from xai_sdk.tools import code_execution client = Client(api_key=os.getenv("XAI_API_KEY")) chat = client.chat.create( model="grok-4.3", # reasoning model tools=[code_execution()], include=["verbose_streaming"], ) ``` -------------------------------- ### Image Edit API Response Example Source: https://docs.x.ai/developers/rest-api-reference/inference/images.md This is an example of the JSON response structure you can expect after successfully editing an image using the API. ```json { "data": [ { "url": "..." } ] } ``` -------------------------------- ### Generate Speech with JavaScript Source: https://docs.x.ai/developers/model-capabilities/audio/text-to-speech.md This JavaScript example demonstrates how to use the fetch API to generate speech. It requires Node.js and saves the audio to 'hello.mp3'. ```javascript import fs from "fs"; const response = await fetch("https://api.x.ai/v1/tts", { method: "POST", headers: { Authorization: `Bearer ${process.env.XAI_API_KEY}`, "Content-Type": "application/json", }, body: JSON.stringify({ text: "Hello! Welcome to the xAI Text to Speech API.", voice_id: "eve", language: "en", }), }); if (!response.ok) throw new Error(`TTS error ${response.status}`); const buffer = Buffer.from(await response.arrayBuffer()); fs.writeFileSync("hello.mp3", buffer); console.log(`Saved ${buffer.length.toLocaleString()} bytes to hello.mp3`); ``` -------------------------------- ### Retrieve Postpaid Spending Limits Response Example Source: https://docs.x.ai/developers/rest-api-reference/management/billing.md Example JSON response showing the hard and soft spending limits for a team. ```json { "spendingLimits": { "hardSlAuto": { "val": "22500" }, "effectiveHardSl": { "val": "22500" }, "softSl": { "val": "20000" }, "effectiveSl": { "val": "20000" } } } ``` -------------------------------- ### Chat with Files using JavaScript (No SDK) Source: https://docs.x.ai/developers/files.md This example demonstrates how to interact with files for chat purposes without using the official SDK. It covers referencing files by URL or ID, uploading new files, sending chat requests with file attachments, and cleaning up uploaded files. ```javascript // 1a. Reference a public file by URL const fileUrl = "https://docs.x.ai/assets/api-examples/documents/sales-report.txt"; // 1b. Or upload a file and reference by ID const formData = new FormData(); formData.append("file", new Blob(["Employee: Alice Johnson\nDepartment: Engineering"], { type: "text/plain" }), "employee.txt"); formData.append("purpose", "assistants"); const uploadRes = await fetch("https://api.x.ai/v1/files", { method: "POST", headers: { Authorization: `Bearer ${process.env.XAI_API_KEY}` }, body: formData, }); const uploadedFile = await uploadRes.json(); // 2. Chat with files const chatRes = await fetch("https://api.x.ai/v1/responses", { method: "POST", headers: { "Content-Type": "application/json", Authorization: `Bearer ${process.env.XAI_API_KEY}`, }, body: JSON.stringify({ model: "grok-4.3", input: [ { role: "user", content: [ { type: "input_text", text: "Summarize both documents" }, { type: "input_file", file_url: fileUrl }, { type: "input_file", file_id: uploadedFile.id }, ], }, ], }), }); // 3. Get the answer const chatData = await chatRes.json(); const lastMessage = chatData.output[chatData.output.length - 1]; const answer = lastMessage?.content?.find((c) => c.type === "output_text")?.text; console.log(answer); // 4. Clean up await fetch(`https://api.x.ai/v1/files/${uploadedFile.id}`, { method: "DELETE", headers: { Authorization: `Bearer ${process.env.XAI_API_KEY}` }, }); ``` -------------------------------- ### Example Image Search Response Source: https://docs.x.ai/developers/tools/web-search.md This is an example of how an image search result might appear in the response content, formatted as a Markdown image embed. ```output ![Why the SpaceX Starship launch pad matters](https://www.astronomy.com/wp-content/uploads/2024/09/starship-test-flight-mission-scaled.jpg) Here are several high-quality images of SpaceX's Starship on the launch pad at Starbase in Boca Chica, Texas. ``` -------------------------------- ### Defining Tools with OpenAI SDK Source: https://docs.x.ai/developers/tools/function-calling.md This example demonstrates how to define a list of tools, including built-in web search and a custom function for saving data, compatible with the OpenAI SDK. Custom functions are specified with a type, name, description, and parameters. ```pythonOpenAISDK tools = [ {"type": "web_search"}, # Built-in {"type": "x_search"}, # Built-in { "type": "function", "name": "save_to_database", "description": "Save research results to the database", "parameters": { "type": "object", "properties": { "data": {"type": "string", "description": "Data to save"} }, "required": ["data"] }, }, ] ``` -------------------------------- ### Image Generation Response Example Source: https://docs.x.ai/developers/rest-api-reference/inference/images.md This is an example of a successful response from the Images API, showing the structure of the 'data' field containing image URLs. ```json { "data": [ { "url": "..." }, { "url": "..." } ] } ``` -------------------------------- ### Example: First Request for Prompt Caching Source: https://docs.x.ai/developers/advanced-api-usage/prompt-caching/how-it-works.md This represents the initial request where the full prompt is processed and cached. ```text [system] "You are a helpful assistant." [user] "What is the capital of France?" [assistant] "The capital of France is Paris." ``` -------------------------------- ### Retrieve Invoice Response Example Source: https://docs.x.ai/developers/rest-api-reference/management/billing.md Example JSON response for a team invoice, showing line items and credit details in USD cents. ```json { "coreInvoice": { "lines": [], "amountBeforeVat": "0", "vatCost": "0", "amountAfterVat": "0", "autoCreditsIssued": "0", "defaultCreditsIssued": "0", "totalWithCorr": { "val": "0" }, "prepaidCredits": { "val": "-4500" }, "prepaidCreditsUsed": { "val": "0" } }, "effectiveSpendingLimit": "20000", "defaultCredits": "0", "billingCycle": { "year": 2025, "month": 11 } } ``` -------------------------------- ### Delete Response Example Source: https://docs.x.ai/developers/rest-api-reference/inference/chat.md Example of a successful response after deleting a previously generated response. It confirms the deletion status and provides the ID and object type. ```json { "id": "ad5663da-63e6-86c6-e0be-ff15effa8357", "object": "response", "deleted": true } ``` -------------------------------- ### Legacy Inference API Request Example Source: https://docs.x.ai/developers/rest-api-reference/inference/legacy.md Example of a request body for the legacy inference API. It specifies the model, maximum tokens, and user messages. ```json { "model": "latest", "max_tokens": 32, "messages": [ { "role": "user", "content": "Hello, world" } ] } ```