Skip to main content

Intents

An intent is a function you declare by what it should do. The first time it's called, a model writes it in Stof, in a sandbox, and it has to pass your examples and checks before it's kept. Every call after runs what it wrote: no model, no tokens, the same answer every time.

import '@formata/ai';

#[intents]
Ai writer: { intent_model: 'anthropic/claude-sonnet-5-5' }

#[init]
fn key() { Http::secret('anthropic', env('ANTHROPIC_API_KEY'), ['api.anthropic.com']); }

intent fn greet(name: str) -> str { 'A greeting for the name, like "Hello, Ada!"' }

#[main]
fn main() {
pln(self.greet('Ada')); // a model writes greet, then it runs
pln(self.greet('CJ')); // runs what it wrote
}

Try it in the playground, with a mock model as the writer. That's the whole program: anthropic is a provider the Ai knows, so its key is all it needs (an app gives the key with secret(..) instead). The rest of this guide is what happens, and how to steer it.

What runs​

intent fn is a function with an #[intent] attribute and this body:

#[intent]
fn greet(name: str) -> str {
const text = 'A greeting for the name, like "Hello, Ada!"'; // the body you wrote, on each call
await intent(this, text, [name])
}

The body you write is what the function should do. It's worked out on each call, like any body, so it can be built from the document's data (self.<field>) or, with #[each], from the call's arguments. Then intent gives the function, its text, and its arguments to the document's intent executor: the intent's #[ai(obj)], or else the one object declared with #[intents]. With no executor, an intent gives null.

Like any function's, the body can be one expression without braces, so a short intent is one line, and a long one is a """ string:

intent fn greet(name: str) -> str 'A greeting for the name, like "Hello, Ada!"';

intent fn tidy(data: str) -> obj """
Shape this unstructured data into an object like { name, email, company }.
"""

async intent fn works like any async fn: a call gives a promise to await, so callers can run several intents at once.

An executor is any object with fn intent(func: fn, text: str, args: list). An Ai is one; so is a test double, or something that serves code written somewhere else. Stof itself knows nothing about models.

How it's written​

