提交 f21dc626 authored 作者: songchuancai's avatar songchuancai

调整聊天接口

上级 6fcbd5a6
import 'package:allen/openai_service.dart';
import 'package:allen/pallete.dart'; import 'package:allen/pallete.dart';
import 'package:animate_do/animate_do.dart'; import 'package:animate_do/animate_do.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
...@@ -9,9 +8,10 @@ import 'package:flutter/foundation.dart' show kIsWeb; ...@@ -9,9 +8,10 @@ import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:uuid/uuid.dart'; import 'package:uuid/uuid.dart';
import 'models/conversation.dart'; import 'models/conversation.dart';
import 'services/storage_service.dart'; import 'services/storage_service.dart';
import 'package:shared_preferences/shared_preferences.dart'; import 'services/chat_service.dart';
import 'models/chat_message.dart'; import 'models/chat_message.dart';
import 'models/user.dart'; import 'models/user.dart';
import 'package:shared_preferences/shared_preferences.dart';
class HomePage extends StatefulWidget { class HomePage extends StatefulWidget {
const HomePage({super.key}); const HomePage({super.key});
...@@ -37,6 +37,7 @@ class _HomePageState extends State<HomePage> { ...@@ -37,6 +37,7 @@ class _HomePageState extends State<HomePage> {
bool _isListeningPressed = false; bool _isListeningPressed = false;
String _currentVoiceText = ''; String _currentVoiceText = '';
late StorageService _storageService; late StorageService _storageService;
late SharedPreferences _prefs;
late Conversation _currentConversation; late Conversation _currentConversation;
List<Conversation> _conversations = []; List<Conversation> _conversations = [];
...@@ -49,8 +50,8 @@ class _HomePageState extends State<HomePage> { ...@@ -49,8 +50,8 @@ class _HomePageState extends State<HomePage> {
} }
Future<void> _initializeStorage() async { Future<void> _initializeStorage() async {
final prefs = await SharedPreferences.getInstance(); _prefs = await SharedPreferences.getInstance();
_storageService = StorageService(prefs); _storageService = StorageService(_prefs);
_conversations = await _storageService.getConversations(); _conversations = await _storageService.getConversations();
if (_conversations.isEmpty) { if (_conversations.isEmpty) {
_createNewConversation(); _createNewConversation();
...@@ -120,6 +121,10 @@ class _HomePageState extends State<HomePage> { ...@@ -120,6 +121,10 @@ class _HomePageState extends State<HomePage> {
Future<void> systemSpeak(String content) async { Future<void> systemSpeak(String content) async {
try { try {
if (kIsWeb) { if (kIsWeb) {
// 设置语速
await flutterTts.setSpeechRate(3);
// 音调
await flutterTts.setPitch(0.8);
await flutterTts.speak(content); await flutterTts.speak(content);
} else { } else {
await flutterTts.setSharedInstance(true); await flutterTts.setSharedInstance(true);
......
import 'dart:convert';
import 'package:http/http.dart' as http;
class OpenAIService {
final String baseUrl =
'https://portal.apps.iytcloud.com/console/api/openapi/chat';
final String apiKey = 'sk-VEug2XmXEmHyFLtSbRBagBgrwMVhCXks';
final String appKey = 'app-UtEKZmmxId1HIjQP';
String? conversationId;
Stream<String> chatGPTAPI(String message) async* {
final client = http.Client();
var buffer = StringBuffer();
try {
final request = http.Request('POST', Uri.parse(baseUrl));
request.headers.addAll({
'Content-Type': 'application/json',
'Authorization': 'Bearer $apiKey',
});
Map<String, dynamic> requestBody = {
'app_key': appKey,
'query': message,
'stream': true,
};
if (conversationId != null) {
requestBody['conversation_id'] = conversationId as String;
}
request.body = jsonEncode(requestBody);
final streamedResponse = await client.send(request);
if (streamedResponse.statusCode == 200) {
DateTime startTime = DateTime.now();
// 直接处理字节流
await for (var bytes in streamedResponse.stream) {
if (DateTime.now().difference(startTime).inMinutes >= 2) {
throw Exception('请求超时,请稍后重试');
}
// 将字节转换为字符串并添加到缓冲区
String chunk = utf8.decode(bytes);
buffer.write(chunk);
// 处理缓冲区中的每一行
while (buffer.toString().contains('\n')) {
int newlineIndex = buffer.toString().indexOf('\n');
String line = buffer.toString().substring(0, newlineIndex).trim();
buffer =
StringBuffer(buffer.toString().substring(newlineIndex + 1));
if (line.startsWith('data: ')) {
try {
final jsonStr = line.substring(6);
final Map<String, dynamic> data = jsonDecode(jsonStr);
if (data['conversation_id'] != null) {
conversationId = data['conversation_id'] as String;
}
if (data['event'] == 'message' && data['answer'] != null) {
yield data['answer'] as String;
} else if (data['event'] == 'message_end') {
return;
}
} catch (e) {
print('JSON解析错误: $e');
continue;
}
}
}
}
} else {
throw Exception('请求失败,状态码: ${streamedResponse.statusCode}');
}
} catch (e) {
throw Exception(e.toString());
} finally {
client.close();
}
}
void clearConversation() {
conversationId = null;
}
}
import 'dart:convert'; import 'dart:convert';
import 'package:http/http.dart' as http; import 'package:http/http.dart' as http;
class ChatService { class OpenAIService {
static const String baseUrl = final String baseUrl =
'https://portal.apps.iytcloud.com/console/api/openapi/chat'; 'https://knowledge-web.apps.iytcloud.com/console/api/openapi/chat';
final String apiKey = 'sk-OVjS7VE9mT68Uvg7kSFoMnbU6EU836FO';
Stream<String> streamChat(String query) async* { final String appKey = 'app-FRP2s2wSx01rsE67';
final response = await http.post( String? conversationId;
Uri.parse(baseUrl),
headers: { Stream<String> chatGPTAPI(String message) async* {
'Accept': '*/*', final client = http.Client();
'Accept-Language': 'zh-CN,zh;q=0.9', var buffer = StringBuffer();
'Authorization': 'Bearer sk-VEug2XmXEmHyFLtSbRBagBgrwMVhCXks',
'Content-Type': 'application/json; charset=utf-8', try {
}, final request = http.Request('POST', Uri.parse(baseUrl));
body: jsonEncode({ request.headers.addAll({
'app_key': 'app-UtEKZmmxId1HIjQP', 'Content-Type': 'application/json',
'query': query, 'Authorization': 'Bearer $apiKey',
});
Map<String, dynamic> requestBody = {
'app_key': appKey,
'query': message,
'stream': true, 'stream': true,
'conversation_id': 'f2a71524-53cd-4cd8-99be-abb6598b52db', };
}),
); if (conversationId != null) {
requestBody['conversation_id'] = conversationId as String;
}
request.body = jsonEncode(requestBody);
final streamedResponse = await client.send(request);
if (streamedResponse.statusCode == 200) {
DateTime startTime = DateTime.now();
// 直接处理字节流
await for (var bytes in streamedResponse.stream) {
if (DateTime.now().difference(startTime).inMinutes >= 2) {
throw Exception('请求超时,请稍后重试');
}
final stream = response.body.split('\n'); // 将字节转换为字符串并添加到缓冲区
String chunk = utf8.decode(bytes);
buffer.write(chunk);
// 处理缓冲区中的每一行
while (buffer.toString().contains('\n')) {
int newlineIndex = buffer.toString().indexOf('\n');
String line = buffer.toString().substring(0, newlineIndex).trim();
buffer =
StringBuffer(buffer.toString().substring(newlineIndex + 1));
for (var line in stream) {
if (line.startsWith('data: ')) { if (line.startsWith('data: ')) {
final jsonStr = line.substring(6);
if (jsonStr.isNotEmpty) {
try { try {
final data = jsonDecode(jsonStr); final jsonStr = line.substring(6);
final Map<String, dynamic> data = jsonDecode(jsonStr);
if (data['conversation_id'] != null) {
conversationId = data['conversation_id'] as String;
}
if (data['event'] == 'message' && data['answer'] != null) { if (data['event'] == 'message' && data['answer'] != null) {
yield data['answer']; yield data['answer'] as String;
} else if (data['event'] == 'message_end') {
return;
} }
} catch (e) { } catch (e) {
print('解析错误: $e'); print('JSON解析错误: $e');
continue;
} }
} }
} }
} }
} else {
throw Exception('请求失败,状态码: ${streamedResponse.statusCode}');
}
} catch (e) {
throw Exception(e.toString());
} finally {
client.close();
}
}
void clearConversation() {
conversationId = null;
} }
} }
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论