Spanish Total.js
English
Documentation For AI agents
Contents

AI models

NEWAIMODEL(), AIMODEL(), the request methods and properties, and the AI stream parser.

.md GitHub
On this page

This page lists the global functions for AI models, the methods and properties of the request object of AIMODEL(), the model handler and, where available, the stream parser and its events. The guide AI models explains how they work together, with a complete handler.

API

method

NEWAIMODEL(name, [config], handler)

since 0.0.16 Registers a handler for one or more AI models.
ParameterTypeDescription
name String The model name, or several names separated by commas.
config? Object Default config (URL, token, settings) copied into ai.config of each request.
handler Function function(ai, callback). Calls the provider and ends with callback(err, response).

Returns undefined

Stores handler with config in F.aimodels under each name of name (names separated by commas are trimmed). A name registered again replaces the previous handler. The handler is called by every request of AIMODEL() with that name. Before it runs, every key of config that the request did not set with ai.configure() is copied into ai.config. When the second argument is a function, it is the handler and there is no config.

Ollama model
NEWAIMODEL('llama3', { url: 'http://localhost:11434/api/chat' }, function(ai, callback) {
	var opt = {};
	opt.method = 'POST';
	opt.headers = { 'Content-Type': 'application/json' };
	opt.body = JSON.stringify({ model: ai.payload.model, messages: ai.payload.messages, stream: false });
	fetch(ai.config.url, opt).then(res => res.json()).then(function(json) {
		callback(null, json.message.content);
	}).catch(callback);
});
delegate

function(ai, callback)

since 0.0.16 The model handler passed to NEWAIMODEL().
ParameterTypeDescription
ai AIModel The request.
callback Function function(err, response) that ends the request.

Called once per request when the request runs. ai is the request object of AIMODEL(): read ai.payload for the data to send, ai.config for the settings (with the defaults of NEWAIMODEL() already applied) and ai.options.stream for the stream function of the caller. Call ai.options.stream(piece) for each piece of a streamed answer, then callback(err, response) once. The response reaches the caller unchanged.

Echo handler for tests
NEWAIMODEL('echo', function(ai, callback) {
	var last = ai.payload.messages[ai.payload.messages.length - 1];
	ai.options.stream && ai.options.stream(last.content);
	callback(null, last.content);
});
method

AIMODEL(name)

since 0.0.16 Creates a request for a registered AI model.
ParameterTypeDescription
name String The name used in NEWAIMODEL(). It is also stored as payload.model.

Returns AIModel A new request.

Returns a new request object. Add messages and settings with its methods, then run it with callback(), stream() or promise(). The request looks up the model when it runs; when no model with the name is registered, the callback gets the error 'AI model not found.'.

Simple question
AIMODEL('assistant').user('What is 2 + 2?').callback(function(err, response) {
	console.log(response);
});
method

ai.system(content, [merge])

since 0.0.16 Adds a system message.
ParameterTypeDescription
content String|Object The text, or an object whose keys are copied into the message.
merge? String A separator. When set and a system message exists, the content is appended to it.

Returns AIModel The same request, for chaining.

The same as ai.message('system', content, merge). Use it for the instructions of the model.

Instructions
AIMODEL('assistant').system('Answer in one sentence.').user('What is Node.js?').callback(console.log);
method

ai.user(content, [merge])

since 0.0.16 Adds a user message.
ParameterTypeDescription
content String|Object The text, or an object whose keys are copied into the message.
merge? String A separator. When set and a user message exists, the content is appended to it.

Returns AIModel The same request, for chaining.

The same as ai.message('user', content, merge).

Message with an image
AIMODEL('vision').user({ content: 'What is in this picture?', images: [base64] }).callback(console.log);
method

ai.assistant(content, [merge])

since 0.0.16 Adds an assistant message.
ParameterTypeDescription
content String|Object The text, or an object whose keys are copied into the message.
merge? String A separator. When set and an assistant message exists, the content is appended to it.

Returns AIModel The same request, for chaining.

The same as ai.message('assistant', content, merge). Use it to replay earlier answers of the model in a conversation.

