Getting Started
The AI package calls models, runs tools, and runs agents from a Stof document. It's built into Stof, so there's nothing to install.
Load it
In Stof code (the CLI, Rust with the ai feature, Python), import it:
import '@formata/ai';
From TypeScript, load it on the document first (the package is a module of its own, fetched only then):
const doc = await StofDoc.new();
await doc.ai();
doc.parse(src);
Python's doc.ai() and Rust's graph.load_ai() do the same.
A first call, with no key
An Ai holds providers and settings. The mock adapter answers from a script, so this runs anywhere, offline:
import '@formata/ai';
Ai ai: {}
#[main]
fn main() {
self.ai.provider('test', {'adapter': 'mock', 'script': [{'text': 'Hello from the mock.'}]});
using request = new {
model: 'test/any',
messages: [new { role: 'user', content: 'Say hello.' }],
};
const response = await self.ai.chat(request);
pln(response.text); // Hello from the mock.
}The examples with the mock provider run here, in your browser. From the CLI: stof run hello.stof.
A model is named 'provider/model': everything after the first slash is the provider's model name. A request is an
object (or a map); using drops it, and everything the call made under it, when the function ends.
A real provider
Swap the mock for a real model: anthropic and openai are providers an Ai knows, so naming one
(model: 'anthropic/claude-sonnet-5-5') is enough, once there's a key of the same name. A provider's key is the
name of a key, so the document never sees the key itself. Other providers are configured with provider (see
Providers).
The host allows the API's host and gives the key, only for that host:
doc.allowHttp(['api.anthropic.com']);
doc.secret('anthropic', process.env.ANTHROPIC_API_KEY, ['api.anthropic.com']);
doc.allow_http_hosts(['api.anthropic.com'])
doc.secret('anthropic', os.environ['ANTHROPIC_API_KEY'], ['api.anthropic.com'])
The CLI has no host to give keys, so a document run there gives its own, Ex. from the environment. It has the key then, so this is for your own documents. A key the host gave with the same name wins, so the same document works in an app too:
#[init]
fn key() { Http::secret('anthropic', env('ANTHROPIC_API_KEY'), ['api.anthropic.com']); }
Then model: 'anthropic/claude-sonnet-5-5' (or any model the provider has) in the request.
The response
chat waits for the whole answer and returns the response:
pln(response.text); // the answer
pln(response.stop); // 'end', 'max_tokens', 'tool_use', ...
pln(response.usage); // input, output, cache_read, cache_write, reasoning
usage.input is the input that wasn't read from a cache, so each count can be priced on its own. To continue the
conversation, add the answer's message and the next question, and call again:
request.messages.push_back(response.message);
request.messages.push_back(new { role: 'user', content: 'Now shorter.' } on request);
const next = await self.ai.chat(request);
A call that fails throws an error map (kind, message, retry, status); see the README's Errors.
Streaming
stream opens the call, and next gives its events until it's done:
const call = await self.ai.stream(request);
loop {
const event = await self.ai.next(call);
if (event == null) break;
if (event.get('type') == 'text') pln(event.get('text'));
}
Or give chat a handler object with an #[ai-event] hook: chat streams by itself then, and the hook sees each
event (see Hooks).
An agent
Mark functions with #[tool], and agent runs the model and the tools it asks for until it's done:
import '@formata/ai';
Ai ai: {}
support: {
#[tool({'description': 'Look up an order', 'params': {'id': 'the order number'}})]
fn order(id: int) -> map { {'id': id, 'status': 'shipped'} }
}
#[main]
fn main() {
self.ai.provider('test', {'adapter': 'mock', 'script': [
{'tool_calls': [{'name': 'order', 'args': {'id': 1042}}]},
{'text': 'Order 1042 shipped.'},
]});
using request = new {
model: 'test/any',
messages: [new { role: 'user', content: 'Where is order 1042?' }],
};
const run = await self.ai.agent(request, self.support);
pln(run.text); // Order 1042 shipped.
pln(run.turns); // 2 (model calls)
pln(run.tool_calls); // 1
}The model can call only the tools it was offered. More in Tools and agents.