Language
API

Images and files#

Send an image or a file with your prompt and ask the model about it, in your API's own image and file fields.

import { Router } from '@tokedex/sdk';
 
const router = new Router();
 
const response = await router.responses.create({
  model: 'openai/gpt-6-luna',
  input: [
    {
      type: 'message',
      role: 'user',
      content: [
        { type: 'input_image', image_url: 'https://example.com/chart.png' },
        { type: 'input_text', text: 'What does this chart show? Answer in one sentence.' },
      ],
    },
  ],
});
const text = response.output
  .flatMap((item) => (item.type === 'message' ? item.content : []))
  .flatMap((part) => (part.type === 'output_text' ? [part.text] : []))
  .join('');
console.log(text);
from tokedex import Router
 
with Router() as router:
    response = router.responses.create(
        model="openai/gpt-6-luna",
        input=[
            {
                "type": "message",
                "role": "user",
                "content": [
                    {"type": "input_image", "image_url": "https://example.com/chart.png"},
                    {
                        "type": "input_text",
                        "text": "What does this chart show? Answer in one sentence.",
                    },
                ],
            }
        ],
    )
    print(response.output_text)
use serde_json::json;
use tokedex::{Router, wire};
 
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let router = Router::builder().build()?;
    let request: wire::ResponsesRequest = serde_json::from_value(json!({
        "model": "openai/gpt-6-luna",
        "input": [{
            "type": "message",
            "role": "user",
            "content": [
                { "type": "input_image", "image_url": "https://example.com/chart.png" },
                { "type": "input_text", "text": "What does this chart show? Answer in one sentence." },
            ],
        }],
    }))?;
    let response = router.responses().create(request).await?;
    println!("{}", response.output_text());
    Ok(())
}
import { Router } from '@tokedex/sdk';
 
const router = new Router();
 
const completion = await router.chat.completions.create({
  model: 'openai/gpt-6-luna',
  messages: [
    {
      role: 'user',
      content: [
        { type: 'image_url', image_url: { url: 'https://example.com/chart.png' } },
        { type: 'text', text: 'What does this chart show? Answer in one sentence.' },
      ],
    },
  ],
});
console.log(completion.choices[0]?.message.content);
from tokedex import Router
 
with Router() as router:
    completion = router.chat.completions.create(
        model="openai/gpt-6-luna",
        messages=[
            {
                "role": "user",
                "content": [
                    {"type": "image_url", "image_url": {"url": "https://example.com/chart.png"}},
                    {"type": "text", "text": "What does this chart show? Answer in one sentence."},
                ],
            }
        ],
    )
    print(completion.choices[0].message.content)
use serde_json::json;
use tokedex::{Router, wire};
 
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let router = Router::builder().build()?;
    let request: wire::ChatCompletionsRequest = serde_json::from_value(json!({
        "model": "openai/gpt-6-luna",
        "messages": [{
            "role": "user",
            "content": [
                { "type": "image_url", "image_url": { "url": "https://example.com/chart.png" } },
                { "type": "text", "text": "What does this chart show? Answer in one sentence." },
            ],
        }],
    }))?;
    let completion = router.chat().completions().create(request).await?;
    if let Some(wire::Content::Text(text)) = &completion.choices[0].message.content {
        println!("{text}");
    }
    Ok(())
}
import { Router } from '@tokedex/sdk';
 
const router = new Router();
 
const message = await router.messages.create({
  model: 'openai/gpt-6-luna',
  messages: [
    {
      role: 'user',
      content: [
        { type: 'image', source: { type: 'url', url: 'https://example.com/chart.png' } },
        { type: 'text', text: 'What does this chart show? Answer in one sentence.' },
      ],
    },
  ],
});
const text = message.content.flatMap((block) => (block.type === 'text' ? [block.text] : [])).join('');
console.log(text);
from tokedex import Router
 
