You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
95 lines
2.8 KiB
95 lines
2.8 KiB
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<Message> _messageHistory = [];
|
|
String _pendingTtsText = '';
|
|
static const int _minTtsLength = 20;
|
|
bool _isProcessing = false;
|
|
|
|
BackgroundAgentService()
|
|
: _aiService = VolcanoAIService(),
|
|
_ttsService = Get.find<VolcanoTtsService>();
|
|
|
|
Future<void> 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<Message> get messageHistory => List.unmodifiable(_messageHistory);
|
|
|
|
void clearHistory() {
|
|
_messageHistory.clear();
|
|
}
|
|
}
|