chat.ts 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240
  1. import { bluebookAiAgent } from "@/xiaolanbenlib/api/index";
  2. import Taro from "@tarojs/taro";
  3. import { getSimpleHeader } from "@/xiaolanbenlib/module/axios.js";
  4. import ChunkParser, { ICompleteCallback } from "@/utils/ChunkParser";
  5. import request from "@/xiaolanbenlib/module/axios.js";
  6. import type { TMessageHistories, TRequestBody, TAppendMessages } from "@/types/bot";
  7. import { TextDecoder } from "text-encoding-shim";
  8. import { getTempFileContent } from "@/utils";
  9. // 获取与指定智能体的历史会话记录--按智能体维度倒序返回
  10. export type TGetMessageHistoriesParams = {
  11. agentId: string;
  12. startId?: string; // 起始ID, 如果未传入则获取最新的N条
  13. pageSize: number;
  14. };
  15. export const getMessageHistories = (data: TGetMessageHistoriesParams) => {
  16. return request.get<TMessageHistories>(
  17. `${bluebookAiAgent}api/v1/chat/messages`,
  18. { params: data }
  19. );
  20. };
  21. // 推荐提问引导。在获取完成并保存完成后,调用推荐提示获取提问引导
  22. export const getRecommendPrompt = (data: {agentId: string, sessionId: string}) => {
  23. return request.get<{questions: string[]}>(
  24. `${bluebookAiAgent}api/v1/chat/recommend/prompt`,
  25. { params: data }
  26. );
  27. };
  28. // 保存消息--追加覆盖保存模式
  29. export const appendMessages = (data: TAppendMessages) => {
  30. return request.post(`${bluebookAiAgent}api/v1/chat/messages/append`, data)
  31. }
  32. // 消息差评或取消差评
  33. type TDislikeMessage = {
  34. agentId: string,
  35. dislikeReason: string,
  36. isDislike: boolean,
  37. msgUk: string
  38. loginId: string
  39. }
  40. export const dislikeMessage = (data: TDislikeMessage) => {
  41. return request.put(`${bluebookAiAgent}api/v1/chat/messages/dislike`, data)
  42. }
  43. // 消息点赞或取消点赞
  44. type TLikeMessage = {
  45. agentId: string,
  46. isLike: boolean,
  47. msgUk: string
  48. loginId: string
  49. }
  50. export const likeMessage = (data: TLikeMessage) => {
  51. return request.put(`${bluebookAiAgent}api/v1/chat/messages/like`, data)
  52. }
  53. export const speechToText = async (agentId: string, tempFilePath: string) => {
  54. const content = await getTempFileContent<string>(tempFilePath, 'base64')
  55. return request.post<{
  56. emotions: string[],
  57. text: string
  58. }>(`${bluebookAiAgent}api/v1/chat/speech/text`, {
  59. agentId,
  60. speechBase64: content,
  61. })
  62. }
  63. // 流式请求
  64. export type TRequestStream<T> = {
  65. url: string,
  66. params: T;
  67. onStart: () => void;
  68. onReceived: (m: ICompleteCallback) => void;
  69. onAudioParsed: (m: ICompleteCallback) => void;
  70. onFinished: (m: ICompleteCallback) => void;
  71. onComplete?: () => void; // 无论失败或成功都会执行
  72. onError: () => void;
  73. };
  74. export const requestStream = <T>({
  75. url,
  76. params,
  77. onStart,
  78. onReceived,
  79. onAudioParsed,
  80. onFinished,
  81. onComplete,
  82. onError,
  83. }: TRequestStream<T>) => {
  84. onStart();
  85. let reqTask: Taro.RequestTask<any>|undefined|null = undefined;
  86. const jsonParser = new ChunkParser();
  87. jsonParser.onParseComplete((m) => {
  88. onFinished(m);
  89. });
  90. const onChunkReceived = (chunk: any) => {
  91. // console.log('chunkReceived: ', chunk);
  92. const uint8Array = new Uint8Array(chunk.data);
  93. // console.log('uint8Array: ', uint8Array);
  94. var string = new TextDecoder("utf-8").decode(uint8Array);
  95. // console.log('chunked:', string);
  96. jsonParser.parseChunk(string, (m) => {
  97. // console.log('parseChunk', m);
  98. onReceived(m);
  99. }, onAudioParsed);
  100. };
  101. const header = getSimpleHeader()
  102. try {
  103. reqTask = Taro.request({
  104. url: url,
  105. data: params,
  106. enableChunked: true,
  107. method: "POST",
  108. header: {
  109. ...header
  110. },
  111. responseType: "arraybuffer",
  112. success: function (res) {
  113. console.log("服务端响应 >>", res);
  114. },
  115. complete: function(res) {
  116. console.log(reqTask)
  117. console.log("reqTask >>", reqTask, res);
  118. if(reqTask) {
  119. onComplete?.()
  120. }
  121. },
  122. fail: function (){
  123. if(reqTask) {
  124. onComplete?.()
  125. }
  126. }
  127. });
  128. // reqTask.
  129. reqTask.onChunkReceived(onChunkReceived);
  130. } catch (e) {
  131. onComplete?.()
  132. onError();
  133. }
  134. const stopChunk = () => {
  135. reqTask?.offChunkReceived(onChunkReceived);
  136. reqTask?.abort();
  137. reqTask = null
  138. console.log('stop reqTask: v1/chat/completions')
  139. };
  140. return {reqTask: reqTask, stopChunk};
  141. };
  142. // 文本转语音
  143. export type TTextToSpeechParams = {
  144. params: {
  145. agentId: string,
  146. loginId: string,
  147. msgUk: string,
  148. text: string
  149. };
  150. onStart: () => void;
  151. onReceived: (m: ICompleteCallback) => void;
  152. onAudioParsed: (m: ICompleteCallback) => void;
  153. onFinished: (m: ICompleteCallback) => void;
  154. onComplete?: () => void; // 无论失败或成功都会执行
  155. onError: () => void;
  156. };
  157. export const requestTextToSpeech = ({
  158. params,
  159. onStart,
  160. onReceived,
  161. onAudioParsed,
  162. onFinished,
  163. onComplete,
  164. onError,
  165. }: TTextToSpeechParams) => {
  166. const url = `${bluebookAiAgent}api/v1/chat/text/speech`;
  167. return requestStream<{
  168. agentId: string,
  169. loginId: string,
  170. msgUk: string,
  171. text: string
  172. }>({
  173. url,
  174. params,
  175. onStart,
  176. onReceived,
  177. onAudioParsed,
  178. onFinished,
  179. onComplete,
  180. onError,
  181. })
  182. };
  183. // 聊天,流式返回消息
  184. export type TTextChatParams = {
  185. params: TRequestBody;
  186. onStart: () => void;
  187. onReceived: (m: ICompleteCallback) => void;
  188. onAudioParsed: (m: ICompleteCallback) => void;
  189. onFinished: (m: ICompleteCallback) => void;
  190. onComplete?: () => void; // 无论失败或成功都会执行
  191. onError: () => void;
  192. };
  193. export const requestTextToChat = ({
  194. params,
  195. onStart,
  196. onReceived,
  197. onAudioParsed,
  198. onFinished,
  199. onComplete,
  200. onError,
  201. }: TTextChatParams) => {
  202. const url = `${bluebookAiAgent}api/v1/chat/completions`;
  203. return requestStream<TRequestBody>({
  204. url,
  205. params,
  206. onStart,
  207. onReceived,
  208. onAudioParsed,
  209. onFinished,
  210. onComplete,
  211. onError,
  212. })
  213. };