文件与集合

管理文件

Files API 提供完整的文件管理操作。如果文件可公开访问,可以在 chat conversation 中直接通过 URL 引用,请参阅 附加文件。对于无法公开访问的文件,请使用下述任一方式上传。

也可以在 xAI Console 的 Files 页面查看和管理所有已上传文件。

上传文件

可以通过多种方式上传文件:file path、raw byte、BytesIO object 或已打开的 file handle。

从 File Path 上传

import os
from xai_sdk import Client

client = Client(api_key=os.getenv("XAI_API_KEY"))

# Upload a file from disk
file = client.files.upload("/path/to/your/document.pdf")

print(f"File ID: {file.id}")
print(f"Filename: {file.filename}")
print(f"Size: {file.size} bytes")
print(f"Created at: {file.created_at}")

从 Byte 上传

Python

import os
from xai_sdk import Client

client = Client(api_key=os.getenv("XAI_API_KEY"))

# Upload file content directly from bytes
content = b"This is my document content.\\nIt can span multiple lines."
file = client.files.upload(content, filename="document.txt")

print(f"File ID: {file.id}")
print(f"Filename: {file.filename}")

从 File Object 上传

Python

import os
from xai_sdk import Client

client = Client(api_key=os.getenv("XAI_API_KEY"))

# Upload a file directly from disk
file = client.files.upload(open("document.pdf", "rb"), filename="document.pdf")

print(f"File ID: {file.id}")
print(f"Filename: {file.filename}")

上传并设置过期时间(TTL)

文件默认永久存储,直到手动删除。如需平台在固定时间窗口后自动删除文件,请在上传时设置 expires_after。这适用于短期附件、ephemeral session data 和合规时间窗口。

工作原理

expires_after 以秒为单位,从上传时间开始计算。取值必须介于 3600(1 小时)和 2592000(30 天)之间(包含边界)。省略该字段则永久保留文件。

Response 包含 expires_at,即文件被删除的绝对 UTC timestamp。超过该时间后,文件即被删除:不再出现在 list response 中,获取其 metadata 或内容会返回 not found,也无法再通过 id 在 chat attachment 中引用。

也可以在 TTL 到期前随时手动删除文件。

import os
from datetime import timedelta
from xai_sdk import Client

client = Client(api_key=os.getenv("XAI_API_KEY"))

# Upload a file that will be auto-deleted in 24 hours.
# expires_after accepts an int (seconds) or a datetime.timedelta.
file = client.files.upload(
    "/path/to/document.pdf",
    expires_after=timedelta(hours=24),
)

print(f"File ID: {file.id}")
print(f"Expires at: {file.expires_at.ToDatetime()}")

上传并追踪进度

使用 callback 或 progress bar 追踪大型文件的上传进度。

Python

import os
from xai_sdk import Client

client = Client(api_key=os.getenv("XAI_API_KEY"))

# Define a custom progress callback
def progress_callback(bytes_uploaded: int, total_bytes: int):
    percentage = (bytes_uploaded / total_bytes) * 100 if total_bytes else 0
    mb_uploaded = bytes_uploaded / (1024 * 1024)
    mb_total = total_bytes / (1024 * 1024)
    print(f"Progress: {mb_uploaded:.2f}/{mb_total:.2f} MB ({percentage:.1f}%)")

# Upload with progress tracking
file = client.files.upload(
    "/path/to/large-file.pdf",
    on_progress=progress_callback
)

print(f"Successfully uploaded: {file.filename}")

列出文件

使用 pagination 和排序选项获取已上传文件列表。

可用选项

  • limit:返回文件的最大数量。未指定时使用 server 默认值 100,最大值为 100。

  • order:排序方式,可为 "asc"(升序)或 "desc"(降序)。默认为 "desc"

  • sort_by:排序字段。可选值:"created_at""filename""size"。默认为 "created_at"

  • pagination_token:传入上一次 response 返回的 pagination_token 以获取下一页。第一页请省略。

Response 始终包含 pagination_token。当返回页面包含的项目数少于 limit 时,说明已经到达列表末尾。

import os
from xai_sdk import Client

