In questa guida avanzata, costruiremo un agente AI RAG che:
- Interagisce via Telegram
- Riceve e gestisce richieste di prenotazione
- Recupera informazioni da documenti o FAQ usando LangChain
- Esegue azioni reali come salvare dati in un database
Useremo LangChain, FastAPI, PostgreSQL (con pgvector) e Telegram Bot API.
🧠 Cos'è un agente RAG (Retrieval-Augmented Generation)
Un agente RAG combina due componenti:
- Retrieval: recupera documenti rilevanti (da un vettorializzatore)
- Generation: genera risposte usando un LLM (es. OpenAI, Mistral, Ollama, ecc.)
Questo migliora la precisione dell'output perché le risposte sono basate su dati reali, non solo su conoscenza pre-addestrata.
⚙️ Architettura del progetto
Utente Telegram ─▶ Bot Telegram ─▶ FastAPI (Webhook) ─▶ LangChain Agent
├─▶ Vector DB (es. pgvector / ChromaDB)
└─▶ DB prenotazioni (PostgreSQL)
🛠️ Setup iniziale
1. Crea un bot Telegram
- Vai su
@BotFather
- Crea un nuovo bot e ottieni il
BOT_TOKEN
2. Setup del progetto Python
mkdir ai-rag-bot && cd ai-rag-bot
python -m venv venv && source venv/bin/activate
pip install fastapi langchain openai python-telegram-bot[asyncio] pgvector psycopg2
3. Setup database PostgreSQL + pgvector
CREATE EXTENSION IF NOT EXISTS vector;
CREATE TABLE documents (id serial PRIMARY KEY, content text, embedding vector(1536));
CREATE TABLE bookings (id serial PRIMARY KEY, name text, date date, time text);
🔗 Integrazione con Telegram
from telegram import Update
from telegram.ext import ApplicationBuilder, ContextTypes, CommandHandler, MessageHandler, filters
BOT_TOKEN = "<your-bot-token>"
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
await update.message.reply_text("Ciao! Scrivimi una domanda o chiedimi di prenotare un appuntamento.")
application = ApplicationBuilder().token(BOT_TOKEN).build()
application.add_handler(CommandHandler("start", start))
application.run_polling()
Puoi anche usare Webhook per FastAPI.
📚 Embedding dei documenti
Usa LangChain + OpenAI (o altri modelli) per vettorializzare documenti:
from langchain.embeddings import OpenAIEmbeddings
from langchain.vectorstores.pgvector import PGVector
embedding = OpenAIEmbeddings()
vectorstore = PGVector.from_documents(docs, embedding=embedding, collection_name="faq", connection_string=...)
🤖 Costruzione dell'agente con LangChain
from langchain.agents import create_react_agent
from langchain.agents.agent_toolkits import Tool
from langchain.llms import OpenAI
# Tool per prenotazioni
async def prenota(args):
name, date, time = args
# salva nel DB
return f"Prenotazione registrata per {name} il {date} alle {time}"
prenotazione_tool = Tool(
name="prenota",
func=prenota,
description="Registra una prenotazione: prenota(nome, data, ora)"
)
agent = create_react_agent(OpenAI(), tools=[prenotazione_tool], verbose=True)
Puoi aggiungere anche un retriever da vectorstore come input contestuale.
🧠 Combinare Retrieval e Tool
from langchain.chains import RetrievalQA
qa_chain = RetrievalQA.from_chain_type(
llm=OpenAI(), retriever=vectorstore.as_retriever(), return_source_documents=True
)
Nel tuo handler Telegram:
async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
query = update.message.text
response = qa_chain.run(query)
await update.message.reply_text(response)
✅ Estendere con nuove funzioni
- Aggiungi validazioni (es. formato orario)
- Crea un sistema multiutente (token o user ID)
- Salva i log delle richieste (per analisi o miglioramento dataset)
- Aggiungi memorie con
ConversationBufferMemory
🧪 Test e deploy
Puoi eseguire tutto in locale, oppure:
- Deploy su Railway.app o Render.com
- Usa ngrok per testare Webhook
- Aggiungi HTTPS e Webhook via FastAPI
📌 Conclusione
Hai appena visto come creare un agente AI completo che combina:
- LangChain + RAG
- Telegram bot
- Esecuzione di azioni reali (prenotazioni)
- Recupero informazioni in tempo reale
Un setup simile è facilmente adattabile a use case come:
- Helpdesk AI
- Booking system intelligente
- Customer service automatizzato
Per altri articoli su agenti AI o LangChain, visita la sezione Blog.