moonshot.ts 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. "use client";
  2. // azure and openai, using same models. so using same LLMApi.
  3. import {
  4. ApiPath,
  5. DEFAULT_API_HOST,
  6. Moonshot,
  7. REQUEST_TIMEOUT_MS,
  8. } from "@/app/constant";
  9. import {
  10. useAccessStore,
  11. useAppConfig,
  12. useChatStore,
  13. ChatMessageTool,
  14. usePluginStore,
  15. } from "@/app/store";
  16. import { stream } from "@/app/utils/chat";
  17. import {
  18. ChatOptions,
  19. getHeaders,
  20. LLMApi,
  21. LLMModel,
  22. SpeechOptions,
  23. } from "../api";
  24. import { getClientConfig } from "@/app/config/client";
  25. import { getMessageTextContent } from "@/app/utils";
  26. import { RequestPayload } from "./openai";
  27. export class MoonshotApi implements LLMApi {
  28. private disableListModels = true;
  29. path(path: string): string {
  30. const accessStore = useAccessStore.getState();
  31. let baseUrl = "";
  32. if (accessStore.useCustomConfig) {
  33. baseUrl = accessStore.moonshotUrl;
  34. }
  35. if (baseUrl.length === 0) {
  36. const isApp = !!getClientConfig()?.isApp;
  37. const apiPath = ApiPath.Moonshot;
  38. baseUrl = isApp ? DEFAULT_API_HOST + "/proxy" + apiPath : apiPath;
  39. }
  40. if (baseUrl.endsWith("/")) {
  41. baseUrl = baseUrl.slice(0, baseUrl.length - 1);
  42. }
  43. if (!baseUrl.startsWith("http") && !baseUrl.startsWith(ApiPath.Moonshot)) {
  44. baseUrl = "https://" + baseUrl;
  45. }
  46. console.log("[Proxy Endpoint] ", baseUrl, path);
  47. return [baseUrl, path].join("/");
  48. }
  49. extractMessage(res: any) {
  50. return res.choices?.at(0)?.message?.content ?? "";
  51. }
  52. speech(options: SpeechOptions): Promise<ArrayBuffer> {
  53. throw new Error("Method not implemented.");
  54. }
  55. async chat(options: ChatOptions) {
  56. const messages: ChatOptions["messages"] = [];
  57. for (const v of options.messages) {
  58. const content = getMessageTextContent(v);
  59. messages.push({ role: v.role, content });
  60. }
  61. const modelConfig = {
  62. ...useAppConfig.getState().modelConfig,
  63. ...useChatStore.getState().currentSession().mask.modelConfig,
  64. ...{
  65. model: options.config.model,
  66. providerName: options.config.providerName,
  67. },
  68. };
  69. const requestPayload: RequestPayload = {
  70. messages,
  71. stream: options.config.stream,
  72. model: modelConfig.model,
  73. temperature: modelConfig.temperature,
  74. presence_penalty: modelConfig.presence_penalty,
  75. frequency_penalty: modelConfig.frequency_penalty,
  76. top_p: modelConfig.top_p,
  77. // max_tokens: Math.max(modelConfig.max_tokens, 1024),
  78. // Please do not ask me why not send max_tokens, no reason, this param is just shit, I dont want to explain anymore.
  79. };
  80. console.log("[Request] openai payload: ", requestPayload);
  81. const shouldStream = !!options.config.stream;
  82. const controller = new AbortController();
  83. options.onController?.(controller);
  84. try {
  85. const chatPath = this.path(Moonshot.ChatPath);
  86. const chatPayload = {
  87. method: "POST",
  88. body: JSON.stringify(requestPayload),
  89. signal: controller.signal,
  90. headers: getHeaders(),
  91. };
  92. // make a fetch request
  93. const requestTimeoutId = setTimeout(
  94. () => controller.abort(),
  95. REQUEST_TIMEOUT_MS,
  96. );
  97. if (shouldStream) {
  98. const [tools, funcs] = usePluginStore
  99. .getState()
  100. .getAsTools(
  101. useChatStore.getState().currentSession().mask?.plugin || [],
  102. );
  103. return stream(
  104. chatPath,
  105. requestPayload,
  106. getHeaders(),
  107. tools as any,
  108. funcs,
  109. controller,
  110. // parseSSE
  111. (text: string, runTools: ChatMessageTool[]) => {
  112. // console.log("parseSSE", text, runTools);
  113. const json = JSON.parse(text);
  114. const choices = json.choices as Array<{
  115. delta: {
  116. content: string;
  117. tool_calls: ChatMessageTool[];
  118. };
  119. }>;
  120. const tool_calls = choices[0]?.delta?.tool_calls;
  121. if (tool_calls?.length > 0) {
  122. const index = tool_calls[0]?.index;
  123. const id = tool_calls[0]?.id;
  124. const args = tool_calls[0]?.function?.arguments;
  125. if (id) {
  126. runTools.push({
  127. id,
  128. type: tool_calls[0]?.type,
  129. function: {
  130. name: tool_calls[0]?.function?.name as string,
  131. arguments: args,
  132. },
  133. });
  134. } else {
  135. // @ts-ignore
  136. runTools[index]["function"]["arguments"] += args;
  137. }
  138. }
  139. return choices[0]?.delta?.content;
  140. },
  141. // processToolMessage, include tool_calls message and tool call results
  142. (
  143. requestPayload: RequestPayload,
  144. toolCallMessage: any,
  145. toolCallResult: any[],
  146. ) => {
  147. // @ts-ignore
  148. requestPayload?.messages?.splice(
  149. // @ts-ignore
  150. requestPayload?.messages?.length,
  151. 0,
  152. toolCallMessage,
  153. ...toolCallResult,
  154. );
  155. },
  156. options,
  157. );
  158. } else {
  159. const res = await fetch(chatPath, chatPayload);
  160. clearTimeout(requestTimeoutId);
  161. const resJson = await res.json();
  162. const message = this.extractMessage(resJson);
  163. options.onFinish(message);
  164. }
  165. } catch (e) {
  166. console.log("[Request] failed to make a chat request", 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. }