|
- import 'dart:convert';
- import 'dart:io';
-
- import 'package:dio/dio.dart';
- import 'package:logger/logger.dart';
- import 'package:http/http.dart' as http;
-
- class ApiClient {
- static final _client = Dio();
-
- static String _baseUrl = 'https://www.aitoyyun.com';
-
- static get(
- {String baseUrl = 'https://www.aitoyyun.com',
- required String url,
- required Map<String, dynamic> param,
- required Function(Map<String, dynamic>) onSuccess,
- required Function(String) onFailed}) async {
- _baseUrl = baseUrl;
- try {
- Response response = await _client.get(
- _baseUrl + url.trim(),
- options: Options(
- headers: {"Accept": 'application/json'},
- sendTimeout: const Duration(seconds: 10),
- receiveTimeout: const Duration(seconds: 10)),
- queryParameters: param,
- );
- final jsonData = response.data;
- _progressData(
- jsonData: jsonData, onSuccess: onSuccess, onFailed: onFailed);
- } on DioException catch (e) {
- _progressError(response: e.response, onFailed: onFailed);
- }
- }
-
- static post(
- {required String url,
- String? token,
- required Map<String, dynamic> param,
- required Function(Map<String, dynamic>) onSuccess,
- required Function(String) onFailed}) async {
- try {
- // Logger().i('---url: ${_baseUrl + url.trim()}---param: $param-----token: $token');
- Response response = await _client.post(
- _baseUrl + url.trim(),
- options: Options(
- headers: {'Authorization': token ?? ''},
- sendTimeout: const Duration(seconds: 10),
- receiveTimeout: const Duration(seconds: 10)),
- queryParameters: param,
- data: param,
- );
- final jsonData = response.data;
- _progressData(
- jsonData: jsonData, onSuccess: onSuccess, onFailed: onFailed);
- } on DioException catch (e) {
- _progressError(response: e.response, onFailed: onFailed);
- }
- }
-
- static put(
- {required String url,
- required Map<String, dynamic> param,
- required Function(Map<String, dynamic>) onSuccess,
- required Function(String) onFailed}) async {
- try {
- Response response = await _client.put(
- _baseUrl + url.trim(),
- options: Options(
- headers: {"Accept": 'application/json'},
- sendTimeout: const Duration(seconds: 10),
- receiveTimeout: const Duration(seconds: 10)),
- queryParameters: param,
- data: param,
- );
- final jsonData = response.data;
- _progressData(
- jsonData: jsonData, onSuccess: onSuccess, onFailed: onFailed);
- } on DioException catch (e) {
- _progressError(response: e.response, onFailed: onFailed);
- }
- }
-
- static delete(
- {required String url,
- required Map<String, dynamic> param,
- required Function(Map<String, dynamic>) onSuccess,
- required Function(String) onFailed}) async {
- try {
- Response response = await _client.delete(
- _baseUrl + url.trim(),
- options: Options(
- headers: {"Accept": 'application/json'},
- sendTimeout: const Duration(seconds: 10),
- receiveTimeout: const Duration(seconds: 10)),
- queryParameters: param,
- data: param,
- );
- final jsonData = response.data;
- _progressData(
- jsonData: jsonData, onSuccess: onSuccess, onFailed: onFailed);
- } on DioException catch (e) {
- _progressError(response: e.response, onFailed: onFailed);
- }
- }
-
- static void _progressData(
- {required Map<String, dynamic> jsonData,
- required Function(Map<String, dynamic>) onSuccess,
- required Function(String) onFailed}) {
- // Logger().i('--_progressData------${jsonData}');
- if (jsonData['code'] == 0) {
- onSuccess(jsonData);
- } else {
- onFailed(jsonData['msg'].toString());
- }
- }
-
- static void _progressError(
- {Response? response, required Function(String) onFailed}) {
- if (response != null && response.data != null) {
- Logger().i('_progressError---------${response.data}');
- if (response.data.runtimeType == String) {
- onFailed('返回数据格式错误');
- } else {
- if (response.data['errCode'] != null) {
- final jsonData = response.data;
- onFailed(jsonData['errMsg'].toString());
- } else {
- final jsonData = response.data;
- onFailed(jsonData['state']['msg'].toString());
- }
- }
- } else {
- onFailed('请求失败');
- }
- }
-
- static final String login = '/api/home/user_sgin';
-
- static final String getPin = '/api/home/user_verification';
-
- // static final String aiChat = '/api/home/ai_chat';
-
- static final String deepseekApiKey = 'sk-3adfd188a3134e718bbf704f525aff17';
- static Stream<String> aiChat(String prompt) async* {
- final client = HttpClient();
- try {
- final request = await client
- .postUrl(Uri.parse('https://api.deepseek.com/chat/completions'));
-
- // 设置流式请求头
- request.headers
- ..set('Content-Type', 'application/json')
- ..set('Authorization', 'Bearer $deepseekApiKey')
- ..set('Accept', 'text/event-stream');
-
- // 构建请求体
- final requestBody = jsonEncode({
- 'model': 'deepseek-chat',
- 'stream': true,
- 'messages': [
- {'role': 'user', 'content': prompt}
- ]
- });
-
- // 写入请求体
- request.add(utf8.encode(requestBody));
- final response = await request.close();
-
- // 检查状态码
- if (response.statusCode != 200) {
- throw Exception('API请求失败: ${response.statusCode}');
- }
-
- // 处理流数据
- String buffer = '';
- await for (final chunk in response.transform(utf8.decoder)) {
- buffer += chunk;
-
- // 分割完整事件(假设使用SSE格式)
- while (buffer.contains('\n\n')) {
- final eventEnd = buffer.indexOf('\n\n');
- final event = buffer.substring(0, eventEnd);
- buffer = buffer.substring(eventEnd + 2);
-
- if (event.startsWith('data: ')) {
- final dataContent = event.substring(6);
- // 增加有效性检查
- if (dataContent == '[DONE]') {
- // print('流式传输结束');
- continue; // 跳过特殊结束标记
- }
- final jsonData = jsonDecode(event.substring(6));
- yield jsonData['choices'][0]['delta']['content'];
- }
- }
- }
- } finally {
- client.close();
- }
- }
-
- static final String dbAppkey = '418ec475-e2dc-4b76-8aca-842d81bc3466';
- static final String dbModelId = 'ep-20250203161136-9lrxg';
- static Stream<String> dbChat(String userMessage) async* {
- final client = http.Client();
- final url =
- Uri.parse('https://ark.cn-beijing.volces.com/api/v3/chat/completions');
-
- final headers = {
- 'Content-Type': 'application/json',
- 'Authorization': 'Bearer $dbAppkey',
- };
-
- final requestBody = {
- "model": dbModelId,
- "messages": [
- {"role": "system", "content": "你是豆包,是由字节跳动开发的 AI 人工智能助手."},
- {"role": "user", "content": userMessage}
- ],
- "stream": true,
- };
-
- 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;
-
- // 假设豆包API使用类似OpenAI的流式格式(data: {...})
- if (chunk.startsWith('data:')) {
- final jsonStr = chunk.substring(5).trim();
- if (jsonStr == '[DONE]') break; // 流结束标志
-
- try {
- final data = jsonDecode(jsonStr);
- final content = data['choices'][0]['delta']['content'] ?? '';
- if (content.isNotEmpty) {
- yield content; // 逐块返回生成的文本
- }
- } catch (e) {
- // print('JSON解析错误: $e');
- }
- // print('请求成功: $jsonStr');
- }
- }
- } catch (e) {
- print('请求异常: $e');
- }
- }
- }
|