AI Chat Assistant
A lightweight, plug-and-play Flutter library that provides AI-powered chat assistance with automatic platform detection and intelligent service selection.
Features
- π Easy Integration: Add AI chat features with just a few lines of code
- π€ Smart Platform Detection: Automatically uses Gemini Nano (on-device) for Android 14+ and Gemini API (cloud) for iOS and older Android
- π¨ Fully Customizable: Customize widgets to match your app's design system
- π± Cross-Platform: Works seamlessly on iOS and Android
- π Privacy-Focused: On-device processing on Android 14+ for better privacy
- β‘ Lightweight: Minimal dependencies and optimized performance
Installation
Add this to your package's pubspec.yaml file:
dependencies:
ai_chat_assistant: ^0.1.0
Then run:
flutter pub get
Quick Start
1. Initialize the Library
import 'package:ai_chat_assistant/ai_chat_assistant.dart';
await AIChatAssistant.initialize(
apiKey: 'your-gemini-api-key',
initialHistory: [
ChatMessage(text: 'Hello', author: 'user'),
ChatMessage(text: 'Hi there!', author: 'agent'),
],
);
2. Use the Widgets
Display AI Suggestions
AISuggestionWidget(
onSuggestionTap: (suggestion) {
print('Selected: $suggestion');
},
style: SuggestionStyle(
backgroundColor: Colors.blue,
textColor: Colors.white,
),
)
Text Input with AI Integration
AITextInputWidget(
onSend: (text) async {
await AIChatAssistant.addMessage(
ChatMessage(text: text, author: 'agent'),
);
},
)
Platform Support
| Platform | AI Service | Processing |
|---|---|---|
| iOS | Gemini API | Cloud |
| Android 14+ | Gemini Nano | On-device |
| Android <14 | Gemini API | Cloud |
The library automatically detects your platform and selects the optimal AI service.
Getting Your API Key
To use the Gemini API:
- Visit Google AI Studio
- Sign in with your Google account
- Create a new API key
- Copy the key and use it in your app
Note: For Android 14+ devices, Gemini Nano runs on-device and doesn't require an API key for processing, but you still need to provide one for fallback scenarios.
Configuration Options
AIChatAssistant.initialize()
await AIChatAssistant.initialize(
apiKey: 'your-api-key', // Required: Your Gemini API key
initialHistory: [], // Required: Initial message history
autoGenerateSuggestions: true, // Optional: Auto-generate on new messages
maxHistorySize: 100, // Optional: Max messages to keep in history
);
AISuggestionWidget
AISuggestionWidget(
onSuggestionTap: (suggestion) {}, // Required: Callback when suggestion tapped
style: SuggestionStyle(...), // Optional: Custom styling
suggestionBuilder: (context, text) {}, // Optional: Custom suggestion builder
loadingWidget: CircularProgressIndicator(), // Optional: Custom loading widget
errorWidget: Text('Error'), // Optional: Custom error widget
maxSuggestions: 5, // Optional: Max suggestions to display
)
AITextInputWidget
AITextInputWidget(
onSend: (text) {}, // Required: Callback when text sent
decoration: InputDecoration(...), // Optional: Custom input decoration
textStyle: TextStyle(...), // Optional: Custom text style
sendButton: Icon(Icons.send), // Optional: Custom send button
populateFromSuggestion: true, // Optional: Auto-populate from suggestions
maxLength: 500, // Optional: Max input length
)
Example
Check out the example directory for a complete working example demonstrating:
- Basic initialization and usage
- Custom styling and theming
- Error handling
- Different configuration options
To run the example:
cd example
flutter run
Requirements
- Flutter SDK: >=3.10.0
- Dart SDK: >=3.0.0 <4.0.0
- iOS: 12.0 or higher
- Android: API 21 (Android 5.0) or higher
How It Works
- Initialization: The library detects your platform and initializes the appropriate AI service
- Message History: As messages are added, the library maintains context (last 100 messages)
- Suggestion Generation: When triggered, the library sends context to the AI service
- Display: Suggestions are displayed in the widget with customizable styling
- Selection: Users can tap suggestions to use them in their replies
Error Handling
The library handles errors gracefully:
- Network Errors: Automatic retry with exponential backoff (up to 3 attempts)
- API Errors: Clear error messages with retry options
- Fallback: Provides default suggestions when AI service fails
- Platform Issues: Automatic fallback from Gemini Nano to API if unavailable
Privacy & Security
- On-Device Processing: Android 14+ uses Gemini Nano for complete on-device processing
- HTTPS Only: All API calls use secure HTTPS connections
- No Persistence: Message history is kept in memory only, never written to disk
- API Key Security: API keys are never logged or exposed in error messages
- Clean Disposal: All data is cleared from memory when the library is disposed
Performance
- Package Size: <500KB
- Response Time: <3 seconds average for suggestion generation
- Memory: Efficient history management with automatic cleanup
- Caching: Smart caching to minimize API calls
Troubleshooting
"Invalid API Key" Error
Make sure you've obtained a valid API key from Google AI Studio.
Suggestions Not Generating
- Check your internet connection (for Gemini API)
- Verify your API key is correct
- Check the debug logs for detailed error messages
Android 14+ Not Using Gemini Nano
Gemini Nano may not be available on all Android 14+ devices. The library will automatically fall back to Gemini API.
Contributing
Contributions are welcome! Please read our contributing guidelines before submitting PRs.
License
This project is licensed under the MIT License - see the LICENSE file for details.
API Documentation
For detailed API documentation, see the inline documentation in the source code. All public classes and methods include comprehensive documentation with examples.
Key classes:
AIChatAssistant: Main entry point for the libraryAISuggestionWidget: Widget for displaying AI suggestionsAITextInputWidget: Widget for text input with AI integrationChatMessage: Data model for chat messagesSuggestionStyle: Styling configuration for suggestionsAssistantController: Advanced controller for custom integrations
Support
For issues, questions, or feature requests, please file an issue on our GitHub repository.
Changelog
See CHANGELOG.md for a list of changes in each version.
Libraries
- ai_chat_assistant
- A lightweight, plug-and-play Flutter library for AI-powered chat assistance.