client = Client(api_key=os.getenv("XAI_API_KEY"))

# List files with pagination and sorting
response = client.files.list(
    limit=10,
    order="desc",
    sort_by="created_at"
)

for file in response.data:
    expires = file.expires_at.ToDatetime() if file.HasField("expires_at") else "never"
    print(f"File: {file.filename} (ID: {file.id}, Size: {file.size} bytes, Expires: {expires})")

遍历所有文件页面

List endpoint 每次调用最多返回 limit 个文件(上限 100)。要枚举所有文件,请使用上一次 response 的 pagination_token 持续调用 endpoint,直到 response 返回少于 limit 个项目。

import os
from xai_sdk import Client

client = Client(api_key=os.getenv("XAI_API_KEY"))

# Walk every page until the API returns a short page.
page_size = 100
token = None
all_files = []

while True:
    response = client.files.list(
        limit=page_size,
        order="desc",
        sort_by="created_at",
        pagination_token=token,
    )
    all_files.extend(response.data)
    if len(response.data) < page_size:
        break
    token = response.pagination_token

print(f"Total files: {len(all_files)}")

获取文件 Metadata

获取特定文件的详细信息。

import os
from xai_sdk import Client

client = Client(api_key=os.getenv("XAI_API_KEY"))

# Get file metadata by ID
file = client.files.get("file-abc123")

print(f"Filename: {file.filename}")
print(f"Size: {file.size} bytes")
print(f"Created: {file.created_at}")
# expires_at is only set when the file was uploaded with expires_after
if file.HasField("expires_at"):
    print(f"Expires at: {file.expires_at.ToDatetime()}")

获取文件内容

下载已上传文件的 raw byte。该 endpoint 会 streaming response,因此可处理任意受支持大小的文件,而无需在 API 层将整个 payload buffer 到内存中。

import os
from xai_sdk import Client

client = Client(api_key=os.getenv("XAI_API_KEY"))

# Returns the complete file content as bytes.
content = client.files.content("file-abc123")

# Save to disk
with open("downloaded.pdf", "wb") as f:
    f.write(content)

print(f"Saved {len(content)} bytes")

删除文件

不再需要文件时将其删除。

import os
from xai_sdk import Client

client = Client(api_key=os.getenv("XAI_API_KEY"))

# Delete a file
delete_response = client.files.delete("file-abc123")

print(f"Deleted: {delete_response.deleted}")
print(f"File ID: {delete_response.id}")

File Object

所有返回 metadata 的 Files API endpoint(Upload、List、Get Metadata)都返回相同的 file object 结构:

字段类型说明
idstring唯一 file identifier(例如 file_a128090d-f0c9-4873-bd84-e499777e7417)。在任何需要 file_id 的位置使用,包括 chat attachment。
filenamestring上传时提供的原始文件名。
bytesinteger文件大小,单位为 byte。
created_atinteger上传时间,以 Unix timestamp(秒)表示。
expires_atinteger 或 null文件删除时间的 Unix timestamp。永久文件为 null;上传文件时设置了 expires_after
objectstring始终为 "file",用于 OpenAI 兼容性。
purposestring回显上传时发送的 purpose 值。xAI 不会强制或解释该字段,仅为 OpenAI SDK 兼容性进行存储。设置为 "assistants" 是惯常选择。

限制与注意事项

文件大小限制

  • 最大文件大小:每个文件 48 MB

  • 处理时间:较大的文件可能需要更长处理时间

文件保留

  • 清理:不再需要文件时将其删除,以管理 storage

  • 访问:文件的 scope 限定为 team / organization

支持的格式

虽然支持许多基于文本的格式,但系统最适合处理:

  • 结构化文档(具有清晰的 section 和 heading)

  • 纯文本和 Markdown

  • 信息层级清晰的文档

支持的文件类型包括:

  • 纯文本文件(.txt)

  • Markdown 文件(.md)

  • 代码文件(.py、.js、.java 等)

  • CSV 文件(.csv)

  • JSON 文件(.json)

  • PDF 文档(.pdf)

  • 以及许多其他基于文本的格式

下一步