controller.dart 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  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 (accountRepository.userInfo.value?.profession == null ||
  143. accountRepository.userInfo.value?.post == null) {
  144. Get.back();
  145. }
  146. });
  147. }
  148. void _sendMessage(String chatContent) {
  149. chatItems.insert(0, createUserChatItem(chatContent));
  150. ProgressingChatItem progressingChatItem = ProgressingChatItem(
  151. id: const Uuid().v4(),
  152. conversationId: chatItems.last.conversationId,
  153. role: "assistant",
  154. content: "",
  155. createTime: DateTime.now().toString(),
  156. );
  157. chatItems.insert(0, progressingChatItem);
  158. _scrollToBottom();
  159. if (talkInfo.value == null) {
  160. EventHandler.report(EventId.event_102003, params: {
  161. EventId.id: EventId.id_002,
  162. });
  163. } else {
  164. EventHandler.report(EventId.event_102003, params: {
  165. EventId.id: EventId.id_001,
  166. });
  167. }
  168. chatRepository
  169. .streamChat(chatContent,
  170. talkId: talkInfo.value?.id, agendaId: agenda.value?.id)
  171. .then((stream) {
  172. stream.listen((event) {
  173. try {
  174. Map<String, dynamic> json = jsonDecode(event.data);
  175. if (json.isEmpty) {
  176. return;
  177. }
  178. StreamChatOriginData data = StreamChatOriginData.fromJson(json);
  179. if (data.choices == null || data.choices!.isEmpty) {
  180. return;
  181. }
  182. Delta? delta = data.choices![0].delta;
  183. if (delta == null) {
  184. return;
  185. }
  186. isConsumeElectric = true;
  187. progressingChatItem.append(delta.content ?? "");
  188. chatAiTagId.value = progressingChatItem.id;
  189. } catch (ignore) {}
  190. }, onDone: () {
  191. progressingChatItem.content = progressingChatItem.streamContent.value;
  192. progressingChatItem.isFinished.value = true;
  193. }, onError: (error) {
  194. progressingChatItem.isFailed.value = true;
  195. progressingChatItem.error.value = "网络错误,请检查网络连接";
  196. debugPrint("error: $error");
  197. debugPrintStack();
  198. });
  199. }).catchError((error) {
  200. progressingChatItem.isFailed.value = true;
  201. if (error is ServerErrorException) {
  202. progressingChatItem.error.value = error.message ?? "服务出错,请稍后再试";
  203. if (error.code == ErrorCode.errorCodeNoLogin) {
  204. Get.toNamed(RoutePath.login)?.then((loginSuccess) async {
  205. if (loginSuccess != null && loginSuccess) {
  206. _clearChat();
  207. await loadMoreHistory();
  208. _sendMessage(chatContent);
  209. }
  210. });
  211. } else if (error.code == ErrorCode.errorCodeNoProfession) {
  212. showStartSheet();
  213. }
  214. } else {
  215. progressingChatItem.error.value = "网络错误,请检查网络连接";
  216. debugPrint("error: $error");
  217. debugPrintStack();
  218. }
  219. });
  220. }
  221. void _clearChat() async {
  222. return chatItems.clear();
  223. }
  224. void _scrollToBottom() {
  225. Future.delayed(const Duration(milliseconds: 300), () {
  226. listScrollController.animateTo(
  227. 0,
  228. duration: const Duration(milliseconds: 300),
  229. curve: Curves.easeOut,
  230. );
  231. });
  232. }
  233. createUserChatItem(String chatContent) {
  234. final id = const Uuid().v4();
  235. final conversationId =
  236. chatItems.isEmpty ? "" : chatItems.last.conversationId;
  237. const role = "user";
  238. final content = chatContent;
  239. final createTime = DateTime.now().toString();
  240. final talkInfo = this.talkInfo.value;
  241. return talkInfo == null
  242. ? ChatItem(
  243. id: id,
  244. conversationId: conversationId,
  245. role: role,
  246. content: chatContent,
  247. createTime: createTime)
  248. : ReferenceChatItem(
  249. talkInfo: talkInfo,
  250. id: id,
  251. conversationId: conversationId,
  252. role: role,
  253. content: content,
  254. createTime: createTime);
  255. }
  256. onDeleteReference() {
  257. talkInfo.value = null;
  258. agenda.value = null;
  259. }
  260. void initReport() {
  261. if (fromType == ChatFromType.fromMain) {
  262. EventHandler.report(EventId.event_102002, params: {
  263. EventId.id: EventId.id_001,
  264. });
  265. } else if (fromType == ChatFromType.fromTalkDetail) {
  266. EventHandler.report(EventId.event_102002, params: {
  267. EventId.id: EventId.id_002,
  268. });
  269. } else if (fromType == ChatFromType.fromAnalysisBtn) {
  270. EventHandler.report(EventId.event_102002, params: {
  271. EventId.id: EventId.id_003,
  272. });
  273. }
  274. }
  275. @override
  276. void onClose() {
  277. super.onClose();
  278. if (isConsumeElectric) {
  279. accountRepository.refreshUserInfo();
  280. }
  281. }
  282. }