文件与集合

文件

Grok 可以搜索附加到 chat message 的文档并对其进行 reasoning。可以通过 URL 引用任意 public file,也可以 上传 private file 并通过 ID 引用。无论采用哪种方式,系统都会自动启用 attachment_search tool,并将请求转换为 agentic workflow。

更多信息请参阅 Files API Reference

正在寻找 Collections?如果需要持久化文档存储,并在大量文档中进行 semantic search,请参阅 Collections。Files 与之不同,它用于将文档附加到 chat conversation,作为即时 context。

Files 如何与 Chat 配合工作

在后台,将文件附加到 chat message 时,xAI API 会隐式地向请求添加 attachment_search server-side tool。这意味着:

  1. 自动 Agentic 行为:chat request 会变成 agentic request,由 Grok 自主搜索文档

  2. 智能文档分析:model 可以对文档内容进行 reasoning、提取相关信息并综合生成答案

  3. 多文档支持:可以附加多个文件,Grok 会跨所有文件进行搜索

通过这种无缝集成,只需附加文件并提问即可,文档搜索与检索的复杂工作会由 agentic workflow 自动处理。

将文件附加到 chat message 时,xAI API 会自动启用 attachment_search server-side tool。这会将请求转换为 agentic workflow,其中 Grok 会:

  1. 分析 query,了解你要查找的信息

  2. 搜索文档,智能地从所有附加文件中找到相关部分

  3. 提取并综合信息,必要时整合多个来源

  4. 提供全面答案,并结合文档中的 context

Agentic Workflow

与其他 agentic tool(web search、X search、code execution)一样,文档搜索会自主运行:

  • 多次搜索:model 可能使用不同 query 多次搜索文档,以找到完整信息

  • Reasoning:model 使用 reasoning 能力决定搜索内容以及如何解释结果

  • Streaming 可见性:在 streaming mode 中,可以通过 tool call notification 查看 model 何时搜索文档

Files 的 Token Usage

基于文件的 chat 与其他 agentic request 具有相似的 token 模式:

  • Prompt token:包含 conversation history 和内部处理。文档内容会得到高效处理

  • Reasoning token:用于规划搜索和分析文档内容

  • Completion token:最终答案文本

  • Cached token:重复的文档内容可利用 prompt caching 提高效率

实际文档内容由 server-side tool 处理,不会直接出现在 message history 中,从而优化 token usage。

定价

除标准 token 费用外,文档搜索还按 tool invocation 计费。Model 每搜索一次文档,就计为一次 tool invocation。完整定价详情请参阅 Tool 定价 表格。

开始使用

要在 Grok 中使用文件,需要:

  1. 获取文件的 public URL,或者了解如何通过 Files API

  2. 与文件对话,将文件附加到 chat message,并针对文档提问

快速示例

以下是完整 workflow 的快速示例:

import os
from xai_sdk import Client
from xai_sdk.chat import user, file

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

# 1a. Reference a public file by URL
file_url = "https://example-files.online-convert.com/document/txt/example.txt"

# 1b. Or upload a file and reference by ID
uploaded_file = client.files.upload(
    b"Employee: Alice Johnson\\nDepartment: Engineering",
    filename="employee.txt",
)

# 2. Chat with files
chat = client.chat.create(model="grok-4.5")
chat.append(user(
    "Summarize both documents",
    file(url=file_url),
    file(uploaded_file.id),
))

# 3. Get the answer
response = chat.sample()
print(response.content)

# 4. Clean up uploaded file
client.files.delete(uploaded_file.id)

主要功能

多文件支持

多个文档 附加到单个 query,Grok 会跨所有文档搜索相关信息。

Multi-Turn Conversation

文件 context 会在多个 conversation turn 之间保留,因此无需重新附加文件即可继续追问。

Code Execution 集成

将文件与 code execution tool 结合,可对上传的数据执行高级数据分析、统计计算和转换。Model 可以编写并执行 Python 代码,直接处理文件。

限制

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

  • 不支持 batch request:带文档搜索的文件附件属于 agentic request,不支持 batch mode(n > 1

  • 仅限 Agentic model:需要支持 agentic tool calling 的 model(例如 grok-4.20grok-4.5

  • 支持的文件格式

    • 纯文本文件(.txt)

    • Markdown 文件(.md)

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

    • CSV 文件(.csv)

    • JSON 文件(.json)

    • PDF 文档(.pdf)

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

下一步