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.
90 lines
2.3 KiB
90 lines
2.3 KiB
import 'dart:convert';
|
|
|
|
import 'package:get_storage/get_storage.dart';
|
|
import 'package:http/http.dart' as http;
|
|
|
|
import '../../core/utils/logger.dart';
|
|
import 'ai_service.dart';
|
|
|
|
class DeapsoundAIService implements AiService {
|
|
late final String apiKey;
|
|
|
|
DeapsoundAIService() {
|
|
final GetStorage storage = GetStorage();
|
|
apiKey = storage.read('logintoken');
|
|
}
|
|
|
|
@override
|
|
Future<String> sendMessage({
|
|
required List<Map<String, String>> messages,
|
|
required String systemPrompt,
|
|
}) async {
|
|
return '';
|
|
}
|
|
|
|
@override
|
|
Stream<String> sendMessageStream({
|
|
required List<Map<String, String>> messages,
|
|
required String systemPrompt,
|
|
}) async* {
|
|
final client = http.Client();
|
|
final url = Uri.parse('https://www.deapsound.com/ai/funcchat');
|
|
|
|
List contextsList = [];
|
|
String msg = '';
|
|
for (var i = 0; i < messages.length; i++) {
|
|
Map item = messages[i];
|
|
if (i < messages.length - 1) {
|
|
if (item['role'] == 'user') {
|
|
contextsList.add(item['content']);
|
|
}
|
|
} else {
|
|
msg = item['content'];
|
|
}
|
|
}
|
|
|
|
final headers = {
|
|
'Content-Type': 'application/json',
|
|
'Authorization': apiKey,
|
|
};
|
|
|
|
final requestBody = {"contexts": contextsList, "msg": msg};
|
|
|
|
try {
|
|
final request = http.Request('POST', url)
|
|
..headers.addAll(headers)
|
|
..body = jsonEncode(requestBody);
|
|
final response = await client.send(request);
|
|
|
|
//流式处理响应数据
|
|
await for (final chunk in response.stream
|
|
.transform(utf8.decoder)
|
|
.transform(const LineSplitter())) {
|
|
if (chunk.isEmpty) continue;
|
|
|
|
if (chunk.startsWith('data:')) {
|
|
final jsonStr = chunk.substring(5).trim();
|
|
|
|
try {
|
|
final data = jsonDecode(jsonStr);
|
|
if (data['event'] == 'workflow_finished') {
|
|
break;
|
|
}
|
|
if (data['content'] != null) {
|
|
String content = data['content'] ?? '';
|
|
if (content.isNotEmpty) {
|
|
yield content;
|
|
}
|
|
}
|
|
} catch (e) {
|
|
Logger.error('JSON解析错误: $e');
|
|
}
|
|
}
|
|
}
|
|
} catch (e) {
|
|
Logger.error('请求异常: $e');
|
|
} finally {
|
|
client.close();
|
|
}
|
|
}
|
|
}
|
|
|