Language
API

Conversations#

Ask a follow-up question that the model answers with the earlier turns in mind.

import { Router } from '@tokedex/sdk';
 
const router = new Router();
 
const first = await router.responses.create({ model: 'openai/gpt-6-luna', input: 'My name is Ada.' });
const second = await router.responses.create({
  model: 'openai/gpt-6-luna',
  previous_response_id: first.id,
  input: 'What is my name?',
});
for (const item of second.output) {
  if (item.type !== 'message') continue;
  for (const part of item.content) if (part.type === 'output_text') console.log(part.text);
}
from tokedex import Router
 
with Router() as router:
    first = router.responses.create(model="openai/gpt-6-luna", input="My name is Ada.")
    second = router.responses.create(
        model="openai/gpt-6-luna", previous_response_id=first.id, input="What is my name?"
    )
    print(second.output_text)
use tokedex::{Router, wire};
 
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let router = Router::builder().build()?;
    let first = router.responses().create(wire::ResponsesRequest::new("openai/gpt-6-luna", "My name is Ada.")).await?;
    let mut next = wire::ResponsesRequest::new("openai/gpt-6-luna", "What is my name?");
    next.previous_response_id = wire::Presence::Value(first.id);
    let second = router.responses().create(next).await?;
    println!("{}", second.output_text());
    Ok(())
}
import { Router, type ChatCompletionRequest } from '@tokedex/sdk';
 
const router = new Router();
 
const history: ChatCompletionRequest['messages'] = [{ role: 'user', content: 'My name is Ada.' }];
const first = await router.chat.completions.create({ model: 'openai/gpt-6-luna', messages: history });
const second = await router.chat.completions.create({
  model: 'openai/gpt-6-luna',
  messages: [...history, first.choices[0]!.message, { role: 'user', content: 'What is my name?' }],
});
console.log(second.choices[0]?.message.content);
from typing import Any
 
from tokedex import Router
 
with Router() as router:
    history: list[Any] = [{"role": "user", "content": "My name is Ada."}]
    first = router.chat.completions.create(model="openai/gpt-6-luna", messages=history)
    history.append(first.choices[0].message.model_dump(exclude_none=True))
    history.append({"role": "user", "content": "What is my name?"})
    second = router.chat.completions.create(model="openai/gpt-6-luna", messages=history)
    print(second.choices[0].message.content)
use tokedex::{Router, wire};
 
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let router = Router::builder().build()?;
    let mut history = vec![wire::Message::user("My name is Ada.")];
    let first = router.chat().completions().create(wire::ChatCompletionsRequest::new("openai/gpt-6-luna", history.clone())).await?;
    history.push(first.choices[0].message.clone());
    history.push(wire::Message::user("What is my name?"));
    let second = router.chat().completions().create(wire::ChatCompletionsRequest::new("openai/gpt-6-luna", history)).await?;
    if let Some(wire::Content::Text(text)) = &second.choices[0].message.content {
        println!("{text}");
    }
    Ok(())
}
import { Router, type MessageRequest } from '@tokedex/sdk';
 
const router = new Router();
 
const history: MessageRequest['messages'] = [{ role: 'user', content: 'My name is Ada.' }];
const first = await router.messages.create({ model: 'openai/gpt-6-luna', messages: history });
const second = await router.messages.create({
  model: 'openai/gpt-6-luna',
  messages: [...history, { role: 'assistant', content: first.content }, { role: 'user', content: 'What is my name?' }],
});
for (const block of second.content) if (block.type === 'text') console.log(block.text);
from typing import Any
 
from tokedex import Router
 
with Router() as router:
    history: list[Any] = [{"role": "user", "content": "My name is Ada."}]
    first = router.messages.create(model="openai/gpt-6-luna", messages=history)
    reply = [block.model_dump(exclude_none=True) for block in first.content]
    history.append({"role": "assistant", "content": reply})
    history.append({"role": "user", "content": "What is my name?"})
    second = router.messages.create(model="openai/gpt-6-luna", messages=history)
    print("".join(block.text for block in second.content if block.type == "text"))
use tokedex::{Router, wire};
 
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let router = Router::builder().build()?;
    let ask = |history: Vec<wire::Message>| wire::MessagesRequest::new("openai/gpt-6-luna", history);
    let mut history = vec![wire::Message::user("My name is Ada.")];
    let first = router.messages().create(ask(history.clone())).await?;
    history.push(wire::Message::assistant(wire::Content::Blocks(first.content)));
    history.push(wire::Message::user("What is my name?"));
    let second = router.messages().create(ask(history)).await?;
    for block in &second.content {
        if let wire::ContentBlock::Text { text, .. } = block {
            println!("{text}");
        }
    }
    Ok(())
}
import { Router, type GeminiRequest } from '@tokedex/sdk';
 
const router = new Router();
const model = 'google/gemini-3.5-flash-lite';
 
const history: GeminiRequest['contents'] = [{ role: 'user', parts: [{ text: 'My name is Ada.' }] }];
const first = await router.generateContent.create({ model, contents: history });
const reply = first.candidates?.[0]?.content;
const second = await router.generateContent.create({
  model,
  contents: [...history, ...(reply ? [reply] : []), { role: 'user', parts: [{ text: 'What is my name?' }] }],
});
for (const part of second.candidates?.[0]?.content?.parts ?? []) if ('text' in part) console.log(part.text);
from typing import Any
 
