A conversational AI system that analyzes health conversation patterns using advanced language models to identify temporal relationships, recurring issues, and behavioral patterns in user-Clary interactions.
Build an intelligent pattern recognition system for health conversations that can:
- Analyze user-Clary dialogue timelines
- Identify meaningful patterns in health-related behaviors
- Provide temporal reasoning about symptom progression and intervention effectiveness
- Generate structured, evidence-based insights from conversation data
- Maintain strict privacy and safety standards (no medical diagnosis)
- Frontend: Streamlit (conversational chat interface)
- Backend: Python 3.10+
- AI/ML: Groq Llama-3.1-8b-instant (primary), Llama-3.1-70b-versatile, Mixtral-8x7b, Gemma-7b
- Data Processing: Pandas, Pydantic
- Environment: python-dotenv
- Deployment: Streamlit Cloud
- Python 3.10 or higher
- Groq API key
-
Clone the repository
git clone <repository-url> cd clary-health-pattern-reasoner
-
Create virtual environment (recommended)
python -m venv venv source venv/bin/activate # On Windows: venv\Scripts\activate
-
Install dependencies
pip install -r requirements.txt
-
Set up environment variables
cp .env.example .env # Edit .env and add your Groq API key -
Run the application
streamlit run app.py
-
Access the app
- Open your browser to
http://localhost:8501 - Upload a dataset and start analyzing patterns!
- Open your browser to
Create a .env file in the project root with:
GROQ_API_KEY=your_groq_api_key_hereSecurity Note: Never commit your .env file or expose API keys in your code.
The application processes JSON datasets with the following structure:
{
"dataset_info": {},
"users": [
{
"user_id": "USR001",
"name": "Alice Johnson",
"occupation": "Software Engineer",
"onboarding_notes": "New hire from engineering team",
"conversations": [
{
"id": "conv_001",
"timestamp": "2024-01-01T10:00:00Z",
"content": "User message here",
"metadata": {
"user_message": "I feel tired today",
"clary_response": "I understand your fatigue",
"severity": "medium",
"tags": ["fatigue", "sleep"],
"session_id": "session_alice_001"
}
}
]
}
]
}- Validation: Ensures required fields exist
- Security: Removes
hidden_patterns_referenceimmediately upon loading - Normalization: Converts nested conversations to flat timeline events
- Enrichment: Calculates week numbers and temporal relationships
The hidden_patterns_reference field is automatically removed during dataset loading and never used anywhere in the application. This field is considered sensitive training data that should not influence pattern analysis results.
- Function: Loads and validates JSON datasets
- Security: Removes sensitive fields immediately
- Validation: Ensures data structure integrity
- Output: Structured Dataset and summary objects
- Function: Converts conversations to temporal event sequences
- Features: Week calculation, event summarization, pattern detection setup
- Output: TimelineEvent objects with rich metadata
- Function: Orchestrates AI analysis of user timelines
- Prompt Engineering: Structured reasoning prompts for pattern detection
- Context Management: User-wise timeline compression and session summaries
- Output: Raw LLM responses for validation
- Function: Validates and parses LLM output against strict schemas
- Schemas: PatternsAnalysis, Pattern, EvidenceTimeline, RejectedHypothesis
- Repair: Attempts to extract valid JSON from malformed responses
- Output: Structured analysis results or error messages
- Function: Provides conversational interface for pattern analysis
- Features: Example buttons, progress streaming, result visualization
- Timeline Display: User and pattern evidence timelines as interactive tables
- Export: JSON download functionality
graph TD
A[Data Loader<br/>src/data_loader.py] --> B[Timeline Builder<br/>src/timeline_builder.py]
B --> C[LLM Reasoning Layer<br/>src/pattern_reasoner.py]
C --> D[JSON Validator<br/>src/schema.py]
D --> E[Streamlit Chat UI<br/>app.py]
- User-wise Processing: Each user analyzed independently to maintain context
- Full History: Complete conversation timeline per user (dataset is small)
- Compact Summaries: Events condensed into structured TimelineEvent objects
- Session Grouping: Conversations grouped by session_id for pattern analysis
- Sliding Window: Recent N weeks + key historical events
- Pattern-based Sampling: Prioritize events relevant to detected patterns
- Hierarchical Summarization: Week β Month β Quarter summaries
- Adaptive Chunking: Context length based on model capabilities
- Metadata Preservation: Severity, tags, session info maintained
- Temporal Relationships: Week numbers and timestamps preserved
- Evidence Linking: Direct mapping between timeline events and pattern evidence
Primary Model: Groq Llama-3.1-8b-instant
- Fast Inference: Extremely quick response times (milliseconds)
- Cost-Effective: Free tier available, low-cost API usage
- Structured Output: Strong performance on JSON generation tasks
- Temporal Reasoning: Excellent at pattern analysis and timeline understanding
- Llama-3.1-70b-versatile: Maximum reasoning capability
- Mixtral-8x7b-32768: Balanced performance for complex tasks
- Gemma-7b-it: Lightweight option for basic analysis
- β Inference Speed: Critical for interactive pattern analysis
- β Cost Efficiency: Enables broader accessibility and testing
- β JSON Generation: Reliable schema-compliant structured output
- β Pattern Recognition: Strong temporal and relational reasoning
- Invalid JSON: Clear error messages with validation details
- Missing Fields: Specific validation errors for required fields
- Empty Dataset: Graceful handling with user feedback
- Rate Limiting: Automatic retry with exponential backoff
- Network Issues: Clear error messages and retry options
- Invalid API Key: Immediate feedback with setup instructions
- Malformed JSON: Attempt repair or extract valid portions
- Schema Violations: Detailed validation error messages
- Empty Responses: Fallback to mock mode with sample data
- Large Datasets: Progress indicators and chunked processing
- Slow Responses: Streaming progress updates
- Browser Timeouts: Optimized chunking and session management
- Multi-user Pattern Detection: Cross-user pattern identification
- Intervention Effectiveness: Quantify treatment response patterns
- Risk Stratification: Automated severity progression analysis
- Predictive Insights: Early warning for pattern development
- Batch Processing: Parallel analysis for multiple users
- Caching Layer: Store analysis results for faster re-analysis
- Model Fine-tuning: Custom models for health pattern recognition
- Real-time Analysis: Streaming conversation analysis
- Advanced Visualizations: Timeline charts and pattern graphs
- Interactive Filtering: Filter patterns by type, severity, time range
- Export Options: PDF reports, CSV data, visualization exports
- Collaboration Features: Share analysis results with team members
- Database Integration: Persistent storage for large datasets
- API Endpoints: REST API for programmatic access
- Queue System: Background processing for large analysis jobs
- Multi-tenant Support: Organization-level data isolation
- GitHub repository with the project
- Groq API key
- Streamlit Cloud account
-
Push to GitHub
git add . git commit -m "Ready for deployment" git push origin main
-
Connect to Streamlit Cloud
- Go to share.streamlit.io
- Connect your GitHub repository
- Select the main branch
-
Configure Secrets
- In Streamlit Cloud dashboard, go to your app settings
- Add secret:
GROQ_API_KEYwith your API key value - The app will automatically use this instead of
.env
-
Deploy
- Click "Deploy" in Streamlit Cloud
- Wait for build completion
- Access your live app URL
# packages.txt (if needed)
# requirements.txt (already configured)
# secrets.toml (configured via UI)
GROQ_API_KEY = "your-key-here"- Resource Limits: Monitor usage within Streamlit Cloud free tier
- API Costs: Track Groq API usage and costs
- Data Privacy: Ensure compliance with health data regulations
- Performance: Consider upgrading to paid tier for heavy usage
This project is developed for educational and research purposes. Please ensure compliance with applicable data privacy regulations when handling health-related conversation data.
- Fork the repository
- Create a feature branch
- Make your changes with proper testing
- Submit a pull request with detailed description
Built with β€οΈ for advancing health conversation analysis through AI-powered pattern recognition.