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

@omnizap/sdk

v1.1.3

Published

Platform-agnostic AI agent SDK for chat applications — WhatsApp, Telegram, Messenger, or any custom channel.

Readme

OmniBrain SDK

Construa agentes de IA em qualquer plataforma de chat — WhatsApp, Telegram, Messenger ou canal interno — sem mudar uma linha da sua lógica de negócio.

npm install @omnibrain/sdk

Os 3 problemas que este SDK resolve

1. Dependência de provedor

"Meu bot parou porque a Evolution API mudou a API. Agora vou perder dias reescrevendo."

Com OmniBrain, você troca o adapter em 2 linhas. A lógica de IA, as tools, a memória — nada muda.

// Antes: Evolution API
const adapter = new EvolutionAdapter({ apiUrl, apiKey, instance });

// Depois: qualquer adapter que implemente IAdapter
const adapter = new TelegramAdapter({ token });

2. Mensagens duplicadas em produção

"Meu bot responde duas vezes para a mesma mensagem — o WhatsApp às vezes entrega o webhook duplicado."

Deduplicação em duas camadas, automática: em memória (TTL 5 min) + Redis NX SET (24h). Zero configuração.

3. Sem controle de custo de tokens

"Recebi uma fatura de $300 da OpenAI e não sei qual bot ou cliente causou isso."

UsageTracker emite eventos por canal com promptTokens, completionTokens e modelo. Plugue no seu sistema de billing em 3 linhas.


Instalação

npm install @omnibrain/sdk

Pré-requisitos: Node.js ≥ 18, TypeScript ≥ 5.


Quickstart — 5 minutos

import {
  OmniBrainClient, OmniBrainEngine,
  OpenAIProvider, EvolutionAdapter,
} from '@omnibrain/sdk';

// 1. Adapter do seu provedor (implementa IAdapter)
const adapter = new EvolutionAdapter({
  apiUrl: 'http://localhost:8080',
  apiKey: 'sua-api-key',
  instance: 'meu-bot',
});

// 2. LLM (implementa ILLMProvider)
const llm = new OpenAIProvider('sk-...');

// 3. Engine de IA
const engine = new OmniBrainEngine(adapter, llm, {
  systemPrompt: 'Você é um assistente de suporte da Empresa X.',
});

// 4. Client unificado
const client = new OmniBrainClient(adapter);
client.registerEngine(engine);

// 5. Webhook — funciona com Express, Fastify, Hono, Next.js, etc.
app.post('/webhook', async (req, res) => {
  await client.handleWebhook(req.body);
  res.json({ ok: true });
});

Demo em 2 minutos

Clone o starter kit e rode no terminal — sem WhatsApp, sem Docker:

git clone https://github.com/omnibrain/starter-kit
cd starter-kit
npm install
cp .env.example .env   # preencha OPENAI_API_KEY
npm run console

Ou suba o stack completo (Redis + bot + webhook HTTP):

cp .env.example .env   # preencha OPENAI_API_KEY + EVOLUTION_*
docker-compose up

Recursos

Troca de plataforma sem reescrita

// Teste local (sem WhatsApp):
const engine = new OmniBrainEngine(new ConsoleAdapter(), llm, config);

// Produção WhatsApp:
const engine = new OmniBrainEngine(new EvolutionAdapter(config), llm, config);

// Telegram, Meta, chat interno: implemente IAdapter (5 métodos)

Tools (Function Calling)

engine.registerTool({
  name: 'consultar_pedido',
  description: 'Verifica status de um pedido. Use quando o cliente perguntar sobre o pedido.',
  parameters: {
    type: 'object',
    properties: { pedido_id: { type: 'string' } },
    required: ['pedido_id'],
  },
  async execute({ pedido_id }, ctx) {
    return await db.getOrder(pedido_id as string);
  },
});

RAG (Base de Conhecimento)

const kb = new SimpleVectorKnowledgeBase();
await kb.addChunk({ id: '1', content: 'Política de reembolso: 7 dias...' });

const engine = new OmniBrainEngine(adapter, llm, { knowledgeBase: kb });
// O LLM usa automaticamente o KB para responder perguntas relevantes

Memória persistente

// InMemory (desenvolvimento)
const engine = new OmniBrainEngine(adapter, llm, config);

// Redis (produção) — histórico sobrevive a restarts
const memory = new RedisMemory({ url: 'redis://localhost:6379' });
const engine = new OmniBrainEngine(adapter, llm, config, memory);

Multi-tenancy — um bot, múltiplas personas

engine
  .registerInstance({ instanceId: 'loja_sp', systemPrompt: 'Atendente da Loja SP.' })
  .registerInstance({ instanceId: 'loja_rj', systemPrompt: 'Atendente da Loja RJ.', tools: [toolRJ] });
// Roteamento automático pelo channelId da mensagem

Token Tracking — saiba quanto cada canal custa

const tracker = new UsageTracker();
tracker.onTokensConsumed(e => {
  console.log(`${e.instanceId}: ${e.totalTokens} tokens`);
  // → salvar no banco, cobrar cliente, bloquear se sem créditos
});
const llm = new OpenAIProvider('sk-...', 'gpt-4o', tracker);

Transcrição de áudio (Whisper)

// Automático: mensagens de voz são transcritas antes do pipeline de IA
// Basta usar OpenAIProvider — nenhuma configuração adicional necessária
const llm = new OpenAIProvider('sk-...'); // whisper-1 incluído

Structured Outputs (Zod)

import { z } from 'zod';

const LeadSchema = z.object({
  nome: z.string(),
  interesse: z.enum(['basico', 'pro', 'enterprise']),
  message: z.string(), // enviado ao usuário
});

engine.registerInstance({
  instanceId: 'captacao',
  outputSchema: LeadSchema,
});

// Na engine:
onStructuredOutput: (data, meta) => {
  saveLead(data, meta.userId); // tipado, validado pelo Zod
}

Criar seu próprio adapter

Implemente IAdapter — 5 métodos — e qualquer plataforma funciona:

class MeuAdapter implements IAdapter {
  readonly name = 'MeuAdapter';
  async initialize() { /* conectar à plataforma */ }
  async sendText(to, text) { /* enviar mensagem */ }
  async sendMedia(to, media, opts) { /* enviar mídia */ }
  async sendPoll(to, name, options) { /* enviar enquete */ }
  onMessage(callback) { /* registrar listener */ }
}

Documentação

| Guia | Conteúdo | |------|---------| | Arquitetura | Fluxo completo, tipos centrais, camadas | | Adapters | Como criar adapter para qualquer plataforma | | LLM Providers | OpenAI, Whisper, Structured Outputs, como criar o seu | | Engine | Pipeline, opções, multi-tenancy | | Memória | InMemory, Redis, interface IMemory | | Tools | ITool, ToolRegistry, ToolContext | | Knowledge Base | RAG, SimpleVectorKB, Pinecone | | Multi-tenancy | registerInstance(), isolamento por canal | | Intent Router | Roteamento de baixo custo | | Token Tracking | UsageTracker, billing | | Structured Outputs | Zod schemas, strict mode | | Fila | BullMQ, deduplicação distribuída | | Connection Watcher | Reconexão automática, heartbeat | | Erros | Tipos de erro, retry, tratamento |


Starter Kit

Um bot de pizzaria funcional para começar: demo/

demo/
├── src/console.ts  # bot interativo no terminal (sem infra)
├── src/server.ts   # servidor HTTP para uso em produção
└── src/tools.ts    # tools: ver_cardapio, criar_pedido, consultar_pedido

Licença

MIT — veja LICENSE.