google.ts 9.2 KB

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