controller.dart 9.4 KB

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