The Ai's model gets the function's signature, its text, your examples, and what its code may use. It writes the function with a define tool, and can try it with attempt. Each define:

  1. parses the code as untrusted source (declarations only: nothing runs while it's parsed),
  2. checks the signature is the one you declared,
  3. seals it in a sandbox: its code reads only what the intent grants, uses only the libraries it allows (pure ones by default: no network, files, or environment), and runs at most #[time(..)] per call (1s by default),
  4. runs your examples, then your checks.

The model sees what failed and defines it again until it passes. If it stops first (or runs out of #[turns(..)], 12 by default), the call throws an intent error and nothing is kept.

Examples and checks​

Examples are arguments and the results they must give. Checks are your functions, given the written function, that throw when it's wrong:

fn rounds_down(price: fn) {
assert_eq(price(3), 3);
assert(price(1000) < 1000, 'big orders get a discount');
}

#[examples([([10], 10), ([100], 90)])]
#[checks(self.rounds_down)]
intent fn price(seats: int) -> int {
'The price in dollars for this many seats: $1 each, 10% off at 100 or more, rounded down.'
}

A check can be an intent too, written by a model from what it should check. Its code is given the function under check, and calls it through a gate, since that function is outside its sandbox:

intent fn adds_one(func: fn) { 'Check that the function adds one to a number: throw when it does not.' }
// its code calls self.call_given(func, [1])

#[checks(self.adds_one)]
intent fn plus_one(n: int) -> int { 'Add one to n.' }

What its code may use​

Nothing outside its sandbox, unless you grant it:

catalog: { apples: 3, pears: 5 }

fn price(fruit: str) -> int { fruit == 'apples' ? 2 : 4 }

#[reads(self.catalog)] // its code reads self.catalog (read only)
#[calls(self.price)] // and calls self.price(..), which runs outside the sandbox, as itself
#[examples([([], 26)])]
intent fn total() -> int { 'The cost of all the fruit in the catalog.' }

To grant a whole API at once, give #[calls] an object: its code calls every function in it (its own, its type's, and its children's) as self.billing.charge(..) or self.billing.rules.discount(..), and reads everything in it. #[calls(root)] grants the whole document, apart from Ais and sealed parts inside it (give those directly). The code can't change the document itself: the functions it calls do that, so they're what you're granting. Each runs unconfined, as itself, so grant objects whose every function you'd let a stranger call.

billing: {
int rate: 3
fn charge(units: int) -> int { units * self.rate }
fn discount(total: int) -> int { total > 10 ? total - 1 : total }
}

#[calls(self.billing)]
intent fn bill(units: int) -> int { 'Charge for the units, then apply the discount.' }
WhatDefaultGrant with
The rest of the documentnothing (a path to it finds nothing)#[reads(obj or list)]: read only
Functions outside itnone#[calls(fn, obj, or a list)]
Librariesthe pure ones: Std, Str, Num, List, Map, Set, Tup, Time, Ver, Obj#[libs([..])] adds to them; #[libs('all')] allows any
The networknone#[hosts([..])], with 'Http' in its libraries
Time per call1s#[time(..)]

Even with Std, its code can't read the environment or exit. #[libs('all')] is for development: it allows any library the document has, the host's included. List the ones it needs for production (#[libs(['App'])]): the model is told each listed library's functions.

What the model sees​

Writing an intent is an agent run. The model gets:

  • a short guide to writing Stof well as its system prompt: the language, the rules that trip people up (Ex. which list methods change the list), and the pure libraries' functions. There are no docs to send it: production builds don't carry them.
  • the task: the signature, the intent's text, your examples, your checks' names, what it may read (as JSON) and call (as signatures), and its libraries (with the functions of any beyond the pure ones).
  • two tools: define (its code: checked, sandboxed, and run against your examples and checks) and attempt (runs its last code with arguments it picks), plus the intent's #[tools] and #[skills], if any.

Defaults you reuse​

#[intent_with(obj)] takes any of these from an object's fields, so a type can hold your house defaults:

#[type]
PricingIntent: {
str model: 'anthropic/claude-sonnet-5-5'
int turns: 6
ms time: 200ms
}
PricingIntent pricing: {}

#[intent_with(self.pricing)]
#[examples([([10], 100)])]
intent fn price(seats: int) -> int { 'The monthly price for this many seats: $10 each.' }

An intent's own attributes win over the object's fields.

When it's written again​

What was written stays in the document, under the Ai's intents, so it goes wherever the document goes. It's written again only when the intent changes: its text, signature, or attributes. The old code is dropped once the new code passes. Checks are known by name, so after you change a check's body, self.writer.forget_intent(self.price) has the next call write it again.

When an intent's text changes (Ex. it describes data the document fetched, and the data's shape changed), it's written again once, for the new text. If its text changes on every call (Ex. it uses an argument), it's written again on every call, which is slow and costs a model call each time: that's what #[each] is for.

self.writer.intent_source(self.price) is the code the model wrote, to read, review, or keep.

Writing ahead of time​

Intents are written lazily, the first time they're called. To write them when the document loads instead, call build_intents from a #[load] function. It writes every intent the Ai runs that isn't written yet, without running them, after the host has given the document its network and keys (doc.load(), or stof run, which loads first):

#[load]
fn intents() { await self.writer.build_intents(); }

To ship with no model at runtime, load the document in CI, export it (the written code is in it), and give the Ai write: false where it runs: it only runs what was written, and an intent that isn't written for what it says now is an intent error instead of a model call.

check_intents() checks what was written against the intents' examples and checks again, so stof test can too:

#[test]
fn intents_pass() { self.writer.check_intents(); }

A model on every call​

Some intents can't be code: judging a sentiment, replying to a ticket. With #[each], a model does the intent on every call: its text (worked out with the call's arguments) is the prompt, your #[calls] and #[tools] are its tools, and your #[reads] are JSON it sees. Its answer is the result: text for a str, else JSON, cast to the return type:

#[each]
intent fn reply(ticket: str, tone: str) -> str {
"""Reply to this support ticket in a ${tone} tone, in two sentences or fewer:

${ticket}"""
}

#[each]
intent fn orders(email: str) -> list { `The order numbers mentioned in this email: ${email}` }

Metering and policy​

An intent's model calls go through hooks like any call. Give it #[handlers(..)] (a meter, a policy), and they're capped, routed, and priced like the rest (each request's meta.intent says which intent it's for). A written intent costs nothing to run.

#[handlers(self.meter)]
intent fn greet(name: str) -> str { 'A greeting for the name.' }

See the README's Intents section for every attribute.