google.ts 8.6 KB

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