google.ts 8.8 KB

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