google.ts 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  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): 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 (!chatPath.includes("gemini-pro")) {
  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(Google.ChatPath(modelConfig.model));
  159. console.log("[Chat Path] ", chatPath);
  160. const chatPayload = {
  161. method: "POST",
  162. body: JSON.stringify(requestPayload),
  163. signal: controller.signal,
  164. headers: getHeaders(),
  165. };
  166. // make a fetch request
  167. const requestTimeoutId = setTimeout(
  168. () => controller.abort(),
  169. REQUEST_TIMEOUT_MS,
  170. );
  171. if (shouldStream) {
  172. const [tools, funcs] = usePluginStore
  173. .getState()
  174. .getAsTools(
  175. useChatStore.getState().currentSession().mask?.plugin || [],
  176. );
  177. return stream(
  178. chatPath,
  179. requestPayload,
  180. getHeaders(),
  181. // @ts-ignore
  182. tools.length > 0
  183. ? // @ts-ignore
  184. [{ functionDeclarations: tools.map((tool) => tool.function) }]
  185. : [],
  186. funcs,
  187. controller,
  188. // parseSSE
  189. (text: string, runTools: ChatMessageTool[]) => {
  190. // console.log("parseSSE", text, runTools);
  191. const chunkJson = JSON.parse(text);
  192. const functionCall = chunkJson?.candidates
  193. ?.at(0)
  194. ?.content.parts.at(0)?.functionCall;
  195. if (functionCall) {
  196. const { name, args } = functionCall;
  197. runTools.push({
  198. id: nanoid(),
  199. type: "function",
  200. function: {
  201. name,
  202. arguments: JSON.stringify(args), // utils.chat call function, using JSON.parse
  203. },
  204. });
  205. }
  206. return chunkJson?.candidates?.at(0)?.content.parts.at(0)?.text;
  207. },
  208. // processToolMessage, include tool_calls message and tool call results
  209. (
  210. requestPayload: RequestPayload,
  211. toolCallMessage: any,
  212. toolCallResult: any[],
  213. ) => {
  214. // @ts-ignore
  215. requestPayload?.contents?.splice(
  216. // @ts-ignore
  217. requestPayload?.contents?.length,
  218. 0,
  219. {
  220. role: "model",
  221. parts: toolCallMessage.tool_calls.map(
  222. (tool: ChatMessageTool) => ({
  223. functionCall: {
  224. name: tool?.function?.name,
  225. args: JSON.parse(tool?.function?.arguments as string),
  226. },
  227. }),
  228. ),
  229. },
  230. // @ts-ignore
  231. ...toolCallResult.map((result) => ({
  232. role: "function",
  233. parts: [
  234. {
  235. functionResponse: {
  236. name: result.name,
  237. response: {
  238. name: result.name,
  239. content: result.content, // TODO just text content...
  240. },
  241. },
  242. },
  243. ],
  244. })),
  245. );
  246. },
  247. options,
  248. );
  249. } else {
  250. const res = await fetch(chatPath, chatPayload);
  251. clearTimeout(requestTimeoutId);
  252. const resJson = await res.json();
  253. if (resJson?.promptFeedback?.blockReason) {
  254. // being blocked
  255. options.onError?.(
  256. new Error(
  257. "Message is being blocked for reason: " +
  258. resJson.promptFeedback.blockReason,
  259. ),
  260. );
  261. }
  262. const message = apiClient.extractMessage(resJson);
  263. options.onFinish(message, res);
  264. }
  265. } catch (e) {
  266. console.log("[Request] failed to make a chat request", e);
  267. options.onError?.(e as Error);
  268. }
  269. }
  270. usage(): Promise<LLMUsage> {
  271. throw new Error("Method not implemented.");
  272. }
  273. async models(): Promise<LLMModel[]> {
  274. return [];
  275. }
  276. }