google.ts 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. import { ApiPath, Google, REQUEST_TIMEOUT_MS } from "@/app/constant";
  2. import {
  3. ChatOptions,
  4. getHeaders,
  5. LLMApi,
  6. LLMModel,
  7. LLMUsage,
  8. SpeechOptions,
  9. } from "../api";
  10. import {
  11. useAccessStore,
  12. useAppConfig,
  13. useChatStore,
  14. usePluginStore,
  15. ChatMessageTool,
  16. } from "@/app/store";
  17. import { stream } from "@/app/utils/chat";
  18. import { getClientConfig } from "@/app/config/client";
  19. import { DEFAULT_API_HOST } from "@/app/constant";
  20. import {
  21. getMessageTextContent,
  22. getMessageImages,
  23. isVisionModel,
  24. } from "@/app/utils";
  25. import { preProcessImageContent } from "@/app/utils/chat";
  26. import { nanoid } from "nanoid";
  27. import { RequestPayload } from "./openai";
  28. export class GeminiProApi implements LLMApi {
  29. path(path: string): string {
  30. const accessStore = useAccessStore.getState();
  31. let baseUrl = "";
  32. if (accessStore.useCustomConfig) {
  33. baseUrl = accessStore.googleUrl;
  34. }
  35. const isApp = !!getClientConfig()?.isApp;
  36. if (baseUrl.length === 0) {
  37. baseUrl = isApp ? DEFAULT_API_HOST + `/api/proxy/google` : ApiPath.Google;
  38. }
  39. if (baseUrl.endsWith("/")) {
  40. baseUrl = baseUrl.slice(0, baseUrl.length - 1);
  41. }
  42. if (!baseUrl.startsWith("http") && !baseUrl.startsWith(ApiPath.Google)) {
  43. baseUrl = "https://" + baseUrl;
  44. }
  45. console.log("[Proxy Endpoint] ", baseUrl, path);
  46. let chatPath = [baseUrl, path].join("/");
  47. chatPath += chatPath.includes("?") ? "&alt=sse" : "?alt=sse";
  48. return chatPath;
  49. }
  50. extractMessage(res: any) {
  51. console.log("[Response] gemini-pro response: ", res);
  52. return (
  53. res?.candidates?.at(0)?.content?.parts.at(0)?.text ||
  54. res?.error?.message ||
  55. ""
  56. );
  57. }
  58. speech(options: SpeechOptions): Promise<ArrayBuffer> {
  59. throw new Error("Method not implemented.");
  60. }
  61. async chat(options: ChatOptions): Promise<void> {
  62. const apiClient = this;
  63. let multimodal = false;
  64. // try get base64image from local cache image_url
  65. const _messages: ChatOptions["messages"] = [];
  66. for (const v of options.messages) {
  67. const content = await preProcessImageContent(v.content);
  68. _messages.push({ role: v.role, content });
  69. }
  70. const messages = _messages.map((v) => {
  71. let parts: any[] = [{ text: getMessageTextContent(v) }];
  72. if (isVisionModel(options.config.model)) {
  73. const images = getMessageImages(v);
  74. if (images.length > 0) {
  75. multimodal = true;
  76. parts = parts.concat(
  77. images.map((image) => {
  78. const imageType = image.split(";")[0].split(":")[1];
  79. const imageData = image.split(",")[1];
  80. return {
  81. inline_data: {
  82. mime_type: imageType,
  83. data: imageData,
  84. },
  85. };
  86. }),
  87. );
  88. }
  89. }
  90. return {
  91. role: v.role.replace("assistant", "model").replace("system", "user"),
  92. parts: parts,
  93. };
  94. });
  95. // google requires that role in neighboring messages must not be the same
  96. for (let i = 0; i < messages.length - 1; ) {
  97. // Check if current and next item both have the role "model"
  98. if (messages[i].role === messages[i + 1].role) {
  99. // Concatenate the 'parts' of the current and next item
  100. messages[i].parts = messages[i].parts.concat(messages[i + 1].parts);
  101. // Remove the next item
  102. messages.splice(i + 1, 1);
  103. } else {
  104. // Move to the next item
  105. i++;
  106. }
  107. }
  108. // if (visionModel && messages.length > 1) {
  109. // options.onError?.(new Error("Multiturn chat is not enabled for models/gemini-pro-vision"));
  110. // }
  111. const accessStore = useAccessStore.getState();
  112. const modelConfig = {
  113. ...useAppConfig.getState().modelConfig,
  114. ...useChatStore.getState().currentSession().mask.modelConfig,
  115. ...{
  116. model: options.config.model,
  117. },
  118. };
  119. const requestPayload = {
  120. contents: messages,
  121. generationConfig: {
  122. // stopSequences: [
  123. // "Title"
  124. // ],
  125. temperature: modelConfig.temperature,
  126. maxOutputTokens: modelConfig.max_tokens,
  127. topP: modelConfig.top_p,
  128. // "topK": modelConfig.top_k,
  129. },
  130. safetySettings: [
  131. {
  132. category: "HARM_CATEGORY_HARASSMENT",
  133. threshold: accessStore.googleSafetySettings,
  134. },
  135. {
  136. category: "HARM_CATEGORY_HATE_SPEECH",
  137. threshold: accessStore.googleSafetySettings,
  138. },
  139. {
  140. category: "HARM_CATEGORY_SEXUALLY_EXPLICIT",
  141. threshold: accessStore.googleSafetySettings,
  142. },
  143. {
  144. category: "HARM_CATEGORY_DANGEROUS_CONTENT",
  145. threshold: accessStore.googleSafetySettings,
  146. },
  147. ],
  148. };
  149. let shouldStream = !!options.config.stream;
  150. const controller = new AbortController();
  151. options.onController?.(controller);
  152. try {
  153. // https://github.com/google-gemini/cookbook/blob/main/quickstarts/rest/Streaming_REST.ipynb
  154. const chatPath = this.path(Google.ChatPath(modelConfig.model));
  155. const chatPayload = {
  156. method: "POST",
  157. body: JSON.stringify(requestPayload),
  158. signal: controller.signal,
  159. headers: getHeaders(),
  160. };
  161. // make a fetch request
  162. const requestTimeoutId = setTimeout(
  163. () => controller.abort(),
  164. REQUEST_TIMEOUT_MS,
  165. );
  166. if (shouldStream) {
  167. const [tools, funcs] = usePluginStore
  168. .getState()
  169. .getAsTools(
  170. useChatStore.getState().currentSession().mask?.plugin || [],
  171. );
  172. return stream(
  173. chatPath,
  174. requestPayload,
  175. getHeaders(),
  176. // @ts-ignore
  177. [{ functionDeclarations: tools.map((tool) => tool.function) }],
  178. funcs,
  179. controller,
  180. // parseSSE
  181. (text: string, runTools: ChatMessageTool[]) => {
  182. // console.log("parseSSE", text, runTools);
  183. const chunkJson = JSON.parse(text);
  184. const functionCall = chunkJson?.candidates
  185. ?.at(0)
  186. ?.content.parts.at(0)?.functionCall;
  187. if (functionCall) {
  188. const { name, args } = functionCall;
  189. runTools.push({
  190. id: nanoid(),
  191. type: "function",
  192. function: {
  193. name,
  194. arguments: JSON.stringify(args), // utils.chat call function, using JSON.parse
  195. },
  196. });
  197. }
  198. return chunkJson?.candidates?.at(0)?.content.parts.at(0)?.text;
  199. },
  200. // processToolMessage, include tool_calls message and tool call results
  201. (
  202. requestPayload: RequestPayload,
  203. toolCallMessage: any,
  204. toolCallResult: any[],
  205. ) => {
  206. // @ts-ignore
  207. requestPayload?.contents?.splice(
  208. // @ts-ignore
  209. requestPayload?.contents?.length,
  210. 0,
  211. {
  212. role: "model",
  213. parts: toolCallMessage.tool_calls.map(
  214. (tool: ChatMessageTool) => ({
  215. functionCall: {
  216. name: tool?.function?.name,
  217. args: JSON.parse(tool?.function?.arguments as string),
  218. },
  219. }),
  220. ),
  221. },
  222. // @ts-ignore
  223. ...toolCallResult.map((result) => ({
  224. role: "function",
  225. parts: [
  226. {
  227. functionResponse: {
  228. name: result.name,
  229. response: {
  230. name: result.name,
  231. content: result.content, // TODO just text content...
  232. },
  233. },
  234. },
  235. ],
  236. })),
  237. );
  238. },
  239. options,
  240. );
  241. } else {
  242. const res = await fetch(chatPath, chatPayload);
  243. clearTimeout(requestTimeoutId);
  244. const resJson = await res.json();
  245. if (resJson?.promptFeedback?.blockReason) {
  246. // being blocked
  247. options.onError?.(
  248. new Error(
  249. "Message is being blocked for reason: " +
  250. resJson.promptFeedback.blockReason,
  251. ),
  252. );
  253. }
  254. const message = apiClient.extractMessage(resJson);
  255. options.onFinish(message);
  256. }
  257. } catch (e) {
  258. console.log("[Request] failed to make a chat request", e);
  259. options.onError?.(e as Error);
  260. }
  261. }
  262. usage(): Promise<LLMUsage> {
  263. throw new Error("Method not implemented.");
  264. }
  265. async models(): Promise<LLMModel[]> {
  266. return [];
  267. }
  268. }