import 'package:get/get.dart'; import 'dart:async'; import 'volcano_ai_service.dart'; import 'volcano_tts_service.dart'; import '../../modules/chat/models/message_model.dart'; class BackgroundAgentService extends GetxService { static BackgroundAgentService get to => Get.find(); final VolcanoAIService _aiService; final VolcanoTtsService _ttsService; final List _messageHistory = []; String _pendingTtsText = ''; static const int _minTtsLength = 20; bool _isProcessing = false; BackgroundAgentService() : _aiService = VolcanoAIService(), _ttsService = Get.find(); Future handleAgentInteraction(String systemPrompt) async { if (_isProcessing) return; _isProcessing = true; try { // 构建用于生成回应的消息列表 final messages = [ {'role': 'system', 'content': systemPrompt}, {'role': 'user', 'content': '请用一句简短的话回应我,要体现你的特点,不要超过12个字。'}, ]; String fullResponse = ''; await for (final chunk in _aiService.sendMessageStream( messages: messages, systemPrompt: systemPrompt, )) { fullResponse += chunk; // 累积文本并处理TTS _pendingTtsText += chunk; if (_ttsService.isEnabled.value) { if (_pendingTtsText.length >= _minTtsLength) { int lastSentenceEnd = _findLastSentenceEnd(_pendingTtsText); if (lastSentenceEnd > 0) { String textToSpeak = _pendingTtsText.substring(0, lastSentenceEnd + 1); await _ttsService.speak(textToSpeak); _pendingTtsText = _pendingTtsText.substring(lastSentenceEnd + 1); } } } } // 处理剩余的文本 if (_ttsService.isEnabled.value && _pendingTtsText.isNotEmpty) { await _ttsService.speak(_pendingTtsText); } _pendingTtsText = ''; // 保存对话历史 _messageHistory.add(Message( role: 'assistant', content: fullResponse, timestamp: DateTime.now(), )); // 限制历史记录长度 if (_messageHistory.length > 10) { _messageHistory.removeAt(0); } } catch (e) { print('Background agent interaction failed: $e'); } finally { _isProcessing = false; } } int _findLastSentenceEnd(String text) { final sentenceEnds = [ text.lastIndexOf('。'), text.lastIndexOf('!'), text.lastIndexOf('?'), text.lastIndexOf('.'), text.lastIndexOf('!'), text.lastIndexOf('?'), ]; return sentenceEnds.reduce((max, pos) => pos > max ? pos : max); } List get messageHistory => List.unmodifiable(_messageHistory); void clearHistory() { _messageHistory.clear(); } }