bigmodel.ts 5.5 KB

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