Roc Solid
Markup in Roc · pages on a native server · components in WebAssembly

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/example/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:

WhenModel
by defaultclaude-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 onethat 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-5

Or pass each setting to Ai.plugin({ key, model, base_url }); code wins over the environment.

OptionEnvironmentDefault
keyANTHROPIC_API_KEYnone: outside --dev the server doesn't start
modelANTHROPIC_MODELclaude-opus-5-5, or claude-haiku-5-5 under --dev
base_urlANTHROPIC_BASE_URLhttps://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.

FieldDefaultWhat 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
modelthe plugin'sthis call's model
max_tokens64_000how much the model may write, thinking included
effortMediumLow, Medium, High, XHigh or Max: how hard it thinks. More costs more and takes longer
cacheBool.Trueuse the API's prompt cache: a later call that starts the same reads it at a tenth of the price or less
max_turns10how many turns run! takes at most
label""names the call on the log (ai.turn's label: "summary", an agent's name)
updatesBool.Falsewhether 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:

packages/ai/example/routes/api/notes/summary/+server.roc
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 }:

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!:

+server.roc, in part
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:

packages/ai/example/Ui/Chat.rocx, in part
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.

packages/ai/example/routes/api/chat/[chat]/+server.roc
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.25

Typed 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:

packages/ai/example/routes/api/meal/+server.roc
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)))
	}
}

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:

packages/ai/example/Notes.roc
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:

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!)?
FieldWhat it is
name, descriptionwhat a model using the agent as a tool reads
systemits role
toolsthe tools it may use ([])
modelits model (the plugin's)
efforthow hard it thinks (Medium)
max_turns, max_tokensas a request's (10, and 64,000)
updateswhether it reports what it is doing (Bool.False; updates)
doingwhat 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:

packages/ai/example/Team.roc
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,
	}
}

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:

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:

packages/ai/example/Chats.roc
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({})
	})

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 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}

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:

TagWhen
NoKeyno 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 "")
Truncatedextract!'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:

FileWhat it shows
main.rocthe header and the plugin
Notes.rocthe notes, and the three tools the notes keeper uses
Team.rocthe agents: the notes keeper, the nutritionist, and the assistant that uses both as tools
Chats.roceach chat's conversation, saved and loaded
routes/api/chat/[chat]/+server.rocthe chat: post! the message, then events! with Agent.chat!, each step kept, each answer under a limit
routes/api/notes/summary/+server.rocthe summary, with ask!, and its cost_usd
routes/api/meal/+server.rocthe meal, with extract!, from words or a photo (files)
Ui/Chat.rocxthe 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 8095

On 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.