xai.ts 5.3 KB

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