Merge pull request #4936 from ConnectAI-E/feat-baidu
feat: support baidu model
This commit is contained in:
commit
47ea383ddd
12
README.md
12
README.md
|
@ -213,6 +213,18 @@ anthropic claude Api version.
|
||||||
|
|
||||||
anthropic claude Api Url.
|
anthropic claude Api Url.
|
||||||
|
|
||||||
|
### `BAIDU_API_KEY` (optional)
|
||||||
|
|
||||||
|
Baidu Api Key.
|
||||||
|
|
||||||
|
### `BAIDU_SECRET_KEY` (optional)
|
||||||
|
|
||||||
|
Baidu Secret Key.
|
||||||
|
|
||||||
|
### `BAIDU_URL` (optional)
|
||||||
|
|
||||||
|
Baidu Api Url.
|
||||||
|
|
||||||
### `HIDE_USER_API_KEY` (optional)
|
### `HIDE_USER_API_KEY` (optional)
|
||||||
|
|
||||||
> Default: Empty
|
> Default: Empty
|
||||||
|
|
12
README_CN.md
12
README_CN.md
|
@ -127,6 +127,18 @@ anthropic claude Api version.
|
||||||
|
|
||||||
anthropic claude Api Url.
|
anthropic claude Api Url.
|
||||||
|
|
||||||
|
### `BAIDU_API_KEY` (可选)
|
||||||
|
|
||||||
|
Baidu Api Key.
|
||||||
|
|
||||||
|
### `BAIDU_SECRET_KEY` (可选)
|
||||||
|
|
||||||
|
Baidu Secret Key.
|
||||||
|
|
||||||
|
### `BAIDU_URL` (可选)
|
||||||
|
|
||||||
|
Baidu Api Url.
|
||||||
|
|
||||||
### `HIDE_USER_API_KEY` (可选)
|
### `HIDE_USER_API_KEY` (可选)
|
||||||
|
|
||||||
如果你不想让用户自行填入 API Key,将此环境变量设置为 1 即可。
|
如果你不想让用户自行填入 API Key,将此环境变量设置为 1 即可。
|
||||||
|
|
|
@ -73,6 +73,9 @@ export function auth(req: NextRequest, modelProvider: ModelProvider) {
|
||||||
case ModelProvider.Claude:
|
case ModelProvider.Claude:
|
||||||
systemApiKey = serverConfig.anthropicApiKey;
|
systemApiKey = serverConfig.anthropicApiKey;
|
||||||
break;
|
break;
|
||||||
|
case ModelProvider.Ernie:
|
||||||
|
systemApiKey = serverConfig.baiduApiKey;
|
||||||
|
break;
|
||||||
case ModelProvider.GPT:
|
case ModelProvider.GPT:
|
||||||
default:
|
default:
|
||||||
if (req.nextUrl.pathname.includes("azure/deployments")) {
|
if (req.nextUrl.pathname.includes("azure/deployments")) {
|
||||||
|
|
|
@ -0,0 +1,169 @@
|
||||||
|
import { getServerSideConfig } from "@/app/config/server";
|
||||||
|
import {
|
||||||
|
BAIDU_BASE_URL,
|
||||||
|
ApiPath,
|
||||||
|
ModelProvider,
|
||||||
|
BAIDU_OATUH_URL,
|
||||||
|
ServiceProvider,
|
||||||
|
} from "@/app/constant";
|
||||||
|
import { prettyObject } from "@/app/utils/format";
|
||||||
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
|
import { auth } from "@/app/api/auth";
|
||||||
|
import { isModelAvailableInServer } from "@/app/utils/model";
|
||||||
|
import { getAccessToken } from "@/app/utils/baidu";
|
||||||
|
|
||||||
|
const serverConfig = getServerSideConfig();
|
||||||
|
|
||||||
|
async function handle(
|
||||||
|
req: NextRequest,
|
||||||
|
{ params }: { params: { path: string[] } },
|
||||||
|
) {
|
||||||
|
console.log("[Baidu Route] params ", params);
|
||||||
|
|
||||||
|
if (req.method === "OPTIONS") {
|
||||||
|
return NextResponse.json({ body: "OK" }, { status: 200 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const authResult = auth(req, ModelProvider.Ernie);
|
||||||
|
if (authResult.error) {
|
||||||
|
return NextResponse.json(authResult, {
|
||||||
|
status: 401,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!serverConfig.baiduApiKey || !serverConfig.baiduSecretKey) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{
|
||||||
|
error: true,
|
||||||
|
message: `missing BAIDU_API_KEY or BAIDU_SECRET_KEY in server env vars`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
status: 401,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await request(req);
|
||||||
|
return response;
|
||||||
|
} catch (e) {
|
||||||
|
console.error("[Baidu] ", e);
|
||||||
|
return NextResponse.json(prettyObject(e));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const GET = handle;
|
||||||
|
export const POST = handle;
|
||||||
|
|
||||||
|
export const runtime = "edge";
|
||||||
|
export const preferredRegion = [
|
||||||
|
"arn1",
|
||||||
|
"bom1",
|
||||||
|
"cdg1",
|
||||||
|
"cle1",
|
||||||
|
"cpt1",
|
||||||
|
"dub1",
|
||||||
|
"fra1",
|
||||||
|
"gru1",
|
||||||
|
"hnd1",
|
||||||
|
"iad1",
|
||||||
|
"icn1",
|
||||||
|
"kix1",
|
||||||
|
"lhr1",
|
||||||
|
"pdx1",
|
||||||
|
"sfo1",
|
||||||
|
"sin1",
|
||||||
|
"syd1",
|
||||||
|
];
|
||||||
|
|
||||||
|
async function request(req: NextRequest) {
|
||||||
|
const controller = new AbortController();
|
||||||
|
|
||||||
|
let path = `${req.nextUrl.pathname}`.replaceAll(ApiPath.Baidu, "");
|
||||||
|
|
||||||
|
let baseUrl = serverConfig.baiduUrl || BAIDU_BASE_URL;
|
||||||
|
|
||||||
|
if (!baseUrl.startsWith("http")) {
|
||||||
|
baseUrl = `https://${baseUrl}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (baseUrl.endsWith("/")) {
|
||||||
|
baseUrl = baseUrl.slice(0, -1);
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log("[Proxy] ", path);
|
||||||
|
console.log("[Base Url]", baseUrl);
|
||||||
|
|
||||||
|
const timeoutId = setTimeout(
|
||||||
|
() => {
|
||||||
|
controller.abort();
|
||||||
|
},
|
||||||
|
10 * 60 * 1000,
|
||||||
|
);
|
||||||
|
|
||||||
|
const { access_token } = await getAccessToken(
|
||||||
|
serverConfig.baiduApiKey as string,
|
||||||
|
serverConfig.baiduSecretKey as string,
|
||||||
|
);
|
||||||
|
const fetchUrl = `${baseUrl}${path}?access_token=${access_token}`;
|
||||||
|
|
||||||
|
const fetchOptions: RequestInit = {
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
},
|
||||||
|
method: req.method,
|
||||||
|
body: req.body,
|
||||||
|
redirect: "manual",
|
||||||
|
// @ts-ignore
|
||||||
|
duplex: "half",
|
||||||
|
signal: controller.signal,
|
||||||
|
};
|
||||||
|
|
||||||
|
// #1815 try to refuse some request to some models
|
||||||
|
if (serverConfig.customModels && req.body) {
|
||||||
|
try {
|
||||||
|
const clonedBody = await req.text();
|
||||||
|
fetchOptions.body = clonedBody;
|
||||||
|
|
||||||
|
const jsonBody = JSON.parse(clonedBody) as { model?: string };
|
||||||
|
|
||||||
|
// not undefined and is false
|
||||||
|
if (
|
||||||
|
isModelAvailableInServer(
|
||||||
|
serverConfig.customModels,
|
||||||
|
jsonBody?.model as string,
|
||||||
|
ServiceProvider.Baidu as string,
|
||||||
|
)
|
||||||
|
) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{
|
||||||
|
error: true,
|
||||||
|
message: `you are not allowed to use ${jsonBody?.model} model`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
status: 403,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
console.error(`[Baidu] filter`, e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const res = await fetch(fetchUrl, fetchOptions);
|
||||||
|
|
||||||
|
// to prevent browser prompt for credentials
|
||||||
|
const newHeaders = new Headers(res.headers);
|
||||||
|
newHeaders.delete("www-authenticate");
|
||||||
|
// to disable nginx buffering
|
||||||
|
newHeaders.set("X-Accel-Buffering", "no");
|
||||||
|
|
||||||
|
return new Response(res.body, {
|
||||||
|
status: res.status,
|
||||||
|
statusText: res.statusText,
|
||||||
|
headers: newHeaders,
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
clearTimeout(timeoutId);
|
||||||
|
}
|
||||||
|
}
|
|
@ -70,7 +70,7 @@ export async function requestOpenai(req: NextRequest) {
|
||||||
// Forward compatibility:
|
// Forward compatibility:
|
||||||
// if display_name(deployment_name) not set, and '{deploy-id}' in AZURE_URL
|
// if display_name(deployment_name) not set, and '{deploy-id}' in AZURE_URL
|
||||||
// then using default '{deploy-id}'
|
// then using default '{deploy-id}'
|
||||||
if (serverConfig.customModels) {
|
if (serverConfig.customModels && serverConfig.azureUrl) {
|
||||||
const modelName = path.split("/")[1];
|
const modelName = path.split("/")[1];
|
||||||
let realDeployName = "";
|
let realDeployName = "";
|
||||||
serverConfig.customModels
|
serverConfig.customModels
|
||||||
|
@ -80,7 +80,9 @@ export async function requestOpenai(req: NextRequest) {
|
||||||
const [fullName, displayName] = m.split("=");
|
const [fullName, displayName] = m.split("=");
|
||||||
const [_, providerName] = fullName.split("@");
|
const [_, providerName] = fullName.split("@");
|
||||||
if (providerName === "azure" && !displayName) {
|
if (providerName === "azure" && !displayName) {
|
||||||
const [_, deployId] = serverConfig.azureUrl.split("deployments/");
|
const [_, deployId] = (serverConfig?.azureUrl ?? "").split(
|
||||||
|
"deployments/",
|
||||||
|
);
|
||||||
if (deployId) {
|
if (deployId) {
|
||||||
realDeployName = deployId;
|
realDeployName = deployId;
|
||||||
}
|
}
|
||||||
|
|
|
@ -9,6 +9,8 @@ import { ChatMessage, ModelType, useAccessStore, useChatStore } from "../store";
|
||||||
import { ChatGPTApi } from "./platforms/openai";
|
import { ChatGPTApi } from "./platforms/openai";
|
||||||
import { GeminiProApi } from "./platforms/google";
|
import { GeminiProApi } from "./platforms/google";
|
||||||
import { ClaudeApi } from "./platforms/anthropic";
|
import { ClaudeApi } from "./platforms/anthropic";
|
||||||
|
import { ErnieApi } from "./platforms/baidu";
|
||||||
|
|
||||||
export const ROLES = ["system", "user", "assistant"] as const;
|
export const ROLES = ["system", "user", "assistant"] as const;
|
||||||
export type MessageRole = (typeof ROLES)[number];
|
export type MessageRole = (typeof ROLES)[number];
|
||||||
|
|
||||||
|
@ -104,6 +106,9 @@ export class ClientApi {
|
||||||
case ModelProvider.Claude:
|
case ModelProvider.Claude:
|
||||||
this.llm = new ClaudeApi();
|
this.llm = new ClaudeApi();
|
||||||
break;
|
break;
|
||||||
|
case ModelProvider.Ernie:
|
||||||
|
this.llm = new ErnieApi();
|
||||||
|
break;
|
||||||
default:
|
default:
|
||||||
this.llm = new ChatGPTApi();
|
this.llm = new ChatGPTApi();
|
||||||
}
|
}
|
||||||
|
@ -220,6 +225,8 @@ export function getClientApi(provider: ServiceProvider): ClientApi {
|
||||||
return new ClientApi(ModelProvider.GeminiPro);
|
return new ClientApi(ModelProvider.GeminiPro);
|
||||||
case ServiceProvider.Anthropic:
|
case ServiceProvider.Anthropic:
|
||||||
return new ClientApi(ModelProvider.Claude);
|
return new ClientApi(ModelProvider.Claude);
|
||||||
|
case ServiceProvider.Baidu:
|
||||||
|
return new ClientApi(ModelProvider.Ernie);
|
||||||
default:
|
default:
|
||||||
return new ClientApi(ModelProvider.GPT);
|
return new ClientApi(ModelProvider.GPT);
|
||||||
}
|
}
|
||||||
|
|
|
@ -0,0 +1,273 @@
|
||||||
|
"use client";
|
||||||
|
import {
|
||||||
|
ApiPath,
|
||||||
|
Baidu,
|
||||||
|
BAIDU_BASE_URL,
|
||||||
|
REQUEST_TIMEOUT_MS,
|
||||||
|
} from "@/app/constant";
|
||||||
|
import { useAccessStore, useAppConfig, useChatStore } from "@/app/store";
|
||||||
|
import { getAccessToken } from "@/app/utils/baidu";
|
||||||
|
|
||||||
|
import {
|
||||||
|
ChatOptions,
|
||||||
|
getHeaders,
|
||||||
|
LLMApi,
|
||||||
|
LLMModel,
|
||||||
|
MultimodalContent,
|
||||||
|
} from "../api";
|
||||||
|
import Locale from "../../locales";
|
||||||
|
import {
|
||||||
|
EventStreamContentType,
|
||||||
|
fetchEventSource,
|
||||||
|
} from "@fortaine/fetch-event-source";
|
||||||
|
import { prettyObject } from "@/app/utils/format";
|
||||||
|
import { getClientConfig } from "@/app/config/client";
|
||||||
|
import { getMessageTextContent } from "@/app/utils";
|
||||||
|
|
||||||
|
export interface OpenAIListModelResponse {
|
||||||
|
object: string;
|
||||||
|
data: Array<{
|
||||||
|
id: string;
|
||||||
|
object: string;
|
||||||
|
root: string;
|
||||||
|
}>;
|
||||||
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class ErnieApi implements LLMApi {
|
||||||
|
path(path: string): string {
|
||||||
|
const accessStore = useAccessStore.getState();
|
||||||
|
|
||||||
|
let baseUrl = "";
|
||||||
|
|
||||||
|
if (accessStore.useCustomConfig) {
|
||||||
|
baseUrl = accessStore.baiduUrl;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (baseUrl.length === 0) {
|
||||||
|
const isApp = !!getClientConfig()?.isApp;
|
||||||
|
// do not use proxy for baidubce api
|
||||||
|
baseUrl = isApp ? BAIDU_BASE_URL : ApiPath.Baidu;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (baseUrl.endsWith("/")) {
|
||||||
|
baseUrl = baseUrl.slice(0, baseUrl.length - 1);
|
||||||
|
}
|
||||||
|
if (!baseUrl.startsWith("http") && !baseUrl.startsWith(ApiPath.Baidu)) {
|
||||||
|
baseUrl = "https://" + baseUrl;
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log("[Proxy Endpoint] ", baseUrl, path);
|
||||||
|
|
||||||
|
return [baseUrl, path].join("/");
|
||||||
|
}
|
||||||
|
|
||||||
|
async chat(options: ChatOptions) {
|
||||||
|
const messages = options.messages.map((v) => ({
|
||||||
|
role: v.role,
|
||||||
|
content: getMessageTextContent(v),
|
||||||
|
}));
|
||||||
|
|
||||||
|
// "error_code": 336006, "error_msg": "the length of messages must be an odd number",
|
||||||
|
if (messages.length % 2 === 0) {
|
||||||
|
messages.unshift({
|
||||||
|
role: "user",
|
||||||
|
content: " ",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const modelConfig = {
|
||||||
|
...useAppConfig.getState().modelConfig,
|
||||||
|
...useChatStore.getState().currentSession().mask.modelConfig,
|
||||||
|
...{
|
||||||
|
model: options.config.model,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
const shouldStream = !!options.config.stream;
|
||||||
|
const requestPayload: RequestPayload = {
|
||||||
|
messages,
|
||||||
|
stream: shouldStream,
|
||||||
|
model: modelConfig.model,
|
||||||
|
temperature: modelConfig.temperature,
|
||||||
|
presence_penalty: modelConfig.presence_penalty,
|
||||||
|
frequency_penalty: modelConfig.frequency_penalty,
|
||||||
|
top_p: modelConfig.top_p,
|
||||||
|
};
|
||||||
|
|
||||||
|
console.log("[Request] Baidu payload: ", requestPayload);
|
||||||
|
|
||||||
|
const controller = new AbortController();
|
||||||
|
options.onController?.(controller);
|
||||||
|
|
||||||
|
try {
|
||||||
|
let chatPath = this.path(Baidu.ChatPath(modelConfig.model));
|
||||||
|
|
||||||
|
// getAccessToken can not run in browser, because cors error
|
||||||
|
if (!!getClientConfig()?.isApp) {
|
||||||
|
const accessStore = useAccessStore.getState();
|
||||||
|
if (accessStore.useCustomConfig) {
|
||||||
|
if (accessStore.isValidBaidu()) {
|
||||||
|
const { access_token } = await getAccessToken(
|
||||||
|
accessStore.baiduApiKey,
|
||||||
|
accessStore.baiduSecretKey,
|
||||||
|
);
|
||||||
|
chatPath = `${chatPath}${
|
||||||
|
chatPath.includes("?") ? "&" : "?"
|
||||||
|
}access_token=${access_token}`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
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 = "";
|
||||||
|
let finished = false;
|
||||||
|
|
||||||
|
// 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) {
|
||||||
|
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();
|
||||||
|
|
||||||
|
const finish = () => {
|
||||||
|
if (!finished) {
|
||||||
|
finished = true;
|
||||||
|
options.onFinish(responseText + remainText);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
controller.signal.onabort = finish;
|
||||||
|
|
||||||
|
fetchEventSource(chatPath, {
|
||||||
|
...chatPayload,
|
||||||
|
async onopen(res) {
|
||||||
|
clearTimeout(requestTimeoutId);
|
||||||
|
const contentType = res.headers.get("content-type");
|
||||||
|
console.log("[Baidu] request response content type: ", contentType);
|
||||||
|
|
||||||
|
if (contentType?.startsWith("text/plain")) {
|
||||||
|
responseText = await res.clone().text();
|
||||||
|
return finish();
|
||||||
|
}
|
||||||
|
|
||||||
|
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 {}
|
||||||
|
|
||||||
|
if (res.status === 401) {
|
||||||
|
responseTexts.push(Locale.Error.Unauthorized);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (extraInfo) {
|
||||||
|
responseTexts.push(extraInfo);
|
||||||
|
}
|
||||||
|
|
||||||
|
responseText = responseTexts.join("\n\n");
|
||||||
|
|
||||||
|
return finish();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
onmessage(msg) {
|
||||||
|
if (msg.data === "[DONE]" || finished) {
|
||||||
|
return finish();
|
||||||
|
}
|
||||||
|
const text = msg.data;
|
||||||
|
try {
|
||||||
|
const json = JSON.parse(text);
|
||||||
|
const delta = json?.result;
|
||||||
|
if (delta) {
|
||||||
|
remainText += delta;
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
console.error("[Request] parse error", text, msg);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
onclose() {
|
||||||
|
finish();
|
||||||
|
},
|
||||||
|
onerror(e) {
|
||||||
|
options.onError?.(e);
|
||||||
|
throw e;
|
||||||
|
},
|
||||||
|
openWhenHidden: true,
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
const res = await fetch(chatPath, chatPayload);
|
||||||
|
clearTimeout(requestTimeoutId);
|
||||||
|
|
||||||
|
const resJson = await res.json();
|
||||||
|
const message = resJson?.result;
|
||||||
|
options.onFinish(message);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
console.log("[Request] failed to make a chat request", e);
|
||||||
|
options.onError?.(e as Error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
async usage() {
|
||||||
|
return {
|
||||||
|
used: 0,
|
||||||
|
total: 0,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async models(): Promise<LLMModel[]> {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
export { Baidu };
|
|
@ -53,6 +53,7 @@ import Link from "next/link";
|
||||||
import {
|
import {
|
||||||
Anthropic,
|
Anthropic,
|
||||||
Azure,
|
Azure,
|
||||||
|
Baidu,
|
||||||
Google,
|
Google,
|
||||||
OPENAI_BASE_URL,
|
OPENAI_BASE_URL,
|
||||||
Path,
|
Path,
|
||||||
|
@ -1187,6 +1188,67 @@ export function Settings() {
|
||||||
</ListItem>
|
</ListItem>
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
|
{accessStore.provider === ServiceProvider.Baidu && (
|
||||||
|
<>
|
||||||
|
<ListItem
|
||||||
|
title={Locale.Settings.Access.Baidu.Endpoint.Title}
|
||||||
|
subTitle={
|
||||||
|
Locale.Settings.Access.Anthropic.Endpoint.SubTitle +
|
||||||
|
Baidu.ExampleEndpoint
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={accessStore.baiduUrl}
|
||||||
|
placeholder={Baidu.ExampleEndpoint}
|
||||||
|
onChange={(e) =>
|
||||||
|
accessStore.update(
|
||||||
|
(access) =>
|
||||||
|
(access.baiduUrl = e.currentTarget.value),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
></input>
|
||||||
|
</ListItem>
|
||||||
|
<ListItem
|
||||||
|
title={Locale.Settings.Access.Baidu.ApiKey.Title}
|
||||||
|
subTitle={Locale.Settings.Access.Baidu.ApiKey.SubTitle}
|
||||||
|
>
|
||||||
|
<PasswordInput
|
||||||
|
value={accessStore.baiduApiKey}
|
||||||
|
type="text"
|
||||||
|
placeholder={
|
||||||
|
Locale.Settings.Access.Baidu.ApiKey.Placeholder
|
||||||
|
}
|
||||||
|
onChange={(e) => {
|
||||||
|
accessStore.update(
|
||||||
|
(access) =>
|
||||||
|
(access.baiduApiKey = e.currentTarget.value),
|
||||||
|
);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</ListItem>
|
||||||
|
<ListItem
|
||||||
|
title={Locale.Settings.Access.Baidu.SecretKey.Title}
|
||||||
|
subTitle={
|
||||||
|
Locale.Settings.Access.Baidu.SecretKey.SubTitle
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<PasswordInput
|
||||||
|
value={accessStore.baiduSecretKey}
|
||||||
|
type="text"
|
||||||
|
placeholder={
|
||||||
|
Locale.Settings.Access.Baidu.SecretKey.Placeholder
|
||||||
|
}
|
||||||
|
onChange={(e) => {
|
||||||
|
accessStore.update(
|
||||||
|
(access) =>
|
||||||
|
(access.baiduSecretKey = e.currentTarget.value),
|
||||||
|
);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</ListItem>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
</>
|
</>
|
||||||
|
|
|
@ -35,6 +35,16 @@ declare global {
|
||||||
// google tag manager
|
// google tag manager
|
||||||
GTM_ID?: string;
|
GTM_ID?: string;
|
||||||
|
|
||||||
|
// anthropic only
|
||||||
|
ANTHROPIC_URL?: string;
|
||||||
|
ANTHROPIC_API_KEY?: string;
|
||||||
|
ANTHROPIC_API_VERSION?: string;
|
||||||
|
|
||||||
|
// baidu only
|
||||||
|
BAIDU_URL?: string;
|
||||||
|
BAIDU_API_KEY?: string;
|
||||||
|
BAIDU_SECRET_KEY?: string;
|
||||||
|
|
||||||
// custom template for preprocessing user input
|
// custom template for preprocessing user input
|
||||||
DEFAULT_INPUT_TEMPLATE?: string;
|
DEFAULT_INPUT_TEMPLATE?: string;
|
||||||
}
|
}
|
||||||
|
@ -92,7 +102,7 @@ export const getServerSideConfig = () => {
|
||||||
const isAzure = !!process.env.AZURE_URL;
|
const isAzure = !!process.env.AZURE_URL;
|
||||||
const isGoogle = !!process.env.GOOGLE_API_KEY;
|
const isGoogle = !!process.env.GOOGLE_API_KEY;
|
||||||
const isAnthropic = !!process.env.ANTHROPIC_API_KEY;
|
const isAnthropic = !!process.env.ANTHROPIC_API_KEY;
|
||||||
|
const isBaidu = !!process.env.BAIDU_API_KEY;
|
||||||
// const apiKeyEnvVar = process.env.OPENAI_API_KEY ?? "";
|
// const apiKeyEnvVar = process.env.OPENAI_API_KEY ?? "";
|
||||||
// const apiKeys = apiKeyEnvVar.split(",").map((v) => v.trim());
|
// const apiKeys = apiKeyEnvVar.split(",").map((v) => v.trim());
|
||||||
// const randomIndex = Math.floor(Math.random() * apiKeys.length);
|
// const randomIndex = Math.floor(Math.random() * apiKeys.length);
|
||||||
|
@ -124,6 +134,11 @@ export const getServerSideConfig = () => {
|
||||||
anthropicApiVersion: process.env.ANTHROPIC_API_VERSION,
|
anthropicApiVersion: process.env.ANTHROPIC_API_VERSION,
|
||||||
anthropicUrl: process.env.ANTHROPIC_URL,
|
anthropicUrl: process.env.ANTHROPIC_URL,
|
||||||
|
|
||||||
|
isBaidu,
|
||||||
|
baiduUrl: process.env.BAIDU_URL,
|
||||||
|
baiduApiKey: getApiKey(process.env.BAIDU_API_KEY),
|
||||||
|
baiduSecretKey: process.env.BAIDU_SECRET_KEY,
|
||||||
|
|
||||||
gtmId: process.env.GTM_ID,
|
gtmId: process.env.GTM_ID,
|
||||||
|
|
||||||
needCode: ACCESS_CODES.size > 0,
|
needCode: ACCESS_CODES.size > 0,
|
||||||
|
|
|
@ -14,6 +14,10 @@ export const ANTHROPIC_BASE_URL = "https://api.anthropic.com";
|
||||||
|
|
||||||
export const GEMINI_BASE_URL = "https://generativelanguage.googleapis.com/";
|
export const GEMINI_BASE_URL = "https://generativelanguage.googleapis.com/";
|
||||||
|
|
||||||
|
export const BAIDU_BASE_URL = "https://aip.baidubce.com";
|
||||||
|
|
||||||
|
export const BAIDU_OATUH_URL = `${BAIDU_BASE_URL}/oauth/2.0/token`;
|
||||||
|
|
||||||
export enum Path {
|
export enum Path {
|
||||||
Home = "/",
|
Home = "/",
|
||||||
Chat = "/chat",
|
Chat = "/chat",
|
||||||
|
@ -28,6 +32,7 @@ export enum ApiPath {
|
||||||
Azure = "/api/azure",
|
Azure = "/api/azure",
|
||||||
OpenAI = "/api/openai",
|
OpenAI = "/api/openai",
|
||||||
Anthropic = "/api/anthropic",
|
Anthropic = "/api/anthropic",
|
||||||
|
Baidu = "/api/baidu",
|
||||||
}
|
}
|
||||||
|
|
||||||
export enum SlotID {
|
export enum SlotID {
|
||||||
|
@ -71,12 +76,14 @@ export enum ServiceProvider {
|
||||||
Azure = "Azure",
|
Azure = "Azure",
|
||||||
Google = "Google",
|
Google = "Google",
|
||||||
Anthropic = "Anthropic",
|
Anthropic = "Anthropic",
|
||||||
|
Baidu = "Baidu",
|
||||||
}
|
}
|
||||||
|
|
||||||
export enum ModelProvider {
|
export enum ModelProvider {
|
||||||
GPT = "GPT",
|
GPT = "GPT",
|
||||||
GeminiPro = "GeminiPro",
|
GeminiPro = "GeminiPro",
|
||||||
Claude = "Claude",
|
Claude = "Claude",
|
||||||
|
Ernie = "Ernie",
|
||||||
}
|
}
|
||||||
|
|
||||||
export const Anthropic = {
|
export const Anthropic = {
|
||||||
|
@ -104,6 +111,23 @@ export const Google = {
|
||||||
ChatPath: (modelName: string) => `v1beta/models/${modelName}:generateContent`,
|
ChatPath: (modelName: string) => `v1beta/models/${modelName}:generateContent`,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export const Baidu = {
|
||||||
|
ExampleEndpoint: BAIDU_BASE_URL,
|
||||||
|
ChatPath: (modelName: string) => {
|
||||||
|
let endpoint = modelName;
|
||||||
|
if (modelName === "ernie-4.0-8k") {
|
||||||
|
endpoint = "completions_pro";
|
||||||
|
}
|
||||||
|
if (modelName === "ernie-4.0-8k-preview-0518") {
|
||||||
|
endpoint = "completions_adv_pro";
|
||||||
|
}
|
||||||
|
if (modelName === "ernie-3.5-8k") {
|
||||||
|
endpoint = "completions";
|
||||||
|
}
|
||||||
|
return `rpc/2.0/ai_custom/v1/wenxinworkshop/chat/${endpoint}`;
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
export const DEFAULT_INPUT_TEMPLATE = `{{input}}`; // input / time / model / lang
|
export const DEFAULT_INPUT_TEMPLATE = `{{input}}`; // input / time / model / lang
|
||||||
// export const DEFAULT_SYSTEM_TEMPLATE = `
|
// export const DEFAULT_SYSTEM_TEMPLATE = `
|
||||||
// You are ChatGPT, a large language model trained by {{ServiceProvider}}.
|
// You are ChatGPT, a large language model trained by {{ServiceProvider}}.
|
||||||
|
@ -173,6 +197,16 @@ const anthropicModels = [
|
||||||
"claude-3-5-sonnet-20240620",
|
"claude-3-5-sonnet-20240620",
|
||||||
];
|
];
|
||||||
|
|
||||||
|
const baiduModels = [
|
||||||
|
"ernie-4.0-turbo-8k",
|
||||||
|
"ernie-4.0-8k",
|
||||||
|
"ernie-4.0-8k-preview",
|
||||||
|
"ernie-4.0-8k-preview-0518",
|
||||||
|
"ernie-4.0-8k-latest",
|
||||||
|
"ernie-3.5-8k",
|
||||||
|
"ernie-3.5-8k-0205",
|
||||||
|
];
|
||||||
|
|
||||||
export const DEFAULT_MODELS = [
|
export const DEFAULT_MODELS = [
|
||||||
...openaiModels.map((name) => ({
|
...openaiModels.map((name) => ({
|
||||||
name,
|
name,
|
||||||
|
@ -210,6 +244,15 @@ export const DEFAULT_MODELS = [
|
||||||
providerType: "anthropic",
|
providerType: "anthropic",
|
||||||
},
|
},
|
||||||
})),
|
})),
|
||||||
|
...baiduModels.map((name) => ({
|
||||||
|
name,
|
||||||
|
available: true,
|
||||||
|
provider: {
|
||||||
|
id: "baidu",
|
||||||
|
providerName: "Baidu",
|
||||||
|
providerType: "baidu",
|
||||||
|
},
|
||||||
|
})),
|
||||||
] as const;
|
] as const;
|
||||||
|
|
||||||
export const CHAT_PAGE_SIZE = 15;
|
export const CHAT_PAGE_SIZE = 15;
|
||||||
|
|
|
@ -347,6 +347,22 @@ const cn = {
|
||||||
SubTitle: "选择一个特定的 API 版本",
|
SubTitle: "选择一个特定的 API 版本",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
Baidu: {
|
||||||
|
ApiKey: {
|
||||||
|
Title: "接口密钥",
|
||||||
|
SubTitle: "使用自定义 Baidu API Key",
|
||||||
|
Placeholder: "Baidu API Key",
|
||||||
|
},
|
||||||
|
SecretKey: {
|
||||||
|
Title: "接口密钥",
|
||||||
|
SubTitle: "使用自定义 Baidu Secret Key",
|
||||||
|
Placeholder: "Baidu Secret Key",
|
||||||
|
},
|
||||||
|
Endpoint: {
|
||||||
|
Title: "接口地址",
|
||||||
|
SubTitle: "样例:",
|
||||||
|
},
|
||||||
|
},
|
||||||
CustomModel: {
|
CustomModel: {
|
||||||
Title: "自定义模型名",
|
Title: "自定义模型名",
|
||||||
SubTitle: "增加自定义模型可选项,使用英文逗号隔开",
|
SubTitle: "增加自定义模型可选项,使用英文逗号隔开",
|
||||||
|
|
|
@ -334,6 +334,22 @@ const en: LocaleType = {
|
||||||
SubTitle: "Select and input a specific API version",
|
SubTitle: "Select and input a specific API version",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
Baidu: {
|
||||||
|
ApiKey: {
|
||||||
|
Title: "Baidu API Key",
|
||||||
|
SubTitle: "Use a custom Baidu API Key",
|
||||||
|
Placeholder: "Baidu API Key",
|
||||||
|
},
|
||||||
|
SecretKey: {
|
||||||
|
Title: "Baidu Secret Key",
|
||||||
|
SubTitle: "Use a custom Baidu Secret Key",
|
||||||
|
Placeholder: "Baidu Secret Key",
|
||||||
|
},
|
||||||
|
Endpoint: {
|
||||||
|
Title: "Endpoint Address",
|
||||||
|
SubTitle: "Example:",
|
||||||
|
},
|
||||||
|
},
|
||||||
CustomModel: {
|
CustomModel: {
|
||||||
Title: "Custom Models",
|
Title: "Custom Models",
|
||||||
SubTitle: "Custom model options, seperated by comma",
|
SubTitle: "Custom model options, seperated by comma",
|
||||||
|
|
|
@ -47,6 +47,11 @@ const DEFAULT_ACCESS_STATE = {
|
||||||
anthropicApiVersion: "2023-06-01",
|
anthropicApiVersion: "2023-06-01",
|
||||||
anthropicUrl: "",
|
anthropicUrl: "",
|
||||||
|
|
||||||
|
// baidu
|
||||||
|
baiduUrl: "",
|
||||||
|
baiduApiKey: "",
|
||||||
|
baiduSecretKey: "",
|
||||||
|
|
||||||
// server config
|
// server config
|
||||||
needCode: true,
|
needCode: true,
|
||||||
hideUserApiKey: false,
|
hideUserApiKey: false,
|
||||||
|
@ -83,6 +88,10 @@ export const useAccessStore = createPersistStore(
|
||||||
return ensure(get(), ["anthropicApiKey"]);
|
return ensure(get(), ["anthropicApiKey"]);
|
||||||
},
|
},
|
||||||
|
|
||||||
|
isValidBaidu() {
|
||||||
|
return ensure(get(), ["baiduApiKey", "baiduSecretKey"]);
|
||||||
|
},
|
||||||
|
|
||||||
isAuthorized() {
|
isAuthorized() {
|
||||||
this.fetch();
|
this.fetch();
|
||||||
|
|
||||||
|
@ -92,6 +101,7 @@ export const useAccessStore = createPersistStore(
|
||||||
this.isValidAzure() ||
|
this.isValidAzure() ||
|
||||||
this.isValidGoogle() ||
|
this.isValidGoogle() ||
|
||||||
this.isValidAnthropic() ||
|
this.isValidAnthropic() ||
|
||||||
|
this.isValidBaidu() ||
|
||||||
!this.enabledAccessControl() ||
|
!this.enabledAccessControl() ||
|
||||||
(this.enabledAccessControl() && ensure(get(), ["accessCode"]))
|
(this.enabledAccessControl() && ensure(get(), ["accessCode"]))
|
||||||
);
|
);
|
||||||
|
|
|
@ -0,0 +1,23 @@
|
||||||
|
import { BAIDU_OATUH_URL } from "../constant";
|
||||||
|
/**
|
||||||
|
* 使用 AK,SK 生成鉴权签名(Access Token)
|
||||||
|
* @return 鉴权签名信息
|
||||||
|
*/
|
||||||
|
export async function getAccessToken(
|
||||||
|
clientId: string,
|
||||||
|
clientSecret: string,
|
||||||
|
): Promise<{
|
||||||
|
access_token: string;
|
||||||
|
expires_in: number;
|
||||||
|
error?: number;
|
||||||
|
}> {
|
||||||
|
const res = await fetch(
|
||||||
|
`${BAIDU_OATUH_URL}?grant_type=client_credentials&client_id=${clientId}&client_secret=${clientSecret}`,
|
||||||
|
{
|
||||||
|
method: "POST",
|
||||||
|
mode: "cors",
|
||||||
|
},
|
||||||
|
);
|
||||||
|
const resJson = await res.json();
|
||||||
|
return resJson;
|
||||||
|
}
|
Loading…
Reference in New Issue