# Talk to language models with AIMODEL(), NEWAIMODEL() and AIPARSER()

> Build a chat request with AIMODEL(), let a driver registered with NEWAIMODEL() send it to a provider, and read streamed answers with AIPARSER().

Framework: total5
Product: Total.js 5 (total5@0.0.19)
Language: en
Content-SHA256: 7c29008f55a6bdf6dc0904f945e8272bb1a3a32c18781f7f4039c6da23dfb8e9
Snapshot: c0700e321579725c5cf4f5ace1ad7d2866d1b4f93c24a63c0b41b6b7998e976c
Sources: total5-installed@total5@0.0.19
Review: not-recorded

`total5` does not ship a connection to any provider. It gives you three pieces that work together:

- `NEWAIMODEL('name', config, driver)` registers the **driver** of one or more models (`'a,b'` registers the same driver for two names). The driver is `function(ai, done)`: `ai.payload` has `model`, `messages`, `tools`, `prompt` and `think`, `ai.config` is the configuration and `ai.options.stream` is the function the caller passed to `stream()` (or `undefined`). Answer with `done(error, response)`.
- `AIMODEL('name')` starts a request for a registered model and returns a builder. `system(text)`, `user(text)` and `assistant(text)` append a message, `prompt(text)`, `tool(definition)` and `think()` fill the rest of the payload, and `configure({ ... })` adds to `ai.config` for this call only. Finish it with `callback(fn)`, `await promise($)` or `stream(fn)`; the driver runs after the current turn, so you can chain everything first.
- `AIPARSER(provider)` returns a parser for the **streamed** answer of a provider (the source of `total5` knows `openai`, `claude`/`anthropic`, `gemini`/`google`, `ollama` and `openai_responses`, and reads any other name as a generic format; only `openai` is run below). `write(chunk)` takes pieces of the stream (it keeps incomplete lines until the next piece), `end()` finishes it, and both return `{ content, thinking, tools, reasoning }`. `parser.on('content', fn)` is called with every part of the text as it arrives.

A model that was not registered answers with the error `AI model not found.`. The example registers a local driver that returns a response from the supplied messages.

```js definitions/ai.js
NEWAIMODEL('echo', { prefix: 'Echo' }, function(ai, done) {

	const last = ai.payload.messages.filter(n => n.role === 'user').pop();
	const text = ai.config.prefix + ': ' + (last ? last.content : '');

	// A real driver would send ai.payload to the provider and send the pieces to ai.options.stream
	if (ai.options.stream) {
		for (const word of text.split(' '))
			ai.options.stream(word + ' ');
	}

	done(null, { content: text, roles: ai.payload.messages.map(n => n.role), tools: ai.payload.tools.length, think: !!ai.payload.think });
});
```

```js controllers/ai.js
exports.install = function() {
	ROUTE('POST /ask/', ask);
	ROUTE('GET /ask-config/', askconfig);
	ROUTE('GET /ask-stream/', askstream);
	ROUTE('GET /ask-missing/', missing);
	ROUTE('GET /parse/', parse);
};

async function ask($) {
	const response = await AIMODEL('echo').system('You are brief.').user($.body.question).tool({ name: 'weather' }).think().promise($);
	$.json(response);
}

function askconfig($) {
	AIMODEL('echo').user('hello').configure({ prefix: 'Custom' }).callback($.callback());
}

function askstream($) {
	const parts = [];
	AIMODEL('echo').user('one two three').stream(part => parts.push(part)).callback(function(err, response) {
		$.json({ parts: parts, content: response.content });
	});
}

function missing($) {
	AIMODEL('nobody').user('hi').callback($.callback());
}

function parse($) {
	const parser = AIPARSER('openai');
	const events = [];
	parser.on('content', e => events.push(e.delta));

	// the second piece starts in the middle of a line
	parser.write('data: {"choices":[{"delta":{"content":"Hel"}}]}\n\ndata: {"choices":[{"delta":{"con');
	parser.write('tent":"lo"}}]}\n\ndata: [DONE]\n');
	const output = parser.end();

	$.json({ output: output, events: events });
}
```
