跳转到内容

模型能力

文件聊天

您可以使用公共 URL 或上传的文件 ID 将文件附加到聊天对话中。当文件被附加时,系统会自动启用文档搜索功能,将您的请求转换为代理工作流程。

附加文件

有两种方法可以将文件附加到消息中:

公共 URL (file_url) — 直接引用任何可公开访问的文件,无需上传步骤:

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

上传文件 (file_id) — 先通过 文件 API 上传文件,然后按 ID 引用。适用于非公开可访问的文件,如私有或敏感文档:

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

下面的示例为简单起见使用 file_url。您可以替换为 file_id 来使用上传的文件。

单文件基础聊天

附加文件到对话中,让模型搜索相关信息。

python
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}")
python
import os
from openai import OpenAI

client = OpenAI(
    api_key=os.getenv("XAI_API_KEY"),
    base_url="https://api.x.ai/v1",
)

# Attach a file by public URL (or use file_id for uploaded files)
response = client.responses.create(
    model="grok-4.5",
    input=[
        {
            "role": "user",
            "content": [
                {"type": "input_text", "text": "What was the total revenue in this report?"},
                {"type": "input_file", "file_url": "https://docs.x.ai/assets/api-examples/documents/sales-report.txt"}
            ]
        }
    ]
)

final_answer = response.output[-1].content[0].text
print(f"Answer: {final_answer}")
python
import os
import requests

api_key = os.getenv("XAI_API_KEY")
headers = {
    "Content-Type": "application/json",
    "Authorization": f"Bearer {api_key}"
}

# Attach a file by public URL (or use file_id for uploaded files)
chat_url = "https://api.x.ai/v1/responses"
payload = {
    "model": "grok-4.5",
    "input": [
        {
            "role": "user",
            "content": [
                {"type": "input_text", "text": "What was the total revenue in this report?"},
                {"type": "input_file", "file_url": "https://docs.x.ai/assets/api-examples/documents/sales-report.txt"}
            ]
        }
    ]
}
response = requests.post(chat_url, headers=headers, json=payload)
print(response.json())
javascript
import OpenAI from "openai";

const client = new OpenAI({
    apiKey: process.env.XAI_API_KEY,
    baseURL: "https://api.x.ai/v1",
});

// Attach a file by public URL (or use file_id for uploaded files)
const response = await client.responses.create({
    model: "grok-4.5",
    input: [
        {
            role: "user",
            content: [
                { type: "input_text", text: "What was the total revenue in this report?" },
                { type: "input_file", file_url: "https://docs.x.ai/assets/api-examples/documents/sales-report.txt" },
            ],
        },
    ],
});

const finalAnswer = response.output[response.output.length - 1].content[0].text;
console.log("Answer: " + finalAnswer);
bash
# Attach a file by public URL (or use file_id for uploaded files)
curl -X POST "https://api.x.ai/v1/responses" \\
  -H "Authorization: Bearer $XAI_API_KEY" \\
  -H "Content-Type: application/json" \\
  -d '{
    "model": "grok-4.5",
    "input": [
      {
        "role": "user",
        "content": [
          {"type": "input_text", "text": "What was the total revenue in this report?"},
          {"type": "input_file", "file_url": "https://docs.x.ai/assets/api-examples/documents/sales-report.txt"}
        ]
      }
    ]
  }'

流式文件聊天

在模型搜索文档时获得实时响应。

python
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}")
javascript
import OpenAI from "openai";

const client = new OpenAI({
    apiKey: process.env.XAI_API_KEY,
    baseURL: "https://api.x.ai/v1",
});

// Attach a file by public URL (or use file_id for uploaded files)
const stream = await client.responses.create({
    model: "grok-4.5",
    input: [
        {
            role: "user",
            content: [
                { type: "input_text", text: "What is the weight of the XR-2000?" },
                { type: "input_file", file_url: "https://docs.x.ai/assets/api-examples/documents/product-specs.txt" },
            ],
        },
    ],
    stream: true,
});

for await (const event of stream) {
    if (event.type === "response.output_text.delta") {
        process.stdout.write(event.delta);
    }
}

console.log();

多文件附加

同时跨多个文档进行查询。

python
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")
javascript
import OpenAI from "openai";

const client = new OpenAI({
    apiKey: process.env.XAI_API_KEY,
    baseURL: "https://api.x.ai/v1",
});

// Attach files by public URL (or use file_id for uploaded files)
const response = await client.responses.create({
    model: "grok-4.5",
    input: [
        {
            role: "user",
            content: [
                {
                    type: "input_text",
                    text: "Based on these documents, when did the project start, what is the budget, and how many people are on the team?",
                },
                { type: "input_file", file_url: "https://docs.x.ai/assets/api-examples/documents/project-timeline.txt" },
                { type: "input_file", file_url: "https://docs.x.ai/assets/api-examples/documents/project-budget.txt" },
                { type: "input_file", file_url: "https://docs.x.ai/assets/api-examples/documents/project-team.txt" },
            ],
        },
    ],
});

