NextChat-U/app/client/platforms/openai.ts

609 lines
18 KiB
TypeScript
Raw Normal View History

"use client";
2024-07-05 20:59:45 +09:00
// azure and openai, using same models. so using same LLMApi.
import {
2023-11-10 03:43:30 +09:00
ApiPath,
DEFAULT_API_HOST,
2023-07-11 00:19:43 +09:00
DEFAULT_MODELS,
OpenaiPath,
2024-07-05 20:59:45 +09:00
Azure,
REQUEST_TIMEOUT_MS,
2023-11-10 03:43:30 +09:00
ServiceProvider,
} from "@/app/constant";
2023-05-15 00:00:17 +09:00
import { useAccessStore, useAppConfig, useChatStore } from "@/app/store";
2024-07-05 20:59:45 +09:00
import { collectModelsWithDefaultModel } from "@/app/utils/model";
2024-08-02 21:58:21 +09:00
import {
preProcessImageContent,
uploadImage,
base64Image2Blob,
} from "@/app/utils/chat";
2024-07-12 13:00:25 +09:00
import { cloudflareAIGatewayUrl } from "@/app/utils/cloudflare";
import { DalleSize, DalleQuality, DalleStyle } from "@/app/typing";
2024-02-20 19:04:32 +09:00
import {
ChatOptions,
getHeaders,
LLMApi,
LLMModel,
LLMUsage,
MultimodalContent,
} from "../api";
import Locale from "../../locales";
2023-05-17 09:50:50 +09:00
import {
EventStreamContentType,
fetchEventSource,
2023-05-20 20:58:12 +09:00
} from "@fortaine/fetch-event-source";
2023-05-16 02:58:58 +09:00
import { prettyObject } from "@/app/utils/format";
import { getClientConfig } from "@/app/config/client";
2024-02-20 19:04:32 +09:00
import {
getMessageTextContent,
getMessageImages,
isVisionModel,
2024-08-02 19:00:42 +09:00
isDalle3 as _isDalle3,
2024-02-20 19:04:32 +09:00
} from "@/app/utils";
2023-05-15 00:00:17 +09:00
export interface OpenAIListModelResponse {
object: string;
data: Array<{
id: string;
object: string;
root: string;
}>;
}
2024-07-07 22:59:56 +09:00
export interface RequestPayload {
messages: {
role: "system" | "user" | "assistant";
content: string | MultimodalContent[];
}[];
stream?: boolean;
model: string;
temperature: number;
presence_penalty: number;
frequency_penalty: number;
top_p: number;
max_tokens?: number;
}
2024-08-02 19:00:42 +09:00
export interface DalleRequestPayload {
model: string;
prompt: string;
2024-08-02 21:58:21 +09:00
response_format: "url" | "b64_json";
2024-08-02 19:00:42 +09:00
n: number;
2024-08-02 19:50:48 +09:00
size: DalleSize;
quality: DalleQuality;
style: DalleStyle;
2024-08-02 19:00:42 +09:00
}
2023-05-15 00:00:17 +09:00
export class ChatGPTApi implements LLMApi {
2023-07-11 00:19:43 +09:00
private disableListModels = true;
2023-05-15 00:00:17 +09:00
path(path: string): string {
2023-11-10 03:43:30 +09:00
const accessStore = useAccessStore.getState();
let baseUrl = "";
2023-11-10 03:43:30 +09:00
2024-07-05 21:15:56 +09:00
const isAzure = path.includes("deployments");
if (accessStore.useCustomConfig) {
if (isAzure && !accessStore.isValidAzure()) {
throw Error(
"incomplete azure config, please check it in your settings page",
);
}
baseUrl = isAzure ? accessStore.azureUrl : accessStore.openaiUrl;
}
2023-11-10 03:43:30 +09:00
if (baseUrl.length === 0) {
const isApp = !!getClientConfig()?.isApp;
2024-07-05 21:15:56 +09:00
const apiPath = isAzure ? ApiPath.Azure : ApiPath.OpenAI;
baseUrl = isApp ? DEFAULT_API_HOST + "/proxy" + apiPath : apiPath;
}
2023-11-10 03:43:30 +09:00
if (baseUrl.endsWith("/")) {
baseUrl = baseUrl.slice(0, baseUrl.length - 1);
}
2024-07-05 21:15:56 +09:00
if (
!baseUrl.startsWith("http") &&
!isAzure &&
!baseUrl.startsWith(ApiPath.OpenAI)
) {
2023-11-10 03:43:30 +09:00
baseUrl = "https://" + baseUrl;
2023-05-16 01:22:11 +09:00
}
2023-11-10 03:43:30 +09:00
console.log("[Proxy Endpoint] ", baseUrl, path);
2024-07-12 13:00:25 +09:00
// try rebuild url, when using cloudflare ai gateway in client
return cloudflareAIGatewayUrl([baseUrl, path].join("/"));
2023-05-15 00:00:17 +09:00
}
2024-08-02 21:58:21 +09:00
async extractMessage(res: any) {
2024-08-02 19:00:42 +09:00
if (res.error) {
return "```\n" + JSON.stringify(res, null, 4) + "\n```";
}
2024-08-02 21:58:21 +09:00
// dalle3 model return url, using url create image message
2024-08-02 19:00:42 +09:00
if (res.data) {
2024-08-02 21:58:21 +09:00
let url = res.data?.at(0)?.url ?? "";
const b64_json = res.data?.at(0)?.b64_json ?? "";
if (!url && b64_json) {
// uploadImage
url = await uploadImage(base64Image2Blob(b64_json, "image/png"));
}
2024-08-02 19:00:42 +09:00
return [
{
type: "image_url",
image_url: {
url,
},
},
];
}
2024-08-02 23:16:08 +09:00
return res.choices?.at(0)?.message?.content ?? res;
2023-05-15 00:00:17 +09:00
}
async chat(options: ChatOptions) {
const modelConfig = {
...useAppConfig.getState().modelConfig,
...useChatStore.getState().currentSession().mask.modelConfig,
...{
model: options.config.model,
2024-07-05 20:59:45 +09:00
providerName: options.config.providerName,
2023-05-15 00:00:17 +09:00
},
};
2024-08-02 19:00:42 +09:00
let requestPayload: RequestPayload | DalleRequestPayload;
2023-05-15 00:00:17 +09:00
2024-08-02 19:00:42 +09:00
const isDalle3 = _isDalle3(options.config.model);
if (isDalle3) {
2024-08-02 19:50:48 +09:00
const prompt = getMessageTextContent(
options.messages.slice(-1)?.pop() as any,
);
2024-08-02 19:00:42 +09:00
requestPayload = {
model: options.config.model,
prompt,
2024-08-02 21:58:21 +09:00
// URLs are only valid for 60 minutes after the image has been generated.
response_format: "b64_json", // using b64_json, and save image in CacheStorage
2024-08-02 19:00:42 +09:00
n: 1,
size: options.config?.size ?? "1024x1024",
quality: options.config?.quality ?? "standard",
style: options.config?.style ?? "vivid",
2024-08-02 19:00:42 +09:00
};
} else {
const visionModel = isVisionModel(options.config.model);
const messages: ChatOptions["messages"] = [];
for (const v of options.messages) {
const content = visionModel
? await preProcessImageContent(v.content)
: getMessageTextContent(v);
messages.push({ role: v.role, content });
}
requestPayload = {
messages,
stream: options.config.stream,
model: modelConfig.model,
temperature: modelConfig.temperature,
presence_penalty: modelConfig.presence_penalty,
frequency_penalty: modelConfig.frequency_penalty,
top_p: modelConfig.top_p,
// max_tokens: Math.max(modelConfig.max_tokens, 1024),
// Please do not ask me why not send max_tokens, no reason, this param is just shit, I dont want to explain anymore.
};
// add max_tokens to vision model
if (visionModel && modelConfig.model.includes("preview")) {
requestPayload["max_tokens"] = Math.max(modelConfig.max_tokens, 4000);
}
}
2023-05-15 00:00:17 +09:00
console.log("[Request] openai payload: ", requestPayload);
2024-08-02 19:00:42 +09:00
const shouldStream = !isDalle3 && !!options.config.stream;
2023-05-15 00:00:17 +09:00
const controller = new AbortController();
options.onController?.(controller);
2023-05-15 00:00:17 +09:00
try {
2024-07-05 20:59:45 +09:00
let chatPath = "";
2024-07-06 00:56:10 +09:00
if (modelConfig.providerName === ServiceProvider.Azure) {
2024-07-05 20:59:45 +09:00
// find model, and get displayName as deployName
const { models: configModels, customModels: configCustomModels } =
useAppConfig.getState();
2024-07-06 01:05:59 +09:00
const {
defaultModel,
customModels: accessCustomModels,
useCustomConfig,
} = useAccessStore.getState();
2024-07-05 20:59:45 +09:00
const models = collectModelsWithDefaultModel(
configModels,
[configCustomModels, accessCustomModels].join(","),
defaultModel,
);
const model = models.find(
(model) =>
2024-07-06 00:56:10 +09:00
model.name === modelConfig.model &&
model?.provider?.providerName === ServiceProvider.Azure,
2024-07-05 20:59:45 +09:00
);
2024-07-05 21:15:56 +09:00
chatPath = this.path(
2024-08-02 19:00:42 +09:00
(isDalle3 ? Azure.ImagePath : Azure.ChatPath)(
2024-07-05 21:20:21 +09:00
(model?.displayName ?? model?.name) as string,
2024-07-06 01:05:59 +09:00
useCustomConfig ? useAccessStore.getState().azureApiVersion : "",
2024-07-05 21:15:56 +09:00
),
);
2024-07-05 20:59:45 +09:00
} else {
2024-08-02 19:00:42 +09:00
chatPath = this.path(
isDalle3 ? OpenaiPath.ImagePath : OpenaiPath.ChatPath,
);
2024-07-05 20:59:45 +09:00
}
2023-05-15 00:00:17 +09:00
const chatPayload = {
method: "POST",
body: JSON.stringify(requestPayload),
signal: controller.signal,
headers: getHeaders(),
2023-05-15 00:00:17 +09:00
};
// make a fetch request
const requestTimeoutId = setTimeout(
2023-05-15 00:00:17 +09:00
() => controller.abort(),
2024-08-02 21:58:21 +09:00
isDalle3 ? REQUEST_TIMEOUT_MS * 2 : REQUEST_TIMEOUT_MS, // dalle3 using b64_json is slow.
2023-05-15 00:00:17 +09:00
);
2023-05-15 00:00:17 +09:00
if (shouldStream) {
let responseText = "";
let remainText = "";
let finished = false;
2024-08-29 00:58:46 +09:00
let running = false;
let runTools = [];
2023-05-15 00:00:17 +09:00
// animate response to make it looks smooth
function animateResponseText() {
if (finished || controller.signal.aborted) {
responseText += remainText;
console.log("[Response Animation] finished");
if (responseText?.length === 0) {
options.onError?.(new Error("empty response from server"));
}
return;
}
if (remainText.length > 0) {
2023-11-19 20:15:11 +09:00
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();
2024-08-29 00:58:46 +09:00
// TODO 后面这里是从选择的plugins中获取function列表
const funcs = {
get_current_weather: (args) => {
console.log("call get_current_weather", args);
return "30";
},
};
const finish = () => {
if (!finished) {
2024-08-29 00:58:46 +09:00
console.log("try run tools", runTools.length, finished, running);
if (!running && runTools.length > 0) {
const toolCallMessage = {
role: "assistant",
tool_calls: [...runTools],
};
running = true;
runTools.splice(0, runTools.length); // empty runTools
return Promise.all(
toolCallMessage.tool_calls.map((tool) => {
options?.onBeforeTool(tool);
return Promise.resolve(
funcs[tool.function.name](
JSON.parse(tool.function.arguments),
),
)
.then((content) => {
options?.onAfterTool({
...tool,
content,
isError: false,
});
return content;
})
.catch((e) => {
options?.onAfterTool({ ...tool, isError: true });
return e.toString();
})
.then((content) => ({
role: "tool",
content,
tool_call_id: tool.id,
}));
}),
).then((toolCallResult) => {
console.log("end runTools", toolCallMessage, toolCallResult);
requestPayload["messages"].splice(
requestPayload["messages"].length,
0,
toolCallMessage,
...toolCallResult,
);
setTimeout(() => {
// call again
console.log("start again");
running = false;
chatApi(chatPath, requestPayload); // call fetchEventSource
}, 0);
});
console.log("try run tools", runTools.length, finished);
return;
}
if (running) {
return;
}
finished = true;
options.onFinish(responseText + remainText);
}
};
2023-05-15 00:00:17 +09:00
2023-05-16 02:58:58 +09:00
controller.signal.onabort = finish;
2024-08-29 00:58:46 +09:00
function chatApi(chatPath, requestPayload) {
const chatPayload = {
method: "POST",
body: JSON.stringify({
...requestPayload,
// TODO 这里暂时写死的后面从store.tools中按照当前session中选择的获取
tools: [
{
type: "function",
function: {
name: "get_current_weather",
description: "Get the current weather",
parameters: {
type: "object",
properties: {
location: {
type: "string",
description:
"The city and country, eg. San Francisco, USA",
},
format: {
type: "string",
enum: ["celsius", "fahrenheit"],
},
},
required: ["location", "format"],
},
},
},
],
}),
signal: controller.signal,
headers: getHeaders(),
};
console.log("chatApi", chatPath, requestPayload, chatPayload);
fetchEventSource(chatPath, {
...chatPayload,
async onopen(res) {
clearTimeout(requestTimeoutId);
const contentType = res.headers.get("content-type");
console.log(
"[OpenAI] request response content type: ",
contentType,
);
if (contentType?.startsWith("text/plain")) {
responseText = await res.clone().text();
return finish();
}
2023-05-18 03:04:12 +09:00
2024-08-29 00:58:46 +09:00
if (
!res.ok ||
!res.headers
.get("content-type")
?.startsWith(EventStreamContentType) ||
res.status !== 200
) {
const responseTexts = [responseText];
let extraInfo = await res.clone().text();
try {
const resJson = await res.clone().json();
extraInfo = prettyObject(resJson);
} catch {}
2023-05-16 02:58:58 +09:00
2024-08-29 00:58:46 +09:00
if (res.status === 401) {
responseTexts.push(Locale.Error.Unauthorized);
}
2023-05-16 02:58:58 +09:00
2024-08-29 00:58:46 +09:00
if (extraInfo) {
responseTexts.push(extraInfo);
}
2023-05-16 02:58:58 +09:00
2024-08-29 00:58:46 +09:00
responseText = responseTexts.join("\n\n");
2023-05-18 03:04:12 +09:00
2024-08-29 00:58:46 +09:00
return finish();
2023-05-15 02:55:45 +09:00
}
2024-08-29 00:58:46 +09:00
},
onmessage(msg) {
if (msg.data === "[DONE]" || finished) {
return finish();
}
2024-08-29 00:58:46 +09:00
const text = msg.data;
try {
const json = JSON.parse(text);
const choices = json.choices as Array<{
delta: { content: string };
}>;
console.log("choices", choices);
const delta = choices[0]?.delta?.content;
const tool_calls = choices[0]?.delta?.tool_calls;
const textmoderation = json?.prompt_filter_results;
if (delta) {
remainText += delta;
}
if (tool_calls?.length > 0) {
const index = tool_calls[0]?.index;
const id = tool_calls[0]?.id;
const args = tool_calls[0]?.function?.arguments;
if (id) {
runTools.push({
id,
type: tool_calls[0]?.type,
function: {
name: tool_calls[0]?.function?.name,
arguments: args,
},
});
} else {
runTools[index]["function"]["arguments"] += args;
}
}
console.log("runTools", runTools);
if (
textmoderation &&
textmoderation.length > 0 &&
ServiceProvider.Azure
) {
const contentFilterResults =
textmoderation[0]?.content_filter_results;
console.log(
`[${ServiceProvider.Azure}] [Text Moderation] flagged categories result:`,
contentFilterResults,
);
}
} catch (e) {
console.error("[Request] parse error", text, msg);
}
},
onclose() {
finish();
},
onerror(e) {
options.onError?.(e);
throw e;
},
openWhenHidden: true,
});
}
chatApi(chatPath, requestPayload); // call fetchEventSource
2023-05-15 00:00:17 +09:00
} else {
const res = await fetch(chatPath, chatPayload);
clearTimeout(requestTimeoutId);
2023-05-15 00:00:17 +09:00
const resJson = await res.json();
2024-08-02 21:58:21 +09:00
const message = await this.extractMessage(resJson);
2023-05-15 00:00:17 +09:00
options.onFinish(message);
}
} catch (e) {
2023-08-01 11:16:36 +09:00
console.log("[Request] failed to make a chat request", e);
options.onError?.(e as Error);
2023-05-15 00:00:17 +09:00
}
}
async usage() {
const formatDate = (d: Date) =>
`${d.getFullYear()}-${(d.getMonth() + 1).toString().padStart(2, "0")}-${d
.getDate()
.toString()
.padStart(2, "0")}`;
const ONE_DAY = 1 * 24 * 60 * 60 * 1000;
const now = new Date();
const startOfMonth = new Date(now.getFullYear(), now.getMonth(), 1);
const startDate = formatDate(startOfMonth);
const endDate = formatDate(new Date(Date.now() + ONE_DAY));
const [used, subs] = await Promise.all([
fetch(
this.path(
`${OpenaiPath.UsagePath}?start_date=${startDate}&end_date=${endDate}`,
),
{
method: "GET",
headers: getHeaders(),
},
),
fetch(this.path(OpenaiPath.SubsPath), {
method: "GET",
headers: getHeaders(),
}),
]);
if (used.status === 401) {
throw new Error(Locale.Error.Unauthorized);
}
if (!used.ok || !subs.ok) {
throw new Error("Failed to query usage from openai");
}
const response = (await used.json()) as {
total_usage?: number;
error?: {
type: string;
message: string;
};
};
const total = (await subs.json()) as {
hard_limit_usd?: number;
};
if (response.error && response.error.type) {
throw Error(response.error.message);
}
if (response.total_usage) {
response.total_usage = Math.round(response.total_usage) / 100;
}
if (total.hard_limit_usd) {
total.hard_limit_usd = Math.round(total.hard_limit_usd * 100) / 100;
}
2023-05-15 00:00:17 +09:00
return {
used: response.total_usage,
total: total.hard_limit_usd,
2023-05-15 00:00:17 +09:00
} as LLMUsage;
}
async models(): Promise<LLMModel[]> {
2023-07-11 00:19:43 +09:00
if (this.disableListModels) {
return DEFAULT_MODELS.slice();
}
const res = await fetch(this.path(OpenaiPath.ListModelPath), {
method: "GET",
headers: {
...getHeaders(),
},
});
const resJson = (await res.json()) as OpenAIListModelResponse;
const chatModels = resJson.data?.filter((m) => m.id.startsWith("gpt-"));
console.log("[Models]", chatModels);
if (!chatModels) {
return [];
}
//由于目前 OpenAI 的 disableListModels 默认为 true所以当前实际不会运行到这场
let seq = 1000; //同 Constant.ts 中的排序保持一致
return chatModels.map((m) => ({
name: m.id,
available: true,
sorted: seq++,
2023-12-24 03:39:06 +09:00
provider: {
id: "openai",
providerName: "OpenAI",
providerType: "openai",
sorted: 1,
2023-12-24 03:39:06 +09:00
},
}));
}
2023-05-15 00:00:17 +09:00
}
export { OpenaiPath };