API / chat-with-files-on-grok-api

API

Chat with files on the Grok API

Chat with files on the Grok API

Attach a public file_url or an uploaded file_id on a Responses message. The API turns the turn into an agentic document-search workflow. Prefer grok-4.6. File attachments with document search do not support batch n > 1. Streaming makes tool calls visible as they run.

Attach by URL

curl -X POST "https://api.x.ai/v1/responses" \
  -H "Authorization: Bearer $XAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "grok-4.6",
    "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"}
        ]
      }
    ]
  }'
import os
from openai import OpenAI

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

response = client.responses.create(
    model="grok-4.6",
    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"},
        ],
    }],
)
print(response.output[-1].content[0].text)

Use {"type": "input_file", "file_id": "file-abc123"} after uploading through the Files API when the document is private.

Multiple files and follow-ups

Pass several input_file parts in one message to search across documents. For multi-turn Q&A, chain with previous_response_id (OpenAI SDK) or xAI SDK use_encrypted_content=True so file context stays available without re-uploading every turn.

Combine with images or code

You can put input_file next to input_image in the same user message. For spreadsheets and CSVs, add tools: [{"type": "code_interpreter"}] so the model can load the file and compute — see Run code execution on the Grok API.

Pitfalls

  • Setting n > 1 on a file-search request — unsupported for this agentic path.
  • Using a model without server-side tool support — stick to agentic models such as grok-4.6.
  • Huge unstructured dumps without a specific question — token use climbs with every search step.