AI models: the claude mod

mods/claude.luma asks Claude, Anthropic’s AI models, through the Messages API. You can ask questions, stream the answer as it is written, get JSON that fits a schema, and let Claude call Luma functions as tools. It is written in Luma, on web requests and their event streams. Copy it next to your program with mods/llm.luma, which it uses, and import it. It needs an API key from the Claude Console, in ANTHROPIC_API_KEY (an .env file works) or given to connect:

import "claude"

ai: claude.client = claude.connect()
print(ai.ask("In one sentence: what is a monad?"))

Asking

MethodWhat it does
claude.connect(), claude.connect(key)a client; with no key it reads ANTHROPIC_API_KEY
ai.ask(text)asks one question and gives the answer, a str
ai.ask(text, files)the same with files: PDFs, pictures (png, jpg, gif, webp) and text files
ai.stream(text, part)asks, and gives each piece of the answer to the function part as it comes; the whole answer is given at the end
ai.extract(text, schema)the answer as a json that fits the schema, ready to convert (see below)
ai.tool(name, about, schema, run)adds a tool Claude may call (see Tools)
ai.chat()starts a conversation
ai.count(text)how many tokens the text is as a question
ai.usage()the tokens used so far: input, output, written and read (the cache)
ai.batch()starts a batch: many questions at half the price, answered within a day
ai.upload(f)sends a file once: questions that give it then send its id
summary: str = ai.ask("Summarize this report in 3 points.", [file("report.pdf")])

answer: str = ai.stream("Write a haiku about the sea", fn(part: str) {
    stdout.write(part)   // shown as it is written; or send it on, to a web page
})

Settings

MethodSetsIf not set
ai.model(id)the model: "claude-opus-5-5", "claude-sonnet-5-5", "claude-haiku-5-5", …"claude-opus-5-5"
ai.system(text)the system prompt: who Claude is and how it answersnone
ai.effort(level)how hard the model thinks: "low", "medium", "high", "xhigh" or "max"the model’s own
ai.tokens(n)the most tokens an answer may have64000
ai.cache(true)prompt caching: what stays the same between requests is read from a cache, faster and cheaper (see below)off
ai.hour(true)keeps what is cached an hour instead of 5 minutes5 minutes
ai.turns(n)the most rounds of tool calls in one question20
ai.approve(check)a function asked before each tool call, fn(name: str, input: json): bool; false declines it (see Tools)every call runs
ai.fallback(false)turns off the refusal fallback (see below)on
ai.url(base)the API’s address, for a proxy or a test serverhttps://api.anthropic.com

Extract

extract asks for JSON that fits a schema, and the API makes sure the answer does (structured outputs). With schema the schema comes from an obj type, and the answer converts into it:

// An invoice read from a document.
obj Invoice {
    number: str        // as printed on the invoice
    total: float
    due: date
    lines: [Line]
}

obj Line {
    text: str
    amount: float
}

inv: Invoice = convert(ai.extract("Read this invoice.", schema(Invoice), [file("invoice.pdf")]))
print(inv.total)
  • A date-time or time the model writes with a zone (2025-03-01T10:00:00Z, +02:00) is put on the local clock, as convert reads it.
  • The API takes a part of JSON Schema. Limits on numbers and lengths (a byte’s 0 to 255) are left out of what is sent, and convert checks them. A map ({str: T}) or a type that contains itself can’t be used: claude.FAILED.

Tools

A tool is a Luma function Claude may call. It takes the input Claude gives, a json that fits the tool’s schema, and gives a str back. ask, stream, extract and say run the tools Claude calls, give it the results, and go on until Claude has answered:

// A city's weather.
obj Weather {
    city: str          // the city's name, e.g. Tartu
}

ai.tool("weather", "Call this when the user asks about the weather in a city", schema(Weather), fn(input: json): str {
    w: Weather = convert(input)
    return lookup(w.city)
})
print(ai.ask("Do I need an umbrella in Tartu today?"))
  • The description says when to call the tool; the field comments say what each input is.
  • An error the function throws goes back to Claude as a failed call, with its message, so Claude can try another way.
  • Claude can call several tools at once; they run one after the other, and their results go back together.
  • After turns(n) rounds (20) the question stops with claude.FAILED.
  • A tool that does something that can’t be undone (deletes, pays, sends) can be confirmed first: ai.approve(check). A call it declines doesn’t run; Claude is told the user declined it.
  • Tools from an MCP server are added the same way.
ai.approve(fn(name: str, input: json): bool {
    if name != "delete" {
        return true
    }
    answer: str = prompt("Delete ${input["path"]}? (y/n) ")
    return answer == "y"
})

A conversation

ai.chat() keeps what was said: each say sends the whole conversation, and adds the answer to it.

import "llm"

c: llm.talk = ai.chat()
print(c.say("My name is Ann."))
print(c.say("What is my name?"))
MethodWhat it does
c.say(text), c.say(text, files)says something and gives Claude’s answer
c.flow(text, part)the same, streaming the answer to part
c.historythe conversation so far, a json list of messages, as the API takes them (once if c is claude.chat)

A conversation is an llm.talk, as the conversations of the openai mod are, so code that talks works with either.

Batches