Conversation history
var ai = AIMODEL('assistant');
for (var item of history) {
	if (item.fromuser)
		ai.user(item.text);
	else
		ai.assistant(item.text);
}
ai.user(question).callback(console.log);
method

ai.message(role, content, [merge])

since 0.0.16 Adds a message with any role.
ParameterTypeDescription
role String The role, e.g. system, user, assistant or tool.
content String|Object The text, or an object whose keys are copied into the message.
merge? String A separator string that turns on merging.

Returns AIModel The same request, for chaining.

Pushes { role, content } to ai.payload.messages. When content is an object, its keys are copied into the message instead of content. When merge is set and a message with the same role exists, nothing is added: a string is appended to the content of the first such message with merge between them, and the keys of an object are copied into it.

Merged instructions
AIMODEL('assistant')
	.message('system', 'You are a translator.')
	.message('system', 'Translate to German.', '\n')
	.user('Good morning')
	.callback(console.log);
method

ai.prompt(content)

since 0.0.16 Sets a single prompt.
ParameterTypeDescription
content String The prompt.

Returns AIModel The same request, for chaining.

Sets ai.payload.prompt. Useful for handlers of endpoints that take one prompt instead of a list of messages (for example the /api/generate endpoint of Ollama). The handler decides how to use it.

Prompt
AIMODEL('generator').prompt('Write a slogan for a bakery').callback(console.log);
method

ai.think()

since 0.0.16 Asks for the thinking mode.

Returns AIModel The same request, for chaining.

Sets ai.payload.think = true. The handler maps it to the option of the provider (for example think of Ollama).

Thinking
AIMODEL('reasoner').think().user('Is 1001 a prime number?').callback(console.log);
method

ai.configure(obj)

since 0.0.16 Sets the config of the request.
ParameterTypeDescription
obj Object The keys to set.

Returns AIModel The same request, for chaining.

Copies the keys of obj into ai.config. These values win over the defaults of NEWAIMODEL(), which fill only the keys that are not set.

Temperature for one request
AIMODEL('assistant').configure({ temperature: 0 }).user('List three colors').callback(console.log);
method

ai.callback(fn)

since 0.0.16 Sets the callback and runs the request.
ParameterTypeDescription
fn Function function(err, response).

Returns AIModel The same request, for chaining.

Stores fn and runs the request on the next turn of the event loop. Calling callback(), stream() or promise() again in the same turn moves the run, so the handler is called only once.

Callback
AIMODEL('assistant').user('Hello').callback(function(err, response) {
	err && console.log(err);
});
method

ai.stream(fn)

since 0.0.16 Sets the stream function and runs the request.
ParameterTypeDescription
fn Function Called by the handler with each piece of the answer.

Returns AIModel The same request, for chaining.

Stores fn in ai.options.stream and runs the request on the next turn of the event loop. The handler calls fn with the pieces of the answer; what a piece is (text, an object) is up to the handler. Add callback() to know when the answer ends.

Stream to the console
AIMODEL('assistant').user('Tell a story').stream(function(text) {
	process.stdout.write(text);
}).callback(function(err) {
	console.log('end', err);
});
method

ai.promise([$])

since 0.0.16 Runs the request and returns a Promise.
ParameterTypeDescription
$? Object The $ of an action or controller, to report errors with $.invalid().

Returns Promise Resolves with the response of the handler.

Runs the request through callback(). The promise resolves with the response. An error rejects it with an Error; when $ with $.invalid() is passed, the error goes to $.invalid(err) instead and the promise stays pending.

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

ai.payload {Object}

since 0.0.16 The data of the request for the provider.

Returns Object

Holds model (the name given to AIMODEL()), messages (an array of message objects) and tools (an array of tool definitions, empty by default), plus prompt and think when set. The handler reads it to build the body of the provider request.

Read the payload
NEWAIMODEL('debug', function(ai, callback) {
	callback(null, JSON.stringify(ai.payload));
});
property

ai.config {Object}

since 0.0.16 The config of the request.

Returns Object

The keys set with ai.configure(), completed with the defaults of NEWAIMODEL() just before the handler runs.

property

ai.options {Object}

since 0.0.16 The run options of the request.

Returns Object