with Router() as router:
    message = router.messages.create(
        model="openai/gpt-6-luna",
        messages=[
            {
                "role": "user",
                "content": [
                    {"type": "image", "source": {"type": "url", "url": "https://example.com/chart.png"}},
                    {"type": "text", "text": "What does this chart show? Answer in one sentence."},
                ],
            }
        ],
    )
    print("".join(block.text for block in message.content if block.type == "text"))
use serde_json::json;
use tokedex::{Router, wire};
 
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let router = Router::builder().build()?;
    let request: wire::MessagesRequest = serde_json::from_value(json!({
        "model": "openai/gpt-6-luna",
        "messages": [{
            "role": "user",
            "content": [
                { "type": "image", "source": { "type": "url", "url": "https://example.com/chart.png" } },
                { "type": "text", "text": "What does this chart show? Answer in one sentence." },
            ],
        }],
    }))?;
    let message = router.messages().create(request).await?;
    for block in &message.content {
        if let wire::ContentBlock::Text { text, .. } = block {
            println!("{text}");
        }
    }
    Ok(())
}
import { Router } from '@tokedex/sdk';
 
const router = new Router();
 
const result = await router.generateContent.create({
  model: 'google/gemini-3.5-flash-lite',
  contents: [
    {
      role: 'user',
      parts: [
        { fileData: { mimeType: 'image/png', fileUri: 'https://example.com/chart.png' } },
        { text: 'What does this chart show? Answer in one sentence.' },
      ],
    },
  ],
});
for (const part of result.candidates?.[0]?.content?.parts ?? []) {
  if ('text' in part) console.log(part.text);
}
from tokedex import Router
 
with Router() as router:
    result = router.generate_content.create(
        model="google/gemini-3.5-flash-lite",
        contents=[
            {
                "role": "user",
                "parts": [
                    {"fileData": {"mimeType": "image/png", "fileUri": "https://example.com/chart.png"}},
                    {"text": "What does this chart show? Answer in one sentence."},
                ],
            }
        ],
    )
    print("".join(getattr(part, "text", "") for part in result.candidates[0].content.parts))
use serde_json::json;
use tokedex::{Router, wire};
 
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let router = Router::builder().build()?;
    let request: wire::GeminiRequest = serde_json::from_value(json!({
        "contents": [{
            "role": "user",
            "parts": [
                { "fileData": { "mimeType": "image/png", "fileUri": "https://example.com/chart.png" } },
                { "text": "What does this chart show? Answer in one sentence." },
            ],
        }],
    }))?;
    let result = router.generate_content().create("google/gemini-3.5-flash-lite", request).await?;
    let candidates = result.candidates.unwrap_or_default();
    if let Some(content) = candidates.first().and_then(|candidate| candidate.content.as_ref()) {
        for part in &content.parts {
            if let Some(text) = part["text"].as_str() {
                println!("{text}");
            }
        }
    }
    Ok(())
}
code
The chart shows sales rising each quarter.

It needs OPENAI_API_KEY, and the call is billed by OpenAI. Run it with npx tsx images.ts.

It needs OPENAI_API_KEY, and the call is billed by OpenAI.

It needs OPENAI_API_KEY, and the call is billed by OpenAI. Add cargo add serde_json to write the request as JSON.

It needs GEMINI_API_KEY, and the call is billed by Google. Run it with npx tsx images.ts.

It needs GEMINI_API_KEY, and the call is billed by Google.

It needs GEMINI_API_KEY, and the call is billed by Google. Add cargo add serde_json to write the request as JSON.

The image goes in an input_image part next to your question. image_url takes a URL or a base64 data URL.

The message's content becomes a list of parts: an image_url part and a text part with your question.

The image goes in an image block whose source is a URL, base64 data or a file ID.

The image goes in a fileData part with its mimeType next to a text part. Google reads the fileUri itself.

Send an image from a local file#

Encode the file as base64 and send it as a data URL, data:<media type>;base64,<data>, in the same field as a URL.

import { readFile } from 'node:fs/promises';
 
