2023-12-23 18:15:30 +00:00
|
|
|
import { Google, REQUEST_TIMEOUT_MS } from "@/app/constant";
|
|
|
|
import { ChatOptions, getHeaders, LLMApi, LLMModel, LLMUsage } from "../api";
|
|
|
|
import { useAccessStore, useAppConfig, useChatStore } from "@/app/store";
|
|
|
|
import {
|
|
|
|
EventStreamContentType,
|
|
|
|
fetchEventSource,
|
|
|
|
} from "@fortaine/fetch-event-source";
|
|
|
|
import { prettyObject } from "@/app/utils/format";
|
|
|
|
import { getClientConfig } from "@/app/config/client";
|
|
|
|
import Locale from "../../locales";
|
2023-12-23 19:05:23 +00:00
|
|
|
import { getServerSideConfig } from "@/app/config/server";
|
2023-12-31 11:08:16 +00:00
|
|
|
import de from "@/app/locales/de";
|
2023-12-23 20:22:12 +00:00
|
|
|
export class GeminiProApi implements LLMApi {
|
2023-12-23 18:15:30 +00:00
|
|
|
extractMessage(res: any) {
|
2023-12-23 20:22:12 +00:00
|
|
|
console.log("[Response] gemini-pro response: ", res);
|
2023-12-23 20:32:25 +00:00
|
|
|
|
2023-12-23 18:15:30 +00:00
|
|
|
return (
|
|
|
|
res?.candidates?.at(0)?.content?.parts.at(0)?.text ||
|
|
|
|
res?.error?.message ||
|
|
|
|
""
|
|
|
|
);
|
|
|
|
}
|
|
|
|
async chat(options: ChatOptions): Promise<void> {
|
2023-12-28 19:42:45 +00:00
|
|
|
const apiClient = this;
|
2023-12-23 18:15:30 +00:00
|
|
|
const messages = options.messages.map((v) => ({
|
2023-12-24 20:33:47 +00:00
|
|
|
role: v.role.replace("assistant", "model").replace("system", "user"),
|
2023-12-23 18:15:30 +00:00
|
|
|
parts: [{ text: v.content }],
|
|
|
|
}));
|
|
|
|
|
2023-12-24 20:33:47 +00:00
|
|
|
// google requires that role in neighboring messages must not be the same
|
|
|
|
for (let i = 0; i < messages.length - 1; ) {
|
|
|
|
// Check if current and next item both have the role "model"
|
|
|
|
if (messages[i].role === messages[i + 1].role) {
|
|
|
|
// Concatenate the 'parts' of the current and next item
|
|
|
|
messages[i].parts = messages[i].parts.concat(messages[i + 1].parts);
|
|
|
|
// Remove the next item
|
|
|
|
messages.splice(i + 1, 1);
|
|
|
|
} else {
|
|
|
|
// Move to the next item
|
|
|
|
i++;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-12-23 18:15:30 +00:00
|
|
|
const modelConfig = {
|
|
|
|
...useAppConfig.getState().modelConfig,
|
|
|
|
...useChatStore.getState().currentSession().mask.modelConfig,
|
|
|
|
...{
|
|
|
|
model: options.config.model,
|
|
|
|
},
|
|
|
|
};
|
|
|
|
const requestPayload = {
|
|
|
|
contents: messages,
|
2023-12-24 09:24:04 +00:00
|
|
|
generationConfig: {
|
|
|
|
// stopSequences: [
|
|
|
|
// "Title"
|
|
|
|
// ],
|
|
|
|
temperature: modelConfig.temperature,
|
|
|
|
maxOutputTokens: modelConfig.max_tokens,
|
|
|
|
topP: modelConfig.top_p,
|
|
|
|
// "topK": modelConfig.top_k,
|
|
|
|
},
|
2023-12-31 11:44:51 +00:00
|
|
|
safetySettings: [
|
|
|
|
{
|
|
|
|
category: "HARM_CATEGORY_HARASSMENT",
|
|
|
|
threshold: "BLOCK_ONLY_HIGH",
|
|
|
|
},
|
|
|
|
{
|
|
|
|
category: "HARM_CATEGORY_HATE_SPEECH",
|
|
|
|
threshold: "BLOCK_ONLY_HIGH",
|
|
|
|
},
|
|
|
|
{
|
|
|
|
category: "HARM_CATEGORY_SEXUALLY_EXPLICIT",
|
|
|
|
threshold: "BLOCK_ONLY_HIGH",
|
|
|
|
},
|
|
|
|
{
|
|
|
|
category: "HARM_CATEGORY_DANGEROUS_CONTENT",
|
|
|
|
threshold: "BLOCK_ONLY_HIGH",
|
|
|
|
},
|
|
|
|
],
|
2023-12-23 18:15:30 +00:00
|
|
|
};
|
|
|
|
|
2023-12-23 19:05:23 +00:00
|
|
|
console.log("[Request] google payload: ", requestPayload);
|
2023-12-23 18:15:30 +00:00
|
|
|
|
2023-12-28 19:42:45 +00:00
|
|
|
const shouldStream = !!options.config.stream;
|
2023-12-23 18:15:30 +00:00
|
|
|
const controller = new AbortController();
|
|
|
|
options.onController?.(controller);
|
|
|
|
try {
|
2023-12-23 19:05:23 +00:00
|
|
|
const chatPath = this.path(Google.ChatPath);
|
2023-12-23 18:15:30 +00:00
|
|
|
const chatPayload = {
|
|
|
|
method: "POST",
|
|
|
|
body: JSON.stringify(requestPayload),
|
|
|
|
signal: controller.signal,
|
|
|
|
headers: getHeaders(),
|
|
|
|
};
|
|
|
|
|
|
|
|
// make a fetch request
|
|
|
|
const requestTimeoutId = setTimeout(
|
|
|
|
() => controller.abort(),
|
|
|
|
REQUEST_TIMEOUT_MS,
|
|
|
|
);
|
|
|
|
if (shouldStream) {
|
|
|
|
let responseText = "";
|
|
|
|
let remainText = "";
|
2023-12-28 19:42:45 +00:00
|
|
|
let streamChatPath = chatPath.replace(
|
|
|
|
"generateContent",
|
|
|
|
"streamGenerateContent",
|
|
|
|
);
|
2023-12-23 18:15:30 +00:00
|
|
|
let finished = false;
|
2023-12-31 11:08:16 +00:00
|
|
|
|
|
|
|
let existingTexts: string[] = [];
|
2023-12-28 19:42:45 +00:00
|
|
|
const finish = () => {
|
|
|
|
finished = true;
|
2023-12-31 11:08:16 +00:00
|
|
|
options.onFinish(existingTexts.join(""));
|
2023-12-28 19:42:45 +00:00
|
|
|
};
|
2023-12-23 18:15:30 +00:00
|
|
|
|
|
|
|
// animate response to make it looks smooth
|
|
|
|
function animateResponseText() {
|
|
|
|
if (finished || controller.signal.aborted) {
|
|
|
|
responseText += remainText;
|
2023-12-28 19:42:45 +00:00
|
|
|
finish();
|
2023-12-23 18:15:30 +00:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (remainText.length > 0) {
|
|
|
|
const fetchCount = Math.max(1, Math.round(remainText.length / 60));
|
|
|
|
const fetchText = remainText.slice(0, fetchCount);
|
|
|
|
responseText += fetchText;
|
|
|
|
remainText = remainText.slice(fetchCount);
|
|
|
|
options.onUpdate?.(responseText, fetchText);
|
|
|
|
}
|
|
|
|
|
|
|
|
requestAnimationFrame(animateResponseText);
|
|
|
|
}
|
|
|
|
|
|
|
|
// start animaion
|
|
|
|
animateResponseText();
|
2023-12-28 19:42:45 +00:00
|
|
|
fetch(streamChatPath, chatPayload)
|
|
|
|
.then((response) => {
|
|
|
|
const reader = response?.body?.getReader();
|
|
|
|
const decoder = new TextDecoder();
|
|
|
|
let partialData = "";
|
|
|
|
|
|
|
|
return reader?.read().then(function processText({
|
|
|
|
done,
|
|
|
|
value,
|
|
|
|
}): Promise<any> {
|
|
|
|
if (done) {
|
|
|
|
console.log("Stream complete");
|
|
|
|
// options.onFinish(responseText + remainText);
|
|
|
|
finished = true;
|
|
|
|
return Promise.resolve();
|
|
|
|
}
|
2023-12-23 18:15:30 +00:00
|
|
|
|
2023-12-28 19:42:45 +00:00
|
|
|
partialData += decoder.decode(value, { stream: true });
|
2023-12-23 18:15:30 +00:00
|
|
|
|
|
|
|
try {
|
2023-12-28 19:42:45 +00:00
|
|
|
let data = JSON.parse(ensureProperEnding(partialData));
|
2023-12-31 11:08:16 +00:00
|
|
|
|
|
|
|
const textArray = data.reduce(
|
|
|
|
(acc: string[], item: { candidates: any[] }) => {
|
|
|
|
const texts = item.candidates.map((candidate) =>
|
|
|
|
candidate.content.parts
|
|
|
|
.map((part: { text: any }) => part.text)
|
|
|
|
.join(""),
|
|
|
|
);
|
|
|
|
return acc.concat(texts);
|
|
|
|
},
|
|
|
|
[],
|
|
|
|
);
|
|
|
|
|
|
|
|
if (textArray.length > existingTexts.length) {
|
|
|
|
const deltaArray = textArray.slice(existingTexts.length);
|
|
|
|
existingTexts = textArray;
|
|
|
|
remainText += deltaArray.join("");
|
|
|
|
}
|
2023-12-28 19:42:45 +00:00
|
|
|
} catch (error) {
|
2023-12-31 11:08:16 +00:00
|
|
|
// console.log("[Response Animation] error: ", error,partialData);
|
2023-12-28 19:42:45 +00:00
|
|
|
// skip error message when parsing json
|
2023-12-23 18:15:30 +00:00
|
|
|
}
|
|
|
|
|
2023-12-28 19:42:45 +00:00
|
|
|
return reader.read().then(processText);
|
|
|
|
});
|
|
|
|
})
|
|
|
|
.catch((error) => {
|
|
|
|
console.error("Error:", error);
|
|
|
|
});
|
2023-12-23 18:15:30 +00:00
|
|
|
} else {
|
|
|
|
const res = await fetch(chatPath, chatPayload);
|
|
|
|
clearTimeout(requestTimeoutId);
|
|
|
|
|
|
|
|
const resJson = await res.json();
|
2023-12-23 20:32:25 +00:00
|
|
|
|
|
|
|
if (resJson?.promptFeedback?.blockReason) {
|
|
|
|
// being blocked
|
|
|
|
options.onError?.(
|
|
|
|
new Error(
|
|
|
|
"Message is being blocked for reason: " +
|
|
|
|
resJson.promptFeedback.blockReason,
|
|
|
|
),
|
|
|
|
);
|
|
|
|
}
|
2023-12-23 18:15:30 +00:00
|
|
|
const message = this.extractMessage(resJson);
|
|
|
|
options.onFinish(message);
|
|
|
|
}
|
|
|
|
} catch (e) {
|
|
|
|
console.log("[Request] failed to make a chat request", e);
|
|
|
|
options.onError?.(e as Error);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
usage(): Promise<LLMUsage> {
|
|
|
|
throw new Error("Method not implemented.");
|
|
|
|
}
|
|
|
|
async models(): Promise<LLMModel[]> {
|
|
|
|
return [];
|
|
|
|
}
|
|
|
|
path(path: string): string {
|
|
|
|
return "/api/google/" + path;
|
|
|
|
}
|
|
|
|
}
|
2023-12-28 19:42:45 +00:00
|
|
|
|
|
|
|
function ensureProperEnding(str: string) {
|
|
|
|
if (str.startsWith("[") && !str.endsWith("]")) {
|
|
|
|
return str + "]";
|
|
|
|
}
|
|
|
|
return str;
|
|
|
|
}
|