ForgeTotal.js 5
pt

Total.js 5

Conversa-se com modelos de idiomas com AIMODEL(), NEWAIMODel() e AIPARSER()

Total.js 5 · total5@0.0.19 aillmintegrations Executada com o Total.js 5

O total5 não inclui uma ligação a nenhum fornecedor. Dá-lhe três peças que funcionam em conjunto:

  • NEWAIMODEL('name', config, driver) regista o driver de um ou mais modelos ('a,b' regista o mesmo driver para dois nomes). O driver é function(ai, done): ai.payload tem model, messages, tools, prompt e think, ai.config é a configuração e ai.options.stream é a função que quem chama passou a stream() (ou undefined). Responda com done(error, response).
  • AIMODEL('name') inicia um pedido para um modelo registado e devolve um builder. system(text), user(text) e assistant(text) acrescentam uma mensagem, prompt(text), tool(definition) e think() preenchem o resto do payload, e configure({ ... }) acrescenta a ai.config apenas para esta chamada. Termine-o com callback(fn), await promise($) ou stream(fn); o driver corre depois do turno atual, por isso pode encadear tudo primeiro.
  • AIPARSER(provider) devolve um parser para a resposta em streaming de um fornecedor (o código de total5 conhece openai, claude/anthropic, gemini/google, ollama e openai_responses, e lê qualquer outro nome como um formato genérico; abaixo só se executa openai). write(chunk) recebe pedaços do stream (guarda as linhas incompletas até ao pedaço seguinte), end() termina-o, e ambos devolvem { content, thinking, tools, reasoning }. parser.on('content', fn) é chamado com cada parte do texto à medida que chega.

Um modelo que não foi registado responde com o erro AI model not found.. O exemplo registra um motorista local que retorna uma resposta das mensagens fornecidas.

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 });
});
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 });
}