google.ts 9.6 KB

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