google.ts 9.3 KB

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