const chart = `data:image/png;base64,${(await readFile('chart.png')).toString('base64')}`;
const completion = await router.chat.completions.create({
  model: 'openai/gpt-6-luna',
  messages: [
    {
      role: 'user',
      content: [
        { type: 'image_url', image_url: { url: chart } },
        { type: 'text', text: 'Describe this image in one sentence.' },
      ],
    },
  ],
});
import base64
from pathlib import Path
 
chart = "data:image/png;base64," + base64.b64encode(Path("chart.png").read_bytes()).decode()
completion = router.chat.completions.create(
    model="openai/gpt-6-luna",
    messages=[
        {
            "role": "user",
            "content": [
                {"type": "image_url", "image_url": {"url": chart}},
                {"type": "text", "text": "Describe this image in one sentence."},
            ],
        }
    ],
)
use base64::Engine;
use serde_json::json;
use tokedex::wire;
 
let data = base64::engine::general_purpose::STANDARD.encode(std::fs::read("chart.png")?);
let request: wire::ChatCompletionsRequest = serde_json::from_value(json!({
    "model": "openai/gpt-6-luna",
    "messages": [{
        "role": "user",
        "content": [
            { "type": "image_url", "image_url": { "url": format!("data:image/png;base64,{data}") } },
            { "type": "text", "text": "Describe this image in one sentence." },
        ],
    }],
}))?;
let completion = router.chat().completions().create(request).await?;

This is the Chat Completions form; on OpenAI ResponsesOpenAI Chat CompletionsAnthropic MessagesGemini GenerateContent, put the same data URL in input_image's image_url.

import { readFile } from 'node:fs/promises';
 
const message = await router.messages.create({
  model: 'openai/gpt-6-luna',
  messages: [
    {
      role: 'user',
      content: [
        {
          type: 'image',
          source: { type: 'base64', media_type: 'image/png', data: (await readFile('chart.png')).toString('base64') },
        },
        { type: 'text', text: 'Describe this image in one sentence.' },
      ],
    },
  ],
});
import base64
from pathlib import Path
 
data = base64.b64encode(Path("chart.png").read_bytes()).decode()
message = router.messages.create(
    model="openai/gpt-6-luna",
    messages=[
        {
            "role": "user",
            "content": [
                {"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": data}},
                {"type": "text", "text": "Describe this image in one sentence."},
            ],
        }
    ],
)
use base64::Engine;
use serde_json::json;
use tokedex::wire;
 
let data = base64::engine::general_purpose::STANDARD.encode(std::fs::read("chart.png")?);
let request: wire::MessagesRequest = serde_json::from_value(json!({
    "model": "openai/gpt-6-luna",
    "messages": [{
        "role": "user",
        "content": [
            { "type": "image", "source": { "type": "base64", "media_type": "image/png", "data": data } },
            { "type": "text", "text": "Describe this image in one sentence." },
        ],
    }],
}))?;
let message = router.messages().create(request).await?;

Send plain base64 in data, without a data: prefix, and the file's type in media_type.

import { readFile } from 'node:fs/promises';
 
const result = await router.generateContent.create({
  model: 'google/gemini-3.5-flash-lite',
  contents: [
    {
      role: 'user',
      parts: [
        { inlineData: { mimeType: 'image/png', data: (await readFile('chart.png')).toString('base64') } },
        { text: 'Describe this image in one sentence.' },
      ],
    },
  ],
});
import base64
from pathlib import Path
 
data = base64.b64encode(Path("chart.png").read_bytes()).decode()
result = router.generate_content.create(
    model="google/gemini-3.5-flash-lite",
    contents=[
        {
            "role": "user",
            "parts": [
                {"inlineData": {"mimeType": "image/png", "data": data}},
                {"text": "Describe this image in one sentence."},
            ],
        }
    ],
)
use base64::Engine;
use serde_json::json;
use tokedex::wire;
 
