跳转到内容

Files & Collections

通过 API 使用集合

本指南将引导您如何使用 xAI SDK 和 REST API 以编程方式管理集合。

创建管理密钥

要使用集合 API,您需要创建一个具有 AddFileToCollection 权限的管理 API 密钥。上传文档到集合需要此权限。

  1. 导航到 xAI Console 中的 Management Keys 部分
  2. 点击 Create Management Key
  3. 选择 AddFileToCollection 权限以及您需要的任何其他权限
  4. 如果您需要执行上传文档以外的操作(如创建、更新或删除集合),请在 Collections Endpoint 组中启用相应权限
  5. 复制并安全存储您的管理 API 密钥

WARNING

确保在创建后立即复制您的管理 API 密钥。您将无法再次查看它。

创建集合

python
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,
)

collection = client.collections.create(
    name="SEC Filings",
)

print(collection)
javascript
const response = await fetch('https://management-api.x.ai/v1/collections', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${process.env.XAI_MANAGEMENT_API_KEY}`,
  },
  body: JSON.stringify({ collection_name: 'SEC Filings' }),
});

const collection = await response.json();
console.log(collection);
bash
curl https://management-api.x.ai/v1/collections \
  -X POST \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $XAI_MANAGEMENT_API_KEY" \
  -d '{"collection_name": "SEC Filings"}'

列出集合

python
# ... Create client
collections = client.collections.list()
print(collections)
javascript
const response = await fetch('https://management-api.x.ai/v1/collections', {
  headers: {
    'Authorization': `Bearer ${process.env.XAI_MANAGEMENT_API_KEY}`,
  },
});

const collections = await response.json();
console.log(collections);
bash
curl https://management-api.x.ai/v1/collections \
  -H "Authorization: Bearer $XAI_MANAGEMENT_API_KEY"

查看集合配置

python
# ... Create client
collection = client.collections.get("collection_dbc087b1-6c99-493d-86c6-b401fee34a9d")

print(collection)
javascript
const collectionId = 'collection_dbc087b1-6c99-493d-86c6-b401fee34a9d';
const response = await fetch(`https://management-api.x.ai/v1/collections/${collectionId}`, {
  headers: {
    'Authorization': `Bearer ${process.env.XAI_MANAGEMENT_API_KEY}`,
  },
});

const collection = await response.json();
console.log(collection);
bash
curl https://management-api.x.ai/v1/collections/collection_dbc087b1-6c99-493d-86c6-b401fee34a9d \
  -H "Authorization: Bearer $XAI_MANAGEMENT_API_KEY"

更新集合配置

python
# ... Create client
collection = client.collections.update(
    "collection_dbc087b1-6c99-493d-86c6-b401fee34a9d",
    name="SEC Filings (New)"
)

print(collection)
javascript
const collectionId = 'collection_dbc087b1-6c99-493d-86c6-b401fee34a9d';
const response = await fetch(`https://management-api.x.ai/v1/collections/${collectionId}`, {
  method: 'PUT',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${process.env.XAI_MANAGEMENT_API_KEY}`,
  },
  body: JSON.stringify({ collection_name: 'SEC Filings (New)' }),
});

const collection = await response.json();
console.log(collection);
bash
curl https://management-api.x.ai/v1/collections/collection_dbc087b1-6c99-493d-86c6-b401fee34a9d \
  -X PUT \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $XAI_MANAGEMENT_API_KEY" \
  -d '{"collection_name": "SEC Filings (New)"}'

上传文档

将文档上传到集合是一个两步过程:

  1. 将文件上传到 xAI API
  2. 将上传的文件添加到您的集合中
python
# ... Create client
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)
javascript
import fs from 'fs';

const collectionId = 'collection_dbc087b1-6c99-493d-86c6-b401fee34a9d';

// Step 1: Upload file
const fileData = fs.readFileSync('tesla-20241231.html');
const formData = new FormData();
formData.append('file', new Blob([fileData], { type: 'text/html' }), 'tesla-20241231.html');
formData.append('purpose', 'assistants');
const uploadResponse = await fetch('https://api.x.ai/v1/files', {
  method: 'POST',
  headers: { 'Authorization': `Bearer ${process.env.XAI_API_KEY}` },
  body: formData,
});

const { id: fileId } = await uploadResponse.json();

// Step 2: Add to collection
await fetch(`https://management-api.x.ai/v1/collections/${collectionId}/documents/${fileId}`, {
  method: 'POST',
  headers: { 'Authorization': `Bearer ${process.env.XAI_MANAGEMENT_API_KEY}` },
});
bash
# 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"

使用元数据字段上传

如果您的集合定义了元数据字段(创建或更新集合时必须在 field_definitions 中设置这些字段 - 详情请参阅链接的元数据页面),请使用 fields 参数包含它们:

