google.ts 9.3 KB

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