let data = base64::engine::general_purpose::STANDARD.encode(std::fs::read("chart.png")?);
let request: wire::GeminiRequest = serde_json::from_value(json!({
    "contents": [{
        "role": "user",
        "parts": [
            { "inlineData": { "mimeType": "image/png", "data": data } },
            { "text": "Describe this image in one sentence." },
        ],
    }],
}))?;
let result = router.generate_content().create("google/gemini-3.5-flash-lite", request).await?;

An inlineData part takes plain base64 in data, without a data: prefix, and the file's type in mimeType.

Add cargo add base64 to encode the file.

Send a PDF or another file#

const response = await router.responses.create({
  model: 'openai/gpt-6-luna',
  input: [
    {
      type: 'message',
      role: 'user',
      content: [
        { type: 'input_file', file_url: 'https://example.com/report.pdf' },
        { type: 'input_text', text: 'Summarise this report in three bullet points.' },
      ],
    },
  ],
});
response = router.responses.create(
    model="openai/gpt-6-luna",
    input=[
        {
            "type": "message",
            "role": "user",
            "content": [
                {"type": "input_file", "file_url": "https://example.com/report.pdf"},
                {"type": "input_text", "text": "Summarise this report in three bullet points."},
            ],
        }
    ],
)
use serde_json::json;
use tokedex::wire;
 
let request: wire::ResponsesRequest = serde_json::from_value(json!({
    "model": "openai/gpt-6-luna",
    "input": [{
        "type": "message",
        "role": "user",
        "content": [
            { "type": "input_file", "file_url": "https://example.com/report.pdf" },
            { "type": "input_text", "text": "Summarise this report in three bullet points." },
        ],
    }],
}))?;
let response = router.responses().create(request).await?;

An input_file part takes the file by URL in file_url. For a local file, send a base64 data URL, such as data:application/pdf;base64,…, in file_data, with the file's name in filename so the model knows what it reads.

import { readFile } from 'node:fs/promises';
 
const report = `data:application/pdf;base64,${(await readFile('report.pdf')).toString('base64')}`;
const completion = await router.chat.completions.create({
  model: 'openai/gpt-6-luna',
  messages: [
    {
      role: 'user',
      content: [
        { type: 'file', file: { file_data: report, filename: 'report.pdf' } },
        { type: 'text', text: 'Summarise this report in three bullet points.' },
      ],
    },
  ],
});
import base64
from pathlib import Path
 
report = "data:application/pdf;base64," + base64.b64encode(Path("report.pdf").read_bytes()).decode()
completion = router.chat.completions.create(
    model="openai/gpt-6-luna",
    messages=[
        {
            "role": "user",
            "content": [
                {"type": "file", "file": {"file_data": report, "filename": "report.pdf"}},
                {"type": "text", "text": "Summarise this report in three bullet points."},
            ],
        }
    ],
)
use base64::Engine;
use serde_json::json;
use tokedex::wire;
 
let data = base64::engine::general_purpose::STANDARD.encode(std::fs::read("report.pdf")?);
let request: wire::ChatCompletionsRequest = serde_json::from_value(json!({
    "model": "openai/gpt-6-luna",
    "messages": [{
        "role": "user",
        "content": [
            { "type": "file", "file": { "file_data": format!("data:application/pdf;base64,{data}"), "filename": "report.pdf" } },
            { "type": "text", "text": "Summarise this report in three bullet points." },
        ],
    }],
}))?;
let completion = router.chat().completions().create(request).await?;

A file part takes the file as a base64 data URL in file_data. Give it a filename, so the model knows what it reads. Chat Completions has no URL field for a file. Download the file yourself, or use OpenAI Responses or Anthropic Messages.

const message = await router.messages.create({
  model: 'openai/gpt-6-luna',
  messages: [
    {
      role: 'user',
      content: [
        { type: 'document', source: { type: 'url', url: 'https://example.com/report.pdf' } },
        { type: 'text', text: 'Summarise this report in three bullet points.' },
      ],
    },
  ],
});
message = router.messages.create(
    model="openai/gpt-6-luna",
    messages=[
        {
            "role": "user",
            "content": [
                {"type": "document", "source": {"type": "url", "url": "https://example.com/report.pdf"}},
                {"type": "text", "text": "Summarise this report in three bullet points."},
            ],
        }
    ],
)
use serde_json::json;
use tokedex::wire;
 
