tools-llm
v2.0.0
Published
Biblioteca minimalista para executar funções via marcadores em texto.
Maintainers
Readme
tools-llm
Biblioteca/Library minimalista para executar funções de texto com marcadores inline.
PT-BR
Sintaxe suportada
Modo padrão (substitui pelo retorno da função):
[[funcao]][[funcao:param1]][[funcao:param1,param2,param3]]
Modo silencioso (executa e remove marcador):
[[!funcao]][[!funcao:param1]][[!funcao:param1,param2,param3]]
Comportamento
- Executa a função apenas se ela existir em
tools - Suporta funções síncronas e assíncronas
- Resolve marcadores da esquerda para a direita
- Converte retorno automaticamente para string no modo padrão
- Modo silencioso (
!) executa a função e ignora o retorno - No modo silencioso, o marcador é removido do texto final
- Marcadores desconhecidos são preservados (inclusive silenciosos)
- Se a função lançar erro, o marcador é preservado
- Detecta automaticamente quando um parâmetro é JSON válido
- Se um parâmetro parecer JSON (iniciar com
{ou[) e for mal formatado, a biblioteca tenta corrigi-lo automaticamente (aspas simples, chaves sem aspas, trailing commas e quebras de linha literais). - Caso o JSON seja totalmente irrecuperável, lança um erro
MarkerJSONErrore o marcador original é preservado. - Tolerância a erros de IA: Aceita comandos com fechamentos ou aberturas truncadas (ex:
[[funcao:1],[funcao:1]]). - Feedback inteligente:
executeMutedToolsretorna um erro desystemcaso o texto não contenha nenhum comando válido executado com sucesso.
Instalação
npm install tools-llmUso (PT-BR)
import { executarTools, executeMutedTools } from "tools-llm";
// ou: import executarTools from "tools-llm";
const tools = {
data_agora() {
return "24/06/2026";
},
async clima(cidade) {
return cidade === "Recife" ? "32°C" : "N/A";
},
somar(a, b) {
return Number(a) + Number(b);
},
processar(payload) {
return payload.cidade;
},
async registrarLog(msg) {
// side effect
return "OK";
}
};
const texto = `Hoje é [[data_agora]]
Clima: [[clima:Recife]]
Soma: [[somar:10,20]]
JSON: [[processar:{"cidade":"Recife","temp":32}]]
[[!registrarLog:usuario entrou]]
Favorito: [[Naruto]]`;
const { text, history } = await executarTools(texto, tools);
console.log(text);
/*
Hoje é 24/06/2026
Clima: 32°C
Soma: 30
JSON: Recife
Favorito: [[Naruto]]
*/
console.log(history);
/*
[
{ tool: "data_agora", args: [] },
{ tool: "clima", args: ["Recife"] },
{ tool: "somar", args: [10, 20] },
{ tool: "processar", args: [{ cidade: "Recife", temp: 32 }] },
{ tool: "registrarLog", args: ["usuario entrou"] }
]
*/
const { results, errors, history: mutedHistory } = await executeMutedTools(texto, tools);
console.log(results);
/*
[
{ tool: "data_agora", result: "24/06/2026" },
{ tool: "clima", result: "32°C" },
{ tool: "somar", result: 30 }
]
*/
console.log(errors);
// [] (ou array de erros caso a IA tenha errado algo ou a função não exista)API (PT-BR)
await executarTools(texto, tools): Retorna um objeto{ text, history }.text: O texto final com os marcadores substituídos (ou removidos no modo silencioso).history: Lista das funções chamadas na ordem em que apareceram (Array<{ tool: string, args: any[] }>).
await executeMutedTools(texto, tools): Executa as funções e retorna um objeto com{ results, errors, history }.results: Lista de objetos com os retornos (Array<{ tool: string, result: any }>).errors: Lista de erros capturados (Array<{ tool: string, error: string }>), ideal para feedback da IA.history: Lista das funções chamadas na ordem de execução (Array<{ tool: string, args: any[] }>).
EN
Supported syntax
Default mode (replaces with function return):
[[functionName]][[functionName:param1]][[functionName:param1,param2,param3]]
Silent mode (executes and removes marker):
[[!functionName]][[!functionName:param1]][[!functionName:param1,param2,param3]]
Behavior
- Executes only if the function exists in
tools - Supports sync and async functions
- Resolves markers left to right
- Converts return values to string in default mode
- Silent mode (
!) executes the function and ignores return value - In silent mode, marker is removed from final text
- Unknown markers are preserved (including silent markers)
- If a function throws, the marker is preserved
- Automatically detects valid JSON parameters
- If a parameter looks like JSON (starts with
{or[), the library attempts to auto-fix common AI syntax errors (single quotes, unquoted keys, trailing commas, and unescaped literal newlines). - If the JSON is completely malformed and unrecoverable, it throws a
MarkerJSONErrorand preserves the marker. - AI Error Tolerance: Accepts commands with missing brackets (e.g.,
[[function:1],[function:1]]). - Smart Feedback:
executeMutedToolsreturns asystemerror if the text does not contain any valid and successfully executed commands.
Installation
npm install tools-llmUsage (EN)
import { executeTools, executeMutedTools } from "tools-llm";
// or: import executarTools from "tools-llm";
const tools = {
date_now() {
return "24/06/2026";
},
async weather(city) {
return city === "Recife" ? "32°C" : "N/A";
},
sum(a, b) {
return Number(a) + Number(b);
},
process(payload) {
return payload.city;
},
async saveMemory(key, value) {
// side effect
return "OK";
}
};
const text = `Today is [[date_now]]
Weather: [[weather:Recife]]
Sum: [[sum:10,20]]
JSON: [[process:{"city":"Recife","temp":32}]]
[[!saveMemory:name,Caio]]
Favorite: [[Naruto]]`;
const { text, history } = await executeTools(text, tools);
console.log(text);
/*
Today is 24/06/2026
Weather: 32°C
Sum: 30
JSON: Recife
Favorite: [[Naruto]]
*/
console.log(history);
/*
[
{ tool: "date_now", args: [] },
{ tool: "weather", args: ["Recife"] },
{ tool: "sum", args: [10, 20] },
{ tool: "process", args: [{ city: "Recife", temp: 32 }] },
{ tool: "saveMemory", args: ["name", "Caio"] }
]
*/
const { results, errors, history: mutedHistory } = await executeMutedTools(text, tools);
console.log(results);
/*
[
{ tool: "date_now", result: "24/06/2026" },
{ tool: "weather", result: "32°C" },
{ tool: "sum", result: 30 }
]
*/API (EN)
API (EN)
await executeTools(text, tools)(alias forexecutarTools): Returns an object containing{ text, history }.text: The final string with markers replaced by the functions' return values.history: Array of functions called in order (Array<{ tool: string, args: any[] }>).
await executeMutedTools(text, tools): Executes the functions and returns an object containing{ results, errors, history }.results: Array of objects (Array<{ tool: string, result: any }>) with successful execution results.errors: Array of caught errors (Array<{ tool: string, error: string }>), useful for providing AI feedback.history: Array of functions called in order (Array<{ tool: string, args: any[] }>).
Notas/Notes
- JSON válido vira objeto/array/valor nativo via
JSON.parse - JSON mal formatado (ex.:
{"cidade":Recife}) lançaMarkerJSONErrorem vez de virar string - Malformed JSON (e.g.
{"city":"Recife"}) throwsMarkerJSONErrorinstead of becoming a string - Texto comum continua string
- Parâmetros com vírgulas internas em JSON são tratados corretamente.
- A biblioteca possui heurísticas avançadas de auto-correção de JSON para contornar falhas comuns de formatação de LLMs.
- Compatível com Node.js e navegador (ESM)
- Exports disponíveis:
executarToolsexecuteToolsexecuteMutedToolsMarkerJSONErrordefault(executarTools)
