google.ts 8.8 KB

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