let request: wire::MessagesRequest = serde_json::from_value(json!({
    "model": "openai/gpt-6-luna",
    "messages": [{
        "role": "user",
        "content": [
            { "type": "document", "source": { "type": "url", "url": "https://example.com/report.pdf" } },
            { "type": "text", "text": "Summarise this report in three bullet points." },
        ],
    }],
}))?;
let message = router.messages().create(request).await?;

A PDF goes in a document block, whose source takes the same three forms as an image's.

const result = await router.generateContent.create({
  model: 'google/gemini-3.5-flash-lite',
  contents: [
    {
      role: 'user',
      parts: [
        { fileData: { mimeType: 'application/pdf', fileUri: 'https://example.com/report.pdf' } },
        { text: 'Summarise this report in three bullet points.' },
      ],
    },
  ],
});
result = router.generate_content.create(
    model="google/gemini-3.5-flash-lite",
    contents=[
        {
            "role": "user",
            "parts": [
                {"fileData": {"mimeType": "application/pdf", "fileUri": "https://example.com/report.pdf"}},
                {"text": "Summarise this report in three bullet points."},
            ],
        }
    ],
)
use serde_json::json;
use tokedex::wire;
 
let request: wire::GeminiRequest = serde_json::from_value(json!({
    "contents": [{
        "role": "user",
        "parts": [
            { "fileData": { "mimeType": "application/pdf", "fileUri": "https://example.com/report.pdf" } },
            { "text": "Summarise this report in three bullet points." },
        ],
    }],
}))?;
let result = router.generate_content().create("google/gemini-3.5-flash-lite", request).await?;

A file takes the same parts as an image, with the file's own mimeType: fileData by URL, or inlineData for a local file.

Send a file the provider already stores#

const response = await router.responses.create({
  model: 'openai/gpt-6-luna',
  input: [
    {
      type: 'message',
      role: 'user',
      content: [
        { type: 'input_file', file_id: 'file-abc123' },
        { type: 'input_text', text: 'Summarise this report in three bullet points.' },
      ],
    },
  ],
});
response = router.responses.create(
    model="openai/gpt-6-luna",
    input=[
        {
            "type": "message",
            "role": "user",
            "content": [
                {"type": "input_file", "file_id": "file-abc123"},
                {"type": "input_text", "text": "Summarise this report in three bullet points."},
            ],
        }
    ],
)
use serde_json::json;
use tokedex::wire;
 
let request: wire::ResponsesRequest = serde_json::from_value(json!({
    "model": "openai/gpt-6-luna",
    "input": [{
        "type": "message",
        "role": "user",
        "content": [
            { "type": "input_file", "file_id": "file-abc123" },
            { "type": "input_text", "text": "Summarise this report in three bullet points." },
        ],
    }],
}))?;
let response = router.responses().create(request).await?;

input_image takes file_id the same way.

const completion = await router.chat.completions.create({
  model: 'openai/gpt-6-luna',
  messages: [
    {
      role: 'user',
      content: [
        { type: 'file', file: { file_id: 'file-abc123' } },
        { type: 'text', text: 'Summarise this report in three bullet points.' },
      ],
    },
  ],
});
completion = router.chat.completions.create(
    model="openai/gpt-6-luna",
    messages=[
        {
            "role": "user",
            "content": [
                {"type": "file", "file": {"file_id": "file-abc123"}},
                {"type": "text", "text": "Summarise this report in three bullet points."},
            ],
        }
    ],
)
use serde_json::json;
use tokedex::wire;
 
