bigmodel.ts 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. "use client";
  2. import { REQUEST_TIMEOUT_MS } from "@/app/constant";
  3. import { useAppConfig, useChatStore } from "@/app/store";
  4. import {
  5. ChatOptions,
  6. LLMApi,
  7. LLMModel,
  8. } from "../api";
  9. import Locale from "../../locales";
  10. import {
  11. EventStreamContentType,
  12. fetchEventSource,
  13. } from "@fortaine/fetch-event-source";
  14. import { prettyObject } from "@/app/utils/format";
  15. import { getMessageTextContent } from "@/app/utils";
  16. export class BigModelApi implements LLMApi {
  17. path(): string {
  18. return 'https://open.bigmodel.cn/api/paas/v4/chat/completions'
  19. }
  20. async chat(options: ChatOptions) {
  21. const messages = options.messages.map((v) => ({
  22. role: v.role,
  23. content: getMessageTextContent(v),
  24. }));
  25. if (messages.length % 2 === 0) {
  26. messages.unshift({
  27. role: "user",
  28. content: " ",
  29. });
  30. }
  31. const modelConfig = {
  32. ...useAppConfig.getState().modelConfig,
  33. ...useChatStore.getState().currentSession().mask.modelConfig,
  34. ...{
  35. model: options.config.model,
  36. },
  37. };
  38. const shouldStream = !!options.config.stream;
  39. // 通用大模型参数
  40. const requestPayload: any = {
  41. messages,
  42. stream: shouldStream,
  43. model: 'glm-4-flash',
  44. temperature: modelConfig.temperature,
  45. top_p: modelConfig.top_p,
  46. };
  47. const controller = new AbortController();
  48. options.onController?.(controller);
  49. try {
  50. const chatPath = this.path();
  51. const chatPayload = {
  52. method: "POST",
  53. body: JSON.stringify(requestPayload),
  54. signal: controller.signal,
  55. headers: {
  56. 'Content-Type': 'application/json',
  57. // APIKey
  58. Authorization: '20480a1ad76c4d9e0a168206a25f9614.bUjEVNXHpgY0H0GH'
  59. },
  60. };
  61. // make a fetch request
  62. const requestTimeoutId = setTimeout(
  63. () => controller.abort(),
  64. REQUEST_TIMEOUT_MS,
  65. );
  66. if (shouldStream) {
  67. let responseText = "";
  68. let remainText = "";
  69. let finished = false;
  70. // animate response to make it looks smooth
  71. function animateResponseText() {
  72. if (finished || controller.signal.aborted) {
  73. responseText += remainText;
  74. console.log("[Response Animation] finished");
  75. if (responseText?.length === 0) {
  76. options.onError?.(new Error("empty response from server"));
  77. }
  78. return;
  79. }
  80. if (remainText.length > 0) {
  81. const fetchCount = Math.max(1, Math.round(remainText.length / 60));
  82. const fetchText = remainText.slice(0, fetchCount);
  83. responseText += fetchText;
  84. remainText = remainText.slice(fetchCount);
  85. options.onUpdate?.(responseText, fetchText);
  86. }
  87. requestAnimationFrame(animateResponseText);
  88. }
  89. // start animaion
  90. animateResponseText();
  91. const finish = () => {
  92. if (!finished) {
  93. finished = true;
  94. options.onFinish(responseText + remainText);
  95. }
  96. };
  97. controller.signal.onabort = finish;
  98. fetchEventSource(chatPath, {
  99. ...chatPayload,
  100. async onopen(res) {
  101. clearTimeout(requestTimeoutId);
  102. const contentType = res.headers.get("content-type");
  103. console.log("[Baidu] request response content type: ", contentType);
  104. if (contentType?.startsWith("text/plain")) {
  105. responseText = await res.clone().text();
  106. return finish();
  107. }
  108. if (
  109. !res.ok ||
  110. !res.headers
  111. .get("content-type")
  112. ?.startsWith(EventStreamContentType) ||
  113. res.status !== 200
  114. ) {
  115. const responseTexts = [responseText];
  116. let extraInfo = await res.clone().text();
  117. try {
  118. const resJson = await res.clone().json();
  119. extraInfo = prettyObject(resJson);
  120. } catch { }
  121. if (res.status === 401) {
  122. responseTexts.push(Locale.Error.Unauthorized);
  123. }
  124. if (extraInfo) {
  125. responseTexts.push(extraInfo);
  126. }
  127. responseText = responseTexts.join("\n\n");
  128. return finish();
  129. }
  130. },
  131. onmessage(msg) {
  132. if (msg.data === "[DONE]" || finished) {
  133. return finish();
  134. }
  135. const text = msg.data;
  136. try {
  137. const json = JSON.parse(text);
  138. const choices = json.choices as Array<{
  139. delta: { content: string };
  140. }>;
  141. const delta = choices[0]?.delta?.content;
  142. if (delta) {
  143. remainText += delta;
  144. }
  145. } catch (e) {
  146. console.error("[Request] parse error", text, msg);
  147. }
  148. },
  149. onclose() {
  150. finish();
  151. },
  152. onerror(e) {
  153. options.onError?.(e);
  154. throw e;
  155. },
  156. openWhenHidden: true,
  157. });
  158. } else {
  159. const res = await fetch(chatPath, chatPayload);
  160. clearTimeout(requestTimeoutId);
  161. const resJson = await res.json();
  162. const message = resJson?.result;
  163. options.onFinish(message);
  164. }
  165. } catch (e) {
  166. options.onError?.(e as Error);
  167. }
  168. }
  169. async usage() {
  170. return {
  171. used: 0,
  172. total: 0,
  173. };
  174. }
  175. async models(): Promise<LLMModel[]> {
  176. return [];
  177. }
  178. }