
Upload a document to a Collections collection
Upload a document to a Collections collection
Collections store documents for semantic search. Max document size is 100 MB. You need a Management API key with AddFileToCollection (create it under Management Keys in the xAI Console). Regular XAI_API_KEY alone is not enough for the management steps.
Two-step REST flow
- Upload the file to Files (
POST https://api.x.ai/v1/fileswith your team API key). - Attach that
file_idto the collection (POST https://management-api.x.ai/v1/collections/{collection_id}/documents/{file_id}with the management key).
# Step 1: Upload file
curl https://api.x.ai/v1/files \
-H "Authorization: Bearer $XAI_API_KEY" \
-F file=@tesla-20241231.html
# Step 2: Add file to collection (use file_id from step 1)
curl -X POST https://management-api.x.ai/v1/collections/$COLLECTION_ID/documents/$FILE_ID \
-H "Authorization: Bearer $XAI_MANAGEMENT_API_KEY"
Create the collection first (POST https://management-api.x.ai/v1/collections with collection_name). See List, update, and delete collections via API.
xAI SDK one-shot helper
client.collections.upload_document uploads and attaches in one call when both keys are on the client:
import os
from xai_sdk import Client
client = Client(
api_key=os.getenv("XAI_API_KEY"),
management_api_key=os.getenv("XAI_MANAGEMENT_API_KEY"),
timeout=3600,
)
with open("tesla-20241231.html", "rb") as file:
file_data = file.read()
document = client.collections.upload_document(
collection_id="collection_dbc087b1-6c99-493d-86c6-b401fee34a9d",
name="tesla-20241231.html",
data=file_data,
)
print(document)
Metadata fields
If the collection defines field_definitions, pass fields={...} on upload (author, year, title, and so on). Required or unique constraints reject bad rows.
document = client.collections.upload_document(
collection_id="collection_dbc087b1-6c99-493d-86c6-b401fee34a9d",
name="paper.pdf",
data=file_data,
fields={
"author": "Sandra Kim",
"year": "2024",
"title": "Q3 Revenue Analysis",
},
)
Poll until the document is processed before searching (Search collections with the Grok API). Credits must be available on the account to upload.
Pitfalls
- Missing
AddFileToCollectionon the management key. - Expecting the standalone Files 512 MB cap inside a collection (100 MB).
- Searching before the document finishes processing.
- Console API credits are a separate bill from SuperGrok's weekly pool on grok.com.