ai_multibridge 0.0.1
ai_multibridge: ^0.0.1 copied to clipboard
A Flutter package that provides a unified interface to multiple AI providers with automatic fallback support.
AI Multi-Bridge ๐ #
A Flutter package that provides a unified interface to multiple AI providers with automatic fallback support. Built by Shalin Shah to make AI integration simple, secure, and reliable for developers of all levels.
๐จโ๐ป About the Author #
Shalin Shah is a passionate Flutter developer and AI enthusiast who believes in making technology accessible to everyone. With experience in mobile development and AI integration, Shalin created this package to solve the common challenges developers face when integrating multiple AI services.
Connect with Shalin:
- ๐ง Email: 2002shalin@gmail.com
- ๐ GitHub: Shalin-Shah-2002
- ๐ผ LinkedIn: Shalin Shah
๐ค Why I Built This #
The Problem #
When integrating AI into applications, developers often face several challenges:
- Vendor Lock-in: Being tied to a single AI provider
- Reliability Issues: What happens when your primary AI service is down?
- Rate Limiting: Hitting API limits and having no backup
- Complex Integration: Different APIs have different formats and requirements
- Security Concerns: Managing multiple API keys securely
- Beginner Friendly: AI integration can be overwhelming for new developers
The Solution #
AI Multi-Bridge provides:
- ๐ Automatic Fallback: If one provider fails, automatically try the next
- ๐ Secure API Management: Centralized configuration with best practices
- ๐ฏ Beginner Friendly: Simple API that works out of the box
- ๐ง Flexible: Support for multiple providers with easy customization
- ๐ Production Ready: Built with reliability and error handling in mind
โจ Features #
- Multiple AI Providers: Support for Gemini, OpenAI, and HuggingFace
- Automatic Fallback: Seamless switching between providers when one fails
- Secure Configuration: Best practices for API key management
- Response Parsing: Clean, parsed responses from any provider
- Error Handling: Graceful failure handling with detailed error messages
- Logging Support: Built-in logging for debugging and monitoring
- Beginner Friendly: Simple API that's easy to understand and use
๐ Quick Start #
1. Add the Package #
Add ai_multibridge to your pubspec.yaml:
dependencies:
ai_multibridge: ^1.0.0
2. Basic Usage #
import 'package:ai_multibridge/ai_multibridge.dart';
void main() async {
// Configure your AI providers
final config = AIMultiBridgeConfig(
geminiKey: 'your-gemini-api-key',
openAIKey: 'your-openai-api-key',
huggingFaceKey: 'your-huggingface-api-key',
fallbackOrder: ['gemini', 'openai', 'huggingface'],
);
// Create the handler
final handler = AiMultibridgeApiHandler(config: config);
// Generate AI content
try {
final response = await handler.generateText('Hello, how are you?');
print('AI Response: $response');
} catch (e) {
print('Error: $e');
}
}
๐ Getting API Keys #
๐ค Gemini (Google AI) - FREE TIER AVAILABLE #
Step-by-step guide:
-
Visit Google AI Studio
- Go to Google AI Studio
- Sign in with your Google account
-
Create API Key
- Click "Create API Key" button
- Select your Google Cloud project (or create a new one)
- Choose "Create API key in new project" for beginners
-
Copy Your Key
- Your API key will look like:
AIzaSyXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX - Important: Save this key securely - you won't be able to see it again!
- Your API key will look like:
-
Free Tier Limits
- 15 requests per minute
- 1 million tokens per day
- Perfect for development and testing
๐ง OpenAI - PAID SERVICE #
Step-by-step guide:
-
Visit OpenAI Platform
- Go to OpenAI Platform
- Sign up or log in to your OpenAI account
-
Add Payment Method
- Go to Billing
- Add a credit card or payment method
- Note: You need to add at least $5 credit to use the API
-
Create API Key
- Go to API Keys
- Click "Create new secret key"
- Give it a name (e.g., "Flutter App")
- Copy the key (starts with
sk-...)
-
Pricing (as of 2024)
- GPT-3.5-turbo: ~$0.002 per 1K tokens
- GPT-4: ~$0.03 per 1K tokens
๐ค HuggingFace - FREE & PAID OPTIONS #
Step-by-step guide:
-
Create HuggingFace Account
- Go to HuggingFace
- Sign up for a free account
-
Create API Token
- Go to Settings > Access Tokens
- Click "New token"
- IMPORTANT: Select "Write" role (not "Read")
- Give it a name (e.g., "AI Multi-Bridge")
- Click "Generate a token"
-
Copy Your Token
- Your token will look like:
hf_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx - Important: Save this token securely!
- Your token will look like:
-
Free vs Paid
- Free: Limited requests, basic models
- Paid: More requests, access to premium models
๐ฏ Which API Key Do I Need? #
For beginners, start with:
-
Gemini (Recommended first choice)
- โ Completely free
- โ Easy to set up
- โ Good quality responses
- โ No credit card required
-
HuggingFace (Second choice)
- โ Free tier available
- โ Many open-source models
- โ Good for experimentation
-
OpenAI (When you need premium quality)
- ๐ฐ Requires payment setup
- โ Highest quality responses
- โ Most reliable service
๐ก Pro Tips for API Keys #
- Start with Gemini: It's free and works great for most use cases
- Test with one provider first: Don't get all keys at once
- Use environment variables: Never hardcode keys in your app
- Monitor usage: Keep track of your API usage to avoid unexpected charges
- Rotate keys regularly: Change your API keys periodically for security
๐ก๏ธ Security Best Practices #
For Beginners: Safe API Key Management #
โ NEVER do this:
// DON'T hardcode API keys in your code
final config = AIMultiBridgeConfig(
geminiKey: 'YOUR_GEMINI_API_KEY_HERE', // EXPOSED!
);
โ DO this instead:
Option 1: Environment Variables (Recommended)
import 'dart:io';
void main() async {
final config = AIMultiBridgeConfig(
geminiKey: Platform.environment['GEMINI_API_KEY'],
openAIKey: Platform.environment['OPENAI_API_KEY'],
huggingFaceKey: Platform.environment['HF_API_KEY'],
);
}
Option 2: Secure Storage
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
class SecureConfig {
static final _storage = FlutterSecureStorage();
static Future<AIMultiBridgeConfig> getConfig() async {
return AIMultiBridgeConfig(
geminiKey: await _storage.read(key: 'gemini_key'),
openAIKey: await _storage.read(key: 'openai_key'),
huggingFaceKey: await _storage.read(key: 'hf_key'),
);
}
}
Option 3: Server-Side Proxy (Most Secure)
// Call your own backend API instead of AI providers directly
final response = await http.post(
Uri.parse('https://your-backend.com/api/ai/generate'),
headers: {'Authorization': 'Bearer $userToken'},
body: jsonEncode({'prompt': userPrompt}),
);
๐ Advanced Usage #
Custom Fallback Order #
final config = AIMultiBridgeConfig(
geminiKey: 'your-key',
openAIKey: 'your-key',
huggingFaceKey: 'your-key',
fallbackOrder: ['openai', 'gemini', 'huggingface'], // Custom order
);
Custom Model URLs #
final config = AIMultiBridgeConfig(
geminiKey: 'your-key',
openAIKey: 'your-key',
huggingFaceKey: 'your-key',
// Use custom models
geminiUrl: 'https://generativelanguage.googleapis.com/v1beta/models/gemini-pro',
openAIUrl: 'https://api.openai.com/v1/chat/completions',
huggingFaceUrl: 'https://router.huggingface.co/v1',
);
Response Parsing #
final rawResponse = await handler.generateText('Hello');
final parsedResponse = AiMultibridgeResponseParser.parseResponse('gemini', rawResponse);
print('Clean text: $parsedResponse');
Logging #
// Enable logging for debugging
AiMultibridgeLogger.info('Starting AI request');
AiMultibridgeLogger.error('Provider failed', error);
๐ How Fallback Works #
- Primary Provider: Tries the first provider in your fallback order
- Automatic Switch: If it fails, automatically tries the next provider
- Graceful Failure: If all providers fail, throws a clear error message
- Transparent: Your app doesn't need to know which provider responded
// With this configuration:
fallbackOrder: ['gemini', 'openai', 'huggingface']
// The flow is:
// 1. Try Gemini โ Success โ
(Use response)
// 2. Try Gemini โ Fail โ โ Try OpenAI โ Success โ
(Use response)
// 3. Try Gemini โ Fail โ โ Try OpenAI โ Fail โ โ Try HuggingFace โ Success โ
// 4. All fail โ Throw exception with helpful message
๐งช Testing #
The package includes comprehensive tests and examples:
# Run tests
flutter test
# Run example
dart run example/test_example.dart
๐ Requirements #
- Dart >=3.0.0
- Flutter >=3.0.0
๐ค Contributing #
Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.
Development Setup #
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
๐ License #
This project is licensed under the MIT License - see the LICENSE file for details.
๐ Acknowledgments #
- Google AI for Gemini API
- OpenAI for their powerful language models
- HuggingFace for democratizing AI access
- Flutter Team for the amazing framework
- Community for feedback and contributions
๐ Support #
If you encounter any issues or have questions:
- Check the Issues page
- Create a new issue with detailed information
- Contact Shalin at 2002shalin@gmail.com
๐ฏ Roadmap #
- โ Support for more AI providers (Claude, Cohere, etc.)
- โ Streaming responses
- โ Custom retry logic
- โ Response caching
- โ Usage analytics
- โ Web support
Made with โค๏ธ by Shalin Shah
Empowering developers to build amazing AI-powered applications with confidence and ease.