controller.dart 9.6 KB

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