google.ts 9.4 KB

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