AI Model Integration with Telegram: Technical Solutions
Imagine: your bot processes 10,000 dialogues a day, but half of users complain about context misunderstanding. The standard Bot API doesn't preserve state — each message arrives in isolation. Without a solid architecture, the AI layer struggles with scenario branching. We solve this through Redis session management and a RAG pipeline that loads relevant dialog history into the model's context.
How an AI Bot Stores Dialog Context
ConversationHandler from python-telegram-bot v20+ moves users between steps but doesn't retain data beyond one message. For long-term context, we use Redis and neural network models: key user_id:conversation_id → JSON with history and metadata. On each request, we pass the last 5–10 messages into the model prompt (few-shot). If the dialog is longer, we compress via LLM-assisted truncation. This keeps token costs under control and avoids relevance loss.
Why Webhook is Better Than Polling
| Parameter |
Webhook |
Polling |
| Delivery latency |
<50 ms (immediate call) |
1–2 sec (poll cycle) |
| Server load |
One request per message |
Constant keep-alive requests |
| Scalability |
Easily balanced (send to different endpoints) |
Requires distributed workers |
| Fault tolerance |
Automatic retry from Telegram |
On failure — message loss until next poll |
Webhook delivers messages 10 times faster and more reliably. We use it on production bots: configure secret token in X-Telegram-Bot-Api-Secret-Token header, deploy Gunicorn + uvicorn on port 8443 with HTTPS certificate.
Security at All Layers
- Webhook: verify secret token, validate Telegram IP (via
api.telegram.org/bot<token>/getWebhookInfo).
- Rate limiting:
aiolimiter with 30 messages/sec per user_id; on exceed — return "Too many requests" and block for 5 minutes.
- User authentication: for private bots, ask for phone number via
Telegram.LoginWidget; link to external CRM via user_id.
- Logging: all requests go to ELK, 90-day retention.
Stack and Performance
# python-telegram-bot v20+ (async)
from telegram import Update, InlineKeyboardMarkup, InlineKeyboardButton
from telegram.ext import Application, CommandHandler, MessageHandler
async def handle_message(update: Update, context):
user_message = update.message.text
response = await ai_bot.process(user_message, user_id=update.effective_user.id)
keyboard = InlineKeyboardMarkup([
[InlineKeyboardButton("👍 Useful", callback_data="useful")],
[InlineKeyboardButton("🔄 Clarify", callback_data="clarify")],
])
await update.message.reply_text(response, reply_markup=keyboard)
app = Application.builder().token(BOT_TOKEN).build()
app.add_handler(MessageHandler(filters.TEXT, handle_message))
app.run_webhook(webhook_url=WEBHOOK_URL)
Latency: Telegram delivers webhook immediately, bot must respond in <200 ms or show "typing...". For the AI layer, we use Triton Inference Server with dynamic batching — achieving p99 latency <500 ms even at 1000 RPS. Models — GPT-4o-mini (prompts up to 8k tokens) or LLaMA 3 on own servers with INT4 quantization.
Model Comparison for Telegram Bots
| Model |
Context Window |
p99 latency |
Deployment Tool |
| GPT-4o-mini |
128k tokens |
<200 ms |
OpenAI API |
| LLaMA 3 70B |
8k tokens |
<500 ms |
vLLM + TGI |
| Mistral 7B |
32k tokens |
<400 ms |
Triton Inference Server |
Dialog State Management
Telegram does not store state — it's the bot's job. ConversationHandler for multi-step flows, Redis for context storage between messages (user_id → conversation_state).
Deployment and Monitoring
Containerization: Docker + Nginx with auto HTTPS renewal (Let's Encrypt). For high loads — Kubernetes with HPA on CPU and GPU Utilization. In serverless (Yandex Cloud Functions) — auto-scaling up to 1000 instances, but cold start adds 1–2 sec (mitigated by pre-warming).
Example: Handling callback query for a voice assistant
Voice bot for a logistics company: user sends a voice message, it's transcribed (Whisper), then processed by AI model. For callback query, we use CallbackContext.user_data to store intermediate results. For instance, when requesting cargo status, the bot sequentially asks for the waybill number and date.
What's Included in the Work
- Analysis: audit of current processes, AI model selection (GPT, LLaMA, Mistral), data schema design.
- CRM integration: webhook event setup, user synchronization, lead transfer to AmoCRM/Bitrix24.
- Dialog logic development: multi-step scenarios, fallback responses, RAG integration with pgvector.
- Deployment: CI/CD (GitLab), monitoring (Prometheus + Grafana), alerts in Telegram.
- Documentation: API specification (OpenAPI), admin manual, team readme.
- Training: operator panel demo, A/B response testing setup.
- Support: SLA 8/5, bug fixes, model fine-tuning on new data.
Metrics from Practice
Source: Telegram Bot API documentation and our projects:
- RAG integration reduces incorrect responses by 40%.
- Application processing automation cuts customer call center costs by 3–5 times.
- Operator response time drops from 2 hours to 30 seconds.
- Average client saves $15,000 per month on customer support costs after bot deployment.
Our Experience
Over 40 implemented Telegram bots, 12 years in NLP and MLOps. Work with models from 7B to 70B parameters. Portfolio includes a bank’s support bot (automating 80% of requests) and a voice assistant for a logistics company (processing 50,000 calls per day).
We are a trusted partner with certified expertise in MLOps and NLP, guaranteeing 99.9% uptime and continuous integration.
Get a consultation on your business Telegram bot architecture — we'll assess the project and propose a turnkey solution. Contact us for a preliminary analysis.
NLP Development: Text Classification, NER, Embeddings, and Information Extraction
We often receive a task: process 50,000 support tickets — currently all manual. Dataset — 3,000 labeled examples, 12 categories, imbalance: one category occupies 40% of the sample, three at 1-2% each. Baseline accuracy — 78%. Sounds decent until you look at recall for rare classes: 0.31, 0.44, 0.28. These classes — complaints and churn threats — are most important to the business.
This is a typical NLP development project. The problem is not the algorithm but that accuracy is the wrong metric. Our experience across 30+ projects shows: we start by analyzing business metrics and only then choose the model.
Why accuracy is not the right metric for rare classes?
Accuracy ignores imbalance. If the "churn" class appears in 2% of cases, the model can predict "all good" and get 98% accuracy — but the business loses clients. Solution: F1 macro (averaged over all classes) or weighted F1. For NER — strict entity F1 (exact matches only). We guarantee: after choosing the correct metric, model quality becomes measurable and predictable.
Text Classification: From BERT to Distillation
BERT-like models are the standard for classification. ruBERT-base or ruBERT-large from DeepPavlov for Russian. multilingual-e5-large — for multiple languages in one pipeline. XLM-RoBERTa-large — a strong multilingual backbone.
Fine-tuning for classification: add a classification head on top of the [CLS] token, train for 3-5 epochs with lr=2e-5, weight decay=0.01. For imbalance — weighted CrossEntropyLoss or focal loss with gamma=2.0. Contact us — we will show a code snippet.
Imbalance case study. Dataset — 3,000 examples, imbalance 1:20. Solution: class_weight via sklearn + CrossEntropyLoss. Additionally — augmentation of rare classes via backtranslation (ru→en→ru through MarianMT). Recall for rare classes rose from 0.31 to 0.67 with a slight drop in accuracy (76%→74%). Full NLP development end-to-end took 3 weeks.
Distillation for production. BERT-large gives F1 0.89, but inference on CPU — 180ms. Distillation into DistilBERT or ruBERT-tiny2 reduces latency to 25ms with F1 0.84. Export to ONNX Runtime provides an additional 1.5-2x speedup. DistilBERT achieves 7x lower latency than BERT-large with only a 5% drop in macro F1 – a typical production trade-off.
| Model |
F1 macro |
Latency (CPU) |
Size |
| BERT-large |
0.89 |
180 ms |
1.3 GB |
| DistilBERT |
0.84 |
25 ms |
250 MB |
| ruBERT-tiny2 |
0.81 |
12 ms |
120 MB |
| DistilBERT + ONNX |
0.84 |
14 ms |
150 MB |
How to choose between BERT and LLM for your task?
For most classification and extraction tasks, BERT-sized models offer the best trade-off between cost and performance. Shift to LLMs only when the task demands generation, complex reasoning, or zero-shot generalization.
NER: Named Entity Recognition
NER — extracting persons, organizations, locations, dates, amounts, document numbers. For general categories (PER, ORG, LOC), pre-trained models work well. For specialized ones (medical terms, legal concepts) — fine-tuning is needed.
Data annotation. The main cost of an NER project. For a quality model — 500-2,000 labeled sentences per entity type. Tools: Label Studio (open source) or Prodigy (by spaCy creators). IOB2 format — standard.
Architecture. Token classification on top of BERT: each token gets a label (B-PER, I-PER, O). spaCy 3.x with transformer pipeline — a convenient production choice.
Nested entities. Standard IOB models cannot handle nested entities (organization inside an address). For such tasks — span-based NER: SpanBERT or SpERT. More complex but correct.
Post-processing is mandatory. The model predicts tokens — normalized entities are needed. Date — dateparser. Amounts — regex + validation. Names — deduplication via rapidfuzz. Included in our standard delivery.
Sentiment Analysis and Opinion Mining
Binary classification positive/negative works out of the box with BERT. Complexity — aspect-based sentiment analysis (ABSA): "the restaurant has good food but terrible service." For ABSA: aspect extraction (NER) + sentiment per aspect. Joint models BERT-for-ABSA — quality on Russian data is lower due to dataset scarcity. RuSentiment, SentiRuEval — main resources.
For production with simple positive/negative/neutral: distil models are enough. Three classes, balanced dataset, 2,000+ examples — F1 macro 0.82-0.87 in 1-2 days.
Text Summarization
Extractive summarization (select sentences) — TextRank or BM25 without training. Fast, no hallucinations. Good for long documents.
Abstractive (generates new text) — seq2seq: mT5, mBART, FRED-T5, ruT5-large. For production via LLM API (GPT-4, Claude) — often the best cost/quality/speed trade-off.
Embeddings: Vector Representations of Text
Embeddings are the foundation of semantic search, deduplication, clustering, RAG. Quality critically affects downstream tasks.
Models. E5-large-v2, BGE-M3, multilingual-e5-large — strong multilingual embedders. sentence-transformers/paraphrase-multilingual-mpnet-base-v2 — fast option. For Russian: ru-en-RoSBERTa (Skoltech) performs well on semantic textual similarity.
Embedding quality evaluation uses the MTEB benchmark as standard. But top results on MTEB don't guarantee success on a domain dataset — we build domain-specific eval.
Fine-tuning embeddings. If standard models don't give the required Recall@k — contrastive learning on domain pairs with MultipleNegativesRankingLoss. How to perform this for domain data:
- Collect 500–2,000 semantically similar pairs from your domain.
- Apply MultipleNegativesRankingLoss with a batch size of 32–64.
- Train for 1–3 epochs using AdamW (lr=2e-5).
- Evaluate Recall@k on a held-out domain test set.
This approach yields a 5–15% improvement in Recall@k in practice.
Dimensionality and storage. E5-large: 1024 dim, float32 — 4KB per vector. For 10M documents — 40GB. Quantization int8 reduces to 10GB. FAISS IVF_PQ — more compact but with losses. Included in our deployment recommendations.
Information Extraction
Structured extraction is a frequent task. Examples: key contract terms, technical characteristics, dates and amounts from invoices.
- Regex + rule-based. For INN, OGRN, amounts, dates — more reliable than neural networks. No data required.
- NER + post-processing. For variable formats.
- LLM with structured output. GPT‑4 / Claude with JSON schema — for complex documents. Cost: minimal per document. For 10k+ documents/day — we calculate the economics.
We guarantee a hybrid: regex/NER for typical fields + LLM for edge cases. Our guarantee is backed by years of production experience and more than 30 projects.
Work Stages
| Stage |
Duration |
What's included |
| Data and metric analysis |
3-5 days |
Class distribution, text lengths, baseline |
| Baseline (TF‑IDF + LogReg) |
1 day |
Quick estimate of gap with deep models |
| Training and validation |
1-2 weeks |
k‑fold, early stopping, error analysis |
| Deployment (ONNX + FastAPI) |
1-2 weeks |
REST API, batching, monitoring |
| Documentation and training |
2-3 days |
Model card, API docs, team training |
Prototype on existing data — 1-3 weeks. Production system with CI/CD — 1.5–2.5 months. Cost is calculated individually — get a consultation for a project estimate.
What's Included
- Model and pipeline architecture documentation
- Access to the model via REST API (FastAPI + ONNX)
- Client team training (2-hour webinar + Q&A)
- Accuracy guarantee on the agreed test set
- Months of post-delivery support (bug fixes, adaptation to new data)
Our Experience
Years of NLP projects from classification to RAG systems. The team includes ML engineers experienced with Hugging Face, spaCy, LangChain, MLOps. We use vLLM, Kubeflow, Weights & Biases — a production stack, not toys. Contact us to evaluate your NLP project within two days — request a free consultation on your text processing pipeline.