A batch sends many questions at once (Anthropic’s Message Batches API). They cost half as much, and are answered together: most batches within an hour, all within 24 hours. For work that doesn’t need its answers now: reading a thousand invoices, sorting reviews, an evaluation.

b: claude.batch = ai.batch()
texts.walk(i, t) {
    b.ask("review-${i}", "Is this review positive? Answer yes or no.\n\n${t}")
}
b.extract("inv-7", "Read this invoice", schema(Invoice), [file("7.pdf")])
id: str = b.send()
b.wait()
print(b.answer("review-0"))
inv: Invoice = convert(b.data("inv-7"))
MethodWhat it does
b.ask(id, text, files)adds a question; id is the program’s name for it: 1 to 64 letters, digits, - and _, each its own
b.extract(id, text, schema, files)adds a question whose answer is JSON that fits the schema
b.send()sends the batch, and gives its id: ai.batch(id) finds it again, in another run of the program
b.wait(every)waits until the batch has ended, asking every every seconds (30 if not given)
b.status()how it is: in_progress, canceling or ended; b.counts has how many questions are processing, succeeded, errored, canceled and expired
b.answer(id)the answer to a question, once the batch has ended
b.data(id)an extract’s answer, as JSON (date-times with a zone on the local clock when the batch was made in this run)
b.cancel()stops the batch: the questions not yet answered are canceled
  • Each question goes with the client’s model, system prompt, effort, tokens and caching. Its tools don’t: a batch can’t run them while it waits. Nor do streaming and the refusal fallback, which batches don’t have.
  • A question that failed, was canceled, or expired when the batch’s 24 hours ended, is claude.FAILED when its answer is asked for, with the reason; one cut by tokens(n) is CUT, a refusal REFUSED, as with ask. The others’ answers are there all the same.
  • The answers come in any order and are found by id. The API keeps them for 29 days.

Files sent once

Every question that gives a file sends its bytes. For a file used again and again (a long PDF asked about in many questions, or in every question of a batch), ai.upload(f) sends it once to Anthropic’s Files API, and from then on every question of that client that gives the same file sends only its id: ask, extract, a conversation, a batch.

manual: file = file("manual.pdf")
ai.upload(manual)
print(ai.ask("How do I reset the device?", [manual]))
print(ai.ask("What does error E7 mean?", [manual]))
ai.forget(manual)
MethodWhat it does
ai.upload(f)uploads a PDF, a picture or a text file, and gives its id
ai.upload(f, hours)the same, deleted by the API after so many hours (1 to 2160: 90 days); without it, kept until deleted
ai.forget(f)deletes it: questions send its bytes again
  • A request may be at most 32 MB, and a batch 256 MB: a file sent by its id doesn’t count toward that. A file may be up to 500 MB.
  • Uploaded files belong to the API key’s workspace: any key of it can use them. Uploading costs nothing; a file in a question costs its tokens, as before.
  • The client remembers what it uploaded while the program runs. Files that are no longer needed should be forgotten, or given hours.

Caching

With ai.cache(true), what a request has in common with one shortly before is read from Anthropic’s cache instead of being read again: a tenth of the input’s price or less, and faster. The mod marks where the parts that stay the same end:

  • after the tools and the system prompt, which are the same in every question;
  • after the files of a question, so that another question about the same files (the same manual, a different question) reads them from the cache;
  • after the whole prompt, so that each turn of a conversation reads what came before from the cache.

Writing to the cache costs 1.25 times the input’s price, so it pays when something is read again within 5 minutes. ai.hour(true) keeps it an hour, for questions further apart and for batches (writing then costs twice the price). A prompt too short to cache (about 1,000 to 4,000 tokens, by model) is simply not cached. ai.usage() shows what was written and read.

How it works

  • Every request streams, even ask: a long answer, or minutes of thinking, never runs into a timeout. The mod puts the message together from its events: text, thinking (sent back as it came, with its signature, as the API needs) and tool calls.
  • A rate limit or an overloaded API (429, 500, 529) is tried again, up to 3 times, after the time the API asks for (retry-after), else 1, 2 and 4 seconds. A spending cap is not tried again.
  • When a model declines a request for safety reasons, another model can answer in the same call (Anthropic’s server-side fallback). It is on for the models that have it, and ai.fallback(false) turns it off.
  • The requests use API version 2026-10-21.

Any model: llm.model

A claude.client is an llm.model, a trait of mods/llm.luma, and so is the openai mod’s client. A function that takes an llm.model works with Claude, OpenAI’s models, Ollama and llama-server alike. See Any model.

Errors

CodeWhen
claude.AUTH (100)no key, a wrong key, or a key without access
claude.LIMIT (101)a rate limit or an overloaded API after the retries, or a spending cap
claude.REFUSED (102)the model declined to answer; the message says why
claude.CUT (103)the answer reached tokens(n)
claude.FAILED (104)any other error the API gives (its message), a schema extract can’t use, a file it can’t send, too many tool rounds
err: error = nil
try err {
    answer: str = ai.ask(question)
}
if err != nil && err.code == claude.LIMIT {
    print("busy, try later")
}

Not available yet

  • Anthropic’s server tools (web search, code execution) and MCP servers.