ChatGPT-Next-Web/app/client/platforms/openai.ts

284 lines
7.6 KiB
TypeScript
Raw Normal View History

import {
DEFAULT_API_HOST,
2023-07-10 15:19:43 +00:00
DEFAULT_MODELS,
OpenaiPath,
REQUEST_TIMEOUT_MS,
} from "@/app/constant";
2023-05-14 15:00:17 +00:00
import { useAccessStore, useAppConfig, useChatStore } from "@/app/store";
import { ChatOptions, getHeaders, LLMApi, LLMModel, LLMUsage } from "../api";
import Locale from "../../locales";
2023-05-17 00:50:50 +00:00
import {
EventStreamContentType,
fetchEventSource,
2023-05-20 11:58:12 +00:00
} from "@fortaine/fetch-event-source";
2023-05-15 17:58:58 +00:00
import { prettyObject } from "@/app/utils/format";
import { getClientConfig } from "@/app/config/client";
2023-05-14 15:00:17 +00:00
export interface OpenAIListModelResponse {
object: string;
data: Array<{
id: string;
object: string;
root: string;
}>;
}
2023-05-14 15:00:17 +00:00
export class ChatGPTApi implements LLMApi {
2023-07-10 15:19:43 +00:00
private disableListModels = true;
2023-05-14 15:00:17 +00:00
path(path: string): string {
2023-05-15 16:22:11 +00:00
let openaiUrl = useAccessStore.getState().openaiUrl;
const apiPath = "/api/openai";
if (openaiUrl.length === 0) {
const isApp = !!getClientConfig()?.isApp;
openaiUrl = isApp ? DEFAULT_API_HOST : apiPath;
}
2023-05-15 16:22:11 +00:00
if (openaiUrl.endsWith("/")) {
openaiUrl = openaiUrl.slice(0, openaiUrl.length - 1);
}
if (!openaiUrl.startsWith("http") && !openaiUrl.startsWith(apiPath)) {
openaiUrl = "https://" + openaiUrl;
}
2023-05-14 15:00:17 +00:00
return [openaiUrl, path].join("/");
}
extractMessage(res: any) {
return res.choices?.at(0)?.message?.content ?? "";
}
async chat(options: ChatOptions) {
const messages = options.messages.map((v) => ({
role: v.role,
content: v.content,
}));
const modelConfig = {
...useAppConfig.getState().modelConfig,
...useChatStore.getState().currentSession().mask.modelConfig,
...{
model: options.config.model,
2023-05-14 15:00:17 +00:00
},
};
const requestPayload = {
messages,
stream: options.config.stream,
model: modelConfig.model,
temperature: modelConfig.temperature,
presence_penalty: modelConfig.presence_penalty,
frequency_penalty: modelConfig.frequency_penalty,
2023-07-03 16:40:57 +00:00
top_p: modelConfig.top_p,
2023-11-09 12:45:25 +00:00
// 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.
2023-05-14 15:00:17 +00:00
};
console.log("[Request] openai payload: ", requestPayload);
const shouldStream = !!options.config.stream;
const controller = new AbortController();
options.onController?.(controller);
2023-05-14 15:00:17 +00:00
try {
const chatPath = this.path(OpenaiPath.ChatPath);
2023-05-14 15:00:17 +00:00
const chatPayload = {
method: "POST",
body: JSON.stringify(requestPayload),
signal: controller.signal,
headers: getHeaders(),
2023-05-14 15:00:17 +00:00
};
// make a fetch request
const requestTimeoutId = setTimeout(
2023-05-14 15:00:17 +00:00
() => controller.abort(),
REQUEST_TIMEOUT_MS,
);
2023-05-14 15:00:17 +00:00
if (shouldStream) {
let responseText = "";
let finished = false;
2023-05-14 15:00:17 +00:00
const finish = () => {
if (!finished) {
options.onFinish(responseText);
finished = true;
}
};
2023-05-14 15:00:17 +00:00
2023-05-15 17:58:58 +00:00
controller.signal.onabort = finish;
fetchEventSource(chatPath, {
...chatPayload,
async onopen(res) {
clearTimeout(requestTimeoutId);
2023-05-17 18:04:12 +00:00
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-17 00:50:50 +00:00
if (
!res.ok ||
!res.headers
.get("content-type")
?.startsWith(EventStreamContentType) ||
res.status !== 200
2023-05-17 00:50:50 +00:00
) {
2023-05-17 18:04:12 +00:00
const responseTexts = [responseText];
let extraInfo = await res.clone().text();
2023-05-15 17:58:58 +00:00
try {
2023-05-17 18:04:12 +00:00
const resJson = await res.clone().json();
extraInfo = prettyObject(resJson);
2023-05-15 17:58:58 +00:00
} catch {}
if (res.status === 401) {
2023-05-17 18:04:12 +00:00
responseTexts.push(Locale.Error.Unauthorized);
}
2023-05-15 17:58:58 +00:00
2023-05-17 18:04:12 +00:00
if (extraInfo) {
responseTexts.push(extraInfo);
2023-05-15 17:58:58 +00:00
}
2023-05-17 18:04:12 +00:00
responseText = responseTexts.join("\n\n");
return finish();
}
},
onmessage(msg) {
2023-05-17 18:09:05 +00:00
if (msg.data === "[DONE]" || finished) {
return finish();
2023-05-14 15:00:17 +00:00
}
const text = msg.data;
2023-05-14 17:55:45 +00:00
try {
const json = JSON.parse(text);
const delta = json.choices[0].delta.content;
if (delta) {
responseText += delta;
options.onUpdate?.(responseText, delta);
}
} catch (e) {
console.error("[Request] parse error", text, msg);
2023-05-14 15:00:17 +00:00
}
},
onclose() {
finish();
},
onerror(e) {
options.onError?.(e);
2023-05-20 11:58:12 +00:00
throw e;
},
2023-05-17 09:20:17 +00:00
openWhenHidden: true,
});
2023-05-14 15:00:17 +00:00
} else {
const res = await fetch(chatPath, chatPayload);
clearTimeout(requestTimeoutId);
2023-05-14 15:00:17 +00:00
const resJson = await res.json();
const message = this.extractMessage(resJson);
options.onFinish(message);
}
} catch (e) {
2023-08-01 02:16:36 +00:00
console.log("[Request] failed to make a chat request", e);
options.onError?.(e as Error);
2023-05-14 15:00:17 +00: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-14 15:00:17 +00:00
return {
used: response.total_usage,
total: total.hard_limit_usd,
2023-05-14 15:00:17 +00:00
} as LLMUsage;
}
async models(): Promise<LLMModel[]> {
2023-07-10 15:19:43 +00: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 [];
}
return chatModels.map((m) => ({
name: m.id,
available: true,
}));
}
2023-05-14 15:00:17 +00:00
}
export { OpenaiPath };