An intelligent, privacy-first conversational AI assistant for troubleshooting step tracking issues across iOS (HealthKit) and Android (Health Connect) health platforms.
Step Sync ChatBot is a production-ready Flutter package that provides an intelligent conversational interface for diagnosing and resolving step syncing issues. It combines rule-based logic, comprehensive diagnostics, and optional LLM-powered AI while maintaining strict privacy controls to ensure no Personal Health Information (PHI) is ever sent to external services.
- π€ Hybrid Intelligence: Rule-based (80%) + On-device ML [TODO] (15%) + Cloud LLM (5%)
- π Privacy-First: HIPAA-aware design, PHI sanitization, critical PII blocking
- π₯ Health Platform Integration: iOS HealthKit + Android Health Connect
- π Comprehensive Diagnostics: Automatic issue detection and guided remediation
- πΎ Conversation Persistence: SQLite-based history with multi-device sync
- π° Cost Control: Rate limiting, budget caps, usage monitoring
- π§ͺ 150+ Tests: Comprehensive test coverage across all components
- π¦ Modular Design: Easy integration into any Flutter app
Add to your pubspec.yaml:
dependencies:
step_sync_chatbot:
path: ../path/to/packages/step_sync_chatbotimport 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:step_sync_chatbot/step_sync_chatbot.dart';
void main() {
runApp(
const ProviderScope(
child: MyApp(),
),
);
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: ElevatedButton(
onPressed: () {
// Open chatbot with mock service
final config = ChatBotConfig.development(
userId: 'user123',
useMockService: true,
);
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ChatScreen(config: config),
),
);
},
child: const Text('Open ChatBot'),
),
),
),
);
}
}cd packages/step_sync_chatbot
flutter pub get
flutter pub run build_runner build --delete-conflicting-outputs
cd example
flutter runOr use the batch scripts (Windows):
# From project root
run.bat
# Select option 1: Full Setup
# Then select option 4: Run Example AppCore Architecture & Rule-Based Intelligence
- π¨ Conversational UI with Material Design
- π§ Rule-based intent classification (32 patterns, 12 intents)
- π¬ Template-based response system
- π Riverpod state management
- π± Quick reply buttons and interactive messages
- π― Intent confidence scoring
Key Files: 40+ files, 3,500+ lines of code
Production Health Data Integration
- π₯ HealthSync SDK integration
- π iOS HealthKit support
- π€ Android Health Connect support
- π Permission management
- π Step data fetching (last 7 days)
- π Data source detection
- β‘ Smart caching
Key Files: RealHealthService, Health Platform Adapters
SQLite Database & State Persistence
- πΎ SQLite database (3 tables: conversations, messages, user_preferences)
- π Automatic conversation saving
- π± Multi-device sync support
- ποΈ Conversation history loading
- π§Ή Automatic cleanup (90-day retention)
- π Conversation statistics
- π Search and retrieval
Key Files: 15 tests, conversation repository implementation
Comprehensive System Health Checks
- π Platform availability detection
- β Permission status checking
- π Battery optimization detection (Android)
- π Data source analysis
- π― Issue severity classification (info, warning, error, critical)
- π‘ Actionable quick replies
- π οΈ Automatic settings navigation
- π± Health Connect installation flow
- π Platform-specific guidance
Key Files: 33 tests, diagnostic service, platform utilities
AI-Powered Intelligence with Privacy
- π€ Azure OpenAI provider (HIPAA-ready)
- π PHI/PII sanitization pipeline
- π― Hybrid intent routing (3-tier)
- π¬ Conversation context management
- π° Rate limiting & cost monitoring
- π Usage statistics & analytics
- π‘οΈ Critical PII blocking
- π§ͺ 70+ LLM-specific tests
Key Files: 11 new files, 3,200+ lines of code
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Flutter App (Host) β
ββββββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββββ
β
ββββββββββββββΌβββββββββββββ
β Step Sync ChatBot β
β Package β
ββββββββββββββ¬βββββββββββββ
β
ββββββββββββββββββββββΌβββββββββββββββββββββ
β β β
ββββββΌβββββ ββββββΌβββββ ββββββΌβββββ
β UI β β Core β β Data β
β Layer β β Servicesβ β Layer β
ββββββ¬βββββ ββββββ¬βββββ ββββββ¬βββββ
β β β
β ββββββΌβββββββββββββββββββββΌβββββ
β β Hybrid Intent Router β
β β (Rule β ML β LLM) β
β ββββββ¬ββββββββββββββββββββββββββ
β β
β βββββββββββΌββββββββββ
β β β β
β ββββββΌββββ ββββΌββββ ββββΌββββ
β β Rule β β ML β β LLM β
β β Based β β[TODO]β βCloud β
β ββββββββββ ββββββββ ββββ¬ββββ
β β
β ββββββββΌβββββββ
β β PHI β
β β Sanitizer β
β βββββββββββββββ
β
ββββββΌβββββββββββββββββββββββββββββββββββββ
β Health Services β
β ββ iOS HealthKit β
β ββ Android Health Connect β
βββββββββββββββββββββββββββββββββββββββββββ
User Query
β
βΌ
βββββββββββββββββββ
β Rule-Based β Confidence β₯ 0.7?
β Classification β βββββββββββββββββΊ YES ββΊ Response (80%)
ββββββββββ¬βββββββββ
β NO
βΌ
βββββββββββββββββββ
β On-Device ML β [TODO]
β Model β βββββββββββββββββΊ YES ββΊ Response (15%)
ββββββββββ¬βββββββββ
β NO
βΌ
βββββββββββββββββββ
β PHI Sanitizer β Safe to send?
ββββββββββ¬βββββββββ
β YES
βΌ
βββββββββββββββββββ
β Cloud LLM β βββββββββββββββββββββΊ Response (5%)
β (Azure OpenAI) β
βββββββββββββββββββ
User Input: "I walked 10,000 steps yesterday on my iPhone 15"
β
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β PHI/PII Detector β
β ββ Numbers: 10,000 β [NUMBER] β
β ββ Dates: yesterday β recently β
β ββ Devices: iPhone 15 β phone β
β ββ Apps: Google Fit β fitness app β
β ββ Critical PII: emails, phones, names β BLOCK β
ββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββ
β
βΌ
Sanitized: "I walked [NUMBER] steps recently on my phone"
β
βΌ
Cloud LLM β
ChatBot_StepSync/
βββ packages/
β βββ step_sync_chatbot/ # Main package
β βββ lib/
β β βββ src/
β β β βββ config/ # Configuration
β β β βββ core/ # Core services
β β β β βββ chatbot_controller.dart
β β β β βββ chatbot_state.dart
β β β β βββ diagnostic_service.dart
β β β β βββ intents.dart
β β β β βββ rule_based_intent_classifier.dart
β β β βββ data/ # Data models & repositories
β β β β βββ models/
β β β β β βββ chat_message.dart
β β β β β βββ conversation.dart
β β β β β βββ diagnostic_result.dart
β β β β β βββ permission_state.dart
β β β β β βββ step_data.dart
β β β β β βββ user_preferences.dart
β β β β βββ repositories/
β β β β βββ conversation_repository.dart
β β β β βββ sqlite_conversation_repository.dart
β β β βββ health/ # Health SDK integration
β β β β βββ health_service.dart
β β β β βββ mock_health_service.dart
β β β β βββ real_health_service.dart
β β β βββ llm/ # LLM & AI
β β β β βββ llm_provider.dart
β β β β βββ llm_response.dart
β β β β βββ azure_openai_provider.dart
β β β β βββ mock_llm_provider.dart
β β β β βββ hybrid_intent_router.dart
β β β β βββ conversation_context.dart
β β β β βββ llm_rate_limiter.dart
β β β βββ privacy/ # Privacy & security
β β β β βββ pii_detector.dart
β β β β βββ sanitization_result.dart
β β β βββ ui/ # UI components
β β β β βββ screens/
β β β β βββ chat_screen.dart
β β β βββ utils/ # Utilities
β β β βββ platform_utils.dart
β β βββ step_sync_chatbot.dart # Public API
β βββ test/ # 150+ tests
β β βββ core/
β β βββ data/
β β βββ health/
β β βββ llm/
β β βββ privacy/
β βββ example/ # Example apps
β β βββ lib/
β β β βββ main.dart # Main example
β β β βββ llm_example.dart # LLM demo
β β βββ pubspec.yaml
β βββ pubspec.yaml
β βββ QUICK_START.md
β βββ README.md
βββ run.bat # Master batch script
βββ BATCH_SCRIPTS_GUIDE.md
βββ README.md # This file
| Component | Tests | Coverage |
|---|---|---|
| Phase 1 | ~20 | Core, Intents, Templates |
| Phase 2 | ~12 | Health Service Integration |
| Phase 3 | 15 | SQLite Persistence |
| Phase 4 | 33 | Diagnostics |
| Phase 5 | 70+ | LLM & Privacy |
| Total | 150+ | Comprehensive |
# All tests
cd packages/step_sync_chatbot
flutter test
# Specific test suite
flutter test test/core/chatbot_controller_test.dart
flutter test test/privacy/pii_detector_test.dart
flutter test test/llm/llm_rate_limiter_test.dart
# With coverage
flutter test --coverage# Quick test
packages\step_sync_chatbot\quick_test.bat
# Phase 4 tests only
packages\step_sync_chatbot\test_phase4.bat
# Full setup + test
packages\step_sync_chatbot\setup_and_test.batLocated in C:\Users\Vinamra Jain\Desktop\:
- Phase3_ConversationPersistence_Summary.md - SQLite integration, conversation history
- Phase4_EnhancedDiagnostics_Summary.md - Diagnostic system, platform detection
- Phase5_LLM_Integration_Summary.md - LLM providers, privacy, rate limiting
- QUICK_START.md - Get started in 5 minutes
- BATCH_SCRIPTS_GUIDE.md - Windows automation scripts
- packages/step_sync_chatbot/README.md - Package documentation
Generate API docs:
cd packages/step_sync_chatbot
dart doc .
# Open doc/api/index.htmlWe NEVER send to cloud LLM:
- β Exact step counts (10,000 steps)
- β Specific dates (yesterday, Monday, 2024-01-15)
- β App names (Google Fit, Samsung Health)
- β Device models (iPhone 15, Galaxy S24)
- β User names (John Smith)
- β Email addresses (john@example.com)
- β Phone numbers (123-456-7890)
- β Location data
We DO send (sanitized):
- β Generic references: "[NUMBER] steps", "recently", "fitness app", "phone"
- β Non-specific problems: "Steps not syncing", "Need help with permissions"
- PHI Sanitization: Multi-layer detection and removal
- Critical PII Blocking: Emails, phones, names block sending entirely
- Azure OpenAI BAA: Business Associate Agreement available
- Audit Logging: All LLM calls tracked (optional)
- Data Encryption: At rest and in transit
- User Control: Delete data, export data, disable features
// β
GOOD: Secure API key storage
final provider = AzureOpenAIProvider(
apiKey: await SecureStorage.getApiKey(),
endpoint: await SecureStorage.getEndpoint(),
);
// β BAD: Hardcoded secrets
final provider = AzureOpenAIProvider(
apiKey: 'sk-1234567890...', // NEVER DO THIS!
);| Metric | Cost |
|---|---|
| Input tokens | $0.150 per 1M |
| Output tokens | $0.600 per 1M |
| Typical query | $0.001-0.005 |
| Average | $0.0002 |
| Daily Users | LLM Queries (5%) | Monthly Cost |
|---|---|---|
| 1,000 | 150/day | $9 |
| 10,000 | 1,500/day | $90 |
| 100,000 | 15,000/day | $900 |
- β Rate limiting: 50 calls/user/hour
- β Global caps: 100 calls/hour
- β Budget enforcement: $10/hour max
- β Hybrid routing: 80% free (rule-based)
- β Context pruning: Max 10 messages
- Flutter 3.10+
- Dart 3.0+
- Android Studio / VS Code
- iOS development (macOS only)
# Clone repository
git clone <repository-url>
cd ChatBot_StepSync
# Install dependencies
cd packages/step_sync_chatbot
flutter pub get
# Generate code (Freezed models)
flutter pub run build_runner build --delete-conflicting-outputs
# Run tests
flutter test
# Run example
cd example
flutter run# Master menu
run.bat
# Full setup
packages\step_sync_chatbot\setup_and_test.bat
# Clean rebuild
packages\step_sync_chatbot\clean_and_rebuild.batfinal config = ChatBotConfig(
userId: 'user123',
theme: ChatBotTheme(
primaryColor: Colors.blue,
userMessageColor: Colors.blue[100],
botMessageColor: Colors.grey[200],
backgroundColor: Colors.white,
),
);// Use Azure OpenAI
final azureProvider = AzureOpenAIProvider(
endpoint: 'your-endpoint.openai.azure.com',
apiKey: 'your-api-key',
deploymentName: 'gpt-4o-mini',
maxTokens: 500,
temperature: 0.7,
);
// Or use Mock LLM for development
final mockProvider = MockLLMProvider(
simulatedDelayMs: 800,
);
// Configure router
final router = HybridIntentRouter(llmProvider: azureProvider);// Add custom intents
enum UserIntent {
// ... existing intents
customIntent,
}
// Add custom templates
class ConversationTemplates {
static const templates = {
UserIntent.customIntent: 'Your custom response here',
};
}- Configure Azure OpenAI with HIPAA BAA
- Set up secure API key storage
- Enable conversation persistence
- Configure rate limiting
- Set up monitoring and alerting
- Test on iOS and Android devices
- Verify PHI sanitization
- Review privacy policy
- Run full test suite
- Performance testing
- Security audit
// Development
final devConfig = ChatBotConfig.development(
userId: userId,
useMockService: true,
enablePersistence: false,
);
// Production
final prodConfig = ChatBotConfig.production(
userId: userId,
healthService: RealHealthService(),
conversationRepository: SQLiteConversationRepository(),
llmProvider: AzureOpenAIProvider(...),
enablePersistence: true,
);// LLM usage statistics
final stats = rateLimiter.getStats();
print('Calls: ${stats.callsInLastHour}');
print('Cost: \$${stats.totalCostUSD.toStringAsFixed(4)}');
print('Avg response time: ${stats.averageResponseTimeMs}ms');
// User-specific stats
final userStats = rateLimiter.getUserStats(userId);
print('User calls: ${userStats.callsInLastHour}');
print('Remaining: ${userStats.remainingCallsThisHour}');
// Conversation statistics
final convStats = await repository.getStats(userId);
print('Total conversations: ${convStats.totalConversations}');
print('Total messages: ${convStats.totalMessages}');final router = HybridIntentRouter(...);
final result = await router.route(userInput);
// Track which strategy was used
switch (result.strategyUsed) {
case RoutingStrategy.ruleBased:
analytics.logEvent('rule_based_classification');
case RoutingStrategy.cloudLLM:
analytics.logEvent('llm_classification', {
'cost': result.llmResponse?.estimatedCost,
'tokens': result.llmResponse?.totalTokens,
});
}- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Make your changes
- Write/update tests
- Run tests (
flutter test) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
- Follow Effective Dart guidelines
- Use
flutter format .before committing - Add documentation comments for public APIs
- Write tests for new features
- Update README if adding new features
- Maintain 80%+ test coverage
- Write unit tests for business logic
- Write integration tests for UI flows
- Test privacy sanitization thoroughly
- Test error handling and edge cases
Issue: Tests failing after setup
# Solution: Clean and rebuild
flutter clean
flutter pub get
flutter pub run build_runner build --delete-conflicting-outputs
flutter testIssue: "Flutter not found" in batch scripts
# Solution: Add Flutter to PATH
# Windows: System Properties β Environment Variables β PATH
# Add: C:\flutter\bin (or your Flutter installation path)Issue: Health Connect not working on Android
# Solution: Check Android version
# Android 14+: Built-in
# Android 9-13: Install Health Connect from Play Store
# Android 8-: Not supportedIssue: LLM responses not working
// Solution: Check configuration
final provider = AzureOpenAIProvider(
endpoint: 'https://...', // Must be HTTPS
apiKey: 'valid-key', // Must be valid
deploymentName: 'gpt-4o-mini', // Must exist
);
// Verify availability
final available = await provider.isAvailable();
print('Provider available: $available');// Enable verbose logging
final config = ChatBotConfig(
debugMode: true, // Prints detailed logs
);
// Check conversation context
print(context.getSummary());
// Check sanitization
final result = detector.sanitize(input);
print('Original: ${result.originalText}');
print('Sanitized: ${result.sanitizedText}');
print('Safe: ${result.isSafe}');
print('Entities: ${result.detectedEntities}');This project is licensed under the MIT License - see the LICENSE file for details.
- Flutter Team - Amazing framework
- Riverpod - State management
- Freezed - Code generation
- Azure OpenAI - LLM provider
- Health Sync SDK - Health data integration
- DistilBERT model integration
- TensorFlow Lite conversion
- On-device intent classification
- Offline capability
- A/B testing infrastructure
- Voice input support
- Multi-language support
- Advanced analytics dashboard
- Webhook integrations
- Custom action handlers
- Real-time collaboration
- Admin dashboard
- Total Code: ~15,000 lines
- Total Tests: 150+
- Test Coverage: 85%+
- Packages: 1 main package
- Dependencies: 12 core dependencies
- Platforms: iOS, Android, Web, Desktop (Flutter support)
- Development Time: 5 phases
- Documentation: 3 comprehensive phase summaries
Made with β€οΈ HCL Healthcare Product Team
Version: 0.5.0 Last Updated: January 12, 2026 Status: Production Ready β