google.ts 9.3 KB

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