58 lines
1.8 KiB
Dart
58 lines
1.8 KiB
Dart
// ignore_for_file: depend_on_referenced_packages
|
|
|
|
import 'dart:async';
|
|
import 'dart:io';
|
|
|
|
import 'package:didvan/services/storage/storage.dart';
|
|
import 'package:http/http.dart' as http;
|
|
import 'package:http/http.dart';
|
|
import 'package:path/path.dart' as p;
|
|
import 'package:http_parser/http_parser.dart' as parser;
|
|
|
|
class AiApiService {
|
|
static const String baseUrl = 'https://api.didvan.app/ai';
|
|
static final _client = http.Client();
|
|
|
|
static Future<http.MultipartRequest> initial(
|
|
{required final String url,
|
|
required final String message,
|
|
final int? chatId,
|
|
final File? file}) async {
|
|
final headers = {
|
|
"Authorization": "Bearer ${await StorageService.getValue(key: 'token')}",
|
|
'Content-Type': 'multipart/form-data'
|
|
};
|
|
|
|
var request = http.MultipartRequest('POST', Uri.parse(baseUrl + url))
|
|
..headers.addAll(headers);
|
|
|
|
request.fields['prompt'] = message;
|
|
if (chatId != null) {
|
|
request.fields['chatId'] = chatId.toString();
|
|
}
|
|
if (file != null) {
|
|
final length = await file.length();
|
|
String basename = p.basename(file.path);
|
|
String mediaExtension = p.extension(file.path).replaceAll('.', '');
|
|
String mediaFormat = 'image';
|
|
if (mediaExtension.contains('pdf')) {
|
|
mediaFormat = 'application';
|
|
}
|
|
request.files.add(
|
|
http.MultipartFile('file', file.readAsBytes().asStream(), length,
|
|
filename: basename,
|
|
contentType: parser.MediaType(mediaFormat, mediaExtension)),
|
|
);
|
|
}
|
|
return request;
|
|
}
|
|
|
|
static Future<ByteStream> getResponse(http.MultipartRequest request) async {
|
|
final res = _client.send(request).timeout(
|
|
const Duration(seconds: 30),
|
|
);
|
|
final http.StreamedResponse response = await res;
|
|
return response.stream;
|
|
}
|
|
}
|