Holds callback (the function set by callback() or promise(), NOOP by default) and stream (the function set by stream(), or undefined). A handler checks ai.options.stream to know if the caller wants a stream.

Check for streaming
if (ai.options.stream)
	body.stream = true;
property

F.aimodels {Object}

since 0.0.16 The registered AI models.

Returns Object

An object with the names of the models as keys and { config, callback } as values, filled by NEWAIMODEL().

Is a model registered?
if (F.aimodels.assistant)
	console.log('ready');
method

ai.tool(content)

since 0.0.17 Adds a tool definition.
ParameterTypeDescription
content Object The tool definition.

Returns AIModel The same request, for chaining.

Pushes content to ai.payload.tools. The framework does not change or check it; the handler sends the tools to the provider in its format. schema.toAITool(name) of an inline schema returns the common function format.

Tool from a schema
NEWSCHEMA('@Task', '*name:String // The name of the task,due:Date');

AIMODEL('assistant')
	.user('Create a task: call Peter tomorrow')
	.tool(F.jsonschemas.Task.toAITool('create_task'))
	.callback(console.log);
method

AIPARSER(provider)

since 0.0.17 Creates a parser for streamed AI responses.
ParameterTypeDescription
provider? String The format of the stream. Default: generic

Returns AIParser A new parser.

Returns a stream parser for the format of provider: ollama, openai (or openai_chat), openai_responses, claude (or anthropic), gemini (or google). Any other value uses a generic parser. Write the raw chunks with parser.write() and finish with parser.end().

Parse a Claude stream
var parser = AIPARSER('claude');
parser.on('content', e => process.stdout.write(e.delta));
for await (var chunk of res.body)
	parser.write(Buffer.from(chunk));
var output = parser.end();
method

parser.write(chunk)

since 0.0.17 Writes a piece of the stream.
ParameterTypeDescription
chunk Buffer|String|Object Raw data or a parsed event.

Returns Object The current output, the same as parser.output().

A Buffer, a string, a Uint8Array or an ArrayBuffer is added to an internal buffer and every complete line is parsed: empty lines and [DONE] are skipped, a data: prefix is removed and the rest is parsed as JSON. A line that is not JSON is ignored. An object is parsed directly as one event of the provider. null only returns the output.

Write parsed objects
var parser = AIPARSER('ollama');
parser.write({ message: { content: 'Hel' } });
parser.write({ message: { content: 'lo' } });
parser.end().content; // 'Hello'
method

parser.end()

since 0.0.17 Finishes the stream.

Returns Object { content, thinking, tools, reasoning }, plus thinking_signature or thought_signatures when the provider sends them.

Parses the rest of the buffer (a last line without a newline), parses the joined arguments of every tool call, emits done with { output } and returns the output.

Final output
var output = parser.end();
console.log(output.content);
Tool calls of a Claude stream
var parser = AIPARSER('claude');

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

// recorded events of an Anthropic Messages stream
parser.write({ type: 'content_block_start', index: 1, content_block: { type: 'tool_use', id: 'toolu_1', name: 'weather', input: {} } });
parser.write({ type: 'content_block_delta', index: 1, delta: { type: 'input_json_delta', partial_json: '{"city": "Bra' } });
parser.write({ type: 'content_block_delta', index: 1, delta: { type: 'input_json_delta', partial_json: 'tislava"}' } });
parser.write({ type: 'message_delta', delta: { stop_reason: 'tool_use' } });

var output = parser.end();
// output.tools: [{ id: 'toolu_1', name: 'weather', arguments: { city: 'Bratislava' } }]
method

parser.output()

since 0.0.17 Returns the current output.

Returns Object The output so far.

Returns { content, thinking, tools, reasoning }. tools is an array of { id, name, arguments } with the tool calls of every provider, where arguments is the parsed JSON of the joined arguments (the trimmed text when it is not valid JSON, for example while the arguments still stream, and {} when it is empty). reasoning is tool when there are tool calls, else thinking or content by the last kind of data. thinking_signature (Claude) and thought_signatures (Gemini) are added when present.

method

parser.on(type, fn)

since 0.0.17 Listens to an event of the parser.
ParameterTypeDescription
type String The event name.
fn Function function(event).

Returns AIParser The parser, for chaining.

