The ecosystem · packages/ai
Claude, from your app's server
Stream answers to a page, read them into Roc types, send images and PDFs, give the model your app's functions as tools, and build agents that hand work to each other. Plain Roc on the server platform's HTTP client: no SDK, no platform change.
The package does the parts that are easy to get wrong: it rebuilds streamed messages exactly, retries when the API asks, makes a refusal an error, stops the model when the page goes, turns Roc types into JSON Schemas, and says what each call cost. Your app keeps its prompts, its tools, and what it does with the answers.
Installing it#
Name the package in the app's header with the two packages it uses (crypto and tools), and list its plugin. It names the server platform, so only the server's half of the app sees it. The example app's main.roc:
## packages/ai's example: a notes assistant. Its page has a chat with an assistant agent that hands
## work to two others, each a tool to it (`Team`: a notes keeper with three tools, `Notes.tools`, and
## a nutritionist), its answers streamed as they are written; a summary of the notes (`Ai.ask!`); and a
## meal described in words read into a typed record (`Ai.extract!`). The notes are in the server's
## memory (`Kv`), and so is each chat (`Chats`).
##
## ANTHROPIC_API_KEY from the environment, or from the `.env` where `rocx dev` runs; under `rocx dev`
## the model is claude-haiku-5-5 unless ANTHROPIC_MODEL names another. The tests run it against a
## stand-in for the API (test/stand-in.mjs).
app [program] { ai: "../main.roc", crypto: "../../crypto/main.roc", pf: platform "../../../server/platform/main.roc", tools: "../../tools/main.roc" }
import ai.Ai
import Generated/App
program = App.program({
init!: |_started| Ok({}),
plugins: [Ai.plugin({})],
})Then set ANTHROPIC_API_KEY (from console.anthropic.com) in the environment or in a .env where you run rocx dev (which passes it to the server). Without a key the server doesn't start, except under --dev, where it logs AI off: no ANTHROPIC_API_KEY and each call answers NoKey.
The model it asks:
| When | Model |
|---|---|
| by default | claude-opus-5-5 |
under --dev (rocx dev) | claude-haiku-5-5: fast and cheap while you develop |
ANTHROPIC_MODEL or the plugin's model names one | that model, under --dev too |
a request names one (model) | that model, for that call |
At start, the server logs the default model (ai.model), and the API's address if it isn't Anthropic's:
default AI model: claude-haiku-5-5Or pass each setting to Ai.plugin({ key, model, base_url }); code wins over the environment.
| Option | Environment | Default |
|---|---|---|
key | ANTHROPIC_API_KEY | none: outside --dev the server doesn't start |
model | ANTHROPIC_MODEL | claude-opus-5-5, or claude-haiku-5-5 under --dev |
base_url | ANTHROPIC_BASE_URL | https://api.anthropic.com |
ANTHROPIC_BASE_URL is the API's address; the example's tests point it at a stand-in.
Asking#
Every call takes an Ai.Request. All fields have defaults; give a prompt or messages.
| Field | Default | What it is |
|---|---|---|
prompt | "" | the user's message, after messages |
files | [] | images and PDFs sent with prompt, before its text (images and PDFs) |
messages | [] | the conversation so far: an earlier reply's messages, or Message.loaded |
system | "" | its role, the rules, the app's facts |
model | the plugin's | this call's model |
max_tokens | 64_000 | how much the model may write, thinking included |
effort | Medium | Low, Medium, High, XHigh or Max: how hard it thinks. More costs more and takes longer |
cache | Bool.True | use the API's prompt cache: a later call that starts the same reads it at a tenth of the price or less |
max_turns | 10 | how many turns run! takes at most |
label | "" | names the call on the log (ai.turn's label: "summary", an agent's name) |
updates | Bool.False | whether run! reports what the model is doing (updates) |
Low effort suits a chat or a label; High and above, careful work. Ai.ask! waits for the whole answer. The example sums up the notes with it:
import pf.Server
import pf.Endpoint
import ai.Ai
import ../../../../Notes
## POST /api/notes/summary: the notes, summed up in a sentence or two (`Ai.ask!`), and what that
## cost, in US dollars.
post! : { request : Server.Request, params : {}, context : c, body : {} } => Try({ text : Str, cost_usd : Dec }, Endpoint.Refusal)
post! = |_input| {
notes = Notes.all!({})
if notes.is_empty() {
Ok({ text: "There are no notes yet.", cost_usd: 0.0 })
} else {
listed = Str.join_with(notes.map(|note| "- ${note.text}"), "\n")
match Ai.ask!({ system: "Sum up these notes for the person who wrote them, in one plain sentence that speaks to them as you.", prompt: listed, effort: Low }) {
Ok(reply) => Ok({ text: reply.text, cost_usd: reply.cost_usd })
Err(problem) => Err(Status(502, Ai.explain(problem)))
}
}
}The reply is { text, messages, stop, usage, cost_usd, model }:
text: the answer;messages: the conversation with the answer, to go on with or keep;stop: why the model stopped:EndTurn,MaxTokens(text cut off),ToolUse, and a few more;usage: tokens spent,{ input, output, cache_read, cache_write }(summed over all turns, forrun!);cost_usd: what those tokens cost, in US dollars, aDec(what it costs);model: the model that wrote it.
Streaming to a page#
Ai.stream!(request, heard!) passes each piece of text to heard! as it is written, then answers the whole reply. In an endpoint's events!, send each piece as an event for the page's Endpoint.listen!:
events! = |{ params, .. }|
Ok(Events.stream(|{ send!, .. }|
match Ai.stream!({ prompt: params.question }, |text| send!({ text: text })) {
Ok(_) => send!({ text: "" })
Err(Stopped(Gone)) => Err(Gone)
Err(problem) => send!({ text: Ai.explain(problem) })
}))events! takes no body, so a page posts its question first, then listens on a path that names it. The example's chat posts to /api/chat/[chat], then listens there:
send! = || {
text = draft!().trim()
if !text.is_empty() and state!() != Thinking {
posted : Try({}, Http.Problem)
posted = Api.post_api_chat_chat({ chat: chat }).send!({ text: text })
…
match posted {
Ok({}) => {
set_state!(Thinking)
Endpoint.listen!(Api.events_api_chat_chat({ chat: chat }), heard!)
}
Err(problem) => set_state!(Failed(explain(problem)))
}
}
}heard! gets Event(said) for each event, then Ended or Failed(problem). On the server, post! adds the message to the chat's conversation (in Kv, by chat id). events! streams the assistant's answer (an agent, via Agent.chat!): its text, a status line while the team works (updates), then the current notes. If the team runs out of turns, its work is kept.
import pf.Server
import pf.Endpoint
import pf.Events
import ai.Agent
import ai.Ai
import ai.Message
import ../../../../Chats
import ../../../../Notes
import ../../../../Team
## POST /api/chat/<chat>: the user's message, added to the chat's conversation; the page then
## listens to this path's events for the answer.
post! : { request : Server.Request, params : { chat : Str }, context : c, body : { text : Str } } => Try({}, Endpoint.Refusal)
post! = |{ params, body, .. }| {
text = body.text.trim()
if text.is_empty() {
Err(BadRequest("say something"))
} else {
Chats.save!(params.chat, Chats.load!(params.chat).append(Message.user(text)))
Ok({})
}
}
## GET /api/chat/<chat>, asked for its events: the assistant's answer to the chat's last message
## (`Team.assistant`, which hands notes to the notes keeper and meals to the nutritionist, each an
## agent it uses as a tool): its text as it is written (`text`); what to show while the team works
## (`status`, from `agent`: a progress note the model wrote, or a tool or agent at work, with what it
## says it is doing); then the notes as they are now (`done`). When the page goes, the model stops.
## Each step (a turn whose tools have run) is kept as it is done, so a run the server stopped in the
## middle goes on from there the next time the page listens: the conversation then ends with the
## tools' results, the user's to answer as much as a message of theirs. An answer may spend
## `limit_usd`, its agents' calls included, checked at each step; the last event says what a
## finished answer cost (`cost_usd`).
events! : { request : Server.Request, params : { chat : Str }, context : c } => Try(Events({ text : Str, status : Str, agent : Str, done : Bool, problem : Str, notes : List({ id : U64, text : Str }), cost_usd : Dec }), Endpoint.Refusal)
events! = |{ params, .. }|
Ok(
Events.stream(
|{ send!, .. }| {
said! = |text| send!({ text: text, status: "", agent: "", done: Bool.False, problem: "", notes: [], cost_usd: 0.0 })
shown! = |agent, status| send!({ text: "", status: status, agent: agent, done: Bool.False, problem: "", notes: [], cost_usd: 0.0 })
finished! = |problem, cost_usd| send!({ text: "", status: "", agent: "", done: Bool.True, problem: problem, notes: Notes.all!({}), cost_usd: cost_usd })
# A page gone, beside the limit reached: what stops the team.
passed = |sent| sent.map_err(|Gone| Gone)
conversation = Chats.load!(params.chat)
waiting = conversation.last().map_ok(|message| message.role_of() == User) ?? Bool.False
if !waiting {
finished!("", 0.0)
} else {
ran = Agent.chat!(
Team.assistant,
conversation,
{},
|heard|
match heard {
Text(text) => passed(said!(text))
Calling(_) => Ok({})
Update(Progress({ agent, says })) => passed(shown!(agent, says))
Update(Using({ agent, tool, says })) => passed(shown!(agent, if (says.is_empty()) "Using ${tool}…" else says))
Step({ messages, cost_usd, .. }) => {
Chats.save!(params.chat, messages)
if (cost_usd > limit_usd) Err(OverLimit) else Ok({})
}
},
)
match ran {
Ok(reply) => {
Chats.save!(params.chat, reply.messages)
finished!("", reply.cost_usd)
}
Err(Stopped(Gone)) => Err(Gone)
Err(Stopped(OverLimit)) => finished!("That answer reached its limit of ${limit_usd.to_str()} USD; ask again to go on.", 0.0)
Err(TooManyTurns(reply)) => {
# What it did before it ran out of turns (its tools ran): kept, so the chat
# goes on from there.
Chats.save!(params.chat, reply.messages)
finished!("That took too many steps; ask again to go on.", reply.cost_usd)
}
Err(problem) => finished!(Ai.explain(problem), 0.0)
}
}
},
),
)
## What one answer may spend, in US dollars, the agents it hands work to included.
limit_usd : Dec
limit_usd = 0.25Typed answers#
Ai.extract!(request, Ai.schema(tags)) holds the model to the JSON Schema of the answer's type (the API's structured outputs), then reads the answer into it with Json, as an endpoint reads a body. The annotation gives the type:
Meal : { items : List({ food : Str, grams : U32, kcal : U32 }), total_kcal : U32 }
meal : Meal
meal = Ai.extract!({ system: "Read the meal into its foods.", prompt: said }, Ai.schema([]))?The example's meal endpoint reads what the user typed, and a photo when the form has one, into that type:
import pf.Server
import pf.Endpoint
import ai.Ai
## POST /api/meal: a meal described in words, and perhaps photographed (a form with a file,
## `photo`), read into a record (`Ai.extract!`): each food, about how much of it, and its calories,
## as the model reckons them.
post! : { request : Server.Request, params : {}, context : c, body : { text : Str } } => Try({ items : List({ food : Str, grams : U32, kcal : U32 }), total_kcal : U32 }, Endpoint.Refusal)
post! = |{ request, body, .. }| {
files =
match Server.file(request, "photo") {
Ok(photo) => [Image({ data: photo.bytes, mime: photo.type })]
Err(_) => []
}
match Ai.extract!({ system: "Read the meal the user describes, or shows in the photo, into its foods, one item per food (two eggs are one item): its name, about how many grams of it, and its calories. Reckon a usual portion when no amount is given. total_kcal is the items' calories added up.", prompt: body.text, files: files, effort: Low }, Ai.schema([])) {
Ok(meal) => Ok(meal)
Err(problem) => Err(Status(502, Ai.explain(problem)))
}
}- The schema is the platform's, the one the OpenAPI document uses.
tagslists the tags of the type's unions (["Breakfast", "Lunch"];[]for none), because a union's parser doesn't say them. - It is cut to the API's subset: every object closed (
additionalProperties: false),oneOfwritten asanyOf, and what the API doesn't enforce (an integer's range, a string's length) left out.Jsonchecks those while reading, so an answer outside aU32isInvalidJson, not a wrong number. - A type that isn't a record is asked for as an object's
resultfield. Ai.schemais a value, made where the type is known, likeMcpHttp.openapi({}).
An answer that reaches max_tokens before its JSON ends is Truncated.
Images and PDFs#
files sends images (Image({ data, mime }): JPEG, PNG, GIF or WebP) and PDFs (Pdf(bytes)) with the prompt, before its text, where the model reads them best. The meal endpoint above passes a photo from a form with a file (Server.file):
files =
match Server.file(request, "photo") {
Ok(photo) => [Image({ data: photo.bytes, mime: photo.type })]
Err(_) => []
}
Ai.extract!({ prompt: body.text, files: files }, Ai.schema([]))For a conversation, Message.user_with(parts) makes the user's message of text, images and PDFs in the order given. With several, a line of text before each names it:
Message.user_with([Text("Last week:"), Image(before), Text("This week:"), Image(after), Text("What changed?")])Files go as base64 in the request: up to 32 MB a request, an image up to 8,000 pixels a side, a PDF up to 600 pages. An image costs about its width times its height over 750 in tokens. A conversation keeps its files and sends them again each turn (from the prompt cache once cached).
Tools#
Ai.run!(request, tools, context, heard!) gives the model tools. The tools a turn asks for run in order, each given context, and their answers go back, until the model stops asking or max_turns is reached (TooManyTurns(reply), with its messages, usage and cost_usd to keep and bill). A turn cut off at max_tokens ends the run; its half-written tool call is neither run nor kept, so the conversation can be sent again. A refused turn runs no tools. heard! gets Text(piece) as the model writes, Calling(name) before a tool runs, with updates, Update(…) (below), and once a turn's tools have run, Step(…) (steps).
A tool is packages/tools' Tool, which the MCP package serves too, so one tool serves both. Ai.tool makes one from a name and description for the model, a function of the app's (given the typed arguments and the context), and the arguments' schema. The example's notes, and its notes keeper's three tools:
import pf.Kv
import ai.Ai
import tools.Tool
## The notes the assistant keeps, in the server's memory, and the tools that keep them: each a
## function of the app's (`add!`), made a tool in a line (`Ai.tool`), its arguments' schema the
## platform's. The same `Tool`s (packages/tools) could be an MCP server's (packages/mcp). Each says
## what a page shows while it runs (`doing`).
Notes := [].{
## A note: its number, and what it says.
Note : { id : U64, text : Str }
## Every note, oldest first.
all! : {} => List(Notes.Note)
all! = |{}| Kv.get!(key) ?? []
## The tools the chat's model has.
tools : List(Tool({}))
tools = [
Ai.tool("list_notes", "Lists every note, oldest first: its id and its text.", listed!, Ai.schema([])).doing("Looking through your notes…"),
Ai.tool("add_note", "Adds a note of the text given. Answers the note, with its id.", added!, Ai.schema([])).doing("Writing that down…"),
Ai.tool("remove_note", "Removes the note with the id given. Answers how many notes are left.", removed!, Ai.schema([])).doing("Crossing it out…"),
]
## What the chat's model is told.
guide : Str
guide = "You keep the user's notes for them, with the tools list_notes, add_note and remove_note. When they tell you something to remember, add it as a note; when they ask what they noted, list the notes first. Answer in a sentence or two, plain text, no Markdown."
}
key : Str
key = "example:notes"
listed! : {}, {} => Try(List(Notes.Note), Str)
listed! = |{}, {}| Ok(Notes.all!({}))
added! : { text : Str }, {} => Try(Notes.Note, Str)
added! = |given, {}| {
text = given.text.trim()
if text.is_empty() {
Err("A note needs some text.")
} else {
notes = Notes.all!({})
id = notes.last().map_ok(|note| note.id + 1) ?? 1
note = { id: id, text: text }
Kv.set!(key, notes.append(note), {})
Ok(note)
}
}
removed! : { id : U64 }, {} => Try({ left : U64 }, Str)
removed! = |given, {}| {
notes = Notes.all!({})
if notes.any(|note| note.id == given.id) {
left = notes.drop_if(|note| note.id == given.id)
Kv.set!(key, left, {})
Ok({ left: left.len() })
} else {
Err("There is no note ${given.id.to_str()}.")
}
}Tools from McpHttp.endpoint, McpHttp.tool and Tool.typed work too, with their own context (an MCP tool's is McpHttp.Caller(c): the request, the context, progress!). A tool's input streams in, then is checked against its type before the tool runs. The model gets back:
- the tool's answer, as JSON text;
- its
Err(why), as a tool error the model can read and act on; - arguments that don't fit the tool's type, input that isn't JSON, or an unknown tool, as tool errors too;
- a failure inside (
Failed), as"<name> failed.", its reason logged (ai.tool), not sent.
Agents#
An Agent(ctx) is a model with a role and tools: a plain value, made once and asked as often as needed:
keeper : Agent({})
keeper = {
name: "notes_keeper",
description: "Keeps the user's notes. Give it a task in words: add a note, say what is noted, or remove one.",
system: "You keep the user's notes, with the tools list_notes, add_note and remove_note.",
tools: Notes.tools,
effort: Low,
}
reply = Agent.ask!(keeper, "What did I note about the dentist?", {}, |_| Ok({}))?
reply = Agent.chat!(keeper, conversation, {}, heard!)?| Field | What it is |
|---|---|
name, description | what a model using the agent as a tool reads |
system | its role |
tools | the tools it may use ([]) |
model | its model (the plugin's) |
effort | how hard it thinks (Medium) |
max_turns, max_tokens | as a request's (10, and 64,000) |
updates | whether it reports what it is doing (Bool.False; updates) |
doing | what a page shows while another agent has it at work ("") |
Agent.ask!(agent, prompt, context, heard!) asks one message; Agent.chat!(agent, messages, context, heard!) answers a conversation whose last message is the user's. Both are Ai.run! with the agent's settings, logged under its name (label).
Agents as tools. agent.as_tool() is the agent as a Tool taking one argument, task: the work, in words. A team is plain values: specialists with their own prompts and tools, and a calling agent that stays in charge and knows which to ask. The example's chat (streaming to a page) talks to such a team:
import ai.Agent
import Notes
## The chat's agents: two specialists, and the assistant the user talks to, which hands each its
## part as a tool (`as_tool`). The notes keeper has the notes tools; the nutritionist has none, only
## its role. Each agent's turns are logged under its name. The assistant asks for `updates`, so the
## chat hears what to show while the team works: its progress notes (on the models that write them),
## each tool and agent as it starts, with what it says it is doing, the keeper's own tools too.
Team := [].{
## Keeps the notes, with the notes tools.
keeper : Agent({})
keeper = {
name: "notes_keeper",
description: "Keeps the user's notes. Give it a task in words: add a note (say exactly what it should say), say what is noted (about something, or all of it), or remove a note. It answers what it did or found.",
system: Notes.guide,
tools: Notes.tools,
effort: Low,
doing: "Seeing to your notes…",
}
## Reckons what a meal holds.
nutritionist : Agent({})
nutritionist = {
name: "nutritionist",
description: "Reckons the calories in a meal described in words, food by food, and the total. Give it the meal as the user said it.",
system: "You reckon the calories in a meal, food by food, with a usual portion where no amount is given. Answer with one short line per food and the total, plain text.",
effort: Low,
doing: "Counting the calories…",
}
## The assistant the chat talks to.
assistant : Agent({})
assistant = {
name: "assistant",
description: "The user's assistant.",
system: "You are the user's assistant. Hand anything about their notes to notes_keeper, and anything about what a meal holds to nutritionist; give each everything it needs, as it sees nothing else of the chat. To note a meal's calories, ask nutritionist first, then notes_keeper. Answer in a sentence or two, plain text, no Markdown.",
tools: [Team.keeper.as_tool(), Team.nutritionist.as_tool()],
effort: Low,
updates: Bool.True,
}
}- A task is a conversation of its own. The agent sees nothing of its caller's, so the task must hold everything. Say so in the caller's system prompt, as the assistant's does.
- An agent's text isn't streamed to its caller. With
updates, its progress notes and tools are (below). - Its answer is the tool's result. A failure is a tool error (
"<name> couldn't do it: …"), and so is a call with no task, without asking the API. - One context. Every agent in a team gives its tools the context it was given.
- An MCP tool too. Being a
Tool, an agent can be an MCP server's tool. - Its cost is its caller's. What its calls cost (its own agents' included, and a failed run's turns) goes back with its result, into the caller's
cost_usdand steps (what it costs).
Updates#
With updates: Bool.True, a request or agent sends its listener Update(update) (the tools package's Tool.Update) for a page to show while the model works:
Progress({ agent, says }): a note the model wrote between tool calls (“I'll look through your notes first.”). Asked for on Claude Opus 5.5, Sonnet 5.5, Fable and Mythos, whose reasoning stays hidden. Claude Haiku 5.5 writes them as plainText.Using({ agent, tool, says }): one of the app's tools starting, with what it says it is doing:Ai.tool(…).doing("Looking through your notes…"), or an agent'sdoingfield.- Agents used as tools pass theirs up, each under its name (
agent).
Your app decides where they go. The example's chat sends each as an event on its page's stream (above), shown as a status line: “Counting the calories…”, “Seeing to your notes…”, “notes_keeper: Writing that down…”. A page that started the work with a form can listen on a channel instead:
Agent.chat!(Team.assistant, conversation, {}, |heard|
match heard {
Update(update) => Ok(Endpoint.publish!(Api.channel_api_chat_chat_updates({ chat }), update))
_ => Ok({})
})Progress notes stay in the conversation and go back to the API. They are billed as output, shown or not.
Conversations#
A conversation is a List(Message); Message.user(text) makes the user's. The model's are kept exactly as the API wrote them, thinking blocks and signatures included, because the API needs them back. To go on, pass reply.messages as the next request's messages with a new prompt.
Message.save(messages) writes a conversation as JSON text, for Kv or a table; Message.load(text) reads it back exactly. Message.text(message) is its text alone, without thinking or tool use. The example keeps each chat in Kv for a day:
import pf.Kv
import ai.Message
## Each chat's conversation, kept in the server's memory for a day: as `Message.save` writes it,
## the model's thinking and its tools' use and all, so the next turn sends it back as it came.
Chats := [].{
## The chat's conversation; none for a chat not seen before.
load! : Str => List(Message)
load! = |chat| {
saved : Try(Str, [NotFound, BadValue(Str)])
saved = Kv.get!(key_of(chat))
match saved {
Ok(text) => Message.load(text) ?? []
Err(_) => []
}
}
## Keeps the chat's conversation.
save! : Str, List(Message) => {}
save! = |chat, messages| Kv.set!(key_of(chat), Message.save(messages), { ttl_ms: 86_400_000 })
}
key_of : Str -> Str
key_of = |chat| "example:chat:${chat}"After a mid-turn server-side fallback (another model took over where the first declined), the message drops the first model's thinking and tool uses before the fallback block, as the API asks, and keeps the block.
Steps#
Each time a turn's tools have run, run! tells its listener Step({ messages, usage, cost_usd }): the conversation so far, ending with the tools' results, and what the run has used and cost. Keep it, and if the server stops in the middle of a run (a deploy, a crash), send it again as a request's messages, with no prompt: the model reads its tools' results and goes on. The example's chat keeps each step, and the page's next listen goes on from there:
Agent.chat!(Team.assistant, conversation, {}, |heard|
match heard {
Step({ messages, .. }) => Ok(Chats.save!(chat, messages))
Text(text) => said!(text)
_ => Ok({})
})- In a job (packages/jobs), the same: keep each step under the job's key, and start from it when the job runs again.
- A run stopped while its tools ran goes on from before that turn, so the model asks for them again: a tool that changes something should be safe to run twice.
- The final turn isn't a step: the reply's
messagesare the whole conversation. - The listener's
Errstops the run (Stopped), so a step is also where a spending limit is checked (below).
What it costs#
Every reply has cost_usd: what its turns cost, in US dollars, at Anthropic's list prices (the package's Price module, read from the pricing page on 2026-11-29). Price.usd(model, usage) prices a usage you kept.
- A cache write is the 5-minute cache's, which the package asks for: 1.25 times the input's price.
- Claude Haiku 5.5 costs five times as much for a prompt over 100,000 tokens.
- After a fallback, each attempt is priced at its own model's prices. A decline before any output is free, except in the categories the API bills then (
bio,frontier_llm,reasoning_extraction). - Not counted: an account's discount, fast mode, US-only inference and the Batch API, none of which the package asks for.
- A model
Pricedoesn't know counts 0, with a warning on the log (ai.price). - An agent used as a tool counts in its caller's
cost_usdand steps, all the way down a team, so a limit checked at a step sees what the agents spent. A run'susagestays its own model's tokens, as tokens of different models don't add up. Ai.run_with_cost!isrun!with what the run cost however it ended (a failed run's turns are billed too), for an app that budgets failed runs.
A spending limit, checked at each step:
Ai.run!(request, tools, {}, |heard|
match heard {
Step({ cost_usd, .. }) if cost_usd > 3.0 => Err(OverBudget)
_ => Ok({})
})Each turn is logged with its tokens and cost (ai.turn):
{"msg":"ai.turn","label":"notes_keeper","model":"claude-haiku-5-5","stop":"tool_use","input":4,"cache_read":640,"cache_write":215,"output":112,"cost_usd":0.000089675,"ms":878}label: the request's, or the agent's name, so each agent's spending can be told apart (absent when empty);input: read without the cache;cache_read: read from the cache, at a tenth of the input price (a twentieth on Opus 5.5 and Sonnet 5.5, a fortieth on Fable 5.2 and 5.1);cache_write: written to the cache, once, at a quarter more;output: what the model wrote;cost_usd: the turn's cost;ms: how long it took.
With cache on (the default), each turn reads the previous one from the cache. A prompt under the model's minimum (512 to 4,096 tokens, by model) isn't cached, and asking costs nothing extra. The other levers are the model and effort: --dev uses claude-haiku-5-5, and the example Low effort.
What went wrong#
A failed call answers an Ai.Problem(err); Ai.explain(problem) puts it in a sentence:
| Tag | When |
|---|---|
NoKey | no ANTHROPIC_API_KEY (under --dev) |
Status(code, why) | the API refused: 400 the request, 401 the key, 429 too many (still, after two retries), 529 overloaded |
Unreachable(why), TimedOut, Broken(why) | no whole answer came |
Refused(category) | the model declined (the API's category, as "cyber"; often "") |
Truncated | extract!'s answer reached max_tokens before its JSON ended |
InvalidJson(why) | extract!'s answer didn't fit its type |
TooManyTurns(reply) | run! took max_turns turns and the model still wanted its tools; reply is what it did (its messages, usage and cost_usd) |
Stopped(err) | heard! answered Err(err): from an endpoint's events!, the page went (Stopped(Gone)); at a step, a spending limit |
A 408, 409, 429, 500, 502, 503, 504 or 529, or a stream error event meaning one (overloaded, a rate limit, a timeout, the API's own error), is retried twice after retry-after (a minute at most; else half a second, then a second), each retry logged (ai.retry). Nothing is retried once text has been passed on, or when the connection fails (Unreachable).
What it sends#
POST <base_url>/v1/messages, with anthropic-version: 2026-10-21, x-api-key and "stream": true: every call streams, so a long answer never times out (30 minutes at most). output_config carries the effort and extract!'s format; cache_control asks for the prompt cache. No sampling parameters (that version refuses temperature and the rest), no thinking (models think as they need; effort says how much), no forced tool_choice (Claude Opus 5.5 refuses it). With updates, on models that write progress notes, thinking is {"type": "adaptive", "display": "updates"} and anthropic-beta lists thinking-display-updates-2026-08-18.
effort is always sent. Claude Opus 4.5 and every model from 4.6 on accept it; Claude Haiku 4.5 and Sonnet 4.5 refuse it (a 400), so ANTHROPIC_MODEL can't name them. Opus 4.5 takes Low to High only, and the 4.6s have no XHigh.
On models that support it (claude-opus-5-5, claude-opus-5, claude-sonnet-5-5, claude-fable-5-2, claude-fable-5-1, and Mythos 5.2 and 5.1), it sends "fallbacks": "default" with anthropic-beta: server-side-fallback-2026-07-01. When the model's safety classifiers decline a request, the API reruns it, in the same call, on the model it names for that refusal. claude-haiku-5-5 has no fallback: a refusal there is Refused.
The example app#
packages/ai/example is a notes assistant, its notes and chats kept in Kv. Its page has:
- a streamed chat with an assistant that hands notes to a notes keeper and meals to a nutritionist, agents it uses as tools, the chat kept after each step and each answer under a spending limit;
- a button that sums up the notes (
ask!) and says what that cost; - a meal described in words, read into a typed record (
extract!); its endpoint takes a photo too.
| File | What it shows |
|---|---|
main.roc | the header and the plugin |
Notes.roc | the notes, and the three tools the notes keeper uses |
Team.roc | the agents: the notes keeper, the nutritionist, and the assistant that uses both as tools |
Chats.roc | each chat's conversation, saved and loaded |
routes/api/chat/[chat]/+server.roc | the chat: post! the message, then events! with Agent.chat!, each step kept, each answer under a limit |
routes/api/notes/summary/+server.roc | the summary, with ask!, and its cost_usd |
routes/api/meal/+server.roc | the meal, with extract!, from words or a photo (files) |
Ui/Chat.rocx | the page's chat: it posts, then listens |
Its tests (example/test/ai.test.mjs) run it against a stand-in for the API (example/test/stand-in.mjs), checking what the app sent and what it made of the answer; they never call the API. To try it for real, put your key in a .env:
echo 'ANTHROPIC_API_KEY=sk-ant-…' >> .env
bin/rocx dev packages/ai/example --port 8095On claude-haiku-5-5, one chat message took six model calls (the assistant three, the nutritionist one, the notes keeper two): about 4,400 tokens read, mostly cached, and 470 written, well under a tenth of a cent.
The package's README.md is the reference. Not built yet (see its PROPOSALS.md): files uploaded once (the Files API), batches, token counting, the API's own tools (web search, code execution), and an agent's text streamed to its caller.