google.ts 8.8 KB

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