controller.dart 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  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. ChatFromType? fromType;
  34. @override
  35. void onInit() {
  36. super.onInit();
  37. loadMoreHistory();
  38. checkArguments();
  39. initReport();
  40. }
  41. @override
  42. void onReady() {
  43. super.onReady();
  44. if (accountRepository.userInfo.value?.profession == null ||
  45. accountRepository.userInfo.value?.post == null) {
  46. showStartSheet();
  47. }
  48. }
  49. void checkArguments() {
  50. List<dynamic> arguments = Get.arguments ?? [];
  51. if (arguments.isEmpty) {
  52. return;
  53. }
  54. if (arguments[0] is ChatFromType) {
  55. fromType = arguments[0];
  56. }
  57. if (arguments.length > 2 && arguments[2] is Agenda) {
  58. agenda.value = arguments[2];
  59. }
  60. if (arguments.length > 1 && arguments[1] is TalkBean) {
  61. talkInfo.value = arguments[1];
  62. sendInitialMessage();
  63. } else if (arguments.length > 1 && arguments[1] is String) {
  64. talkRepository
  65. .talkInfo(arguments[1])
  66. .then((response) => talkInfo.value = response.talkInfo)
  67. .then((_) => sendInitialMessage());
  68. }
  69. }
  70. void sendInitialMessage() {
  71. final talkInfo = this.talkInfo.value;
  72. if (talkInfo == null) {
  73. return;
  74. }
  75. chatItems.insert(
  76. 0,
  77. FileChatItem(talkInfo,
  78. id: const Uuid().v4(),
  79. conversationId: "",
  80. role: "user",
  81. content: "",
  82. createTime: DateTime.now().toString()));
  83. if (agenda.value != null) {
  84. _sendMessage("以这份谈话为背景,你为我执行“${agenda.value?.content}”这一事项");
  85. }
  86. }
  87. onSendClick() {
  88. if (inputController.text.isEmpty) {
  89. return;
  90. }
  91. String chatContent = inputController.text;
  92. inputController.clear();
  93. _sendMessage(chatContent);
  94. }
  95. void onAddFileClick() {
  96. Get.toNamed(RoutePath.fileSearch)?.then((talkInfo) {
  97. if (talkInfo is TalkBean) {
  98. this.talkInfo.value = talkInfo;
  99. agenda.value = null;
  100. sendInitialMessage();
  101. }
  102. });
  103. }
  104. Future<void> loadMoreHistory() {
  105. bool isEmpty = chatItems.isEmpty;
  106. return chatRepository
  107. .chatHistory(chatItems.isEmpty ? null : chatItems.last.id)
  108. .then((value) => chatItems.addAll(value))
  109. .whenComplete(() => refreshController.loadComplete())
  110. .whenComplete(() {
  111. if (isEmpty) {
  112. _scrollToBottom();
  113. }
  114. });
  115. }
  116. void showStartSheet() {
  117. WidgetsBinding.instance.addPostFrameCallback((_) {
  118. if (fromType == ChatFromType.fromMain) {
  119. EventHandler.report(EventId.event_102001, params: {
  120. EventId.id: EventId.id_001,
  121. });
  122. } else if (fromType == ChatFromType.fromTalkDetail) {
  123. EventHandler.report(EventId.event_102001, params: {
  124. EventId.id: EventId.id_002,
  125. });
  126. } else if (fromType == ChatFromType.fromAnalysisBtn) {
  127. EventHandler.report(EventId.event_102001, params: {
  128. EventId.id: EventId.id_003,
  129. });
  130. }
  131. showModalBottomSheet(
  132. context: Get.context!,
  133. isScrollControlled: true,
  134. barrierColor: ColorName.black55,
  135. backgroundColor: ColorName.transparent,
  136. builder: (BuildContext context) {
  137. return const ChatStartPage();
  138. },
  139. ).then((result) {
  140. if (accountRepository.userInfo.value?.profession == null ||
  141. accountRepository.userInfo.value?.post == null) {
  142. Get.back();
  143. }
  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. progressingChatItem.append(delta.content ?? "");
  186. } catch (ignore) {}
  187. }, onDone: () {
  188. progressingChatItem.content = progressingChatItem.streamContent.value;
  189. progressingChatItem.isFinished.value = true;
  190. }, onError: (error) {
  191. progressingChatItem.isFailed.value = true;
  192. progressingChatItem.error.value = "网络错误,请检查网络连接";
  193. debugPrint("error: $error");
  194. debugPrintStack();
  195. });
  196. }).catchError((error) {
  197. progressingChatItem.isFailed.value = true;
  198. if (error is ServerErrorException) {
  199. progressingChatItem.error.value = error.message ?? "服务出错,请稍后再试";
  200. if (error.code == ErrorCode.errorCodeNoLogin) {
  201. Get.toNamed(RoutePath.login)?.then((loginSuccess) async {
  202. if (loginSuccess != null && loginSuccess) {
  203. _clearChat();
  204. await loadMoreHistory();
  205. _sendMessage(chatContent);
  206. }
  207. });
  208. } else if (error.code == ErrorCode.errorCodeNoProfession) {
  209. showStartSheet();
  210. }
  211. } else {
  212. progressingChatItem.error.value = "网络错误,请检查网络连接";
  213. debugPrint("error: $error");
  214. debugPrintStack();
  215. }
  216. });
  217. }
  218. void _clearChat() async {
  219. return chatItems.clear();
  220. }
  221. void _scrollToBottom() {
  222. Future.delayed(const Duration(milliseconds: 300), () {
  223. listScrollController.animateTo(
  224. 0,
  225. duration: const Duration(milliseconds: 300),
  226. curve: Curves.easeOut,
  227. );
  228. });
  229. }
  230. createUserChatItem(String chatContent) {
  231. final id = const Uuid().v4();
  232. final conversationId =
  233. chatItems.isEmpty ? "" : chatItems.last.conversationId;
  234. const role = "user";
  235. final content = chatContent;
  236. final createTime = DateTime.now().toString();
  237. final talkInfo = this.talkInfo.value;
  238. return talkInfo == null
  239. ? ChatItem(
  240. id: id,
  241. conversationId: conversationId,
  242. role: role,
  243. content: chatContent,
  244. createTime: createTime)
  245. : ReferenceChatItem(
  246. talkInfo: talkInfo,
  247. id: id,
  248. conversationId: conversationId,
  249. role: role,
  250. content: content,
  251. createTime: createTime);
  252. }
  253. onDeleteReference() {
  254. talkInfo.value = null;
  255. agenda.value = null;
  256. }
  257. void initReport() {
  258. if (fromType == ChatFromType.fromMain) {
  259. EventHandler.report(EventId.event_102002, params: {
  260. EventId.id: EventId.id_001,
  261. });
  262. } else if (fromType == ChatFromType.fromTalkDetail) {
  263. EventHandler.report(EventId.event_102002, params: {
  264. EventId.id: EventId.id_002,
  265. });
  266. } else if (fromType == ChatFromType.fromAnalysisBtn) {
  267. EventHandler.report(EventId.event_102002, params: {
  268. EventId.id: EventId.id_003,
  269. });
  270. }
  271. }
  272. }