Skip to main content

AI From Your App

An app uses the package through a Stof document: it loads the package, gives the document its keys, and calls functions. Requests and responses cross as plain data (maps, which are what JSON becomes), so the app never builds Stof objects.

TypeScript​

import { StofDoc, initStof, toPlain } from '@formata/stof';

await initStof();
const doc = await StofDoc.new();
await doc.ai(); // the package (a module of its own, loaded now)
doc.parse(`
Ai ai: {}
`);
doc.allowHttp(['api.anthropic.com']);
doc.secret('anthropic', process.env.ANTHROPIC_API_KEY!, ['api.anthropic.com']);

const response = toPlain(await doc.call('ai.chat', {
model: 'anthropic/claude-sonnet-5-5',
messages: [{ role: 'user', content: 'Hello!' }],
}));
console.log(response.text, response.usage);

chat, agent, and count take the request as a map and give the response (or run) back as a map, and everything the call made in the document is dropped when it returns, so nothing builds up. Stof maps come to JavaScript as Map; toPlain turns them into plain objects. A run's messages are plain too, so an app can store a conversation and send it back later (messages: run.messages).

Python​

import os
from pystof import Doc

doc = Doc()
doc.ai()
doc.parse("""
Ai ai: {}
""")
doc.allow_http_hosts(['api.anthropic.com'])
doc.secret('anthropic', os.environ['ANTHROPIC_API_KEY'], ['api.anthropic.com'])

response = doc.call('ai.chat', [{'model': 'anthropic/claude-sonnet-5-5', 'messages': [{'role': 'user', 'content': 'Hello!'}]}])
print(response['text'], response['usage'])

doc.call(path, args) takes the arguments as a list and gives a dict back. An agent can run long: give the call a timeout (seconds), and an id to stop it from another thread with doc.exit(id).

Rust​

With the ai feature (in full):

let mut graph = Graph::default();
graph.load_ai()?;
graph.parse_stof_src(r#"
Ai ai: {}
fn ask(question: str) -> str {
const response = await self.ai.chat({'model': 'anthropic/claude-sonnet-5-5', 'messages': [{'role': 'user', 'content': question}]});
response.get('text')
}
"#, None, Profile::prod())?;
graph.allow_http_hosts(["api.anthropic.com"]);
graph.http_secret("anthropic", &key, ["api.anthropic.com"]);
let answer = Runtime::call(&mut graph, "ask", vec![Val::from("Hello!")])?;

Hooks in the app​

Hooks are Stof functions, and a hook can call a library function the app added. That's how events reach a UI, and how an app's own code can record usage or decide a tool call:

watcher: {
#[ai-event]
fn forward(ctx: obj, event: map) { App::event(event); }
}
fn ask(request: map) -> map { await self.ai.chat(request, self.watcher) }
doc.lib('App', 'event', (event: unknown) => {
const e = toPlain(event) as Record<string, any>;
if (e.type === 'text') process.stdout.write(e.text);
});
await doc.call('ask', { model: 'anthropic/claude-sonnet-5-5', messages: [{ role: 'user', content: 'Tell me a story.' }] });
def event(e):
if e['type'] == 'text': print(e['text'], end='')
doc.lib('App', 'event', event)
doc.call('ask', [{'model': 'anthropic/claude-sonnet-5-5', 'messages': [{'role': 'user', 'content': 'Tell me a story.'}]}])

Providers the app runs​

For a provider the package has no adapter for, a vendor's SDK, a company proxy, or a request that needs signing (Ex. AWS SigV4), the app makes the call and gives back events in the common format as they arrive. Hooks, tools, retries, fallback, and agents work as with any other provider.

doc.aiProvider('bedrock', async function* (call) {
// call: { provider, model, stream, request }, the request as the hooks left it
yield { type: 'start', id: 'r1', model: call.model };
for await (const piece of mySdk.stream(call.request)) yield { type: 'text', text: piece };
yield { type: 'usage', usage: { input: 120, output: 40 } };
yield { type: 'stop', stop: 'end' };
});
def bedrock(call):
yield {'type': 'start', 'id': 'r1', 'model': call['model']}
for piece in my_sdk.stream(call['request']):
yield {'type': 'text', 'text': piece}
yield {'type': 'stop', 'stop': 'end'}

doc.ai_provider('bedrock', bedrock)
self.ai.provider('bedrock', {'adapter': 'host'});

The request has model, system, messages, tools (with name, description, and schema), tool_choice, max_tokens, temperature, top_p, stop, parallel, and options. Give tool calls as tool_call events (id, name, args). An error event ({type: 'error', error: {kind, message, retry}}) fails the call as it says, so retry: true lets it be tried again; a thrown error isn't tried again. When the call ends early (closed, cancelled, or stopped with doc.exit), the generator is closed, so its finally runs.

A Rust host adds the AiHost library's open, next, and close functions itself (see the README's Hosts section).