google.ts 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  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. if (!finished) {
  145. finished = true;
  146. options.onFinish(responseText + remainText);
  147. }
  148. };
  149. // animate response to make it looks smooth
  150. function animateResponseText() {
  151. if (finished || controller.signal.aborted) {
  152. responseText += remainText;
  153. finish();
  154. return;
  155. }
  156. if (remainText.length > 0) {
  157. const fetchCount = Math.max(1, Math.round(remainText.length / 60));
  158. const fetchText = remainText.slice(0, fetchCount);
  159. responseText += fetchText;
  160. remainText = remainText.slice(fetchCount);
  161. options.onUpdate?.(responseText, fetchText);
  162. }
  163. requestAnimationFrame(animateResponseText);
  164. }
  165. // start animaion
  166. animateResponseText();
  167. controller.signal.onabort = finish;
  168. // https://github.com/google-gemini/cookbook/blob/main/quickstarts/rest/Streaming_REST.ipynb
  169. const chatPath =
  170. baseUrl.replace("generateContent", "streamGenerateContent") +
  171. (baseUrl.indexOf("?") > -1 ? "&alt=sse" : "?alt=sse");
  172. fetchEventSource(chatPath, {
  173. ...chatPayload,
  174. async onopen(res) {
  175. clearTimeout(requestTimeoutId);
  176. const contentType = res.headers.get("content-type");
  177. console.log(
  178. "[Gemini] request response content type: ",
  179. contentType,
  180. );
  181. if (contentType?.startsWith("text/plain")) {
  182. responseText = await res.clone().text();
  183. return finish();
  184. }
  185. if (
  186. !res.ok ||
  187. !res.headers
  188. .get("content-type")
  189. ?.startsWith(EventStreamContentType) ||
  190. res.status !== 200
  191. ) {
  192. const responseTexts = [responseText];
  193. let extraInfo = await res.clone().text();
  194. try {
  195. const resJson = await res.clone().json();
  196. extraInfo = prettyObject(resJson);
  197. } catch {}
  198. if (res.status === 401) {
  199. responseTexts.push(Locale.Error.Unauthorized);
  200. }
  201. if (extraInfo) {
  202. responseTexts.push(extraInfo);
  203. }
  204. responseText = responseTexts.join("\n\n");
  205. return finish();
  206. }
  207. },
  208. onmessage(msg) {
  209. if (msg.data === "[DONE]" || finished) {
  210. return finish();
  211. }
  212. const text = msg.data;
  213. try {
  214. const json = JSON.parse(text);
  215. const delta = apiClient.extractMessage(json);
  216. if (delta) {
  217. remainText += delta;
  218. }
  219. const blockReason = json?.promptFeedback?.blockReason;
  220. if (blockReason) {
  221. // being blocked
  222. console.log(`[Google] [Safety Ratings] result:`, blockReason);
  223. }
  224. } catch (e) {
  225. console.error("[Request] parse error", text, msg);
  226. }
  227. },
  228. onclose() {
  229. finish();
  230. },
  231. onerror(e) {
  232. options.onError?.(e);
  233. throw e;
  234. },
  235. openWhenHidden: true,
  236. });
  237. } else {
  238. const res = await fetch(baseUrl, chatPayload);
  239. clearTimeout(requestTimeoutId);
  240. const resJson = await res.json();
  241. if (resJson?.promptFeedback?.blockReason) {
  242. // being blocked
  243. options.onError?.(
  244. new Error(
  245. "Message is being blocked for reason: " +
  246. resJson.promptFeedback.blockReason,
  247. ),
  248. );
  249. }
  250. const message = apiClient.extractMessage(resJson);
  251. options.onFinish(message);
  252. }
  253. } catch (e) {
  254. console.log("[Request] failed to make a chat request", e);
  255. options.onError?.(e as Error);
  256. }
  257. }
  258. usage(): Promise<LLMUsage> {
  259. throw new Error("Method not implemented.");
  260. }
  261. async models(): Promise<LLMModel[]> {
  262. return [];
  263. }
  264. path(path: string): string {
  265. return "/api/google/" + path;
  266. }
  267. }
  268. function ensureProperEnding(str: string) {
  269. if (str.startsWith("[") && !str.endsWith("]")) {
  270. return str + "]";
  271. }
  272. return str;
  273. }