useChat.ts 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  1. import { useXAgent, XStream } from "@ant-design/x";
  2. import { useEffect, useRef, useState } from "react";
  3. import { useSessionStorageState } from "ahooks";
  4. import { GetSessionList, GetSessionMessageList } from "@/api/ai";
  5. import { getDateGroupString } from "@/utils";
  6. import type { ConversationsProps } from "@ant-design/x";
  7. import type { ReactNode } from "react";
  8. // 消息格式
  9. type MessageItem = {
  10. id: string;
  11. content: string | ReactNode;
  12. role: "user" | "assistant" | "system";
  13. status: "loading" | "done" | "error" | "stop";
  14. loading?: boolean;
  15. footer?: ReactNode;
  16. };
  17. // 后端返回格式
  18. type ResponseMessageItem = {
  19. answer: string;
  20. conversation_id: string;
  21. created_at: number;
  22. event: "message" | "message_end" | "message_error" | "ping";
  23. message_id: string;
  24. task_id: string;
  25. };
  26. type ChatParams = {
  27. // 应用名称
  28. app_name: string;
  29. // 会话内容
  30. chat_query: string;
  31. // 会话名称 第一次
  32. chat_name?: string;
  33. // 会话id 后续会话带入
  34. conversation_id?: string;
  35. };
  36. type ChatProps = {
  37. // 应用名称
  38. app_name: string;
  39. // 会话id 后续会话带入
  40. conversation_id?: string;
  41. // 成功获取会话内容
  42. onSuccess?: (data: ResponseMessageItem) => void;
  43. // 更新流式消息内容
  44. onUpdate: (data: ResponseMessageItem) => void;
  45. // 异常
  46. onError?: (error: Error) => void;
  47. };
  48. const defaultConversation = {
  49. // 会话id
  50. key: "1",
  51. label: "新的对话",
  52. group: '今日'
  53. };
  54. export function useChat({ app_name, onSuccess, onUpdate, onError }: ChatProps) {
  55. /**
  56. * 发送消息加载状态
  57. */
  58. const [loading, setLoading] = useState(false);
  59. /**
  60. * 加载会话记录列表
  61. */
  62. const [loadingSession, setLoadingSession] = useState(false);
  63. /**
  64. * 加载消息列表
  65. */
  66. const [loadingMessages, setLoadingMessages] = useState(false);
  67. // 用于停止对话
  68. const abortController = useRef<AbortController | null>(null);
  69. /**
  70. * 消息列表
  71. */
  72. const [messages, setMessages] = useState<Array<MessageItem>>([]);
  73. // 会话列表
  74. const [conversationList, setConversationList] = useState<
  75. ConversationsProps["items"]
  76. >([{ ...defaultConversation }]);
  77. // 活动对话
  78. const [activeConversation, setActiveConversation] = useState("1");
  79. // 当前智能体对象
  80. const [currentAgent, setCurrentAgent] = useSessionStorageState("agent-map");
  81. // 有更多对话
  82. const [hasMoreConversation, setHasMoreConversation] = useState(false);
  83. // 会话分页
  84. const [pageIndex, setPageIndex] = useState(1);
  85. const getSession = (page: number) => {
  86. setLoadingSession(true);
  87. GetSessionList({
  88. app_name,
  89. page_index: page,
  90. })
  91. .then((res) => {
  92. if(page === 1) {
  93. setConversationList([
  94. { ...defaultConversation },
  95. ...(res?.result?.model || []).map((item: any) => ({
  96. ...item,
  97. key: item.sessionId,
  98. label: item.name,
  99. group: getDateGroupString(item.updateTime)
  100. })),
  101. ]);
  102. } else {
  103. setConversationList([
  104. ...(conversationList || []),
  105. ...(res?.result?.model || []).map((item: any) => ({
  106. ...item,
  107. key: item.sessionId,
  108. label: item.name,
  109. group: getDateGroupString(item.updateTime)
  110. })),
  111. ]);
  112. }
  113. setHasMoreConversation(res?.result.totalPages > page);
  114. })
  115. .finally(() => {
  116. setLoadingSession(false);
  117. });
  118. }
  119. // 切换app时获取会话记录
  120. useEffect(() => {
  121. setPageIndex(1);
  122. getSession(1);
  123. }, [app_name]);
  124. /**
  125. * 加载更多会话
  126. */
  127. const loadMoreConversation = () => {
  128. getSession(pageIndex + 1);
  129. setPageIndex(pageIndex + 1);
  130. };
  131. /**
  132. * 切换会话
  133. * @param key 会话id
  134. * @returns
  135. */
  136. const changeConversation = async (key: string) => {
  137. setActiveConversation(key);
  138. if (key === "1") {
  139. setMessages([]);
  140. return;
  141. }
  142. cancel();
  143. setLoadingMessages(true);
  144. // 获取会话内容
  145. try {
  146. const res = await GetSessionMessageList({
  147. app_name,
  148. session_id: key,
  149. page_index: 1,
  150. });
  151. const list: MessageItem[] = [];
  152. (res?.result?.model || []).forEach((item: any) => {
  153. list.push(
  154. {
  155. id: item.id + "_query",
  156. content: item.query,
  157. role: "user",
  158. status: "done",
  159. },
  160. {
  161. id: item.id + "_query",
  162. content: item.answer,
  163. role: "assistant",
  164. status: "done",
  165. }
  166. );
  167. });
  168. setMessages(list);
  169. } finally {
  170. setLoadingMessages(false);
  171. }
  172. };
  173. /**
  174. * 封装智能体
  175. */
  176. const [agent] = useXAgent<ResponseMessageItem>({
  177. request: async (message, { onError, onSuccess, onUpdate }) => {
  178. abortController.current = new AbortController();
  179. const signal = abortController.current.signal;
  180. try {
  181. setLoading(true);
  182. const response = await fetch(
  183. "https://design.shalu.com/api/ai/chat-message",
  184. {
  185. method: "POST",
  186. body: JSON.stringify(message),
  187. headers: {
  188. Authorization: localStorage.getItem("token_a") || "",
  189. "Content-Type": "application/json",
  190. },
  191. signal,
  192. }
  193. );
  194. // 判断当前是否流式返回
  195. if(response.headers.get('content-type')?.includes('text/event-stream')) {
  196. if (response.body) {
  197. for await (const chunk of XStream({
  198. readableStream: response.body,
  199. })) {
  200. const data = JSON.parse(chunk.data);
  201. if (data?.event === "message") {
  202. onUpdate(data);
  203. } else if (data?.event === "message_end") {
  204. onSuccess(data);
  205. } else if (data?.event === "message_error") {
  206. onError(data);
  207. } else if (data?.event === "ping") {
  208. console.log(">>>> stream start <<<<");
  209. } else {
  210. console.log(">>>> stream error <<<<");
  211. onError(Error(data?.message || '请求失败'));
  212. }
  213. }
  214. }
  215. } else {
  216. // 接口异常处理
  217. response.json().then(res => {
  218. if(res.code === 0 ) {
  219. onError?.(Error(res?.error || '请求失败'));
  220. cancel();
  221. }
  222. });
  223. }
  224. } catch (error) {
  225. // 判断是不是 abort 错误
  226. if (signal.aborted) {
  227. return;
  228. }
  229. onError(error as Error);
  230. } finally {
  231. setLoading(false);
  232. }
  233. },
  234. });
  235. /**
  236. * 发起请求
  237. * @param chat_query 对话内容
  238. */
  239. const onRequest = (chat_query: string) => {
  240. activeConversation === '1' && setConversationList((list) => {
  241. return list?.map((item) => {
  242. return {
  243. ...item,
  244. label: item.key === "1" ? chat_query : item.label,
  245. };
  246. });
  247. });
  248. agent.request(
  249. {
  250. app_name,
  251. chat_query,
  252. chat_name: activeConversation === "1" ? chat_query : undefined,
  253. conversation_id:
  254. activeConversation === "1" ? undefined : activeConversation,
  255. },
  256. {
  257. onSuccess: (data) => {
  258. onSuccess?.(data);
  259. },
  260. onUpdate: (data) => {
  261. onUpdate(data);
  262. // 更新会话相关信息
  263. if (activeConversation === "1") {
  264. setConversationList((list) => {
  265. return list?.map((item) => {
  266. return {
  267. ...item,
  268. // 更新当前会话id
  269. key: item.key === "1" ? data.conversation_id : item.key,
  270. };
  271. });
  272. });
  273. setActiveConversation(data.conversation_id);
  274. }
  275. },
  276. onError: (error) => {
  277. console.log("error", error);
  278. onError?.(error);
  279. },
  280. }
  281. );
  282. };
  283. /**
  284. * 停止对话
  285. */
  286. const cancel = () => {
  287. abortController.current?.abort();
  288. setLoading(false);
  289. };
  290. /**
  291. * 新增会话
  292. */
  293. const addConversation = () => {
  294. cancel();
  295. setMessages([]);
  296. setActiveConversation("1");
  297. // 还没产生对话时 直接清除当前对话
  298. if (!conversationList?.find((item) => item.key === "1")) {
  299. setConversationList([
  300. {
  301. ...defaultConversation,
  302. },
  303. ...(conversationList || []),
  304. ]);
  305. }
  306. };
  307. return {
  308. agent,
  309. loading,
  310. loadingMessages,
  311. loadingSession,
  312. cancel,
  313. messages,
  314. setMessages,
  315. conversationList,
  316. setConversationList,
  317. activeConversation,
  318. setActiveConversation,
  319. onRequest,
  320. addConversation,
  321. changeConversation,
  322. loadMoreConversation,
  323. hasMoreConversation
  324. };
  325. }