|
| 1 | +import 'package:flutter/foundation.dart'; |
| 2 | +import 'package:flutter_dotenv/flutter_dotenv.dart'; |
| 3 | +import 'package:google_generative_ai/google_generative_ai.dart'; |
| 4 | +import 'package:supabase_flutter/supabase_flutter.dart'; |
| 5 | + |
| 6 | +class ChatBotAssistantService { |
| 7 | + final String _apiKey = (dotenv.env['GEMINI_API_KEY'] ?? '').trim(); |
| 8 | + GenerativeModel? _model; |
| 9 | + ChatSession? _chatSession; |
| 10 | + |
| 11 | + ChatBotAssistantService() { |
| 12 | + if (_apiKey.isEmpty) { |
| 13 | + debugPrint("Forget to set GEMINI_API_KEY in .env file"); |
| 14 | + return; |
| 15 | + } |
| 16 | + |
| 17 | + _model = GenerativeModel( |
| 18 | + apiKey: _apiKey, |
| 19 | + model: 'gemini-2.5-flash', |
| 20 | + tools: [ |
| 21 | + Tool( |
| 22 | + functionDeclarations: [ |
| 23 | + FunctionDeclaration( |
| 24 | + 'create_task_full', |
| 25 | + 'Tạo một công việc mới. Hãy tự động trích xuất tên công việc, suy luận độ ưu tiên (1-Thấp, 2-Trung bình, 3-Cao) và các thẻ (tags) dựa trên câu nói của người dùng.', |
| 26 | + Schema( |
| 27 | + SchemaType.object, |
| 28 | + properties: { |
| 29 | + 'title': Schema( |
| 30 | + SchemaType.string, |
| 31 | + description: 'Tên công việc cần làm', |
| 32 | + ), |
| 33 | + 'priority': Schema( |
| 34 | + SchemaType.integer, |
| 35 | + description: |
| 36 | + 'Độ ưu tiên: 1 (Thấp), 2 (Trung bình), 3 (Cao). Nếu người dùng không nói rõ, mặc định là 1.', |
| 37 | + ), |
| 38 | + 'tags': Schema( |
| 39 | + SchemaType.array, |
| 40 | + items: Schema(SchemaType.string), |
| 41 | + description: |
| 42 | + 'Danh sách các thẻ phân loại (ví dụ: ["Học tập", "Gấp", "Backend"]). Gửi mảng rỗng [] nếu không có.', |
| 43 | + ), |
| 44 | + }, |
| 45 | + requiredProperties: ['title', 'priority', 'tags'], |
| 46 | + ), |
| 47 | + ), |
| 48 | + ], |
| 49 | + ), |
| 50 | + ], |
| 51 | + systemInstruction: Content.system( |
| 52 | + 'Bạn là một chuyên gia quản lý thời gian và trợ lý năng suất cho ứng dụng Task Management. ' |
| 53 | + 'Nhiệm vụ của bạn là đưa ra lời khuyên ngắn gọn (dưới 100 chữ), thực tế để giúp người dùng ' |
| 54 | + 'hoàn thành công việc. Trả lời bằng tiếng Việt thân thiện, nhiệt tình. ' |
| 55 | + 'Từ chối mọi câu hỏi không liên quan đến công việc hoặc quản lý thời gian.', |
| 56 | + ), |
| 57 | + ); |
| 58 | + |
| 59 | + _chatSession = _model!.startChat(); |
| 60 | + } |
| 61 | + |
| 62 | + Future<String> sendMessage(String userMessage) async { |
| 63 | + if (_chatSession == null) { |
| 64 | + return 'Chatbot chưa được cấu hình API key. Vui lòng kiểm tra file .env.'; |
| 65 | + } |
| 66 | + |
| 67 | + try { |
| 68 | + final response = await _chatSession!.sendMessage( |
| 69 | + Content.text(userMessage), |
| 70 | + ); |
| 71 | + |
| 72 | + if (response.functionCalls.isNotEmpty) { |
| 73 | + final functionCall = response.functionCalls.first; |
| 74 | + if (functionCall.name == 'create_task_full') { |
| 75 | + final args = functionCall.args; |
| 76 | + final title = args['title'] as String; |
| 77 | + final priority = (args['priority'] as num?)?.toInt() ?? 1; |
| 78 | + final rawTags = args['tags'] as List<dynamic>? ?? []; |
| 79 | + final tags = rawTags.map((e) => e.toString()).toList(); |
| 80 | + |
| 81 | + final userId = Supabase.instance.client.auth.currentUser?.id; |
| 82 | + if (userId == null) { |
| 83 | + return 'Vui lòng đăng nhập để tạo công việc.'; |
| 84 | + } |
| 85 | + |
| 86 | + final dbResponse = await Supabase.instance.client.rpc( |
| 87 | + 'create_task_full', |
| 88 | + params: { |
| 89 | + 'p_title': title, |
| 90 | + 'p_priority': priority, |
| 91 | + 'p_profile_id': userId, |
| 92 | + 'p_tag_names': tags, |
| 93 | + }, |
| 94 | + ); |
| 95 | + |
| 96 | + final isSuccess = dbResponse['success'] == true; |
| 97 | + final functionResponse = await _chatSession!.sendMessage( |
| 98 | + Content.functionResponse('create_task_full', { |
| 99 | + 'status': isSuccess ? 'Thành công' : 'Thất bại', |
| 100 | + }), |
| 101 | + ); |
| 102 | + return functionResponse.text ?? 'Đã xử lý xong yêu cầu của bạn!'; |
| 103 | + } |
| 104 | + } |
| 105 | + return response.text ?? 'Xin lỗi, trợ lý đang bận xíu. Thử lại sau nhé!'; |
| 106 | + } catch (e) { |
| 107 | + final errorString = e.toString(); |
| 108 | + if (errorString.contains('503')) { |
| 109 | + return 'Bạn đợi vài phút rồi chat lại nhé!'; |
| 110 | + } else if (errorString.contains('429')) { |
| 111 | + return 'Bạn chat nhanh quá! Vui lòng chờ chút'; |
| 112 | + } |
| 113 | + return 'Lỗi kết nối AI: $e'; |
| 114 | + } |
| 115 | + } |
| 116 | +} |
0 commit comments