npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

tools-llm

v2.0.0

Published

Biblioteca minimalista para executar funções via marcadores em texto.

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 MarkerJSONError e o marcador original é preservado.
  • Tolerância a erros de IA: Aceita comandos com fechamentos ou aberturas truncadas (ex: [[funcao:1], [funcao:1]]).
  • Feedback inteligente: executeMutedTools retorna um erro de system caso o texto não contenha nenhum comando válido executado com sucesso.

Instalação

npm install tools-llm

Uso (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 MarkerJSONError and preserves the marker.
  • AI Error Tolerance: Accepts commands with missing brackets (e.g., [[function:1], [function:1]]).
  • Smart Feedback: executeMutedTools returns a system error if the text does not contain any valid and successfully executed commands.

Installation

npm install tools-llm

Usage (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 for executarTools): 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ça MarkerJSONError em vez de virar string
  • Malformed JSON (e.g. {"city":"Recife"}) throws MarkerJSONError instead 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:
    • executarTools
    • executeTools
    • executeMutedTools
    • MarkerJSONError
    • default (executarTools)