模型能力

与文件对话

可以使用 public URL 或已上传的 file ID 将文件附加到 chat conversation。附加文件后,系统会自动启用文档搜索能力,将请求转换为 agentic workflow。

附加文件

可以通过两种方式将文件附加到 message:

Public URL(file_url,直接引用任意公开可访问的文件,无需上传:

JSON

{"type": "input_file", "file_url": "https://example.com/document.pdf"}

已上传文件(file_id,先通过 Files API 上传文件,再通过 ID 引用。适用于无法公开访问的文件,例如私有或敏感文档:

JSON

{"type": "input_file", "file_id": "file-abc123"}

为简单起见,以下示例使用 file_url。也可以替换为 file_id,改用已上传文件。

使用单个文件进行基础对话

将文件附加到 conversation,让 model 在其中搜索相关信息。

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

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

# Attach a file by public URL (or use file(file_id) for uploaded files)
chat = client.chat.create(model="grok-4.5")
chat.append(user(
    "What was the total revenue in this report?",
    file(url="https://docs.x.ai/assets/api-examples/documents/sales-report.txt"),
))

# Get the response
response = chat.sample()

print(f"Answer: {response.content}")

使用文件进行 Streaming 对话

在 model 搜索文档时实时获取 response。

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

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

# Attach a file by public URL (or use file(file_id) for uploaded files)
chat = client.chat.create(model="grok-4.5")
chat.append(user(
    "What is the weight of the XR-2000?",
    file(url="https://docs.x.ai/assets/api-examples/documents/product-specs.txt"),
))

# Stream the response
is_thinking = True
for response, chunk in chat.stream():
    # Show tool calls as they happen
    for tool_call in chunk.tool_calls:
        print(f"\\nSearching: {tool_call.function.name}")
    
    if response.usage.reasoning_tokens and is_thinking:
        print(f"\\rThinking... ({response.usage.reasoning_tokens} tokens)", end="", flush=True)
    
    if chunk.content and is_thinking:
        print("\\n\\nAnswer:")
        is_thinking = False
    
    if chunk.content:
        print(chunk.content, end="", flush=True)

print(f"\\n\\nUsage: {response.usage}")

附加多个文件

同时查询多个文档。

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

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

# Attach files by public URL (or use file(file_id) for uploaded files)
chat = client.chat.create(model="grok-4.5")
chat.append(
    user(
        "Based on these documents, when did the project start, what is the budget, and how many people are on the team?",
        file(url="https://docs.x.ai/assets/api-examples/documents/project-timeline.txt"),
        file(url="https://docs.x.ai/assets/api-examples/documents/project-budget.txt"),
        file(url="https://docs.x.ai/assets/api-examples/documents/project-team.txt"),
    )
)

response = chat.sample()

print(f"Answer: {response.content}")
print("\\nDocuments searched: 3")

使用文件进行 Multi-Turn Conversation

在针对同一文档的多个问题之间保持 context。使用 encrypted content 可在多个 turn 之间高效保留文件 context。

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

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

# Create a multi-turn conversation with encrypted content
chat = client.chat.create(
    model="grok-4.5",
    use_encrypted_content=True,  # Enable encrypted content for efficient multi-turn
)

# First turn: Attach a file by public URL (or use file(file_id) for uploaded files)
chat.append(user(
    "What is the employee's name?",
    file(url="https://docs.x.ai/assets/api-examples/documents/employee-info.txt"),
))
response1 = chat.sample()
print("Q1: What is the employee's name?")
print(f"A1: {response1.content}\\n")

# Add the response to conversation history
chat.append(response1)

# Second turn: Ask about department (agentic context is retained via encrypted content)
chat.append(user("What department does this employee work in?"))
response2 = chat.sample()
print("Q2: What department does this employee work in?")
print(f"A2: {response2.content}\\n")

# Add the response to conversation history
chat.append(response2)

# Third turn: Ask about skills
chat.append(user("What skills does this employee have?"))
response3 = chat.sample()
print("Q3: What skills does this employee have?")
print(f"A3: {response3.content}\\n")

将文件与其他 Modality 结合

可以在一条 message 中组合文件附件、图像和其他内容类型。

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

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

# Attach files by public URL (or use file(file_id) for uploaded files)
chat = client.chat.create(model="grok-4.5")
chat.append(
    user(
        "Based on the attached care guide, do you have any advice about the pictured cat?",
        file(url="https://docs.x.ai/assets/api-examples/documents/cat-care.txt"),
        image("https://media.x.ai/v1/docs/example-cat-in-tree-8e9ac3e0.png"),
    )
)

response = chat.sample()

print(f"Analysis: {response.content}")

将文件与 Code Execution 结合

对于数据分析任务,可以附加数据文件并启用 code execution tool。这样 Grok 就能编写并运行 Python 代码来分析和处理数据。

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

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

# Attach a file by public URL (or use file(file_id) for uploaded files)
chat = client.chat.create(
    model="grok-4.5",
    tools=[code_execution()],  # Enable code execution
)

chat.append(
    user(
        "Analyze this sales data and calculate: 1) Total revenue by product, 2) Average units sold by region, 3) Which product-region combination has the highest revenue",
        file(url="https://docs.x.ai/assets/api-examples/documents/sales-data.csv"),
    )
)

# Stream the response to see code execution in real-time
is_thinking = True
for response, chunk in chat.stream():
    for tool_call in chunk.tool_calls:
        if tool_call.function.name == "code_execution":
            print("\\n[Executing Code]")
    
    if response.usage.reasoning_tokens and is_thinking:
        print(f"\\rThinking... ({response.usage.reasoning_tokens} tokens)", end="", flush=True)
    
    if chunk.content and is_thinking:
        print("\\n\\nAnalysis Results:")
        is_thinking = False
    
    if chunk.content:
        print(chunk.content, end="", flush=True)

print(f"\\n\\nUsage: {response.usage}")

Model 将会:

  1. 访问附加的数据文件

  2. 编写 Python 代码来加载和分析数据

  3. 在 sandboxed environment 中执行代码

  4. 执行计算和统计分析

  5. 在 response 中返回结果与洞察

限制与注意事项

请求约束

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

  • 推荐使用 streaming:使用 streaming mode 可更好地观察文档搜索过程

文档复杂度

  • 高度非结构化或非常长的文档可能需要更多处理

  • 组织良好且结构清晰的文档更容易搜索

  • 大型文档和大量搜索可能导致更高的 token usage

Model 兼容性

  • 推荐 modelgrok-4.5 可提供最佳文档理解效果

  • Agentic 要求:文件附件需要支持 server-side tool 的 agentic-capable model。

下一步

进一步了解如何管理文件: