Spanish Total.js
English
Documentation For AI agents
Contents

AI models

Register AI model handlers with NEWAIMODEL() and build chat requests with AIMODEL(): messages, config, callbacks, promises, streaming and tool calls.

.md GitHub
On this page

Total.js 5 has a small layer for large language models in the aimodel.js module. It does not talk to any AI service by itself. You register a model handler with NEWAIMODEL() that knows how to call your provider (OpenAI, Ollama, Claude, Gemini or your own server), and the rest of the application builds requests with AIMODEL() without caring where the model runs.

// definitions/ai.js
NEWAIMODEL('assistant', function(ai, callback) {
    // ai.payload.model, ai.payload.messages, ai.config, ai.options.stream
    callback(null, 'Hello from the model');
});

// anywhere in the application
AIMODEL('assistant').user('Say hello').callback(function(err, response) {
    console.log(err, response);
});

The full list of functions, methods and properties is in the reference of AI models.

Registering a model

NEWAIMODEL(name, [config], handler) stores the handler in F.aimodels under name. The name can contain several names separated by commas; each one gets the same handler and the same config. Registering a name again replaces the previous handler. Put the registrations in a file in /definitions/ so they exist before the first request.

NEWAIMODEL('gpt-4o-mini, gpt-4o', { url: 'https://api.openai.com/v1/chat/completions', token: 'sk-...', temperature: 0.2 }, function(ai, callback) {
    // the same handler serves both models
});

The handler is called as handler(ai, callback):

  • ai is the request object created by AIMODEL(). The handler reads ai.payload (what to send), ai.config (how to send it) and ai.options.stream (whether the caller wants a stream).
  • callback(err, response) ends the request. Whatever you pass as response reaches the caller unchanged, so you decide if it is a string, the parsed JSON of the provider or your own object.

The config object of NEWAIMODEL() holds defaults. Before the handler runs, every key of it that the request did not set with ai.configure() is copied into ai.config. This is the place for the URL, the token and default generation settings.

Building a request

AIMODEL(name) returns a new request for the model name. Its methods return the request, so you chain them:

MethodWhat it does
system(content, [merge])Adds a message with the role system
user(content, [merge])Adds a message with the role user
assistant(content, [merge])Adds a message with the role assistant
message(role, content, [merge])Adds a message with any role
prompt(content)Sets payload.prompt, for single-prompt endpoints
think()Sets payload.think = true
configure(obj)Copies the keys of obj into ai.config
tool(content)Adds a tool definition to payload.tools

The messages are kept in ai.payload.messages as { role, content } objects in the order you add them. When content is an object, its keys are copied into the message instead, so you can add fields like images or tool_call_id:

AIMODEL('assistant')
    .system('You are a helpful assistant. Answer briefly.')
    .user('What is Total.js?')
    .assistant('A Node.js framework.')
    .user({ content: 'Describe this picture', images: [base64] })
    .configure({ temperature: 0 })
    .callback(console.log);

Merging messages

The merge argument is a separator string. When it is set and a message with the same role already exists, the content is appended to the first such message, joined with the separator, instead of adding a new message. With object content, the keys are copied into that message. This is handy when you build the system instructions in several steps:

var ai = AIMODEL('assistant');
ai.system('You are a support agent.');
ai.system('Answer in English.', '\n');
ai.system('Never share internal links.', '\n');
// one system message with three lines

Running the request

A request does not run when you create it. It runs when you call one of callback(), stream() or promise(). The run is delayed to the next turn of the event loop, so calling stream() and then callback() in the same chain runs the handler only once with both set.

AIMODEL('assistant').user('Hello').callback(function(err, response) {
    if (err)
        console.log('AI error:', err);
    else
        console.log(response);
});

promise([$]) wraps the callback in a Promise. An error rejects it with an Error. When you pass the $ object of an action or a controller, an error is sent to $.invalid(err) instead and the promise does not settle, so the request ends with the error response:

NEWACTION('Assistant/ask', {
    name: 'Ask the assistant',
    input: '*question:String',
    action: async function($, model) {
        var response = await AIMODEL('assistant').user(model.question).promise($);
        $.callback({ answer: response });
    }
});

When no model with the name is registered, the callback receives the error 'AI model not found.'.

Streaming

stream(fn) stores fn in ai.options.stream and starts the request. The framework does not call fn itself: it is the handler that reads the answer of the provider piece by piece and calls ai.options.stream() with each piece. When the stream ends, the handler calls callback() as usual. A request started with stream() alone has no callback, so add callback() when you need to know the end.

AIMODEL('assistant')
    .user('Write a short poem about Node.js')
    .stream(function(text) {
        process.stdout.write(text);
    })
    .callback(function(err) {
        console.log('\nDone', err || '');
    });

Tools

tool(content) adds a tool definition to ai.payload.tools, an array that every request has. The framework does not check the content; the handler sends it to the provider in the format the provider expects. An inline schema can create the common function format for you with schema.toAITool(name) (see JSON schemas).

var weather = {
    type: 'function',
    function: {
        name: 'weather',
        description: 'Returns the weather forecast for a city',
        parameters: { type: 'object', properties: { city: { type: 'string' } }, required: ['city'] }
    }
};

AIMODEL('assistant')
    .user('What is the weather in Bratislava?')
    .tool(weather)
    .callback(console.log);

In the handler, add the tools to the body when there are some:

if (ai.payload.tools.length)
    body.tools = ai.payload.tools;

When the model asks for a tool, run it and send the result back in a new request: add the assistant message with the tool call and a message with the role tool using message('tool', { content: result, tool_call_id: id }).

Parsing streams with AIPARSER()

AIPARSER(provider) returns a stream parser that understands the streaming formats of the common providers. You write the raw chunks of the response into it and it collects the text, the reasoning ("thinking") and the tool calls, and emits events as they arrive.

ProviderFormat
ollamaOllama /api/chat and /api/generate (and its OpenAI-compatible endpoint)
openai, openai_chatOpenAI Chat Completions
openai_responsesOpenAI Responses API
claude, anthropicAnthropic Messages
gemini, googleGoogle Gemini
anything elseA generic parser that reads content, text, thinking, reasoning, message.* and tool_calls

parser.write(chunk) takes a Buffer, a string, a Uint8Array or an ArrayBuffer with raw lines (newline-delimited JSON or server-sent events with data:), or an already parsed object. It returns the current output. parser.end() processes the rest of the buffer, emits done and returns the final output:

{
    content: 'The text of the answer',
    thinking: 'The reasoning, if the model sends it',
    tools: [], // the tool calls: { id, name, arguments }
    reasoning: 'content' // or 'thinking' or 'tool'
}

The events are content, thinking, tool_start, tool_update, tool_arguments and done; * listens to all of them. Each event object has type and the data of the event, for example delta (the new piece) and content (all text so far). With it, the streaming part of the handler becomes:

var parser = AIPARSER('openai');

parser.on('content', function(e) {
    ai.options.stream(e.delta);
});

for await (var chunk of res.body)
    parser.write(Buffer.from(chunk));

var output = parser.end();
callback(null, output);

The parser does not depend on AIMODEL(), so you can also use it to read a stream that you requested yourself.

Tool calls in a stream

The parser collects the tool calls of every provider in the table above. OpenAI (openai and openai_responses) and Claude send the arguments of a call as pieces of JSON text; Ollama, Gemini and the generic parser send them whole. The parser joins the pieces of each call, and it keeps calls apart when they arrive in separate chunks: Ollama calls by their index (or function.index), and generic calls without an id by their arguments (an object is a complete call, a string is a piece of the call at the same position). The parser returns the calls with parser.end() in output.tools, with the arguments parsed:

var parser = AIPARSER('openai');

// recorded server-sent events of an OpenAI Chat Completions stream
var chunks = [
    'data: {"choices":[{"index":0,"delta":{"role":"assistant","tool_calls":[{"index":0,"id":"call_A","type":"function","function":{"name":"weather","arguments":""}}]}}]}\n\n',
    'data: {"choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"{\\"city\\":"}}]}}]}\n\n',
    'data: {"choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\\"Bratislava\\"}"}}]}}]}\n\n',
    'data: {"choices":[{"index":0,"delta":{},"finish_reason":"tool_calls"}]}\n\n',
    'data: [DONE]\n\n'
];

parser.on('tool_start', function(e) {
    console.log('calling', e.tool.name);
});

for (var chunk of chunks)
    parser.write(chunk);

var output = parser.end();
console.log(output.reasoning); // 'tool'
console.log(output.tools);     // [{ id: 'call_A', name: 'weather', arguments: { city: 'Bratislava' } }]

Each item of output.tools is { id, name, arguments }. id is the id the provider gives the call (call_... for OpenAI, the call_id for the Responses API, toolu_... for Claude). Gemini calls without an id get gemini_<candidate>_<part>, and Ollama and generic calls without an id have null. arguments is an object when the joined text is valid JSON, the trimmed text when it is not (for example a stream that was cut off) and {} when it is empty. When there is at least one call, output.reasoning is tool.

Three events follow a call while it streams. Each one has e.tool, a copy { id, name, arguments } of the call with the arguments parsed so far:

EventWhen
tool_startA new call appears
tool_updateMore data of a known call arrives (before each further piece of its arguments)
tool_argumentsA piece of the arguments arrives: e.delta is the piece and e.arguments all argument text so far (for providers that send the arguments whole, both are the object)

With openai_responses, the events in the middle of a call carry the id of the output item (fc_...); the call_id is back in e.tool.id and in the output after the response.output_item.done event of the call.

To answer the model, run the tools and send the results in a new request, as described in the section Tools above. parser.tools holds the same calls while the stream runs.

A complete handler

This handler calls an OpenAI-compatible Chat Completions endpoint with the global fetch() of Node.js. It sends the messages, applies the config and, when the caller asked for a stream, parses the server-sent events with AIPARSER().

NEWAIMODEL('gpt-4o-mini', { url: 'https://api.openai.com/v1/chat/completions', token: 'sk-...' }, function(ai, callback) {

    var body = {};
    body.model = ai.payload.model;
    body.messages = ai.payload.messages;

    if (ai.config.temperature != null)
        body.temperature = ai.config.temperature;

    if (ai.payload.tools.length)
        body.tools = ai.payload.tools;

    if (ai.options.stream)
        body.stream = true;

    var opt = {};
    opt.method = 'POST';
    opt.headers = { 'Content-Type': 'application/json', Authorization: 'Bearer ' + ai.config.token };
    opt.body = JSON.stringify(body);

    fetch(ai.config.url, opt).then(async function(res) {

        if (!res.ok) {
            callback('HTTP ' + res.status + ': ' + (await res.text()));
            return;
        }

        if (!ai.options.stream) {
            var json = await res.json();
            callback(null, json.choices[0].message.content);
            return;
        }

        var parser = AIPARSER('openai');
        parser.on('content', function(e) {
            ai.options.stream(e.delta);
        });

        for await (var chunk of res.body)
            parser.write(Buffer.from(chunk));

        callback(null, parser.end().content);

    }).catch(callback);
});

The same pattern works for Ollama: point url to http://localhost:11434/api/chat, read json.message.content instead of json.choices[0].message.content and use AIPARSER('ollama'). Because the handler gets the whole request object, it can also map ai.payload.think or ai.payload.prompt to the fields your provider expects.

Tips

  • Keep tokens in the configuration and pass them to NEWAIMODEL() as config, not in every request.
  • Register one name per use (summarizer, translator) and decide in the handler which real model it uses. The application code does not change when you switch providers.
  • ai.payload is a plain object. A handler can send it almost as it is to providers whose API takes model and messages.
Made in Europe