controller.dart 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  1. import 'dart:async';
  2. import 'dart:convert';
  3. import 'package:electronic_assistant/base/base_controller.dart';
  4. import 'package:electronic_assistant/data/bean/agenda.dart';
  5. import 'package:electronic_assistant/data/bean/chat_item.dart';
  6. import 'package:electronic_assistant/data/bean/file_chat_item.dart';
  7. import 'package:electronic_assistant/data/bean/progressing_chat_item.dart';
  8. import 'package:electronic_assistant/data/bean/reference_chat_item.dart';
  9. import 'package:electronic_assistant/data/consts/event_report_id.dart';
  10. import 'package:electronic_assistant/data/repositories/account_repository.dart';
  11. import 'package:electronic_assistant/data/repositories/chat_repository.dart';
  12. import 'package:electronic_assistant/data/repositories/talk_repository.dart';
  13. import 'package:electronic_assistant/handler/event_handler.dart';
  14. import 'package:electronic_assistant/module/chat/start/view.dart';
  15. import 'package:electronic_assistant/module/chat/view.dart';
  16. import 'package:electronic_assistant/resource/colors.gen.dart';
  17. import 'package:electronic_assistant/resource/string.gen.dart';
  18. import 'package:electronic_assistant/utils/toast_util.dart';
  19. import 'package:flutter/material.dart';
  20. import 'package:flutter/services.dart';
  21. import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
  22. import 'package:get/get.dart';
  23. import 'package:pull_to_refresh/pull_to_refresh.dart';
  24. import 'package:uuid/uuid.dart';
  25. import '../../data/bean/stream_chat_origin_data.dart';
  26. import '../../data/bean/talks.dart';
  27. import '../../data/consts/error_code.dart';
  28. import '../../dialog/model_explain_dialog.dart';
  29. import '../../router/app_pages.dart';
  30. import '../../utils/http_handler.dart';
  31. import '../../widget/gradually_md_text.dart';
  32. class ChatController extends BaseController {
  33. final RefreshController refreshController =
  34. RefreshController(initialLoadStatus: LoadStatus.loading);
  35. final ScrollController listScrollController = ScrollController();
  36. final TextEditingController inputController = TextEditingController();
  37. final RxList chatItems = [].obs;
  38. final Rxn<TalkBean> talkInfo = Rxn<TalkBean>();
  39. final Rxn<Agenda> agenda = Rxn<Agenda>();
  40. final Rxn<String> chatAiTagId = Rxn<String>();
  41. ChatFromType? fromType;
  42. bool isConsumeElectric = false;
  43. StreamSubscription? _streamChatSubscription;
  44. ProgressingChatItem? _nowProgressingChatItem;
  45. @override
  46. void onInit() {
  47. super.onInit();
  48. loadMoreHistory();
  49. checkArguments();
  50. initReport();
  51. }
  52. @override
  53. void onReady() {
  54. super.onReady();
  55. if (accountRepository.userInfo.value?.profession == null ||
  56. accountRepository.userInfo.value?.post == null) {
  57. showStartSheet();
  58. } else {
  59. _showModelExplainDialog();
  60. }
  61. }
  62. void checkArguments() {
  63. List<dynamic> arguments = Get.arguments ?? [];
  64. if (arguments.isEmpty) {
  65. return;
  66. }
  67. if (arguments[0] is ChatFromType) {
  68. fromType = arguments[0];
  69. }
  70. if (arguments.length > 2 && arguments[2] is Agenda) {
  71. agenda.value = arguments[2];
  72. }
  73. if (arguments.length > 1 && arguments[1] is TalkBean) {
  74. talkInfo.value = arguments[1];
  75. sendInitialMessage();
  76. } else if (arguments.length > 1 && arguments[1] is String) {
  77. talkRepository
  78. .talkInfo(arguments[1])
  79. .then((response) => talkInfo.value = response.talkInfo)
  80. .then((_) => sendInitialMessage());
  81. }
  82. }
  83. void sendInitialMessage() {
  84. final talkInfo = this.talkInfo.value;
  85. if (talkInfo == null) {
  86. return;
  87. }
  88. chatItems.insert(
  89. 0,
  90. FileChatItem(talkInfo,
  91. id: const Uuid().v4(),
  92. conversationId: "",
  93. role: "user",
  94. content: "",
  95. createTime: DateTime.now().toString()));
  96. if (agenda.value != null) {
  97. _sendMessage("以这份谈话为背景,你为我执行“${agenda.value?.content}”这一事项");
  98. }
  99. }
  100. onSendClick() {
  101. if (inputController.text.isEmpty) {
  102. return;
  103. }
  104. String chatContent = inputController.text;
  105. _sendMessage(chatContent);
  106. }
  107. void onAddFileClick() {
  108. Get.toNamed(RoutePath.fileSearch)?.then((talkInfo) {
  109. if (talkInfo is TalkBean) {
  110. this.talkInfo.value = talkInfo;
  111. agenda.value = null;
  112. sendInitialMessage();
  113. }
  114. });
  115. }
  116. Future<void> loadMoreHistory() {
  117. bool isEmpty = chatItems.isEmpty;
  118. return chatRepository
  119. .chatHistory(chatItems.isEmpty ? null : chatItems.last.id)
  120. .then((value) => chatItems.addAll(value))
  121. .whenComplete(() => refreshController.loadComplete())
  122. .whenComplete(() {
  123. if (isEmpty) {
  124. for (var element in chatItems.reversed) {
  125. if (element is ChatItem && element.role == "assistant") {
  126. chatAiTagId.value = element.id;
  127. }
  128. }
  129. _scrollToBottom();
  130. }
  131. });
  132. }
  133. void showStartSheet() {
  134. if (fromType == ChatFromType.fromMain) {
  135. EventHandler.report(EventId.event_102001, params: {
  136. EventId.id: EventId.id_001,
  137. });
  138. } else if (fromType == ChatFromType.fromTalkDetail) {
  139. EventHandler.report(EventId.event_102001, params: {
  140. EventId.id: EventId.id_002,
  141. });
  142. } else if (fromType == ChatFromType.fromAnalysisBtn) {
  143. EventHandler.report(EventId.event_102001, params: {
  144. EventId.id: EventId.id_003,
  145. });
  146. }
  147. Get.bottomSheet(const ChatStartPage(),
  148. isScrollControlled: true,
  149. barrierColor: ColorName.black55,
  150. backgroundColor: ColorName.transparent)
  151. .then((result) {
  152. if (result == null || result == false) {
  153. Get.back();
  154. } else {
  155. _showModelExplainDialog();
  156. }
  157. });
  158. }
  159. void _showModelExplainDialog() {
  160. showModelExplainTipsDialog();
  161. }
  162. void _sendMessage(String chatContent) {
  163. final lastItem = chatItems.first;
  164. if ((lastItem is ProgressingChatItem) &&
  165. !(lastItem.isFinished.value || lastItem.isFailed.value)) {
  166. ToastUtil.showToast(StringName.chatReplying.tr,
  167. displayType: SmartToastType.onlyRefresh);
  168. return;
  169. }
  170. inputController.clear();
  171. chatItems.insert(0, createUserChatItem(chatContent));
  172. ProgressingChatItem progressingChatItem = ProgressingChatItem(
  173. id: const Uuid().v4(),
  174. graduallyController: GraduallyController(),
  175. conversationId: chatItems.last.conversationId,
  176. role: "assistant",
  177. content: "",
  178. createTime: DateTime.now().toString(),
  179. );
  180. chatItems.insert(0, progressingChatItem);
  181. _nowProgressingChatItem?.graduallyController.dispose();
  182. _nowProgressingChatItem = progressingChatItem;
  183. _scrollToBottom();
  184. if (talkInfo.value == null) {
  185. EventHandler.report(EventId.event_102003, params: {
  186. EventId.id: EventId.id_002,
  187. });
  188. } else {
  189. EventHandler.report(EventId.event_102003, params: {
  190. EventId.id: EventId.id_001,
  191. });
  192. }
  193. _streamChatSubscription?.cancel();
  194. chatRepository
  195. .streamChat(chatContent,
  196. talkId: talkInfo.value?.id, agendaId: agenda.value?.id)
  197. .then((stream) {
  198. progressingChatItem.setGraduallyFinishedListener();
  199. _streamChatSubscription = stream.listen((event) {
  200. try {
  201. Map<String, dynamic> json = jsonDecode(event.data);
  202. if (json.isEmpty) {
  203. return;
  204. }
  205. StreamChatOriginData data = StreamChatOriginData.fromJson(json);
  206. if (data.choices == null || data.choices!.isEmpty) {
  207. return;
  208. }
  209. Delta? delta = data.choices![0].delta;
  210. if (delta == null) {
  211. return;
  212. }
  213. isConsumeElectric = true;
  214. progressingChatItem.append(delta.content ?? "");
  215. chatAiTagId.value = progressingChatItem.id;
  216. } catch (ignore) {}
  217. }, onDone: () {
  218. progressingChatItem.setAppendDone();
  219. progressingChatItem.content =
  220. progressingChatItem.graduallyController.graduallyTxt;
  221. }, onError: (error) {
  222. progressingChatItem.isFailed.value = true;
  223. progressingChatItem.error.value = "网络错误,请检查网络连接";
  224. debugPrint("error: $error");
  225. debugPrintStack();
  226. });
  227. }).catchError((error) {
  228. progressingChatItem.isFailed.value = true;
  229. if (error is ServerErrorException) {
  230. progressingChatItem.error.value = error.message ?? "服务出错,请稍后再试";
  231. if (error.code == ErrorCode.errorCodeNoLogin) {
  232. Get.toNamed(RoutePath.login)?.then((loginSuccess) async {
  233. if (loginSuccess != null && loginSuccess) {
  234. _clearChat();
  235. await loadMoreHistory();
  236. _sendMessage(chatContent);
  237. }
  238. });
  239. } else if (error.code == ErrorCode.errorCodeNoProfession) {
  240. showStartSheet();
  241. }
  242. } else {
  243. progressingChatItem.error.value = "网络错误,请检查网络连接";
  244. debugPrint("error: $error");
  245. debugPrintStack();
  246. }
  247. });
  248. }
  249. void _clearChat() async {
  250. return chatItems.clear();
  251. }
  252. void _scrollToBottom() {
  253. Future.delayed(const Duration(milliseconds: 300), () {
  254. listScrollController.animateTo(
  255. 0,
  256. duration: const Duration(milliseconds: 300),
  257. curve: Curves.easeOut,
  258. );
  259. });
  260. }
  261. createUserChatItem(String chatContent) {
  262. final id = const Uuid().v4();
  263. final conversationId =
  264. chatItems.isEmpty ? "" : chatItems.last.conversationId;
  265. const role = "user";
  266. final content = chatContent;
  267. final createTime = DateTime.now().toString();
  268. final talkInfo = this.talkInfo.value;
  269. return talkInfo == null
  270. ? ChatItem(
  271. id: id,
  272. conversationId: conversationId,
  273. role: role,
  274. content: chatContent,
  275. createTime: createTime)
  276. : ReferenceChatItem(
  277. talkInfo: talkInfo,
  278. id: id,
  279. conversationId: conversationId,
  280. role: role,
  281. content: content,
  282. createTime: createTime);
  283. }
  284. onDeleteReference() {
  285. talkInfo.value = null;
  286. agenda.value = null;
  287. }
  288. void initReport() {
  289. if (fromType == ChatFromType.fromMain) {
  290. EventHandler.report(EventId.event_102002, params: {
  291. EventId.id: EventId.id_001,
  292. });
  293. } else if (fromType == ChatFromType.fromTalkDetail) {
  294. EventHandler.report(EventId.event_102002, params: {
  295. EventId.id: EventId.id_002,
  296. });
  297. } else if (fromType == ChatFromType.fromAnalysisBtn) {
  298. EventHandler.report(EventId.event_102002, params: {
  299. EventId.id: EventId.id_003,
  300. });
  301. }
  302. }
  303. void onCopyClick(String? content) {
  304. if (content != null) {
  305. Clipboard.setData(ClipboardData(text: content));
  306. }
  307. ToastUtil.showToast(StringName.copySuccess.tr);
  308. }
  309. @override
  310. void onClose() {
  311. super.onClose();
  312. if (isConsumeElectric) {
  313. accountRepository.refreshUserInfo();
  314. }
  315. _nowProgressingChatItem?.graduallyController.dispose();
  316. _streamChatSubscription?.cancel();
  317. }
  318. }