Adds fn for the event type: content, thinking, tool_start, tool_update, tool_arguments, done, or * for all events. fn gets an object with type and the data of the event.

All events
AIPARSER('openai').on('*', function(e) {
	console.log(e.type);
});
method

parser.off(type, fn)

since 0.0.17 Removes a listener.
ParameterTypeDescription
type String The event name.
fn Function The function given to parser.on().

Returns AIParser The parser, for chaining.

Removes fn from the listeners of type.

method

parser.reset()

since 0.0.17 Clears the parser.

Returns AIParser The parser.

Clears the content, the thinking, the tools, the buffer and the signatures, so the parser can read another stream of the same provider. The listeners stay.

property

parser.content {String}

since 0.0.17 The text collected so far.

Returns String

All text of the answer, joined from the deltas.

property

parser.thinking {String}

since 0.0.17 The reasoning collected so far.

Returns String

All reasoning or thinking text sent by the model (for example reasoning_content, Claude thinking_delta or Gemini thought parts).

property

parser.reasoning {String}

since 0.0.17 What the model is producing now.

Returns String

content, thinking or tool, by the last kind of data received.

property

parser.tools {Array}

The tool calls collected so far.

Returns Array

One object for each tool call, in the order the calls started: id and name of the call, arguments (the argument text joined from the pieces; for providers that send the arguments as an object, its JSON) and input (the parsed arguments, filled by parser.output() and parser.end()). Use output.tools of parser.end() for the final calls with the parsed arguments.

Raw and parsed arguments
var parser = AIPARSER('ollama');
parser.write({ message: { role: 'assistant', content: '', tool_calls: [{ function: { name: 'weather', arguments: { city: 'Bratislava' } } }] } });
console.log(parser.tools[0].name);      // 'weather'
console.log(parser.tools[0].arguments); // '{"city":"Bratislava"}'
console.log(parser.end().tools[0].arguments); // { city: 'Bratislava' }
event

parser.on('content', function(e) {})

since 0.0.17 New text of the answer.

e.delta is the new text and e.content all text so far.

event

parser.on('thinking', function(e) {})

since 0.0.17 New reasoning text.

e.delta is the new text and e.thinking all reasoning so far.

event

parser.on('tool_start', function(e) {})

A new tool call appears.

e.tool is { id, name, arguments } of the new call; arguments is usually {} at this point. e.reasoning is tool.

Log the calls
var parser = AIPARSER('openai');
parser.on('tool_start', function(e) {
	console.log('The model calls', e.tool.name, e.tool.id);
});
event

parser.on('tool_update', function(e) {})

More data of a known tool call.

Emitted when the stream sends more data for a call that already started, before each further piece of its arguments. e.tool is { id, name, arguments } with the arguments parsed so far: an object once the joined text is valid JSON, else the trimmed text.

Watch the arguments grow
var parser = AIPARSER('openai');
parser.on('tool_update', function(e) {
	console.log(e.tool.id, e.tool.arguments);
});
event

parser.on('tool_arguments', function(e) {})

A piece of the arguments of a tool call.

e.delta is the new piece and e.arguments all argument text of the call so far. For providers that send the arguments whole as an object (Ollama, Gemini), both are that object. e.tool is { id, name, arguments } with the arguments parsed so far.

Arguments of a Claude stream
var parser = AIPARSER('claude');

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

// recorded events of an Anthropic Messages stream
parser.write({ type: 'content_block_start', index: 1, content_block: { type: 'tool_use', id: 'toolu_1', name: 'weather', input: {} } });
parser.write({ type: 'content_block_delta', index: 1, delta: { type: 'input_json_delta', partial_json: '{"city": "Bra' } });
parser.write({ type: 'content_block_delta', index: 1, delta: { type: 'input_json_delta', partial_json: 'tislava"}' } });
parser.write({ type: 'message_delta', delta: { stop_reason: 'tool_use' } });

var output = parser.end();
// output.tools: [{ id: 'toolu_1', name: 'weather', arguments: { city: 'Bratislava' } }]
event

parser.on('done', function(e) {})

since 0.0.17 The stream ended.

Emitted by parser.end(). e.output is the final output.

Made in Europe