from tokedex import Router
 
with Router() as router:
    history: list[Any] = [{"role": "user", "parts": [{"text": "My name is Ada."}]}]
    first = router.generate_content.create(model="google/gemini-3.5-flash-lite", contents=history)
    history.append(first.model_dump(exclude_none=True)["candidates"][0]["content"])
    history.append({"role": "user", "parts": [{"text": "What is my name?"}]})
    second = router.generate_content.create(model="google/gemini-3.5-flash-lite", contents=history)
    for candidate in second.candidates or []:
        print("".join(getattr(part, "text", "") for part in candidate.content.parts))
use serde_json::{Value, json};
use tokedex::{Router, wire};
 
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let router = Router::builder().build()?;
    let model = "google/gemini-3.5-flash-lite";
    let ask = |history: &[Value]| serde_json::from_value::<wire::GeminiRequest>(json!({ "contents": history }));
    let mut history = vec![json!({ "role": "user", "parts": [{ "text": "My name is Ada." }] })];
    let first = router.generate_content().create(model, ask(&history)?).await?;
    history.push(serde_json::to_value(&first)?["candidates"][0]["content"].clone());
    history.push(json!({ "role": "user", "parts": [{ "text": "What is my name?" }] }));
    let second = serde_json::to_value(router.generate_content().create(model, ask(&history)?).await?)?;
    for part in second["candidates"][0]["content"]["parts"].as_array().into_iter().flatten() {
        println!("{}", part["text"].as_str().unwrap_or_default());
    }
    Ok(())
}
code
Your name is Ada.

It needs OPENAI_API_KEYGEMINI_API_KEY, and each call is billed by OpenAIGoogle.

The Router stored the first turn, so the second request sends only the new input and the first reply's id as previous_response_id.

OpenAI ResponsesOpenAI Chat CompletionsAnthropic MessagesGemini GenerateContent keeps nothing between calls, so the second request carries the whole conversation: the first message, the model's reply and the new question. Send each reply back as it arrived. Some providers put state the next call needs into the reply, such as Gemini's thought signatures.

Add cargo add serde_json to write the request as JSON.

Conversation lifetime#

You can continue a turn for 24 hours, unless its request set store: false. The Router keeps its record of each turn in memory, so the turns end with the process; set ttlMsttl_ms in the continuation options below to change the 24 hours.

A turn continues only on the same model and the same provider account. A missing, expired or foreign turn fails with a GatewayError of kind PreviousResponseNotFound.

Create one Router and reuse it for every turn: by default each Router keeps its stored turns in its own memory, so a new Router cannot find them. A restart ends every conversation too; when conversations must survive restarts, run through a gateway or give the Router the shared stores below.

To keep the history yourself instead, set store: false and send the earlier turns, including each reply's output items, in input. Do this when a conversation must move to another model, or outlive the process without the shared stores below, since a stored turn continues only on its own model and, by default, only in memory.

A conversation lasts as long as you keep the history. The Router stores nothing for OpenAI ResponsesOpenAI Chat CompletionsAnthropic MessagesGemini GenerateContent, so save each turn where your application keeps its data and send it all with every request. If you want the Router to keep the turns for you, write against OpenAI Responses instead: it is the only API whose turns the Router stores.

Because every request carries the whole conversation, the prompt grows with each turn. Count the tokens of a long conversation before you send it, so it does not outgrow the model's context window.

runToolsrun_tools keeps nothing between calls: pass the conversation in its messages.

Share a conversation between processes#

Give every Router the same shared stores in continuation: a store, a leaseStore and an ownerKey, backed by your own database. Routers with the same owner key continue each other's turns. The store implements ReservableResponseContinuationStore from @tokedex/engine (get, put and reserveWrite), and the lease store implements ContinuationLeaseStore from @tokedex/sdk (put, resolve and consume).

Give every Router the same shared stores in continuation: a store, a lease_store and an owner_key, backed by your own database. Routers with the same owner key continue each other's turns. The store implements ReservableResponseContinuationStore from tokedex.engine (get, reserve, renew, release and commit), and the lease store implements ContinuationLeaseStore from tokedex.core.ir (put, resolve and consume).

Give every Router the same shared stores with Router::builder().continuation(…): a store, a lease_store and an owner_key, backed by your own database. Routers with the same owner key continue each other's turns. The store implements tokedex::router::ResponseContinuationStore (get, reserve, renew, release and put), and the lease store implements tokedex_core::continuation::ContinuationLeaseStore (put, resolve and consume).

Load the history from your own database in any process and send it. The Router needs nothing else.

The default in-memory store holds up to 4,096 turns per owner, subject to a 64 MiB per-owner byte limit. Each stored turn, including replay history and routing metadata, must fit in 1,500,000 UTF-8 bytes. A request can fit and still exceed this limit once the provider has answered. In gateway mode this returns HTTP 413 with code continuation_too_large.

When a shared store does not answer, or the call outlives its hold on the stored turn, the call fails with the kind ServiceUnavailableUnavailableConflict. Python and Rust fail with Conflict when another call is continuing the same turn. Send the request again.

Through a gateway#

The gateway stores the turns instead of your process, so any process with the same API key can continue them. See Run through a gateway. When several processes must share conversations, start with a gateway before you build shared stores of your own, because it gives you that sharing with no store code.

Nothing changes: you still send the whole history with each request. See Run through a gateway.

Next: Stream a reply or Run through a gateway.