let request: wire::ChatCompletionsRequest = serde_json::from_value(json!({
    "model": "openai/gpt-6-luna",
    "messages": [{
        "role": "user",
        "content": [
            { "type": "file", "file": { "file_id": "file-abc123" } },
            { "type": "text", "text": "Summarise this report in three bullet points." },
        ],
    }],
}))?;
let completion = router.chat().completions().create(request).await?;

The Router reads the ID as an OpenAI file.

const message = await router.messages.create({
  model: 'anthropic/claude-haiku-5.5',
  messages: [
    {
      role: 'user',
      content: [
        { type: 'document', source: { type: 'file', file_id: 'file_abc123' } },
        { type: 'text', text: 'Summarise this report in three bullet points.' },
      ],
    },
  ],
});
message = router.messages.create(
    model="anthropic/claude-haiku-5.5",
    messages=[
        {
            "role": "user",
            "content": [
                {"type": "document", "source": {"type": "file", "file_id": "file_abc123"}},
                {"type": "text", "text": "Summarise this report in three bullet points."},
            ],
        }
    ],
)
use serde_json::json;
use tokedex::wire;
 
let request: wire::MessagesRequest = serde_json::from_value(json!({
    "model": "anthropic/claude-haiku-5.5",
    "messages": [{
        "role": "user",
        "content": [
            { "type": "document", "source": { "type": "file", "file_id": "file_abc123" } },
            { "type": "text", "text": "Summarise this report in three bullet points." },
        ],
    }],
}))?;
let message = router.messages().create(request).await?;

The Router reads the ID as an Anthropic file, so the model here is Anthropic's.

Send the ID the provider issued when you uploaded the file. The Router sends the call only to that provider and the one account whose key can read the file, with no fallback to another. A file ID fails before anything is sent when the model reaches no account that can read it, or more than one.

Use a file ID only for a file you upload once and send in many requests to that provider. For anything else, send a URL or the data, so that a failed attempt can still move to another provider or account.

Put the URI that Google's Files API returned in fileUri, with the file's mimeType, as in the last section. Upload the file with the key the Router uses, GEMINI_API_KEY, so Google lets the call read it.

URLs the Router downloads#

Some providers read an image or a PDF only as data inside the request. When the model you call is served by one of them, the Router downloads each https URL from your process and sends the bytes instead. It connects only to public addresses, follows at most five redirects, gives up after 30 seconds, and reads at most 16 URLs per request and 12 MB per file. A URL it cannot read fails the call with a DocumentInputErrorRouterError::DocumentInput before the provider is called.

Send a file on a private network or behind a sign-in as data, not as a URL. The Router connects only to public addresses, so such a URL fails whenever the model's provider needs the bytes.

On GenerateContent the Router never downloads a URL: Google reads each fileUri itself, and the Router passes it on unchanged. On the other three APIs, the Router downloads a URL for a provider that reads images and PDFs only as data inside the request.

So send a file that only your own network can reach as inlineData, not as a fileUri: Google, not your process, has to read the URI.

The files the Router downloads for one request may total 12 MB.

The files the Router downloads for one request may total 16 MiB.

To send those downloads through your own network code, pass documentFetch when you create the Router. It must connect only to public addresses and must not follow redirects itself.

To send those downloads through your own network code, pass an httpx2 transport as fetch_document when you create the Router.

To send those downloads through your own network code, pass your transport to the builder's document_transport.

Check whether a model accepts an image or a file#

Send the request. A model that cannot take an image or a file refuses it before anything is sent, so nothing is billed.

The refusal is a GatewayError with kind CapabilityUnsupported.

The refusal is a FidelityError, from tokedex.core.ir, that names the image or file part.

The refusal is RouterError::FidelityError inside tokedex::Error::Router, and it names the image or file part.

Before you move a feature that sends images or files to a new model, send it one such request, so you learn before release whether the model takes the input. A refusal costs nothing.

A router tries only the models that accept the input, so call one when any capable model will do. router.models.list()router.models().list() does not say which inputs a model takes. Custom models take text and function tools only, so they refuse every image and file.

Next: Structured output, Choose a model or Errors, retries and timeouts.