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:

  1. Visit Google AI Studio
  2. Sign in with your Google account
  3. Create a new API key
  4. 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

  1. Initialization: The library detects your platform and initializes the appropriate AI service
  2. Message History: As messages are added, the library maintains context (last 100 messages)
  3. Suggestion Generation: When triggered, the library sends context to the AI service
  4. Display: Suggestions are displayed in the widget with customizable styling
  5. 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

  1. Check your internet connection (for Gemini API)
  2. Verify your API key is correct
  3. 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 library
  • AISuggestionWidget: Widget for displaying AI suggestions
  • AITextInputWidget: Widget for text input with AI integration
  • ChatMessage: Data model for chat messages
  • SuggestionStyle: Styling configuration for suggestions
  • AssistantController: 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.