google.ts 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. import { ApiPath, Google, REQUEST_TIMEOUT_MS } from "@/app/constant";
  2. import { ChatOptions, getHeaders, LLMApi, LLMModel, LLMUsage } from "../api";
  3. import { useAccessStore, useAppConfig, useChatStore } from "@/app/store";
  4. import { getClientConfig } from "@/app/config/client";
  5. import { DEFAULT_API_HOST } from "@/app/constant";
  6. import Locale from "../../locales";
  7. import {
  8. EventStreamContentType,
  9. fetchEventSource,
  10. } from "@fortaine/fetch-event-source";
  11. import { prettyObject } from "@/app/utils/format";
  12. import {
  13. getMessageTextContent,
  14. getMessageImages,
  15. isVisionModel,
  16. } from "@/app/utils";
  17. import { preProcessImageContent } from "@/app/utils/chat";
  18. export class GeminiProApi implements LLMApi {
  19. path(path: string): string {
  20. const accessStore = useAccessStore.getState();
  21. let baseUrl = "";
  22. if (accessStore.useCustomConfig) {
  23. baseUrl = accessStore.googleUrl;
  24. }
  25. const isApp = !!getClientConfig()?.isApp;
  26. if (baseUrl.length === 0) {
  27. baseUrl = isApp ? DEFAULT_API_HOST + `/api/proxy/google` : ApiPath.Google;
  28. }
  29. if (baseUrl.endsWith("/")) {
  30. baseUrl = baseUrl.slice(0, baseUrl.length - 1);
  31. }
  32. if (!baseUrl.startsWith("http") && !baseUrl.startsWith(ApiPath.Google)) {
  33. baseUrl = "https://" + baseUrl;
  34. }
  35. console.log("[Proxy Endpoint] ", baseUrl, path);
  36. let chatPath = [baseUrl, path].join("/");
  37. chatPath += chatPath.includes("?") ? "&alt=sse" : "?alt=sse";
  38. // if chatPath.startsWith('http') then add key in query string
  39. if (chatPath.startsWith("http") && accessStore.googleApiKey) {
  40. chatPath += `&key=${accessStore.googleApiKey}`;
  41. }
  42. return chatPath;
  43. }
  44. extractMessage(res: any) {
  45. console.log("[Response] gemini-pro response: ", res);
  46. return (
  47. res?.candidates?.at(0)?.content?.parts.at(0)?.text ||
  48. res?.error?.message ||
  49. ""
  50. );
  51. }
  52. async chat(options: ChatOptions): Promise<void> {
  53. const apiClient = this;
  54. let multimodal = false;
  55. // try get base64image from local cache image_url
  56. const _messages: ChatOptions["messages"] = [];
  57. for (const v of options.messages) {
  58. const content = await preProcessImageContent(v.content);
  59. _messages.push({ role: v.role, content });
  60. }
  61. const messages = _messages.map((v) => {
  62. let parts: any[] = [{ text: getMessageTextContent(v) }];
  63. if (isVisionModel(options.config.model)) {
  64. const images = getMessageImages(v);
  65. if (images.length > 0) {
  66. multimodal = true;
  67. parts = parts.concat(
  68. images.map((image) => {
  69. const imageType = image.split(";")[0].split(":")[1];
  70. const imageData = image.split(",")[1];
  71. return {
  72. inline_data: {
  73. mime_type: imageType,
  74. data: imageData,
  75. },
  76. };
  77. }),
  78. );
  79. }
  80. }
  81. return {
  82. role: v.role.replace("assistant", "model").replace("system", "user"),
  83. parts: parts,
  84. };
  85. });
  86. // google requires that role in neighboring messages must not be the same
  87. for (let i = 0; i < messages.length - 1; ) {
  88. // Check if current and next item both have the role "model"
  89. if (messages[i].role === messages[i + 1].role) {
  90. // Concatenate the 'parts' of the current and next item
  91. messages[i].parts = messages[i].parts.concat(messages[i + 1].parts);
  92. // Remove the next item
  93. messages.splice(i + 1, 1);
  94. } else {
  95. // Move to the next item
  96. i++;
  97. }
  98. }
  99. // if (visionModel && messages.length > 1) {
  100. // options.onError?.(new Error("Multiturn chat is not enabled for models/gemini-pro-vision"));
  101. // }
  102. const accessStore = useAccessStore.getState();
  103. const modelConfig = {
  104. ...useAppConfig.getState().modelConfig,
  105. ...useChatStore.getState().currentSession().mask.modelConfig,
  106. ...{
  107. model: options.config.model,
  108. },
  109. };
  110. const requestPayload = {
  111. contents: messages,
  112. generationConfig: {
  113. // stopSequences: [
  114. // "Title"
  115. // ],
  116. temperature: modelConfig.temperature,
  117. maxOutputTokens: modelConfig.max_tokens,
  118. topP: modelConfig.top_p,
  119. // "topK": modelConfig.top_k,
  120. },
  121. safetySettings: [
  122. {
  123. category: "HARM_CATEGORY_HARASSMENT",
  124. threshold: accessStore.googleSafetySettings,
  125. },
  126. {
  127. category: "HARM_CATEGORY_HATE_SPEECH",
  128. threshold: accessStore.googleSafetySettings,
  129. },
  130. {
  131. category: "HARM_CATEGORY_SEXUALLY_EXPLICIT",
  132. threshold: accessStore.googleSafetySettings,
  133. },
  134. {
  135. category: "HARM_CATEGORY_DANGEROUS_CONTENT",
  136. threshold: accessStore.googleSafetySettings,
  137. },
  138. ],
  139. };
  140. let shouldStream = !!options.config.stream;
  141. const controller = new AbortController();
  142. options.onController?.(controller);
  143. try {
  144. // https://github.com/google-gemini/cookbook/blob/main/quickstarts/rest/Streaming_REST.ipynb
  145. const chatPath = this.path(Google.ChatPath(modelConfig.model));
  146. const chatPayload = {
  147. method: "POST",
  148. body: JSON.stringify(requestPayload),
  149. signal: controller.signal,
  150. headers: getHeaders(),
  151. };
  152. // make a fetch request
  153. const requestTimeoutId = setTimeout(
  154. () => controller.abort(),
  155. REQUEST_TIMEOUT_MS,
  156. );
  157. if (shouldStream) {
  158. let responseText = "";
  159. let remainText = "";
  160. let finished = false;
  161. const finish = () => {
  162. if (!finished) {
  163. finished = true;
  164. options.onFinish(responseText + remainText);
  165. }
  166. };
  167. // animate response to make it looks smooth
  168. function animateResponseText() {
  169. if (finished || controller.signal.aborted) {
  170. responseText += remainText;
  171. finish();
  172. return;
  173. }
  174. if (remainText.length > 0) {
  175. const fetchCount = Math.max(1, Math.round(remainText.length / 60));
  176. const fetchText = remainText.slice(0, fetchCount);
  177. responseText += fetchText;
  178. remainText = remainText.slice(fetchCount);
  179. options.onUpdate?.(responseText, fetchText);
  180. }
  181. requestAnimationFrame(animateResponseText);
  182. }
  183. // start animaion
  184. animateResponseText();
  185. controller.signal.onabort = finish;
  186. fetchEventSource(chatPath, {
  187. ...chatPayload,
  188. async onopen(res) {
  189. clearTimeout(requestTimeoutId);
  190. const contentType = res.headers.get("content-type");
  191. console.log(
  192. "[Gemini] request response content type: ",
  193. contentType,
  194. );
  195. if (contentType?.startsWith("text/plain")) {
  196. responseText = await res.clone().text();
  197. return finish();
  198. }
  199. if (
  200. !res.ok ||
  201. !res.headers
  202. .get("content-type")
  203. ?.startsWith(EventStreamContentType) ||
  204. res.status !== 200
  205. ) {
  206. const responseTexts = [responseText];
  207. let extraInfo = await res.clone().text();
  208. try {
  209. const resJson = await res.clone().json();
  210. extraInfo = prettyObject(resJson);
  211. } catch {}
  212. if (res.status === 401) {
  213. responseTexts.push(Locale.Error.Unauthorized);
  214. }
  215. if (extraInfo) {
  216. responseTexts.push(extraInfo);
  217. }
  218. responseText = responseTexts.join("\n\n");
  219. return finish();
  220. }
  221. },
  222. onmessage(msg) {
  223. if (msg.data === "[DONE]" || finished) {
  224. return finish();
  225. }
  226. const text = msg.data;
  227. try {
  228. const json = JSON.parse(text);
  229. const delta = apiClient.extractMessage(json);
  230. if (delta) {
  231. remainText += delta;
  232. }
  233. const blockReason = json?.promptFeedback?.blockReason;
  234. if (blockReason) {
  235. // being blocked
  236. console.log(`[Google] [Safety Ratings] result:`, blockReason);
  237. }
  238. } catch (e) {
  239. console.error("[Request] parse error", text, msg);
  240. }
  241. },
  242. onclose() {
  243. finish();
  244. },
  245. onerror(e) {
  246. options.onError?.(e);
  247. throw e;
  248. },
  249. openWhenHidden: true,
  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);
  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. }