const finalAnswer = response.output[response.output.length - 1].content[0].text;
console.log("Answer: " + finalAnswer);
console.log("Documents searched: 3");

文件多轮对话

在关于同一文档的多个问题中保持上下文。使用加密内容来高效地在多个轮次中保留文件上下文。

python
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")
javascript
import OpenAI from "openai";

const client = new OpenAI({
    apiKey: process.env.XAI_API_KEY,
    baseURL: "https://api.x.ai/v1",
});

// Attach a file by public URL (or use file_id for uploaded files)

// First turn: Ask about the document
const response1 = await client.responses.create({
    model: "grok-4.5",
    input: [
        {
            role: "user",
            content: [
                { type: "input_text", text: "What is the employee's name?" },
                { type: "input_file", file_url: "https://docs.x.ai/assets/api-examples/documents/employee-info.txt" },
            ],
        },
    ],
});

console.log("Q1: What is the employee's name?");
console.log("A1: " + response1.output[response1.output.length - 1].content[0].text + "\\n");

// Second turn: Ask about department (uses previous_response_id for context)
const response2 = await client.responses.create({
    model: "grok-4.5",
    previous_response_id: response1.id,
    input: [
        { role: "user", content: "What department does this employee work in?" },
    ],
});

console.log("Q2: What department does this employee work in?");
console.log("A2: " + response2.output[response2.output.length - 1].content[0].text + "\\n");

// Third turn: Ask about skills
const response3 = await client.responses.create({
    model: "grok-4.5",
    previous_response_id: response2.id,
    input: [
        { role: "user", content: "What skills does this employee have?" },
    ],
});

console.log("Q3: What skills does this employee have?");
console.log("A3: " + response3.output[response3.output.length - 1].content[0].text + "\\n");

文件与其他模态结合

您可以在单个消息中将文件附件与图像和其他内容类型结合使用。

python
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}")
javascript
import OpenAI from "openai";

const client = new OpenAI({
    apiKey: process.env.XAI_API_KEY,
    baseURL: "https://api.x.ai/v1",
});

// Attach files by public URL (or use file_id for uploaded files)
const response = await client.responses.create({
    model: "grok-4.5",
    input: [
        {
            role: "user",
            content: [
                {
                    type: "input_text",
                    text: "Based on the attached care guide, do you have any advice about the pictured cat?",
                },
                { type: "input_file", file_url: "https://docs.x.ai/assets/api-examples/documents/cat-care.txt" },
                {
                    type: "input_image",
                    image_url: "https://media.x.ai/v1/docs/example-cat-in-tree-8e9ac3e0.png",
                },
            ],
        },
    ],
});

const analysis = response.output[response.output.length - 1].content[0].text;
console.log("Analysis: " + analysis);

文件与代码执行结合

对于数据分析任务,您可以附加数据文件并启用代码执行工具。这允许 Grok 编写和运行 Python 代码来分析和处理您的数据。

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}")
javascript
import OpenAI from "openai";

const client = new OpenAI({
    apiKey: process.env.XAI_API_KEY,
    baseURL: "https://api.x.ai/v1",
});

// Attach a file by public URL (or use file_id for uploaded files)
const stream = await client.responses.create({
    model: "grok-4.5",
    input: [
        {
            role: "user",
            content: [
                {
                    type: "input_text",
                    text: "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",
                },
                { type: "input_file", file_url: "https://docs.x.ai/assets/api-examples/documents/sales-data.csv" },
            ],
        },
    ],
    tools: [{ type: "code_interpreter" }],
    stream: true,
});

for await (const event of stream) {
    if (event.type === "response.output_text.delta") {
        process.stdout.write(event.delta);
    }
}

console.log();

模型将:

  1. 访问附加的数据文件
  2. 编写 Python 代码来加载和分析数据
  3. 在沙盒环境中执行代码
  4. 执行计算和统计分析
  5. 在响应中返回结果和见解

限制与注意事项

请求限制

  • 不支持批量请求:带文档搜索的文件附件是代理请求,不支持批处理模式(n > 1
  • 推荐使用流式:使用流式模式以更好地观察文档搜索过程

文档复杂性

  • 高度非结构化或非常长的文档可能需要更多处理
  • 结构清晰、组织良好的文档更容易搜索
  • 大文档进行多次搜索会导致更高的 token 使用量

模型兼容性

  • 推荐模型grok-4.5 用于最佳文档理解
  • 代理要求:文件附件需要支持服务器端工具的代理能力模型。

下一步

了解有关管理文件的更多信息:

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