SPB Git

Repository Public

chat-with-files.md 16.4 KB 548 lines markdown

1<!-- source: https://docs.x.ai/developers/model-capabilities/files/chat-with-files (from https://docs.x.ai/llms-full.txt, retrieved 2026-09-19T05:28:55Z) -->2#### Model Capabilities34# Chat with Files56You can attach files to chat conversations using a public URL or an uploaded file ID. When files are attached, the system automatically enables document search capabilities, transforming your request into an agentic workflow.78## Attaching Files910There are two ways to attach a file to a message:1112**Public URL (`file_url`)** — reference any publicly accessible file directly, no upload step needed:1314```json15{"type": "input_file", "file_url": "https://example.com/document.pdf"}16```1718**Uploaded file (`file_id`)** — [upload](/developers/files/managing-files) files first via the Files API and reference by ID. Useful for files that aren't publicly accessible, such as private or sensitive documents:1920```json21{"type": "input_file", "file_id": "file-abc123"}22```2324The examples below use `file_url` for simplicity. You can replace with `file_id` to use uploaded files instead.2526## Basic Chat with a Single File2728Attach a file to a conversation to let the model search through it for relevant information.2930```pythonXAI31import os32from xai_sdk import Client33from xai_sdk.chat import user, file3435client = Client(api_key=os.getenv("XAI_API_KEY"))3637# Attach a file by public URL (or use file(file_id) for uploaded files)38chat = client.chat.create(model="grok-4.6")39chat.append(user(40    "What was the total revenue in this report?",41    file(url="https://docs.x.ai/assets/api-examples/documents/sales-report.txt"),42))4344# Get the response45response = chat.sample()4647print(f"Answer: {response.content}")48```4950```pythonOpenAISDK51import os52from openai import OpenAI5354client = OpenAI(55    api_key=os.getenv("XAI_API_KEY"),56    base_url="https://api.x.ai/v1",57)5859# Attach a file by public URL (or use file_id for uploaded files)60response = client.responses.create(61    model="grok-4.6",62    input=[63        {64            "role": "user",65            "content": [66                {"type": "input_text", "text": "What was the total revenue in this report?"},67                {"type": "input_file", "file_url": "https://docs.x.ai/assets/api-examples/documents/sales-report.txt"}68            ]69        }70    ]71)7273final_answer = response.output[-1].content[0].text74print(f"Answer: {final_answer}")75```7677```pythonRequests78import os79import requests8081api_key = os.getenv("XAI_API_KEY")82headers = {83    "Content-Type": "application/json",84    "Authorization": f"Bearer {api_key}"85}8687# Attach a file by public URL (or use file_id for uploaded files)88chat_url = "https://api.x.ai/v1/responses"89payload = {90    "model": "grok-4.6",91    "input": [92        {93            "role": "user",94            "content": [95                {"type": "input_text", "text": "What was the total revenue in this report?"},96                {"type": "input_file", "file_url": "https://docs.x.ai/assets/api-examples/documents/sales-report.txt"}97            ]98        }99    ]100}101response = requests.post(chat_url, headers=headers, json=payload)102print(response.json())103```104105```javascriptOpenAISDK106import OpenAI from "openai";107108const client = new OpenAI({109    apiKey: process.env.XAI_API_KEY,110    baseURL: "https://api.x.ai/v1",111});112113// Attach a file by public URL (or use file_id for uploaded files)114const response = await client.responses.create({115    model: "grok-4.6",116    input: [117        {118            role: "user",119            content: [120                { type: "input_text", text: "What was the total revenue in this report?" },121                { type: "input_file", file_url: "https://docs.x.ai/assets/api-examples/documents/sales-report.txt" },122            ],123        },124    ],125});126127const finalAnswer = response.output[response.output.length - 1].content[0].text;128console.log("Answer: " + finalAnswer);129```130131```bash132# Attach a file by public URL (or use file_id for uploaded files)133curl -X POST "https://api.x.ai/v1/responses" \\134  -H "Authorization: Bearer $XAI_API_KEY" \\135  -H "Content-Type: application/json" \\136  -d '{137    "model": "grok-4.6",138    "input": [139      {140        "role": "user",141        "content": [142          {"type": "input_text", "text": "What was the total revenue in this report?"},143          {"type": "input_file", "file_url": "https://docs.x.ai/assets/api-examples/documents/sales-report.txt"}144        ]145      }146    ]147  }'148```149150## Streaming Chat with Files151152Get real-time responses while the model searches through your documents.153154```pythonXAI155import os156from xai_sdk import Client157from xai_sdk.chat import user, file158159client = Client(api_key=os.getenv("XAI_API_KEY"))160161# Attach a file by public URL (or use file(file_id) for uploaded files)162chat = client.chat.create(model="grok-4.6")163chat.append(user(164    "What is the weight of the XR-2000?",165    file(url="https://docs.x.ai/assets/api-examples/documents/product-specs.txt"),166))167168# Stream the response169is_thinking = True170for response, chunk in chat.stream():171    # Show tool calls as they happen172    for tool_call in chunk.tool_calls:173        print(f"\\nSearching: {tool_call.function.name}")174    175    if response.usage.reasoning_tokens and is_thinking:176        print(f"\\rThinking... ({response.usage.reasoning_tokens} tokens)", end="", flush=True)177    178    if chunk.content and is_thinking:179        print("\\n\\nAnswer:")180        is_thinking = False181    182    if chunk.content:183        print(chunk.content, end="", flush=True)184185print(f"\\n\\nUsage: {response.usage}")186```187188```javascriptOpenAISDK189import OpenAI from "openai";190191const client = new OpenAI({192    apiKey: process.env.XAI_API_KEY,193    baseURL: "https://api.x.ai/v1",194});195196// Attach a file by public URL (or use file_id for uploaded files)197const stream = await client.responses.create({198    model: "grok-4.6",199    input: [200        {201            role: "user",202            content: [203                { type: "input_text", text: "What is the weight of the XR-2000?" },204                { type: "input_file", file_url: "https://docs.x.ai/assets/api-examples/documents/product-specs.txt" },205            ],206        },207    ],208    stream: true,209});210211for await (const event of stream) {212    if (event.type === "response.output_text.delta") {213        process.stdout.write(event.delta);214    }215}216217console.log();218```219220## Multiple File Attachments221222Query across multiple documents simultaneously.223224```pythonXAI225import os226from xai_sdk import Client227from xai_sdk.chat import user, file228229client = Client(api_key=os.getenv("XAI_API_KEY"))230231# Attach files by public URL (or use file(file_id) for uploaded files)232chat = client.chat.create(model="grok-4.6")233chat.append(234    user(235        "Based on these documents, when did the project start, what is the budget, and how many people are on the team?",236        file(url="https://docs.x.ai/assets/api-examples/documents/project-timeline.txt"),237        file(url="https://docs.x.ai/assets/api-examples/documents/project-budget.txt"),238        file(url="https://docs.x.ai/assets/api-examples/documents/project-team.txt"),239    )240)241242response = chat.sample()243244print(f"Answer: {response.content}")245print("\\nDocuments searched: 3")246```247248```javascriptOpenAISDK249import OpenAI from "openai";250251const client = new OpenAI({252    apiKey: process.env.XAI_API_KEY,253    baseURL: "https://api.x.ai/v1",254});255256// Attach files by public URL (or use file_id for uploaded files)257const response = await client.responses.create({258    model: "grok-4.6",259    input: [260        {261            role: "user",262            content: [263                {264                    type: "input_text",265                    text: "Based on these documents, when did the project start, what is the budget, and how many people are on the team?",266                },267                { type: "input_file", file_url: "https://docs.x.ai/assets/api-examples/documents/project-timeline.txt" },268                { type: "input_file", file_url: "https://docs.x.ai/assets/api-examples/documents/project-budget.txt" },269                { type: "input_file", file_url: "https://docs.x.ai/assets/api-examples/documents/project-team.txt" },270            ],271        },272    ],273});274275const finalAnswer = response.output[response.output.length - 1].content[0].text;276console.log("Answer: " + finalAnswer);277console.log("Documents searched: 3");278```279280## Multi-Turn Conversations with Files281282Maintain context across multiple questions about the same documents. Use encrypted content to preserve file context efficiently across multiple turns.283284```pythonXAI285import os286from xai_sdk import Client287from xai_sdk.chat import user, file288289client = Client(api_key=os.getenv("XAI_API_KEY"))290291# Create a multi-turn conversation with encrypted content292chat = client.chat.create(293    model="grok-4.6",294    use_encrypted_content=True,  # Enable encrypted content for efficient multi-turn295)296297# First turn: Attach a file by public URL (or use file(file_id) for uploaded files)298chat.append(user(299    "What is the employee's name?",300    file(url="https://docs.x.ai/assets/api-examples/documents/employee-info.txt"),301))302response1 = chat.sample()303print("Q1: What is the employee's name?")304print(f"A1: {response1.content}\\n")305306# Add the response to conversation history307chat.append(response1)308309# Second turn: Ask about department (agentic context is retained via encrypted content)310chat.append(user("What department does this employee work in?"))311response2 = chat.sample()312print("Q2: What department does this employee work in?")313print(f"A2: {response2.content}\\n")314315# Add the response to conversation history316chat.append(response2)317318# Third turn: Ask about skills319chat.append(user("What skills does this employee have?"))320response3 = chat.sample()321print("Q3: What skills does this employee have?")322print(f"A3: {response3.content}\\n")323```324325```javascriptOpenAISDK326import OpenAI from "openai";327328const client = new OpenAI({329    apiKey: process.env.XAI_API_KEY,330    baseURL: "https://api.x.ai/v1",331});332333// Attach a file by public URL (or use file_id for uploaded files)334335// First turn: Ask about the document336const response1 = await client.responses.create({337    model: "grok-4.6",338    input: [339        {340            role: "user",341            content: [342                { type: "input_text", text: "What is the employee's name?" },343                { type: "input_file", file_url: "https://docs.x.ai/assets/api-examples/documents/employee-info.txt" },344            ],345        },346    ],347});348349console.log("Q1: What is the employee's name?");350console.log("A1: " + response1.output[response1.output.length - 1].content[0].text + "\\n");351352// Second turn: Ask about department (uses previous_response_id for context)353const response2 = await client.responses.create({354    model: "grok-4.6",355    previous_response_id: response1.id,356    input: [357        { role: "user", content: "What department does this employee work in?" },358    ],359});360361console.log("Q2: What department does this employee work in?");362console.log("A2: " + response2.output[response2.output.length - 1].content[0].text + "\\n");363364// Third turn: Ask about skills365const response3 = await client.responses.create({366    model: "grok-4.6",367    previous_response_id: response2.id,368    input: [369        { role: "user", content: "What skills does this employee have?" },370    ],371});372373console.log("Q3: What skills does this employee have?");374console.log("A3: " + response3.output[response3.output.length - 1].content[0].text + "\\n");375```376377## Combining Files with Other Modalities378379You can combine file attachments with images and other content types in a single message.380381```pythonXAI382import os383from xai_sdk import Client384from xai_sdk.chat import user, file, image385386client = Client(api_key=os.getenv("XAI_API_KEY"))387388# Attach files by public URL (or use file(file_id) for uploaded files)389chat = client.chat.create(model="grok-4.6")390chat.append(391    user(392        "Based on the attached care guide, do you have any advice about the pictured cat?",393        file(url="https://docs.x.ai/assets/api-examples/documents/cat-care.txt"),394        image("https://media.x.ai/v1/docs/example-cat-in-tree-8e9ac3e0.png"),395    )396)397398response = chat.sample()399400print(f"Analysis: {response.content}")401```402403```javascriptOpenAISDK404import OpenAI from "openai";405406const client = new OpenAI({407    apiKey: process.env.XAI_API_KEY,408    baseURL: "https://api.x.ai/v1",409});410411// Attach files by public URL (or use file_id for uploaded files)412const response = await client.responses.create({413    model: "grok-4.6",414    input: [415        {416            role: "user",417            content: [418                {419                    type: "input_text",420                    text: "Based on the attached care guide, do you have any advice about the pictured cat?",421                },422                { type: "input_file", file_url: "https://docs.x.ai/assets/api-examples/documents/cat-care.txt" },423                {424                    type: "input_image",425                    image_url: "https://media.x.ai/v1/docs/example-cat-in-tree-8e9ac3e0.png",426                },427            ],428        },429    ],430});431432const analysis = response.output[response.output.length - 1].content[0].text;433console.log("Analysis: " + analysis);434```435436## Combining Files with Code Execution437438For data analysis tasks, you can attach data files and enable the code execution tool. This allows Grok to write and run Python code to analyze and process your data.439440```pythonXAI441import os442from xai_sdk import Client443from xai_sdk.chat import user, file444from xai_sdk.tools import code_execution445446client = Client(api_key=os.getenv("XAI_API_KEY"))447448# Attach a file by public URL (or use file(file_id) for uploaded files)449chat = client.chat.create(450    model="grok-4.6",451    tools=[code_execution()],  # Enable code execution452)453454chat.append(455    user(456        "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",457        file(url="https://docs.x.ai/assets/api-examples/documents/sales-data.csv"),458    )459)460461# Stream the response to see code execution in real-time462is_thinking = True463for response, chunk in chat.stream():464    for tool_call in chunk.tool_calls:465        if tool_call.function.name == "code_execution":466            print("\\n[Executing Code]")467    468    if response.usage.reasoning_tokens and is_thinking:469        print(f"\\rThinking... ({response.usage.reasoning_tokens} tokens)", end="", flush=True)470    471    if chunk.content and is_thinking:472        print("\\n\\nAnalysis Results:")473        is_thinking = False474    475    if chunk.content:476        print(chunk.content, end="", flush=True)477478print(f"\\n\\nUsage: {response.usage}")479```480481```javascriptOpenAISDK482import OpenAI from "openai";483484const client = new OpenAI({485    apiKey: process.env.XAI_API_KEY,486    baseURL: "https://api.x.ai/v1",487});488489// Attach a file by public URL (or use file_id for uploaded files)490const stream = await client.responses.create({491    model: "grok-4.6",492    input: [493        {494            role: "user",495            content: [496                {497                    type: "input_text",498                    text: "Analyze this sales data and calculate: 1) Total revenue by product, " +499                        "2) Average units sold by region, " +500                        "3) Which product-region combination has the highest revenue",501                },502                { type: "input_file", file_url: "https://docs.x.ai/assets/api-examples/documents/sales-data.csv" },503            ],504        },505    ],506    tools: [{ type: "code_interpreter" }],507    stream: true,508});509510for await (const event of stream) {511    if (event.type === "response.output_text.delta") {512        process.stdout.write(event.delta);513    }514}515516console.log();517```518519The model will:5205211. Access the attached data file5222. Write Python code to load and analyze the data5233. Execute the code in a sandboxed environment5244. Perform calculations and statistical analysis5255. Return the results and insights in the response526527## Limitations and Considerations528529### Request Constraints530531* **No batch requests**: File attachments with document search are agentic requests and do not support batch mode (`n > 1`)532* **Streaming recommended**: Use streaming mode for better observability of document search process533534### Document Complexity535536* Highly unstructured or very long documents may require more processing537* Well-organized documents with clear structure are easier to search538* Large documents with many searches can result in higher token usage539540### Model Compatibility541542* **Recommended model**: `grok-4.6` for best document understanding543* **Agentic requirement**: File attachments require [agentic-capable](/developers/tools/overview) models that support server-side tools.544545## Next Steps546547Learn more about managing your files:548
Files main
Menu

Theme