Smart Telegram Assistant with Dynamic AI Routing and Persistent Memory - n8n Workflow

A powerful n8n workflow template utilizing Gemini AI and PostgreSQL for a high-performance, cost-optimized Telegram chatbot with dynamic model selection based on task complexity.

Workflow Preview

Ready to automate?

Download this n8n workflow template and start using it instantly.

Who is this best for?


  • AI Developers & Integrators: Looking for advanced n8n templates for building RAG/memory-enabled chatbots.

  • Businesses Seeking Efficiency: Users wanting to minimize AI costs by only deploying high-tier models for complex queries.

  • n8n Automation Specialists: Seeking a robust example of dynamic LangChain n8n node usage and custom scripting for API compliance.

Overview

This high-performance n8n workflow solves the problem of high conversational AI costs and slow responses by implementing a dynamic routing strategy. Instead of running every query on the most expensive model (like Gemini 2.5 Pro), this n8n template first analyzes the request difficulty using a cheaper, faster model (Gemini 2.5 Flash Lite).

The core of the system is the persistence provided by PostgreSQL, acting as the chat memory. The n8n workflow efficiently retrieves and summarizes this memory, ensuring the main AI agent only receives necessary context, drastically reducing token usage and improving response times. It also expertly handles different input types, including text and voice messages, making this a highly versatile n8n solution.

How it Works

The n8n workflow begins with the Telegram Trigger n8n node, initiating the flow upon receiving a message.


  1. Input Routing: The flow immediately routes the input via a Switch node, separating standard text from voice messages. Voice messages are downloaded, processed by a custom Code n8n node to fix the MIME type, and transcribed/analyzed by a Gemini AI n8n node.

  2. Context and Memory: The incoming request is normalized. A PostgreSQL n8n node retrieves the chat history (memory) associated with the user’s chat ID. This history is aggregated.

  3. Summarize & Categorize: A dedicated Chain LLM n8n node, running on the budget-friendly Google Gemini 2.5 Flash Lite model, processes the full context. It uses a Structured Output Parser n8n node to return a JSON object defining the relevant context summary and a task difficulty score (1, 2, or 3).

  4. Dynamic Routing: The main Agent n8n node is connected to the Model Selector n8n node. This selector dynamically assigns the language model based on the difficulty score:

Difficulty 1 → Gemini 2.5 Flash Lite (Fastest, cheapest)
Difficulty 2 → Gemini 2.5 Flash (Balanced)
* Difficulty 3 → Gemini 2.5 Pro (Max reasoning power)

  1. Response and Delivery: The Agent generates the final response. A crucial MarkdownV2 custom Code n8n node formats the output, ensuring Telegram MarkdownV2 compliance and splitting messages longer than 4096 characters into chunks.

  2. Memory Update: The final step uses a PostgreSQL n8n node to update the chat_memory table, storing both the user's message and the agent's response in a single, efficient entry.

Installation Guide

To deploy this comprehensive n8n workflow template, follow these steps:


  1. Import: Copy the provided JSON and import it into your n8n instance.

  2. Credentials Setup:

Telegram: Set up your Telegram API credentials for the Telegram Trigger and the Send a text message n8n node.
Google Gemini (PaLM): Configure your Google Gemini API credentials for all AI n8n nodes (Analyze voice message, Google Gemini 2.5 Flash Lite, Gemini 2.5 Flash, Gemini 2.5 Pro).
* PostgreSQL: Set up credentials for your PostgreSQL database. Ensure the host is accessible from your n8n environment.

  1. Database Initialization: Manually execute the When clicking ‘Execute workflow’ n8n trigger to run the Create Chat Memory Table n8n node. This will create the necessary chat_memory table in your PostgreSQL instance.

  2. Activation: Activate the main Telegram Trigger webhook for the n8n workflow to start listening for incoming messages.

Node Details

Telegram Trigger (n8n trigger): Listens for incoming messages (updates) from Telegram users, initiating the entire n8n workflow.
Input Message Router1 (Switch n8n node): Directs the flow based on message type: Text, Voice Message, or falls back to an error handler for unsupported types.
Download Voice Message (Telegram n8n node): Downloads the binary audio file if a voice message is detected.
Fix mime (Code n8n node): Contains custom JavaScript logic to analyze the file extension and assign the correct MIME type, crucial for successful analysis by the Gemini n8n node.
Analyze voice message (Google Gemini n8n node): Uses Gemini Pro to perform speech-to-text analysis on the downloaded audio file, converting the voice message into usable text input.
Get Chat Memory (PostgreSQL n8n node): Queries the chatmemory table to retrieve up to 25 past messages for the current session ID (chatid).
Summarize & Categorize (Chain LLM n8n node): A smart stage utilizing Gemini 2.5 Flash Lite for cost optimization. It summarizes the aggregated chat history and assigns a numerical difficulty level (1-3) to the current user request.
Model Selector (LangChain n8n node): A routing mechanism that uses conditional rules based on the 'difficulty' output to select one of the three available Gemini Language Model n8n nodes for the final reasoning task.
Agent (LangChain n8n node): The core reasoning component. It receives the categorized context and user request, generating the intelligent response using the dynamically selected LLM.
MarkdownV2 (Code n8n node): Advanced custom script that ensures the Agent's output is safe and compliant with Telegram's MarkdownV2 parsing rules, including escaping special characters and chunking long messages into smaller parts.
Update Chat Memory (User and Agent) (PostgreSQL n8n node): Logs both the user's input and the agent's full response into the database for persistent context management in subsequent interactions of this n8n workflow.
Send a text message (Telegram n8n node): Delivers the final, formatted response back to the user on Telegram using the MarkdownV2 parse mode.

Related n8n Workflows

Free

Nodes: 15 Nodes
Updated: December 26 2025
View all
Created by

Detail-oriented professional with a dual degree in Systems Engineering and Business Administration and international experience in technology and process improvement. I specialize in workflow automation with n8n, API integration, programming, and data analysis. Known for strong analytical skills and clear technical documentation.

Featured*