From 080ee28f4b9d1283655b0ff1353238bdc2dd1a49 Mon Sep 17 00:00:00 2001 From: Seven <88984809@qq.com> Date: Tue, 14 Jul 2026 20:28:37 +0800 Subject: [PATCH] feat(provider): add DaoXE multi-model gateway Add DaoXE as a built-in OpenAI-compatible provider (Chat Completions at https://daoxe.com/v1). Model IDs come from account GET /v1/models; no static public price list. Not available in mainland China. Signed-off-by: seven7763 --- .env.template | 6 + app/api/[provider]/[...path]/route.ts | 3 + app/api/auth.ts | 3 + app/api/daoxe.ts | 128 ++++++++++++ app/client/api.ts | 7 + app/client/platforms/daoxe.ts | 287 ++++++++++++++++++++++++++ app/components/settings.tsx | 43 ++++ app/config/server.ts | 9 + app/constant.ts | 24 +++ app/locales/cn.ts | 11 + app/locales/en.ts | 11 + app/store/access.ts | 11 + 12 files changed, 543 insertions(+) create mode 100644 app/api/daoxe.ts create mode 100644 app/client/platforms/daoxe.ts diff --git a/.env.template b/.env.template index 7f5a033dd77..b74517b9986 100644 --- a/.env.template +++ b/.env.template @@ -155,3 +155,9 @@ CHATGLM_API_KEY= ### ChatGLM Api url (optional) CHATGLM_URL= + +### DaoXE Api key (optional) +# https://daoxe.com/dashboard +DAOXE_API_KEY= +### DaoXE Api url (optional) +# DAOXE_URL=https://daoxe.com diff --git a/app/api/[provider]/[...path]/route.ts b/app/api/[provider]/[...path]/route.ts index e8af34f29f8..e4c2ecb9878 100644 --- a/app/api/[provider]/[...path]/route.ts +++ b/app/api/[provider]/[...path]/route.ts @@ -12,6 +12,7 @@ import { handle as stabilityHandler } from "../../stability"; import { handle as iflytekHandler } from "../../iflytek"; import { handle as deepseekHandler } from "../../deepseek"; import { handle as siliconflowHandler } from "../../siliconflow"; +import { handle as daoxeHandler } from "../../daoxe"; import { handle as xaiHandler } from "../../xai"; import { handle as chatglmHandler } from "../../glm"; import { handle as proxyHandler } from "../../proxy"; @@ -51,6 +52,8 @@ async function handle( return chatglmHandler(req, { params }); case ApiPath.SiliconFlow: return siliconflowHandler(req, { params }); + case ApiPath.DaoXE: + return daoxeHandler(req, { params }); case ApiPath.OpenAI: return openaiHandler(req, { params }); case ApiPath["302.AI"]: diff --git a/app/api/auth.ts b/app/api/auth.ts index 8c78c70c865..0948c3005e5 100644 --- a/app/api/auth.ts +++ b/app/api/auth.ts @@ -104,6 +104,9 @@ export function auth(req: NextRequest, modelProvider: ModelProvider) { case ModelProvider.SiliconFlow: systemApiKey = serverConfig.siliconFlowApiKey; break; + case ModelProvider.DaoXE: + systemApiKey = serverConfig.daoxeApiKey; + break; case ModelProvider.GPT: default: if (req.nextUrl.pathname.includes("azure/deployments")) { diff --git a/app/api/daoxe.ts b/app/api/daoxe.ts new file mode 100644 index 00000000000..c2a0353a97d --- /dev/null +++ b/app/api/daoxe.ts @@ -0,0 +1,128 @@ +import { getServerSideConfig } from "@/app/config/server"; +import { + DAOXE_BASE_URL, + ApiPath, + ModelProvider, + ServiceProvider, +} from "@/app/constant"; +import { prettyObject } from "@/app/utils/format"; +import { NextRequest, NextResponse } from "next/server"; +import { auth } from "@/app/api/auth"; +import { isModelNotavailableInServer } from "@/app/utils/model"; + +const serverConfig = getServerSideConfig(); + +export async function handle( + req: NextRequest, + { params }: { params: { path: string[] } }, +) { + console.log("[DaoXE Route] params ", params); + + if (req.method === "OPTIONS") { + return NextResponse.json({ body: "OK" }, { status: 200 }); + } + + const authResult = auth(req, ModelProvider.DaoXE); + if (authResult.error) { + return NextResponse.json(authResult, { + status: 401, + }); + } + + try { + const response = await request(req); + return response; + } catch (e) { + console.error("[DaoXE] ", e); + return NextResponse.json(prettyObject(e)); + } +} + +async function request(req: NextRequest) { + const controller = new AbortController(); + + // alibaba use base url or just remove the path + let path = `${req.nextUrl.pathname}`.replaceAll(ApiPath.DaoXE, ""); + + let baseUrl = serverConfig.daoxeUrl || DAOXE_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 fetchUrl = `${baseUrl}${path}`; + const fetchOptions: RequestInit = { + headers: { + "Content-Type": "application/json", + Authorization: req.headers.get("Authorization") ?? "", + }, + 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 ( + isModelNotavailableInServer( + serverConfig.customModels, + jsonBody?.model as string, + ServiceProvider.DaoXE as string, + ) + ) { + return NextResponse.json( + { + error: true, + message: `you are not allowed to use ${jsonBody?.model} model`, + }, + { + status: 403, + }, + ); + } + } catch (e) { + console.error(`[DaoXE] 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); + } +} diff --git a/app/client/api.ts b/app/client/api.ts index f60b0e2ad71..d707fbfaf73 100644 --- a/app/client/api.ts +++ b/app/client/api.ts @@ -24,6 +24,7 @@ import { DeepSeekApi } from "./platforms/deepseek"; import { XAIApi } from "./platforms/xai"; import { ChatGLMApi } from "./platforms/glm"; import { SiliconflowApi } from "./platforms/siliconflow"; +import { DaoxeApi } from "./platforms/daoxe"; import { Ai302Api } from "./platforms/ai302"; export const ROLES = ["system", "user", "assistant"] as const; @@ -174,6 +175,9 @@ export class ClientApi { case ModelProvider.SiliconFlow: this.llm = new SiliconflowApi(); break; + case ModelProvider.DaoXE: + this.llm = new DaoxeApi(); + break; case ModelProvider["302.AI"]: this.llm = new Ai302Api(); break; @@ -269,6 +273,7 @@ export function getHeaders(ignoreHeaders: boolean = false) { const isChatGLM = modelConfig.providerName === ServiceProvider.ChatGLM; const isSiliconFlow = modelConfig.providerName === ServiceProvider.SiliconFlow; + const isDaoXE = modelConfig.providerName === ServiceProvider.DaoXE; const isAI302 = modelConfig.providerName === ServiceProvider["302.AI"]; const isEnabledAccessControl = accessStore.enabledAccessControl(); const apiKey = isGoogle @@ -311,6 +316,7 @@ export function getHeaders(ignoreHeaders: boolean = false) { isXAI, isChatGLM, isSiliconFlow, + isDaoXE, isAI302, apiKey, isEnabledAccessControl, @@ -340,6 +346,7 @@ export function getHeaders(ignoreHeaders: boolean = false) { isXAI, isChatGLM, isSiliconFlow, + isDaoXE, isAI302, apiKey, isEnabledAccessControl, diff --git a/app/client/platforms/daoxe.ts b/app/client/platforms/daoxe.ts new file mode 100644 index 00000000000..f90db85aad0 --- /dev/null +++ b/app/client/platforms/daoxe.ts @@ -0,0 +1,287 @@ +"use client"; +// azure and openai, using same models. so using same LLMApi. +import { + ApiPath, + DAOXE_BASE_URL, + DaoXE, + DEFAULT_MODELS, +} from "@/app/constant"; +import { + useAccessStore, + useAppConfig, + useChatStore, + ChatMessageTool, + usePluginStore, +} from "@/app/store"; +import { preProcessImageContent, streamWithThink } from "@/app/utils/chat"; +import { + ChatOptions, + getHeaders, + LLMApi, + LLMModel, + SpeechOptions, +} from "../api"; +import { getClientConfig } from "@/app/config/client"; +import { + getMessageTextContent, + getMessageTextContentWithoutThinking, + isVisionModel, + getTimeoutMSByModel, +} from "@/app/utils"; +import { RequestPayload } from "./openai"; + +import { fetch } from "@/app/utils/stream"; +export interface DaoXEListModelResponse { + object: string; + data: Array<{ + id: string; + object: string; + root: string; + }>; +} + +export class DaoxeApi implements LLMApi { + private disableListModels = false; + + path(path: string): string { + const accessStore = useAccessStore.getState(); + + let baseUrl = ""; + + if (accessStore.useCustomConfig) { + baseUrl = accessStore.daoxeUrl; + } + + if (baseUrl.length === 0) { + const isApp = !!getClientConfig()?.isApp; + const apiPath = ApiPath.DaoXE; + baseUrl = isApp ? DAOXE_BASE_URL : apiPath; + } + + if (baseUrl.endsWith("/")) { + baseUrl = baseUrl.slice(0, baseUrl.length - 1); + } + if ( + !baseUrl.startsWith("http") && + !baseUrl.startsWith(ApiPath.DaoXE) + ) { + baseUrl = "https://" + baseUrl; + } + + console.log("[Proxy Endpoint] ", baseUrl, path); + + return [baseUrl, path].join("/"); + } + + extractMessage(res: any) { + return res.choices?.at(0)?.message?.content ?? ""; + } + + speech(options: SpeechOptions): Promise { + throw new Error("Method not implemented."); + } + + async chat(options: ChatOptions) { + const visionModel = isVisionModel(options.config.model); + const messages: ChatOptions["messages"] = []; + for (const v of options.messages) { + if (v.role === "assistant") { + const content = getMessageTextContentWithoutThinking(v); + messages.push({ role: v.role, content }); + } else { + const content = visionModel + ? await preProcessImageContent(v.content) + : getMessageTextContent(v); + messages.push({ role: v.role, content }); + } + } + + const modelConfig = { + ...useAppConfig.getState().modelConfig, + ...useChatStore.getState().currentSession().mask.modelConfig, + ...{ + model: options.config.model, + providerName: options.config.providerName, + }, + }; + + const requestPayload: 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. + }; + + console.log("[Request] openai payload: ", requestPayload); + + const shouldStream = !!options.config.stream; + const controller = new AbortController(); + options.onController?.(controller); + + try { + const chatPath = this.path(DaoXE.ChatPath); + const chatPayload = { + method: "POST", + body: JSON.stringify(requestPayload), + signal: controller.signal, + headers: getHeaders(), + }; + + // console.log(chatPayload); + + // Use extended timeout for thinking models as they typically require more processing time + const requestTimeoutId = setTimeout( + () => controller.abort(), + getTimeoutMSByModel(options.config.model), + ); + + if (shouldStream) { + const [tools, funcs] = usePluginStore + .getState() + .getAsTools( + useChatStore.getState().currentSession().mask?.plugin || [], + ); + return streamWithThink( + chatPath, + requestPayload, + getHeaders(), + tools as any, + funcs, + controller, + // parseSSE + (text: string, runTools: ChatMessageTool[]) => { + // console.log("parseSSE", text, runTools); + const json = JSON.parse(text); + const choices = json.choices as Array<{ + delta: { + content: string | null; + tool_calls: ChatMessageTool[]; + reasoning_content: string | null; + }; + }>; + const tool_calls = choices[0]?.delta?.tool_calls; + 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 as string, + arguments: args, + }, + }); + } else { + // @ts-ignore + runTools[index]["function"]["arguments"] += args; + } + } + const reasoning = choices[0]?.delta?.reasoning_content; + const content = choices[0]?.delta?.content; + + // Skip if both content and reasoning_content are empty or null + if ( + (!reasoning || reasoning.length === 0) && + (!content || content.length === 0) + ) { + return { + isThinking: false, + content: "", + }; + } + + if (reasoning && reasoning.length > 0) { + return { + isThinking: true, + content: reasoning, + }; + } else if (content && content.length > 0) { + return { + isThinking: false, + content: content, + }; + } + + return { + isThinking: false, + content: "", + }; + }, + // processToolMessage, include tool_calls message and tool call results + ( + requestPayload: RequestPayload, + toolCallMessage: any, + toolCallResult: any[], + ) => { + // @ts-ignore + requestPayload?.messages?.splice( + // @ts-ignore + requestPayload?.messages?.length, + 0, + toolCallMessage, + ...toolCallResult, + ); + }, + options, + ); + } else { + const res = await fetch(chatPath, chatPayload); + clearTimeout(requestTimeoutId); + + const resJson = await res.json(); + const message = this.extractMessage(resJson); + options.onFinish(message, res); + } + } 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 { + if (this.disableListModels) { + return DEFAULT_MODELS.slice(); + } + + const res = await fetch(this.path(DaoXE.ListModelPath), { + method: "GET", + headers: { + ...getHeaders(), + }, + }); + + const resJson = (await res.json()) as DaoXEListModelResponse; + const chatModels = resJson.data; + console.log("[Models]", chatModels); + + if (!chatModels) { + return []; + } + + let seq = 1000; //同 Constant.ts 中的排序保持一致 + return chatModels.map((m) => ({ + name: m.id, + available: true, + sorted: seq++, + provider: { + id: "daoxe", + providerName: "DaoXE", + providerType: "daoxe", + sorted: 16, + }, + })); + } +} diff --git a/app/components/settings.tsx b/app/components/settings.tsx index 881c12caeb3..c29d1623f73 100644 --- a/app/components/settings.tsx +++ b/app/components/settings.tsx @@ -75,6 +75,7 @@ import { ChatGLM, DeepSeek, SiliconFlow, + DaoXE, AI302, } from "../constant"; import { Prompt, SearchService, usePromptStore } from "../store/prompt"; @@ -1459,6 +1460,47 @@ export function Settings() { ); + const daoxeConfigComponent = accessStore.provider === + ServiceProvider.DaoXE && ( + <> + + + accessStore.update( + (access) => (access.daoxeUrl = e.currentTarget.value), + ) + } + > + + + { + accessStore.update( + (access) => (access.daoxeApiKey = e.currentTarget.value), + ); + }} + /> + + + ); + const ai302ConfigComponent = accessStore.provider === ServiceProvider["302.AI"] && ( <> )} diff --git a/app/config/server.ts b/app/config/server.ts index 14175eadc8c..96598f09857 100644 --- a/app/config/server.ts +++ b/app/config/server.ts @@ -88,6 +88,10 @@ declare global { SILICONFLOW_URL?: string; SILICONFLOW_API_KEY?: string; + // DaoXE only + DAOXE_URL?: string; + DAOXE_API_KEY?: string; + // 302.AI only AI302_URL?: string; AI302_API_KEY?: string; @@ -167,6 +171,7 @@ export const getServerSideConfig = () => { const isXAI = !!process.env.XAI_API_KEY; const isChatGLM = !!process.env.CHATGLM_API_KEY; const isSiliconFlow = !!process.env.SILICONFLOW_API_KEY; + const isDaoXE = !!process.env.DAOXE_API_KEY; const isAI302 = !!process.env.AI302_API_KEY; // const apiKeyEnvVar = process.env.OPENAI_API_KEY ?? ""; // const apiKeys = apiKeyEnvVar.split(",").map((v) => v.trim()); @@ -251,6 +256,10 @@ export const getServerSideConfig = () => { siliconFlowUrl: process.env.SILICONFLOW_URL, siliconFlowApiKey: getApiKey(process.env.SILICONFLOW_API_KEY), + isDaoXE, + daoxeUrl: process.env.DAOXE_URL, + daoxeApiKey: getApiKey(process.env.DAOXE_API_KEY), + isAI302, ai302Url: process.env.AI302_URL, ai302ApiKey: getApiKey(process.env.AI302_API_KEY), diff --git a/app/constant.ts b/app/constant.ts index db9842d6027..776db089cf4 100644 --- a/app/constant.ts +++ b/app/constant.ts @@ -35,6 +35,7 @@ export const XAI_BASE_URL = "https://api.x.ai"; export const CHATGLM_BASE_URL = "https://open.bigmodel.cn"; export const SILICONFLOW_BASE_URL = "https://api.siliconflow.cn"; +export const DAOXE_BASE_URL = "https://daoxe.com"; export const AI302_BASE_URL = "https://api.302.ai"; @@ -75,6 +76,7 @@ export enum ApiPath { DeepSeek = "/api/deepseek", SiliconFlow = "/api/siliconflow", "302.AI" = "/api/302ai", + DaoXE = "/api/daoxe", } export enum SlotID { @@ -134,6 +136,7 @@ export enum ServiceProvider { DeepSeek = "DeepSeek", SiliconFlow = "SiliconFlow", "302.AI" = "302.AI", + DaoXE = "DaoXE", } // Google API safety settings, see https://ai.google.dev/gemini-api/docs/safety-settings @@ -161,6 +164,7 @@ export enum ModelProvider { DeepSeek = "DeepSeek", SiliconFlow = "SiliconFlow", "302.AI" = "302.AI", + DaoXE = "DaoXE", } export const Stability = { @@ -271,6 +275,12 @@ export const SiliconFlow = { ListModelPath: "v1/models?&sub_type=chat", }; +export const DaoXE = { + ExampleEndpoint: DAOXE_BASE_URL, + ChatPath: "v1/chat/completions", + ListModelPath: "v1/models", +}; + export const AI302 = { ExampleEndpoint: AI302_BASE_URL, ChatPath: "v1/chat/completions", @@ -742,6 +752,9 @@ const ai302Models = [ "gemini-2.5-pro", ]; +// Account-scoped catalog; runtime listModels via GET /v1/models. +const daoxeModels: string[] = []; + let seq = 1000; // 内置的模型序号生成器从1000开始 export const DEFAULT_MODELS = [ ...openaiModels.map((name) => ({ @@ -909,6 +922,17 @@ export const DEFAULT_MODELS = [ sorted: 15, }, })), + ...daoxeModels.map((name) => ({ + name, + available: true, + sorted: seq++, + provider: { + id: "daoxe", + providerName: "DaoXE", + providerType: "daoxe", + sorted: 16, + }, + })), ] as const; export const CHAT_PAGE_SIZE = 15; diff --git a/app/locales/cn.ts b/app/locales/cn.ts index 2cb7dd1e535..daa9fbbca69 100644 --- a/app/locales/cn.ts +++ b/app/locales/cn.ts @@ -502,6 +502,17 @@ const cn = { SubTitle: "使用自定义硅基流动 API Key", Placeholder: "硅基流动 API Key", }, + DaoXE: { + ApiKey: { + Title: "DaoXE API Key", + SubTitle: "使用自定义 DaoXE API Key(多模型多协议网关)", + Placeholder: "DaoXE API Key", + }, + Endpoint: { + Title: "DaoXE 接口地址", + SubTitle: "自定义 API 端点,默认:", + }, + }, Endpoint: { Title: "接口地址", SubTitle: "样例:", diff --git a/app/locales/en.ts b/app/locales/en.ts index a6d1919045c..6d77fd68a74 100644 --- a/app/locales/en.ts +++ b/app/locales/en.ts @@ -486,6 +486,17 @@ const en: LocaleType = { SubTitle: "Use a custom SiliconFlow API Key", Placeholder: "SiliconFlow API Key", }, + DaoXE: { + ApiKey: { + Title: "DaoXE API Key", + SubTitle: "Use a custom DaoXE API Key (multi-model gateway)", + Placeholder: "DaoXE API Key", + }, + Endpoint: { + Title: "DaoXE Endpoint", + SubTitle: "Custom API endpoint, default: ", + }, + }, Endpoint: { Title: "Endpoint Address", SubTitle: "Example: ", diff --git a/app/store/access.ts b/app/store/access.ts index fd55fbdd3d1..70a1dd4afd5 100644 --- a/app/store/access.ts +++ b/app/store/access.ts @@ -18,6 +18,7 @@ import { CHATGLM_BASE_URL, SILICONFLOW_BASE_URL, AI302_BASE_URL, + DAOXE_BASE_URL, } from "../constant"; import { getHeaders } from "../client/api"; import { getClientConfig } from "../config/client"; @@ -62,6 +63,8 @@ const DEFAULT_SILICONFLOW_URL = isApp const DEFAULT_AI302_URL = isApp ? AI302_BASE_URL : ApiPath["302.AI"]; +const DEFAULT_DAOXE_URL = isApp ? DAOXE_BASE_URL : ApiPath.DaoXE; + const DEFAULT_ACCESS_STATE = { accessCode: "", useCustomConfig: false, @@ -139,6 +142,10 @@ const DEFAULT_ACCESS_STATE = { ai302Url: DEFAULT_AI302_URL, ai302ApiKey: "", + // DaoXE + daoxeUrl: DEFAULT_DAOXE_URL, + daoxeApiKey: "", + // server config needCode: true, hideUserApiKey: false, @@ -225,6 +232,9 @@ export const useAccessStore = createPersistStore( isValidSiliconFlow() { return ensure(get(), ["siliconflowApiKey"]); }, + isValidDaoXE() { + return ensure(get(), ["daoxeApiKey"]); + }, isAuthorized() { this.fetch(); @@ -245,6 +255,7 @@ export const useAccessStore = createPersistStore( this.isValidXAI() || this.isValidChatGLM() || this.isValidSiliconFlow() || + this.isValidDaoXE() || !this.enabledAccessControl() || (this.enabledAccessControl() && ensure(get(), ["accessCode"])) );