SPB Git

Repository Public

api.md 11.5 KB 369 lines markdown

1<!-- source: https://docs.x.ai/developers/files/collections/api (from https://docs.x.ai/llms-full.txt, retrieved 2026-09-19T05:28:55Z) -->2#### Files & Collections34# Using Collections via API56This guide walks you through managing collections programmatically using the xAI SDK and REST API.78## Creating a Management Key910To use the Collections API, you need to create a Management API Key with the `AddFileToCollection` permission. This permission is required for uploading documents to collections.11121. Navigate to the **Management Keys** section in the [xAI Console](https://console.x.ai/team/default/settings/management-keys?utm_source=docs\&utm_medium=referral\&utm_campaign=developers-files-collections-api\&utm_content=management-keys)132. Click on **Create Management Key**143. Select the `AddFileToCollection` permission along with any other permissions you need154. If you need to perform operations other than uploading documents (such as creating, updating, or deleting collections), enable the corresponding permissions in the **Collections Endpoint** group165. Copy and securely store your Management API Key1718> [!WARNING]19>20> Make sure to copy your Management API Key immediately after creation. You won't be able to see it again.2122## Creating a collection2324```python customLanguage="pythonXAI"25import os26from xai_sdk import Client27client = Client(28    api_key=os.getenv("XAI_API_KEY"),29    management_api_key=os.getenv("XAI_MANAGEMENT_API_KEY"),30    timeout=3600,31)3233collection = client.collections.create(34    name="SEC Filings",35)3637print(collection)38```3940```javascript customLanguage="javascriptWithoutSDK"41const response = await fetch('https://management-api.x.ai/v1/collections', {42  method: 'POST',43  headers: {44    'Content-Type': 'application/json',45    'Authorization': `Bearer ${process.env.XAI_MANAGEMENT_API_KEY}`,46  },47  body: JSON.stringify({ collection_name: 'SEC Filings' }),48});4950const collection = await response.json();51console.log(collection);52```5354```bash55curl https://management-api.x.ai/v1/collections \56  -X POST \57  -H "Content-Type: application/json" \58  -H "Authorization: Bearer $XAI_MANAGEMENT_API_KEY" \59  -d '{"collection_name": "SEC Filings"}'60```6162## Listing collections6364```python customLanguage="pythonXAI"65# ... Create client66collections = client.collections.list()67print(collections)68```6970```javascript customLanguage="javascriptWithoutSDK"71const response = await fetch('https://management-api.x.ai/v1/collections', {72  headers: {73    'Authorization': `Bearer ${process.env.XAI_MANAGEMENT_API_KEY}`,74  },75});7677const collections = await response.json();78console.log(collections);79```8081```bash82curl https://management-api.x.ai/v1/collections \83  -H "Authorization: Bearer $XAI_MANAGEMENT_API_KEY"84```8586## Viewing collection configuration8788```python customLanguage="pythonXAI"89# ... Create client90collection = client.collections.get("collection_dbc087b1-6c99-493d-86c6-b401fee34a9d")9192print(collection)93```9495```javascript customLanguage="javascriptWithoutSDK"96const collectionId = 'collection_dbc087b1-6c99-493d-86c6-b401fee34a9d';97const response = await fetch(`https://management-api.x.ai/v1/collections/${collectionId}`, {98  headers: {99    'Authorization': `Bearer ${process.env.XAI_MANAGEMENT_API_KEY}`,100  },101});102103const collection = await response.json();104console.log(collection);105```106107```bash108curl https://management-api.x.ai/v1/collections/collection_dbc087b1-6c99-493d-86c6-b401fee34a9d \109  -H "Authorization: Bearer $XAI_MANAGEMENT_API_KEY"110```111112## Updating collection configuration113114```python customLanguage="pythonXAI"115# ... Create client116collection = client.collections.update(117    "collection_dbc087b1-6c99-493d-86c6-b401fee34a9d",118    name="SEC Filings (New)"119)120121print(collection)122```123124```javascript customLanguage="javascriptWithoutSDK"125const collectionId = 'collection_dbc087b1-6c99-493d-86c6-b401fee34a9d';126const response = await fetch(`https://management-api.x.ai/v1/collections/${collectionId}`, {127  method: 'PUT',128  headers: {129    'Content-Type': 'application/json',130    'Authorization': `Bearer ${process.env.XAI_MANAGEMENT_API_KEY}`,131  },132  body: JSON.stringify({ collection_name: 'SEC Filings (New)' }),133});134135const collection = await response.json();136console.log(collection);137```138139```bash140curl https://management-api.x.ai/v1/collections/collection_dbc087b1-6c99-493d-86c6-b401fee34a9d \141  -X PUT \142  -H "Content-Type: application/json" \143  -H "Authorization: Bearer $XAI_MANAGEMENT_API_KEY" \144  -d '{"collection_name": "SEC Filings (New)"}'145```146147## Uploading documents148149Uploading a document to a collection is a two-step process:1501511. Upload the file to the xAI API1522. Add the uploaded file to your collection153154```python customLanguage="pythonXAI"155# ... Create client156with open("tesla-20241231.html", "rb") as file:157    file_data = file.read()158159document = client.collections.upload_document(160    collection_id="collection_dbc087b1-6c99-493d-86c6-b401fee34a9d",161    name="tesla-20241231.html",162    data=file_data,163)164print(document)165```166167```javascript customLanguage="javascriptWithoutSDK"168import fs from 'fs';169170const collectionId = 'collection_dbc087b1-6c99-493d-86c6-b401fee34a9d';171172// Step 1: Upload file173const fileData = fs.readFileSync('tesla-20241231.html');174const formData = new FormData();175formData.append('file', new Blob([fileData], { type: 'text/html' }), 'tesla-20241231.html');176formData.append('purpose', 'assistants');177const uploadResponse = await fetch('https://api.x.ai/v1/files', {178  method: 'POST',179  headers: { 'Authorization': `Bearer ${process.env.XAI_API_KEY}` },180  body: formData,181});182183const { id: fileId } = await uploadResponse.json();184185// Step 2: Add to collection186await fetch(`https://management-api.x.ai/v1/collections/${collectionId}/documents/${fileId}`, {187  method: 'POST',188  headers: { 'Authorization': `Bearer ${process.env.XAI_MANAGEMENT_API_KEY}` },189});190191```192193```bash194# Step 1: Upload file195curl https://api.x.ai/v1/files \196  -H "Authorization: Bearer $XAI_API_KEY" \197  -F file=@tesla-20241231.html198199# Step 2: Add file to collection (use file_id from step 1)200curl -X POST https://management-api.x.ai/v1/collections/$COLLECTION_ID/documents/$FILE_ID \201  -H "Authorization: Bearer $XAI_MANAGEMENT_API_KEY"202```203204### Uploading with metadata fields205206If your collection has [metadata fields](/developers/files/collections/metadata) defined (the collection must have these fields set in `field_definitions` when created or updated - see the linked metadata page for details), include them using the `fields` parameter:207208```python customLanguage="pythonXAI"209# ... Create client210with open("paper.pdf", "rb") as file:211    file_data = file.read()212213document = client.collections.upload_document(214    collection_id="collection_dbc087b1-6c99-493d-86c6-b401fee34a9d",215    name="paper.pdf",216    data=file_data,217    fields={218        "author": "Sandra Kim",219        "year": "2024",220        "title": "Q3 Revenue Analysis"221    },222)223print(document)224```225226```bash227curl https://management-api.x.ai/v1/collections/collection_dbc087b1-6c99-493d-86c6-b401fee34a9d/documents \228  -H "Authorization: Bearer $XAI_MANAGEMENT_API_KEY" \229  -F "name=paper.pdf" \230  -F "data=@paper.pdf" \231  -F "content_type=application/pdf" \232  -F 'fields={"author": "Sandra Kim", "year": "2024", "title": "Q3 Revenue Analysis"}'233```234235## Searching documents236237You can also search documents using the Responses API with the `file_search` tool. See the [Collections Search Tool](/developers/tools/collections-search) guide for more details.238239```python customLanguage="pythonXAI"240# ... Create client241response = client.collections.search(242    query="What were the key revenue drivers based on the SEC filings?",243    collection_ids=["collection_dbc087b1-6c99-493d-86c6-b401fee34a9d"],244)245print(response)246```247248```javascript customLanguage="javascriptWithoutSDK"249const response = await fetch('https://api.x.ai/v1/documents/search', {250  method: 'POST',251  headers: {252    'Content-Type': 'application/json',253    'Authorization': `Bearer ${process.env.XAI_API_KEY}`,254  },255  body: JSON.stringify({256    query: 'What were the key revenue drivers based on the SEC filings?',257    source: {258      collection_ids: ['collection_dbc087b1-6c99-493d-86c6-b401fee34a9d'],259    },260  }),261});262263const results = await response.json();264console.log(results);265```266267```bash268curl https://api.x.ai/v1/documents/search \269  -H "Content-Type: application/json" \270  -H "Authorization: Bearer $XAI_API_KEY" \271  -d '{272    "query": "What were the key revenue drivers based on the SEC filings?",273    "source": {274      "collection_ids": ["collection_dbc087b1-6c99-493d-86c6-b401fee34a9d"]275    }276  }'277```278279### Search modes280281There are three search methods available:282283* **Keyword search**284* **Semantic search**285* **Hybrid search** (combines both keyword and semantic methods)286287By default, the system uses hybrid search, which generally delivers the best and most comprehensive results.288289| Mode | Description | Best for | Drawbacks |290|------|-------------|----------|-----------|291| Keyword | Searches for exact matches of specified words, phrases, or numbers | Precise terms (e.g., account numbers, dates, specific financial figures) | May miss contextually relevant content |292| Semantic | Understands meaning and context to find conceptually related content | Discovering general ideas, topics, or intent even when exact words differ | Less precise for specific terms |293| Hybrid | Combines keyword and semantic search for broader and more accurate results | Most real-world use cases | Slightly higher latency |294295The hybrid approach balances precision and recall, making it the recommended default for the majority of queries.296297An example to set hybrid mode:298299```bash300curl https://api.x.ai/v1/documents/search \301  -H "Content-Type: application/json" \302  -H "Authorization: Bearer $XAI_API_KEY" \303  -d '{304      "query": "What were the key revenue drivers based on the SEC filings?",305      "source": {306          "collection_ids": [307              "collection_dbc087b1-6c99-493d-86c6-b401fee34a9d"308          ]309      },310      "retrieval_mode": {"type": "hybrid"}311}'312```313314You can set `"retrieval_mode": {"type": "keyword"}` for keyword search and `"retrieval_mode": {"type": "semantic"}` for semantic search.315316## Deleting a document317318```python customLanguage="pythonXAI"319# ... Create client320321client.collections.remove_document(322    collection_id="collection_dbc087b1-6c99-493d-86c6-b401fee34a9d",323    file_id="file_55a709d4-8edc-4f83-84d9-9f04fe49f832",324)325```326327```javascript customLanguage="javascriptWithoutSDK"328const collectionId = 'collection_dbc087b1-6c99-493d-86c6-b401fee34a9d';329const fileId = 'file_55a709d4-8edc-4f83-84d9-9f04fe49f832';330331await fetch(`https://management-api.x.ai/v1/collections/${collectionId}/documents/${fileId}`, {332  method: 'DELETE',333  headers: { 'Authorization': `Bearer ${process.env.XAI_MANAGEMENT_API_KEY}` },334});335336```337338```bash339curl https://management-api.x.ai/v1/collections/collection_dbc087b1-6c99-493d-86c6-b401fee34a9d/documents/file_55a709d4-8edc-4f83-84d9-9f04fe49f832 \340  -X DELETE \341  -H "Authorization: Bearer $XAI_MANAGEMENT_API_KEY"342```343344## Deleting a collection345346```python customLanguage="pythonXAI"347# ... Create client348349client.collections.delete(collection_id="collection_dbc087b1-6c99-493d-86c6-b401fee34a9d")350```351352```javascript customLanguage="javascriptWithoutSDK"353const collectionId = 'collection_dbc087b1-6c99-493d-86c6-b401fee34a9d';354355await fetch(`https://management-api.x.ai/v1/collections/${collectionId}`, {356  method: 'DELETE',357  headers: { 'Authorization': `Bearer ${process.env.XAI_MANAGEMENT_API_KEY}` },358});359360```361362```bash363curl https://management-api.x.ai/v1/collections/collection_dbc087b1-6c99-493d-86c6-b401fee34a9d \364  -X DELETE \365  -H "Authorization: Bearer $XAI_MANAGEMENT_API_KEY"366```367368## Next Steps369
Files main
Menu

Theme