pocket_brain 1.0.1
pocket_brain: ^1.0.1 copied to clipboard
An Offline RAG (Retrieval-Augmented Generation) AI Library for Flutter. Embeds knowledge base from CSV and performs semantic search on-device.
example/lib/main.dart
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:file_picker/file_picker.dart';
import 'package:dash_chat_2/dash_chat_2.dart';
// Import the PocketBrain library
import 'package:pocket_brain/pocket_brain.dart';
void main() {
runApp(const MaterialApp(
home: PocketBrainExample(),
debugShowCheckedModeBanner: false,
));
}
class PocketBrainExample extends StatefulWidget {
const PocketBrainExample({super.key});
@override
State<PocketBrainExample> createState() => _PocketBrainExampleState();
}
class _PocketBrainExampleState extends State<PocketBrainExample> {
// Instance of the PocketBrain library
final PocketBrain _brain = PocketBrain();
// Chat UI Identities
final ChatUser _user = ChatUser(id: '1', firstName: 'Me');
final ChatUser _bot = ChatUser(
id: '2',
firstName: 'PocketBrain',
profileImage: "https://robohash.org/brain");
List<ChatMessage> messages = [];
bool _isReady = false;
@override
void initState() {
super.initState();
// 1. Initialize the Brain (Loads AI Model & Database into memory)
_initBrain();
}
Future<void> _initBrain() async {
// This method prepares the TFLite model and ObjectBox store
await _brain.init();
setState(() {
_isReady = true;
// Add a welcome message once initialized
messages.add(ChatMessage(
user: _bot,
createdAt: DateTime.now(),
text:
"Hello! I am ready to answer questions based on your knowledge base.",
));
});
}
// 2. Knowledge Acquisition Feature (Import CSV)
// or you can directly add your CSV file into your project assets and load it from there.
Future<void> _pickCsv() async {
// Pick a CSV file from the device storage
FilePickerResult? result = await FilePicker.platform.pickFiles(
type: FileType.custom,
allowedExtensions: ['csv'],
);
if (result != null) {
File file = File(result.files.single.path!);
// Import the CSV.
// NOTE: This function automatically wipes old data and learns the new facts.
int count = await _brain.importFromCsv(file);
if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text("Successfully learned $count new facts!")),
);
}
}
// 3. Q&A Feature (Semantic Search Inference)
void _onSend(ChatMessage msg) {
// Immediately show user's message in the UI
setState(() => messages.insert(0, msg));
// IMPORTANT
// Core Logic: Ask the Brain
// This performs a vector similarity search in the offline database
String? answer = _brain.ask(msg.text);
// Prepare the bot's response
final botReply = ChatMessage(
user: _bot,
createdAt: DateTime.now(),
text: answer ?? "Sorry, I couldn't find an answer in your data.",
);
// Simulate a small "thinking" delay for better UX
Future.delayed(const Duration(milliseconds: 300), () {
setState(() => messages.insert(0, botReply));
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("Pocket Brain Demo"),
actions: [
IconButton(
icon: const Icon(Icons.upload_file),
onPressed: _isReady ? _pickCsv : null,
tooltip: "Upload Knowledge Base (.csv)",
)
],
),
body: DashChat(
currentUser: _user,
onSend: _onSend,
messages: messages,
inputOptions: InputOptions(
// Show different placeholder text based on initialization status
inputDecoration: InputDecoration(
hintText: _isReady
? "Ask me anything based on your data..."
: "Loading AI Model and Database...",
),
textCapitalization: TextCapitalization.sentences,
),
),
);
}
}