python
# ... Create client
with open("paper.pdf", "rb") as file:
    file_data = file.read()

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"
    },
)
print(document)
bash
curl https://management-api.x.ai/v1/collections/collection_dbc087b1-6c99-493d-86c6-b401fee34a9d/documents \
  -H "Authorization: Bearer $XAI_MANAGEMENT_API_KEY" \
  -F "name=paper.pdf" \
  -F "data=@paper.pdf" \
  -F "content_type=application/pdf" \
  -F 'fields={"author": "Sandra Kim", "year": "2024", "title": "Q3 Revenue Analysis"}'

搜索文档

您也可以使用 Responses API 和 file_search 工具搜索文档。有关更多详细信息,请参阅集合搜索工具指南

python
# ... Create client
response = client.collections.search(
    query="What were the key revenue drivers based on the SEC filings?",
    collection_ids=["collection_dbc087b1-6c99-493d-86c6-b401fee34a9d"],
)
print(response)
javascript
const response = await fetch('https://api.x.ai/v1/documents/search', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${process.env.XAI_API_KEY}`,
  },
  body: JSON.stringify({
    query: 'What were the key revenue drivers based on the SEC filings?',
    source: {
      collection_ids: ['collection_dbc087b1-6c99-493d-86c6-b401fee34a9d'],
    },
  }),
});

const results = await response.json();
console.log(results);
bash
curl https://api.x.ai/v1/documents/search \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $XAI_API_KEY" \
  -d '{
    "query": "What were the key revenue drivers based on the SEC filings?",
    "source": {
      "collection_ids": ["collection_dbc087b1-6c99-493d-86c6-b401fee34a9d"]
    }
  }'

搜索模式

提供三种搜索方法:

  • 关键词搜索
  • 语义搜索
  • 混合搜索(结合关键词和语义方法)

默认情况下,系统使用混合搜索,这通常能提供最佳和最全面的结果。

ModeDescriptionBest forDrawbacks
Keyword搜索指定单词、短语或数字的精确匹配精确术语(例如,账号、日期、特定财务数字)可能错过上下文相关内容
Semantic理解含义和上下文以查找概念上相关的内容发现一般性想法、主题或意图,即使具体词语不同对特定术语不够精确
Hybrid结合关键词和语义搜索以获得更广泛和更准确的结果大多数实际用例稍高的延迟

混合方法平衡了精确度和召回率,使其成为大多数查询的推荐默认设置。

设置混合模式的示例:

bash
curl https://api.x.ai/v1/documents/search \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $XAI_API_KEY" \
  -d '{
      "query": "What were the key revenue drivers based on the SEC filings?",
      "source": {
          "collection_ids": [
              "collection_dbc087b1-6c99-493d-86c6-b401fee34a9d"
          ]
      },
      "retrieval_mode": {"type": "hybrid"}
}'

您可以为关键词搜索设置 "retrieval_mode": {"type": "keyword"},为语义搜索设置 "retrieval_mode": {"type": "semantic"}

删除文档

python
# ... Create client

client.collections.remove_document(
    collection_id="collection_dbc087b1-6c99-493d-86c6-b401fee34a9d",
    file_id="file_55a709d4-8edc-4f83-84d9-9f04fe49f832",
)
javascript
const collectionId = 'collection_dbc087b1-6c99-493d-86c6-b401fee34a9d';
const fileId = 'file_55a709d4-8edc-4f83-84d9-9f04fe49f832';

await fetch(`https://management-api.x.ai/v1/collections/${collectionId}/documents/${fileId}`, {
  method: 'DELETE',
  headers: { 'Authorization': `Bearer ${process.env.XAI_MANAGEMENT_API_KEY}` },
});
bash
curl https://management-api.x.ai/v1/collections/collection_dbc087b1-6c99-493d-86c6-b401fee34a9d/documents/file_55a709d4-8edc-4f83-84d9-9f04fe49f832 \
  -X DELETE \
  -H "Authorization: Bearer $XAI_MANAGEMENT_API_KEY"

删除集合

python
# ... Create client

client.collections.delete(collection_id="collection_dbc087b1-6c99-493d-86c6-b401fee34a9d")
javascript
const collectionId = 'collection_dbc087b1-6c99-493d-86c6-b401fee34a9d';

await fetch(`https://management-api.x.ai/v1/collections/${collectionId}`, {
  method: 'DELETE',
  headers: { 'Authorization': `Bearer ${process.env.XAI_MANAGEMENT_API_KEY}` },
});
bash
curl https://management-api.x.ai/v1/collections/collection_dbc087b1-6c99-493d-86c6-b401fee34a9d \
  -X DELETE \
  -H "Authorization: Bearer $XAI_MANAGEMENT_API_KEY"

下一步

本文档为 docs.x.ai 全站中文翻译,由 AI 自动翻译生成。代码示例请以原文为准。