---
title: AI models
project: Total.js V5
version: 0.0.20
section: reference
language: en
license: MIT
url: https://totaljs.es/docs/total-js-v5/0-0-20/reference/ai-models/
updated: 2026-11-18T16:57:34.578Z
---

# AI models

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

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](../../guides/ai-models/) explains how they work together, with a complete handler.

## API

### NEWAIMODEL(name, [config], handler)

Type: `method` · Since: `0.0.16`

Registers a handler for one or more AI models.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | The model name, or several names separated by commas. |
| `config` | `Object` | no |  | Default config (URL, token, settings) copied into `ai.config` of each request. |
| `handler` | `Function` | yes |  | `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.

Example: Ollama model
```js
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);
});
```

### function(ai, callback)

Type: `delegate` · Since: `0.0.16`

The model handler passed to NEWAIMODEL().

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `ai` | `AIModel` | yes |  | The request. |
| `callback` | `Function` | yes |  | `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.

Example: Echo handler for tests
```js
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);
});
```

### AIMODEL(name)

Type: `method` · Since: `0.0.16`

Creates a request for a registered AI model.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `name` | `String` | yes |  | 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.'`.

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

### ai.system(content, [merge])

Type: `method` · Since: `0.0.16`

Adds a system message.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `content` | `String|Object` | yes |  | The text, or an object whose keys are copied into the message. |
| `merge` | `String` | no |  | 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.

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

### ai.user(content, [merge])

Type: `method` · Since: `0.0.16`

Adds a user message.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `content` | `String|Object` | yes |  | The text, or an object whose keys are copied into the message. |
| `merge` | `String` | no |  | 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)`.

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

### ai.assistant(content, [merge])

Type: `method` · Since: `0.0.16`

Adds an assistant message.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `content` | `String|Object` | yes |  | The text, or an object whose keys are copied into the message. |
| `merge` | `String` | no |  | 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.

Example: Conversation history
```js
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);
```

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

Type: `method` · Since: `0.0.16`

Adds a message with any role.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `role` | `String` | yes |  | The role, e.g. `system`, `user`, `assistant` or `tool`. |
| `content` | `String|Object` | yes |  | The text, or an object whose keys are copied into the message. |
| `merge` | `String` | no |  | 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.

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

### ai.prompt(content)

Type: `method` · Since: `0.0.16`

Sets a single prompt.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `content` | `String` | yes |  | 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.

Example: Prompt
```js
AIMODEL('generator').prompt('Write a slogan for a bakery').callback(console.log);
```

### ai.think()

Type: `method` · 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).

Example: Thinking
```js
AIMODEL('reasoner').think().user('Is 1001 a prime number?').callback(console.log);
```

### ai.configure(obj)

Type: `method` · Since: `0.0.16`

Sets the config of the request.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `obj` | `Object` | yes |  | 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.

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

### ai.callback(fn)

Type: `method` · Since: `0.0.16`

Sets the callback and runs the request.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `fn` | `Function` | yes |  | `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.

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

### ai.stream(fn)

Type: `method` · Since: `0.0.16`

Sets the stream function and runs the request.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `fn` | `Function` | yes |  | 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.

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

### ai.promise([$])

Type: `method` · Since: `0.0.16`

Runs the request and returns a Promise.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `$` | `Object` | no |  | 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.

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

### ai.payload {Object}

Type: `property` · 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.

Example: Read the payload
```js
NEWAIMODEL('debug', function(ai, callback) {
	callback(null, JSON.stringify(ai.payload));
});
```

### ai.config {Object}

Type: `property` · 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.

### ai.options {Object}

Type: `property` · 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.

Example: Check for streaming
```js
if (ai.options.stream)
	body.stream = true;
```

### F.aimodels {Object}

Type: `property` · 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()`.

Example: Is a model registered?
```js
if (F.aimodels.assistant)
	console.log('ready');
```

### ai.tool(content)

Type: `method` · Since: `0.0.17`

Adds a tool definition.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `content` | `Object` | yes |  | 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.

Example: Tool from a schema
```js
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);
```

### AIPARSER(provider)

Type: `method` · Since: `0.0.17`

Creates a parser for streamed AI responses.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `provider` | `String` | no | `generic` | The format of the stream. |

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()`.

Example: Parse a Claude stream
```js
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();
```

### parser.write(chunk)

Type: `method` · Since: `0.0.17`

Writes a piece of the stream.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `chunk` | `Buffer|String|Object` | yes |  | 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.

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

### parser.end()

Type: `method` · 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.

Example: Final output
```js
var output = parser.end();
console.log(output.content);
```

Example: Tool calls of a Claude stream
```js
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' } }]
```

### parser.output()

Type: `method` · 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.

### parser.on(type, fn)

Type: `method` · Since: `0.0.17`

Listens to an event of the parser.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `type` | `String` | yes |  | The event name. |
| `fn` | `Function` | yes |  | `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.

Example: All events
```js
AIPARSER('openai').on('*', function(e) {
	console.log(e.type);
});
```

### parser.off(type, fn)

Type: `method` · Since: `0.0.17`

Removes a listener.

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| `type` | `String` | yes |  | The event name. |
| `fn` | `Function` | yes |  | The function given to `parser.on()`. |

Returns: `AIParser` The parser, for chaining.

Removes `fn` from the listeners of `type`.

### parser.reset()

Type: `method` · 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.

### parser.content {String}

Type: `property` · Since: `0.0.17`

The text collected so far.

Returns: `String`

All text of the answer, joined from the deltas.

### parser.thinking {String}

Type: `property` · 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).

### parser.reasoning {String}

Type: `property` · Since: `0.0.17`

What the model is producing now.

Returns: `String`

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

### parser.tools {Array}

Type: `property`

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.

Example: Raw and parsed arguments
```js
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' }
```

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

Type: `event` · Since: `0.0.17`

New text of the answer.

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

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

Type: `event` · Since: `0.0.17`

New reasoning text.

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

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

Type: `event`

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`.

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

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

Type: `event`

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.

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

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

Type: `event`

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.

Example: Arguments of a Claude stream
```js
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' } }]
```

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

Type: `event` · Since: `0.0.17`

The stream ended.

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