- Stack: GPT4All + Llama 3.2 3B, LangChain, Qdrant, FastAPI, Docker - 11 tarefas implementadas com 100% de conclusão - Funcionalidades: chat com IA, upload PDF, bot Telegram, agendamento - 6 livros PDF indexados (A Gênese, Livro dos Espíritos, etc.) - Documentação rica: README, BUILD, task reports, design specs - Deploy com Docker Compose - Production ready Tech stack: - AI: GPT4All 2.4.6, Llama 3.2 3B q4_0 - Backend: FastAPI 0.115.0, Celery 5.4.0, Redis 5.2.0 - RAG: LangChain 0.3.7, Qdrant 1.11.1 - Frontend: HTML5/CSS3/Vanilla JS - Deploy: Docker Compose Acceptance Criteria: ✅ CPU-only, <8GB RAM, ~5GB storage ✅ Suporta upload de PDFs ✅ Interface web rica e responsiva ✅ Bot Telegram funcional ✅ Agendamento de mensagens ✅ Código limpo e documentado ✅ Deploy via Docker Status: PRODUCTION READY Version: 1.0.0 Date: 2026-11-01
5.9 KiB
5.9 KiB
@self.bot.message_handler(commands=['content'])
def send_content(message):
try:
book = self.rag_service.query("Conteúdo aleatório sobre espiritismo", top_k=1)
self.bot.reply_to(message, book['response'])
except Exception as e:
logger.error(f"Error sending content: {e}")
self.bot.reply_to(message, "Erro ao gerar conteúdo.")
@self.bot.message_handler(commands=['schedule'])
def schedule_message(message):
args = message.text.split()[1:]
if not args:
self.bot.reply_to(message, "Uso: /schedule <horário> [livro]")
return
time = args[0]
if len(args) > 1:
book = " ".join(args[1:])
else:
book = None
try:
self.schedule_manager.create(time=time, book=book)
self.bot.reply_to(
message,
f"✅ Agendamento criado para {time}\n"
f"📝 Livro: {book or 'Todos os livros'}"
)
except Exception as e:
logger.error(f"Error creating schedule: {e}")
self.bot.reply_to(message, f"Erro ao criar agendamento: {e}")
@self.bot.message_handler(commands=['schedule', 'list'])
def list_schedules(message):
schedules = self.schedule_manager.get_all()
if not schedules:
self.bot.reply_to(message, "Não há agendamentos.")
return
schedules_text = "\n".join([
f"{s.id}. {s.time} - {s.book or 'Todos'} - {'✅' if s.enabled else '❌'}"
for s in schedules
])
self.bot.reply_to(message, f"📅 *Agendamentos:*\n\n{schedules_text}")
@self.bot.message_handler(commands=['schedule'])
def remove_schedule(message):
try:
args = message.text.split()
if len(args) < 3:
self.bot.reply_to(message, "Uso: /schedule remove <id>")
return
schedule_id = int(args[2])
self.schedule_manager.delete(schedule_id)
self.bot.reply_to(message, f"✅ Agendamento {schedule_id} removido.")
except ValueError:
self.bot.reply_to(message, "ID deve ser um número.")
except Exception as e:
logger.error(f"Error removing schedule: {e}")
self.bot.reply_to(message, f"Erro ao remover agendamento: {e}")
def start(self):
"""Start the bot."""
logger.info("Starting Telegram bot...")
self.bot.infinity_polling(timeout=10, long_polling_timeout=1)
- [ ] **Passo 2: Criar celery_tasks.py**
```python
from celery import Celery
from celery.schedules import crontab
from app.services.bot_service import TelegramBot
from app.services.rag_service import RAGService
from app.utils.schedule_manager import ScheduleManager
import os
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
celery = Celery(
"espiritismo_tasks",
broker=os.getenv("CELERY_BROKER_URL", "redis://redis:6379/0"),
backend=os.getenv("CELERY_RESULT_BACKEND", "redis://redis:6379/0"),
)
# Initialize services
qdrant_service = qdrant_client.QdrantClient(
url=os.getenv("QDRANT_URL", "http://qdrant:6333")
)
rag_service = RAGService(qdrant_service, os.getenv("GPT4ALL_MODEL", "llama-3.2-3b-instruct-q4_0.gguf"))
schedule_manager = ScheduleManager("/app/schedules.json")
bot = TelegramBot(os.getenv("TELEGRAM_BOT_TOKEN", ""), os.getenv("TELEGRAM_CHAT_ID", ""))
@celery.task
def send_scheduled_message():
"""Send a random message from the books."""
logger.info("Sending scheduled message...")
try:
# Get all books
books = qdrant_service.get_books()
if not books:
logger.warning("No books found in database")
return
# Choose a random book
book = random.choice(books)
# Generate random query
queries = [
"O que diz o livro sobre amor?",
"Qual é a mensagem principal deste livro?",
"Dê uma reflexão sobre este livro",
"Conte uma história importante deste livro"
]
query = random.choice(queries)
# Query the RAG system
result = rag_service.query(query, top_k=1)
# Send via Telegram
message = f"📖 *{book}*\n\n{result['response']}"
bot.bot.send_message(
bot.chat_id,
message,
parse_mode="Markdown"
)
logger.info(f"Message sent successfully: {book}")
except Exception as e:
logger.error(f"Error sending scheduled message: {e}")
raise
@celery.periodic_task(
run_every=crontab(minute="*"),
)
def check_schedules():
"""Check and execute scheduled messages."""
logger.info("Checking schedules...")
schedules = schedule_manager.get_all()
for schedule in schedules:
if not schedule.enabled:
continue
# Check if this is the scheduled time
current_time = datetime.now().strftime("%H:%M")
if current_time == schedule.time:
send_scheduled_message.delay()
logger.info("Schedule check completed")
Tarefa 7: Utilitários Adicionais
Arquivos:
- Criar:
backend/app/utils/schedule_manager.py - Criar:
backend/app/__init__.py
Interfaces:
-
Consumes: N/A
-
Produces: Gerenciamento de agendamentos funcional
-
Passo 1: Criar __init__.py
from .models import ChatRequest, ChatResponse, BookInfo, ChatRequestResponse, UploadResponse, ScheduleInfo, ScheduleRequest
__all__ = [
"ChatRequest",
"ChatResponse",
"BookInfo",
"ChatRequestResponse",
"UploadResponse",
"ScheduleInfo",
"ScheduleRequest",
]
- Passo 2: Criar schedule_manager.py
import json