google.ts 9.4 KB

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