A sophisticated Discord bot that transforms microbiome PDF reports into actionable health insights through an intelligent, step-by-step AI-powered conversation workflow.
BiomeAI analyzes microbiome test reports (PDF format) and guides users through a structured conversation to provide personalized health predictions and recommendations. The bot uses advanced RAG (Retrieval-Augmented Generation) with vector embeddings to understand report content and maintain context throughout the conversation.
- PDF Processing: Extracts and analyzes microbiome report data from PDF uploads
- Structured Conversation Flow: Guides users through a specific sequence of questions and predictions
- Vector Search: Uses pgvector for semantic similarity search across report content
- Cost Tracking: Monitors OpenAI API usage and costs for each interaction
- Thread Management: Creates dedicated Discord threads for each report analysis
- Automated Follow-ups: Sends actionable insights and Q&A prompts automatically
- Discord.py: Bot framework for Discord integration
- OpenAI GPT-4: Natural language processing and analysis
- PostgreSQL + pgvector: Vector database for embedding storage
- PyPDF2: PDF text extraction
- SQLAlchemy: Database ORM
The bot follows a specific 8-step conversation sequence:
- PDF Upload: User uploads microbiome report PDF
- Date/Antibiotics Questions: Bot asks about sample date and recent antibiotic use
- Diet Prediction: Short prediction about user's diet based on microbiome data
- User Diet Confirmation: User confirms/corrects diet information and mentions allergies
- Energy Prediction: Short prediction about energy levels
- User Energy Confirmation: User confirms/corrects energy level information
- Digestive Prediction: Short prediction about digestive health
- User Digestive Confirmation: User confirms/corrects digestive symptoms
- Executive Summary: Comprehensive summary combining all data
- Automated Follow-ups:
- One actionable insight
- Q&A invitation
The core prompts and conversation logic are located in:
openai_client.py- Lines 60-140: Contains all conversation stage promptsbot.py- Lines 340-394: Automated follow-up message logic
The bot determines conversation stages by analyzing:
- Previous bot messages in the thread
- User response patterns
- Specific keywords and phrases
-
Initial Analysis Prompt (
openai_client.pylines 65-75):- Handles first user questions after PDF upload
- Asks about sample date and antibiotics
-
Diet Prediction Prompt (
openai_client.pylines 77-90):- Creates concise diet predictions (3-4 sentences max)
- Uses "BE CONCISE" instruction for brevity
-
Energy Prediction Prompt (
openai_client.pylines 92-105):- Generates energy level predictions
- Prompts user for confirmation
-
Digestive Prediction Prompt (
openai_client.pylines 107-115):- Predicts digestive health patterns
- Asks about specific digestive issues
-
Executive Summary Prompt (
openai_client.pylines 117-127):- Comprehensive analysis combining all data
- Must start with "Executive Summary of microbiome report and lifestyle:"
-
General Q&A Prompt (
openai_client.pylines 129-140):- Handles follow-up questions
- Provides detailed explanations when needed
Located in bot.py lines 340-394:
# Detects executive summary and triggers automatic messages
if response_data['content'].lower().startswith('executive summary of microbiome report and lifestyle:'):
# 1. Generate and send actionable insight
# 2. Send Q&A invitation- Users: Discord user information
- Reports: PDF report metadata and conversation tracking
- ReportChunks: Vectorized text chunks with embeddings
- Messages: Complete conversation history with cost tracking
- Vector similarity search using pgvector
- Conversation stage tracking
- Token usage and cost monitoring
- Thread-based organization
DISCORD_TOKEN=your_discord_bot_token
OPENAI_API_KEY=your_openai_api_key
DATABASE_URL=postgresql_connection_string
- Install dependencies:
pip install discord.py PyPDF2 python-dotenv sqlalchemy psycopg2-binary pgvector openai-
Set up PostgreSQL with pgvector extension
-
Configure environment variables
-
Run the bot:
python main.py- Invite the bot to your Discord server
- Upload a microbiome PDF report in any channel
- The bot will create a dedicated thread
- Follow the conversation prompts
- Receive personalized insights and recommendations
├── main.py # Entry point and environment setup
├── bot.py # Core Discord bot logic and message handling
├── openai_client.py # OpenAI integration and prompt management
├── pdf_processor.py # PDF parsing and text extraction
├── database.py # Database connection and initialization
├── models.py # SQLAlchemy database models
└── config.py # Configuration constants
The bot includes comprehensive logging:
- PDF processing status
- Conversation stage transitions
- API costs and token usage
- Error handling and recovery
- Tracks OpenAI API usage per message
- Estimates embedding generation costs
- Monitors total conversation costs
- Stores cost data in database for analysis
When modifying prompts or conversation logic:
- Prompt Changes: Edit
openai_client.pylines 60-140 - Flow Logic: Modify conversation detection in
bot.py - Database Changes: Update models in
models.py - Testing: Use
/healthand/statscommands for monitoring
To modify the conversation flow:
- Stage Detection: Update conditions in
openai_client.py - Prompt Content: Modify system prompts for each stage
- Response Format: Adjust required response formats
- Follow-ups: Edit automated message content in
bot.py
The prompts are designed to be:
- Concise (3-4 sentences for predictions)
- Medically informed but accessible
- Contextually aware of previous conversation
- Structured to guide user responses
This project is designed for educational and research purposes in microbiome health analysis.