google.ts 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  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 modelConfig = {
  101. ...useAppConfig.getState().modelConfig,
  102. ...useChatStore.getState().currentSession().mask.modelConfig,
  103. ...{
  104. model: options.config.model,
  105. },
  106. };
  107. const requestPayload = {
  108. contents: messages,
  109. generationConfig: {
  110. // stopSequences: [
  111. // "Title"
  112. // ],
  113. temperature: modelConfig.temperature,
  114. maxOutputTokens: modelConfig.max_tokens,
  115. topP: modelConfig.top_p,
  116. // "topK": modelConfig.top_k,
  117. },
  118. safetySettings: [
  119. {
  120. category: "HARM_CATEGORY_HARASSMENT",
  121. threshold: "BLOCK_ONLY_HIGH",
  122. },
  123. {
  124. category: "HARM_CATEGORY_HATE_SPEECH",
  125. threshold: "BLOCK_ONLY_HIGH",
  126. },
  127. {
  128. category: "HARM_CATEGORY_SEXUALLY_EXPLICIT",
  129. threshold: "BLOCK_ONLY_HIGH",
  130. },
  131. {
  132. category: "HARM_CATEGORY_DANGEROUS_CONTENT",
  133. threshold: "BLOCK_ONLY_HIGH",
  134. },
  135. ],
  136. };
  137. let shouldStream = !!options.config.stream;
  138. const controller = new AbortController();
  139. options.onController?.(controller);
  140. try {
  141. // https://github.com/google-gemini/cookbook/blob/main/quickstarts/rest/Streaming_REST.ipynb
  142. const chatPath = this.path(Google.ChatPath(modelConfig.model));
  143. const chatPayload = {
  144. method: "POST",
  145. body: JSON.stringify(requestPayload),
  146. signal: controller.signal,
  147. headers: getHeaders(),
  148. };
  149. // make a fetch request
  150. const requestTimeoutId = setTimeout(
  151. () => controller.abort(),
  152. REQUEST_TIMEOUT_MS,
  153. );
  154. if (shouldStream) {
  155. let responseText = "";
  156. let remainText = "";
  157. let finished = false;
  158. const finish = () => {
  159. if (!finished) {
  160. finished = true;
  161. options.onFinish(responseText + remainText);
  162. }
  163. };
  164. // animate response to make it looks smooth
  165. function animateResponseText() {
  166. if (finished || controller.signal.aborted) {
  167. responseText += remainText;
  168. finish();
  169. return;
  170. }
  171. if (remainText.length > 0) {
  172. const fetchCount = Math.max(1, Math.round(remainText.length / 60));
  173. const fetchText = remainText.slice(0, fetchCount);
  174. responseText += fetchText;
  175. remainText = remainText.slice(fetchCount);
  176. options.onUpdate?.(responseText, fetchText);
  177. }
  178. requestAnimationFrame(animateResponseText);
  179. }
  180. // start animaion
  181. animateResponseText();
  182. controller.signal.onabort = finish;
  183. fetchEventSource(chatPath, {
  184. ...chatPayload,
  185. async onopen(res) {
  186. clearTimeout(requestTimeoutId);
  187. const contentType = res.headers.get("content-type");
  188. console.log(
  189. "[Gemini] request response content type: ",
  190. contentType,
  191. );
  192. if (contentType?.startsWith("text/plain")) {
  193. responseText = await res.clone().text();
  194. return finish();
  195. }
  196. if (
  197. !res.ok ||
  198. !res.headers
  199. .get("content-type")
  200. ?.startsWith(EventStreamContentType) ||
  201. res.status !== 200
  202. ) {
  203. const responseTexts = [responseText];
  204. let extraInfo = await res.clone().text();
  205. try {
  206. const resJson = await res.clone().json();
  207. extraInfo = prettyObject(resJson);
  208. } catch {}
  209. if (res.status === 401) {
  210. responseTexts.push(Locale.Error.Unauthorized);
  211. }
  212. if (extraInfo) {
  213. responseTexts.push(extraInfo);
  214. }
  215. responseText = responseTexts.join("\n\n");
  216. return finish();
  217. }
  218. },
  219. onmessage(msg) {
  220. if (msg.data === "[DONE]" || finished) {
  221. return finish();
  222. }
  223. const text = msg.data;
  224. try {
  225. const json = JSON.parse(text);
  226. const delta = apiClient.extractMessage(json);
  227. if (delta) {
  228. remainText += delta;
  229. }
  230. const blockReason = json?.promptFeedback?.blockReason;
  231. if (blockReason) {
  232. // being blocked
  233. console.log(`[Google] [Safety Ratings] result:`, blockReason);
  234. }
  235. } catch (e) {
  236. console.error("[Request] parse error", text, msg);
  237. }
  238. },
  239. onclose() {
  240. finish();
  241. },
  242. onerror(e) {
  243. options.onError?.(e);
  244. throw e;
  245. },
  246. openWhenHidden: true,
  247. });
  248. } else {
  249. const res = await fetch(chatPath, chatPayload);
  250. clearTimeout(requestTimeoutId);
  251. const resJson = await res.json();
  252. if (resJson?.promptFeedback?.blockReason) {
  253. // being blocked
  254. options.onError?.(
  255. new Error(
  256. "Message is being blocked for reason: " +
  257. resJson.promptFeedback.blockReason,
  258. ),
  259. );
  260. }
  261. const message = apiClient.extractMessage(resJson);
  262. options.onFinish(message);
  263. }
  264. } catch (e) {
  265. console.log("[Request] failed to make a chat request", e);
  266. options.onError?.(e as Error);
  267. }
  268. }
  269. usage(): Promise<LLMUsage> {
  270. throw new Error("Method not implemented.");
  271. }
  272. async models(): Promise<LLMModel[]> {
  273. return [];
  274. }
  275. }