stream) ·
strategies per channel: drafts, edits, chunks ·
“typing…” while generating ·
Telegram provider ·
cost and latency settings ·
testing streams with MockProvider
Prerequisites
- Node.js 22.12 or newer.
- A Telegram bot token from @BotFather in
TELEGRAM_TOKEN. - An Anthropic API key in
ANTHROPIC_API_KEY(or another model provider, see below).
The bot
How it works
-
One option.
streammakes the autoresponder send the answer withctx.stream()while the model generates it. The same code picks the best strategy for each channel: -
cursoris shown at the end of the text while it is being written and never in the final message.canStopadds Telegram’s stop button to the draft: pressing it aborts the model request, so you stop paying for it. -
Typing.
humanizeTyping(on by default) shows “typing…” until the first words arrive. -
Tools turn streaming off. A turn that may call tools
needs the whole answer first, so with
toolsconfigured the reply is sent in one message.
Cost and latency tips
Answer the obvious without the model (commands,
bot.when() triggers,
flows), and see Cost and latency for the rest.
Try it
packages/ai/tests/docs-examples-ai.test.ts), which also runs the bot on a
mock Telegram-like provider and checks that the answer arrives as a growing
draft there.
Other model providers
Switch to OpenAI, Gemini or a local Ollama model
Switch to OpenAI, Gemini or a local Ollama model
Every provider streams. Keep the other options as they are.OpenAI (Gemini (Ollama on your machine (no package, no key; run
npm install openai, key in OPENAI_API_KEY):npm install @google/genai, key in GEMINI_API_KEY):ollama pull llama3.1 first):
the first token arrives with no network round trip, and there is no output cap
unless you set maxTokens.Run it on Telegram or WhatsApp
Put the token and the key in a.env file next to bot.js
(TELEGRAM_TOKEN=... and ANTHROPIC_API_KEY=...), run
node --env-file=.env bot.js and write to your bot in Telegram. For WhatsApp,
install @botmesh/baileys and start the factory with
new BaileysProvider({ session: 'pantry-bot' }) instead: the same code sends
the answer in chunks with “typing…”.
Next steps
- Streaming replies:
ctx.stream()for your own handlers and every option - AI FAQ assistant: the persona and guardrails of a business assistant
- Examples overview