SPB Git

Repository Public

managing-files.md 20.2 KB 764 lines markdown

1<!-- source: https://docs.x.ai/developers/files/managing-files (from https://docs.x.ai/llms-full.txt, retrieved 2026-09-19T05:28:55Z) -->2#### Files & Collections34# Managing Files56The Files API provides a complete set of operations for managing your files. If your files are publicly accessible, you can reference them directly by URL in chat conversations — see [Attaching Files](/developers/model-capabilities/files/chat-with-files#attaching-files). For files that aren't publicly accessible, upload them using one of the methods described below.78You can also view and manage all of your uploaded files from the [Files page](https://console.x.ai/team/default/files?utm_source=docs\&utm_medium=referral\&utm_campaign=developers-files-managing-files\&utm_content=files) on the xAI Console.910## Uploading Files1112You can upload files in several ways: from a file path, raw bytes, BytesIO object, or an open file handle.1314### Upload from File Path1516```pythonXAI17import os18from xai_sdk import Client1920client = Client(api_key=os.getenv("XAI_API_KEY"))2122# Upload a file from disk23file = client.files.upload("/path/to/your/document.pdf")2425print(f"File ID: {file.id}")26print(f"Filename: {file.filename}")27print(f"Size: {file.size} bytes")28print(f"Created at: {file.created_at}")29```3031```pythonOpenAISDK32import os33from openai import OpenAI3435client = OpenAI(36    api_key=os.getenv("XAI_API_KEY"),37    base_url="https://api.x.ai/v1",38)3940# Upload a file41with open("/path/to/your/document.pdf", "rb") as f:42    file = client.files.create(43        file=f,44        purpose="assistants"45    )4647print(f"File ID: {file.id}")48print(f"Filename: {file.filename}")49```5051```pythonRequests52import os53import requests5455url = "https://api.x.ai/v1/files"56headers = {57    "Authorization": f"Bearer {os.getenv('XAI_API_KEY')}"58}5960with open("/path/to/your/document.pdf", "rb") as f:61    files = {"file": f}62    data = {"purpose": "assistants"}63    response = requests.post(url, headers=headers, files=files, data=data)6465file_data = response.json()66print(f"File ID: {file_data['id']}")67print(f"Filename: {file_data['filename']}")68```6970```javascriptOpenAISDK71import OpenAI from "openai";72import fs from "fs";7374const client = new OpenAI({75    apiKey: process.env.XAI_API_KEY,76    baseURL: "https://api.x.ai/v1",77});7879// Upload a file80const file = await client.files.create({81    file: fs.createReadStream("/path/to/your/document.pdf"),82    purpose: "assistants",83});8485console.log("File ID: " + file.id);86console.log("Filename: " + file.filename);87```8889```javascriptWithoutSDK90import fs from "fs";9192const formData = new FormData();93formData.append("file", new Blob([fs.readFileSync("/path/to/your/document.pdf")]), "document.pdf");94formData.append("purpose", "assistants");9596const response = await fetch("https://api.x.ai/v1/files", {97  method: "POST",98  headers: { Authorization: \`Bearer \${process.env.XAI_API_KEY}\` },99  body: formData,100});101102const file = await response.json();103console.log("File ID: " + file.id);104console.log("Filename: " + file.filename);105```106107```bash108curl https://api.x.ai/v1/files \\109  -H "Authorization: Bearer $XAI_API_KEY" \\110  -F file=@/path/to/your/document.pdf \\111  -F purpose=assistants112```113114### Upload from Bytes115116```pythonXAI117import os118from xai_sdk import Client119120client = Client(api_key=os.getenv("XAI_API_KEY"))121122# Upload file content directly from bytes123content = b"This is my document content.\\nIt can span multiple lines."124file = client.files.upload(content, filename="document.txt")125126print(f"File ID: {file.id}")127print(f"Filename: {file.filename}")128```129130### Upload from file object131132```pythonXAI133import os134from xai_sdk import Client135136client = Client(api_key=os.getenv("XAI_API_KEY"))137138# Upload a file directly from disk139file = client.files.upload(open("document.pdf", "rb"), filename="document.pdf")140141print(f"File ID: {file.id}")142print(f"Filename: {file.filename}")143```144145## Upload with Expiration (TTL)146147Files default to permanent storage until you delete them. To have the platform automatically delete a file after a fixed window, set `expires_after` at upload time. This is useful for short-lived attachments, ephemeral session data, and compliance windows.148149### How it works150151`expires_after` is set in seconds, measured from upload time. It must be between `3600` (1 hour) and `2592000` (30 days), inclusive. Omit the field to keep the file permanently.152153The response includes `expires_at`, the absolute UTC timestamp at which the file will be deleted. Once that time passes, the file is gone: it no longer appears in list responses, retrieving its metadata or content returns `not found`, and it can no longer be referenced by `id` in chat attachments.154155You can also delete the file manually at any time before its TTL elapses.156157> [!WARNING]158>159> **Multipart field ordering matters**: `expires_after` must appear **before** the `file` field in the multipart body. Requests that send `expires_after` after `file` are rejected with `400`.160161```pythonXAI162import os163from datetime import timedelta164from xai_sdk import Client165166client = Client(api_key=os.getenv("XAI_API_KEY"))167168# Upload a file that will be auto-deleted in 24 hours.169# expires_after accepts an int (seconds) or a datetime.timedelta.170file = client.files.upload(171    "/path/to/document.pdf",172    expires_after=timedelta(hours=24),173)174175print(f"File ID: {file.id}")176print(f"Expires at: {file.expires_at.ToDatetime()}")177```178179```pythonOpenAISDK180import os181from openai import OpenAI182183client = OpenAI(184    api_key=os.getenv("XAI_API_KEY"),185    base_url="https://api.x.ai/v1",186)187188# expires_after follows the OpenAI shape: an object anchored at "created_at".189with open("/path/to/document.pdf", "rb") as f:190    file = client.files.create(191        file=f,192        purpose="assistants",193        expires_after={"anchor": "created_at", "seconds": 86400},  # 24 hours194    )195196print(f"File ID: {file.id}")197print(f"Expires at: {file.expires_at}")  # Unix seconds, 24h from now198```199200```pythonRequests201import os202import requests203204url = "https://api.x.ai/v1/files"205headers = {206    "Authorization": f"Bearer {os.getenv('XAI_API_KEY')}"207}208209# expires_after MUST appear before file in the multipart body — see the note below.210with open("/path/to/document.pdf", "rb") as f:211    response = requests.post(212        url,213        headers=headers,214        data=[215            ("expires_after", "86400"),  # 24 hours in seconds216            ("purpose", "assistants"),217        ],218        files={"file": f},219    )220221file_data = response.json()222print(f"File ID: {file_data['id']}")223print(f"Expires at: {file_data['expires_at']}")224```225226```javascriptOpenAISDK227import OpenAI from "openai";228import fs from "fs";229230const client = new OpenAI({231    apiKey: process.env.XAI_API_KEY,232    baseURL: "https://api.x.ai/v1",233});234235const file = await client.files.create({236    file: fs.createReadStream("/path/to/document.pdf"),237    purpose: "assistants",238    expires_after: { anchor: "created_at", seconds: 86400 },  // 24 hours239});240241console.log("File ID: " + file.id);242console.log("Expires at: " + file.expires_at);243```244245```javascriptWithoutSDK246import fs from "fs";247248const formData = new FormData();249// expires_after MUST be appended before the file field.250formData.append("expires_after", "86400");  // 24 hours in seconds251formData.append("purpose", "assistants");252formData.append(253  "file",254  new Blob([fs.readFileSync("/path/to/document.pdf")]),255  "document.pdf",256);257258const response = await fetch("https://api.x.ai/v1/files", {259  method: "POST",260  headers: { Authorization: \`Bearer \${process.env.XAI_API_KEY}\` },261  body: formData,262});263264const file = await response.json();265console.log("File ID: " + file.id);266console.log("Expires at: " + file.expires_at);267```268269```bash270# -F fields are sent in declaration order.271# expires_after must come before file in the form body.272curl https://api.x.ai/v1/files \\273  -H "Authorization: Bearer $XAI_API_KEY" \\274  -F expires_after=86400 \\275  -F purpose=assistants \\276  -F file=@/path/to/document.pdf277```278279## Upload with Progress Tracking280281Track upload progress for large files using callbacks or progress bars.282283```pythonXAI284import os285from xai_sdk import Client286287client = Client(api_key=os.getenv("XAI_API_KEY"))288289# Define a custom progress callback290def progress_callback(bytes_uploaded: int, total_bytes: int):291    percentage = (bytes_uploaded / total_bytes) * 100 if total_bytes else 0292    mb_uploaded = bytes_uploaded / (1024 * 1024)293    mb_total = total_bytes / (1024 * 1024)294    print(f"Progress: {mb_uploaded:.2f}/{mb_total:.2f} MB ({percentage:.1f}%)")295296# Upload with progress tracking297file = client.files.upload(298    "/path/to/large-file.pdf",299    on_progress=progress_callback300)301302print(f"Successfully uploaded: {file.filename}")303```304305## Listing Files306307Retrieve a list of your uploaded files with pagination and sorting options.308309### Available Options310311* **`limit`**: Maximum number of files to return. If not specified, uses the server default of 100. Maximum is 100.312* **`order`**: Sort order. Either `"asc"` (ascending) or `"desc"` (descending). Defaults to `"desc"`.313* **`sort_by`**: Field to sort by. Options: `"created_at"`, `"filename"`, or `"size"`. Defaults to `"created_at"`.314* **`pagination_token`**: Pass the `pagination_token` returned by the previous response to fetch the next page. Omit it for the first page.315316The response always includes a `pagination_token`. When the returned page is shorter than `limit`, you've reached the end of the list.317318```pythonXAI319import os320from xai_sdk import Client321322client = Client(api_key=os.getenv("XAI_API_KEY"))323324# List files with pagination and sorting325response = client.files.list(326    limit=10,327    order="desc",328    sort_by="created_at"329)330331for file in response.data:332    expires = file.expires_at.ToDatetime() if file.HasField("expires_at") else "never"333    print(f"File: {file.filename} (ID: {file.id}, Size: {file.size} bytes, Expires: {expires})")334```335336```pythonOpenAISDK337import os338from openai import OpenAI339340client = OpenAI(341    api_key=os.getenv("XAI_API_KEY"),342    base_url="https://api.x.ai/v1",343)344345# List files346files = client.files.list()347348for file in files.data:349    print(f"File: {file.filename} (ID: {file.id})")350```351352```pythonRequests353import os354import requests355356url = "https://api.x.ai/v1/files"357headers = {358    "Authorization": f"Bearer {os.getenv('XAI_API_KEY')}"359}360361response = requests.get(url, headers=headers)362files = response.json()363364for file in files.get("data", []):365    print(f"File: {file['filename']} (ID: {file['id']})")366```367368```javascriptOpenAISDK369import OpenAI from "openai";370371const client = new OpenAI({372    apiKey: process.env.XAI_API_KEY,373    baseURL: "https://api.x.ai/v1",374});375376// List files377const files = await client.files.list();378379for (const file of files.data) {380    console.log(\`File: \${file.filename} (ID: \${file.id})\`);381}382```383384```javascriptWithoutSDK385const response = await fetch("https://api.x.ai/v1/files", {386  headers: { Authorization: \`Bearer \${process.env.XAI_API_KEY}\` },387});388389const files = await response.json();390391for (const file of files.data) {392  console.log(\`File: \${file.filename} (ID: \${file.id})\`);393}394```395396```bash397curl https://api.x.ai/v1/files \\398  -H "Authorization: Bearer $XAI_API_KEY"399```400401### Paginating Through All Files402403The List endpoint returns at most `limit` files per call (capped at 100). To enumerate every file, keep calling the endpoint with the `pagination_token` from the previous response until the response returns fewer than `limit` items.404405```pythonXAI406import os407from xai_sdk import Client408409client = Client(api_key=os.getenv("XAI_API_KEY"))410411# Walk every page until the API returns a short page.412page_size = 100413token = None414all_files = []415416while True:417    response = client.files.list(418        limit=page_size,419        order="desc",420        sort_by="created_at",421        pagination_token=token,422    )423    all_files.extend(response.data)424    if len(response.data) < page_size:425        break426    token = response.pagination_token427428print(f"Total files: {len(all_files)}")429```430431```pythonRequests432import os433import requests434435url = "https://api.x.ai/v1/files"436headers = {"Authorization": f"Bearer {os.getenv('XAI_API_KEY')}"}437438page_size = 100439params = {"limit": page_size, "order": "desc", "sort_by": "created_at"}440all_files = []441442while True:443    response = requests.get(url, headers=headers, params=params).json()444    all_files.extend(response.get("data", []))445    if len(response.get("data", [])) < page_size:446        break447    params["pagination_token"] = response["pagination_token"]448449print(f"Total files: {len(all_files)}")450```451452```javascriptWithoutSDK453const pageSize = 100;454const baseParams = { limit: String(pageSize), order: "desc", sort_by: "created_at" };455const allFiles = [];456let token;457458while (true) {459  const params = new URLSearchParams({ ...baseParams, ...(token ? { pagination_token: token } : {}) });460  const response = await fetch(\`https://api.x.ai/v1/files?\${params}\`, {461    headers: { Authorization: \`Bearer \${process.env.XAI_API_KEY}\` },462  });463  const page = await response.json();464  allFiles.push(...page.data);465  if (page.data.length < pageSize) break;466  token = page.pagination_token;467}468469console.log(\`Total files: \${allFiles.length}\`);470```471472## Getting File Metadata473474Retrieve detailed information about a specific file.475476```pythonXAI477import os478from xai_sdk import Client479480client = Client(api_key=os.getenv("XAI_API_KEY"))481482# Get file metadata by ID483file = client.files.get("file-abc123")484485print(f"Filename: {file.filename}")486print(f"Size: {file.size} bytes")487print(f"Created: {file.created_at}")488# expires_at is only set when the file was uploaded with expires_after489if file.HasField("expires_at"):490    print(f"Expires at: {file.expires_at.ToDatetime()}")491```492493```pythonOpenAISDK494import os495from openai import OpenAI496497client = OpenAI(498    api_key=os.getenv("XAI_API_KEY"),499    base_url="https://api.x.ai/v1",500)501502# Get file metadata503file = client.files.retrieve("file-abc123")504505print(f"Filename: {file.filename}")506print(f"Size: {file.bytes} bytes")507# Unix seconds, or None if the file does not expire.508print(f"Expires at: {file.expires_at}")509```510511```pythonRequests512import os513import requests514515file_id = "file-abc123"516url = f"https://api.x.ai/v1/files/{file_id}"517headers = {518    "Authorization": f"Bearer {os.getenv('XAI_API_KEY')}"519}520521response = requests.get(url, headers=headers)522file = response.json()523524print(f"Filename: {file['filename']}")525print(f"Size: {file['bytes']} bytes")526```527528```javascriptOpenAISDK529import OpenAI from "openai";530531const client = new OpenAI({532    apiKey: process.env.XAI_API_KEY,533    baseURL: "https://api.x.ai/v1",534});535536// Get file metadata537const file = await client.files.retrieve("file-abc123");538539console.log("Filename: " + file.filename);540console.log("Size: " + file.bytes + " bytes");541```542543```javascriptWithoutSDK544const response = await fetch("https://api.x.ai/v1/files/file-abc123", {545  headers: { Authorization: \`Bearer \${process.env.XAI_API_KEY}\` },546});547548const file = await response.json();549console.log("Filename: " + file.filename);550console.log("Size: " + file.bytes + " bytes");551```552553```bash554curl https://api.x.ai/v1/files/file-abc123 \\555  -H "Authorization: Bearer $XAI_API_KEY"556```557558## Getting File Content559560Download the raw bytes of an uploaded file. The endpoint streams the response, so it works for files of any supported size without buffering the whole payload in memory at the API layer.561562```pythonXAI563import os564from xai_sdk import Client565566client = Client(api_key=os.getenv("XAI_API_KEY"))567568# Returns the complete file content as bytes.569content = client.files.content("file-abc123")570571# Save to disk572with open("downloaded.pdf", "wb") as f:573    f.write(content)574575print(f"Saved {len(content)} bytes")576```577578```pythonOpenAISDK579import os580from openai import OpenAI581582client = OpenAI(583    api_key=os.getenv("XAI_API_KEY"),584    base_url="https://api.x.ai/v1",585)586587# Stream content straight to disk588client.files.content("file-abc123").write_to_file("downloaded.pdf")589```590591```pythonRequests592import os593import requests594595file_id = "file-abc123"596url = f"https://api.x.ai/v1/files/{file_id}/content"597headers = {"Authorization": f"Bearer {os.getenv('XAI_API_KEY')}"}598599# Stream to disk so large files don't sit in memory600with requests.get(url, headers=headers, stream=True) as response:601    response.raise_for_status()602    with open("downloaded.pdf", "wb") as f:603        for chunk in response.iter_content(chunk_size=1024 * 1024):604            f.write(chunk)605```606607```javascriptOpenAISDK608import OpenAI from "openai";609import fs from "fs";610611const client = new OpenAI({612    apiKey: process.env.XAI_API_KEY,613    baseURL: "https://api.x.ai/v1",614});615616const response = await client.files.content("file-abc123");617const buffer = Buffer.from(await response.arrayBuffer());618fs.writeFileSync("downloaded.pdf", buffer);619```620621```javascriptWithoutSDK622import fs from "fs";623624const response = await fetch("https://api.x.ai/v1/files/file-abc123/content", {625  headers: { Authorization: \`Bearer \${process.env.XAI_API_KEY}\` },626});627628const buffer = Buffer.from(await response.arrayBuffer());629fs.writeFileSync("downloaded.pdf", buffer);630```631632```bash633curl https://api.x.ai/v1/files/file-abc123/content \\634  -H "Authorization: Bearer $XAI_API_KEY" \\635  --output downloaded.pdf636```637638## Deleting Files639640Remove files when they're no longer needed.641642```pythonXAI643import os644from xai_sdk import Client645646client = Client(api_key=os.getenv("XAI_API_KEY"))647648# Delete a file649delete_response = client.files.delete("file-abc123")650651print(f"Deleted: {delete_response.deleted}")652print(f"File ID: {delete_response.id}")653```654655```pythonOpenAISDK656import os657from openai import OpenAI658659client = OpenAI(660    api_key=os.getenv("XAI_API_KEY"),661    base_url="https://api.x.ai/v1",662)663664# Delete a file665delete_response = client.files.delete("file-abc123")666667print(f"Deleted: {delete_response.deleted}")668print(f"File ID: {delete_response.id}")669```670671```pythonRequests672import os673import requests674675file_id = "file-abc123"676url = f"https://api.x.ai/v1/files/{file_id}"677headers = {678    "Authorization": f"Bearer {os.getenv('XAI_API_KEY')}"679}680681response = requests.delete(url, headers=headers)682result = response.json()683684print(f"Deleted: {result['deleted']}")685print(f"File ID: {result['id']}")686```687688```javascriptOpenAISDK689import OpenAI from "openai";690691const client = new OpenAI({692    apiKey: process.env.XAI_API_KEY,693    baseURL: "https://api.x.ai/v1",694});695696// Delete a file697const deleteResponse = await client.files.delete("file-abc123");698699console.log("Deleted: " + deleteResponse.deleted);700console.log("File ID: " + deleteResponse.id);701```702703```javascriptWithoutSDK704const response = await fetch("https://api.x.ai/v1/files/file-abc123", {705  method: "DELETE",706  headers: { Authorization: \`Bearer \${process.env.XAI_API_KEY}\` },707});708709const result = await response.json();710console.log("Deleted: " + result.deleted);711console.log("File ID: " + result.id);712```713714```bash715curl -X DELETE https://api.x.ai/v1/files/file-abc123 \\716  -H "Authorization: Bearer $XAI_API_KEY"717```718719## The File Object720721Every Files API endpoint that returns metadata (Upload, List, Get Metadata) returns the same `file` object shape:722723| Field | Type | Description |724| --- | --- | --- |725| `id` | string | Unique file identifier (e.g. `file_a128090d-f0c9-4873-bd84-e499777e7417`). Use this anywhere a `file_id` is expected, including chat attachments. |726| `filename` | string | Original filename you supplied at upload time. |727| `bytes` | integer | File size in bytes. |728| `created_at` | integer | Upload time as a Unix timestamp (seconds). |729| `expires_at` | integer or null | Unix timestamp at which the file will be deleted. `null` for permanent files; set when the file was uploaded with `expires_after`. |730| `object` | string | Always `"file"`. Returned for OpenAI compatibility. |731| `purpose` | string | Echoes the `purpose` value sent at upload time. xAI does not enforce or interpret this field; it is stored for OpenAI SDK compatibility. Setting `"assistants"` is the conventional choice. |732733## Limitations and Considerations734735### File Size Limits736737* **Maximum file size**: 512 MB per file738* **Processing time**: Larger files may take longer to process739740### File Retention741742* **Cleanup**: Delete files when no longer needed to manage storage743* **Access**: Files are scoped to your team/organization744745### Supported Formats746747While many text-based formats are supported, the system works best with:748749* Structured documents (with clear sections, headings)750* Plain text and markdown751* Documents with clear information hierarchy752753Supported file types include:754755* Plain text files (.txt)756* Markdown files (.md)757* Code files (.py, .js, .java, etc.)758* CSV files (.csv)759* JSON files (.json)760* PDF documents (.pdf)761* And many other text-based formats762763## Next Steps764
Files main
Menu

Theme