diff --git a/app/api/[provider]/[...path]/route.ts b/app/api/[provider]/[...path]/route.ts index e8af34f29f8..f43f103e3c1 100644 --- a/app/api/[provider]/[...path]/route.ts +++ b/app/api/[provider]/[...path]/route.ts @@ -16,6 +16,7 @@ import { handle as xaiHandler } from "../../xai"; import { handle as chatglmHandler } from "../../glm"; import { handle as proxyHandler } from "../../proxy"; import { handle as ai302Handler } from "../../302ai"; +import { handle as qiniuHandler } from "../../qiniu"; async function handle( req: NextRequest, @@ -51,6 +52,8 @@ async function handle( return chatglmHandler(req, { params }); case ApiPath.SiliconFlow: return siliconflowHandler(req, { params }); + case ApiPath.Qiniu: + return qiniuHandler(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..225a7eccdcc 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.Qiniu: + systemApiKey = serverConfig.qiniuApiKey; + break; case ModelProvider.GPT: default: if (req.nextUrl.pathname.includes("azure/deployments")) { diff --git a/app/api/qiniu.ts b/app/api/qiniu.ts new file mode 100644 index 00000000000..9392781c837 --- /dev/null +++ b/app/api/qiniu.ts @@ -0,0 +1,123 @@ +import { getServerSideConfig } from "@/app/config/server"; +import { + QINIU_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("[Qiniu Route] params ", params); + + if (req.method === "OPTIONS") { + return NextResponse.json({ body: "OK" }, { status: 200 }); + } + + const authResult = auth(req, ModelProvider.Qiniu); + if (authResult.error) { + return NextResponse.json(authResult, { + status: 401, + }); + } + + try { + const response = await request(req); + return response; + } catch (e) { + console.error("[Qiniu] ", e); + return NextResponse.json(prettyObject(e)); + } +} + +async function request(req: NextRequest) { + const controller = new AbortController(); + + let path = `${req.nextUrl.pathname}`.replaceAll(ApiPath.Qiniu, ""); + + let baseUrl = serverConfig.qiniuUrl || QINIU_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, + }; + + if (serverConfig.customModels && req.body) { + try { + const clonedBody = await req.text(); + fetchOptions.body = clonedBody; + + const jsonBody = JSON.parse(clonedBody) as { model?: string }; + + if ( + isModelNotavailableInServer( + serverConfig.customModels, + jsonBody?.model as string, + ServiceProvider.Qiniu as string, + ) + ) { + return NextResponse.json( + { + error: true, + message: `you are not allowed to use ${jsonBody?.model} model`, + }, + { + status: 403, + }, + ); + } + } catch (e) { + console.error(`[Qiniu] filter`, e); + } + } + try { + const res = await fetch(fetchUrl, fetchOptions); + + const newHeaders = new Headers(res.headers); + newHeaders.delete("www-authenticate"); + 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..0ef498dfac2 100644 --- a/app/client/api.ts +++ b/app/client/api.ts @@ -25,6 +25,7 @@ import { XAIApi } from "./platforms/xai"; import { ChatGLMApi } from "./platforms/glm"; import { SiliconflowApi } from "./platforms/siliconflow"; import { Ai302Api } from "./platforms/ai302"; +import { QiniuApi } from "./platforms/qiniu"; export const ROLES = ["system", "user", "assistant"] as const; export type MessageRole = (typeof ROLES)[number]; @@ -177,6 +178,9 @@ export class ClientApi { case ModelProvider["302.AI"]: this.llm = new Ai302Api(); break; + case ModelProvider.Qiniu: + this.llm = new QiniuApi(); + break; default: this.llm = new ChatGPTApi(); } @@ -270,6 +274,7 @@ export function getHeaders(ignoreHeaders: boolean = false) { const isSiliconFlow = modelConfig.providerName === ServiceProvider.SiliconFlow; const isAI302 = modelConfig.providerName === ServiceProvider["302.AI"]; + const isQiniu = modelConfig.providerName === ServiceProvider.Qiniu; const isEnabledAccessControl = accessStore.enabledAccessControl(); const apiKey = isGoogle ? accessStore.googleApiKey @@ -297,6 +302,8 @@ export function getHeaders(ignoreHeaders: boolean = false) { : "" : isAI302 ? accessStore.ai302ApiKey + : isQiniu + ? accessStore.qiniuApiKey : accessStore.openaiApiKey; return { isGoogle, @@ -312,6 +319,7 @@ export function getHeaders(ignoreHeaders: boolean = false) { isChatGLM, isSiliconFlow, isAI302, + isQiniu, apiKey, isEnabledAccessControl, }; @@ -341,6 +349,7 @@ export function getHeaders(ignoreHeaders: boolean = false) { isChatGLM, isSiliconFlow, isAI302, + isQiniu, apiKey, isEnabledAccessControl, } = getConfig(); @@ -393,6 +402,8 @@ export function getClientApi(provider: ServiceProvider): ClientApi { return new ClientApi(ModelProvider.SiliconFlow); case ServiceProvider["302.AI"]: return new ClientApi(ModelProvider["302.AI"]); + case ServiceProvider.Qiniu: + return new ClientApi(ModelProvider.Qiniu); default: return new ClientApi(ModelProvider.GPT); } diff --git a/app/client/platforms/qiniu.ts b/app/client/platforms/qiniu.ts new file mode 100644 index 00000000000..bc98b8ee77f --- /dev/null +++ b/app/client/platforms/qiniu.ts @@ -0,0 +1,272 @@ +"use client"; +import { ApiPath, QINIU_BASE_URL, Qiniu, 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 QiniuListModelResponse { + object: string; + data: Array<{ + id: string; + object: string; + root?: string; + }>; +} + +export class QiniuApi implements LLMApi { + path(path: string): string { + const accessStore = useAccessStore.getState(); + + let baseUrl = ""; + + if (accessStore.useCustomConfig) { + baseUrl = accessStore.qiniuUrl; + } + + if (baseUrl.length === 0) { + const isApp = !!getClientConfig()?.isApp; + const apiPath = ApiPath.Qiniu; + baseUrl = isApp ? QINIU_BASE_URL : apiPath; + } + + if (baseUrl.endsWith("/")) { + baseUrl = baseUrl.slice(0, baseUrl.length - 1); + } + if (!baseUrl.startsWith("http") && !baseUrl.startsWith(ApiPath.Qiniu)) { + 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, + }; + + console.log("[Request] openai payload: ", requestPayload); + + const shouldStream = !!options.config.stream; + const controller = new AbortController(); + options.onController?.(controller); + + try { + const chatPath = this.path(Qiniu.ChatPath); + const chatPayload = { + method: "POST", + body: JSON.stringify(requestPayload), + signal: controller.signal, + headers: getHeaders(), + }; + + 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, + (text: string, runTools: ChatMessageTool[]) => { + 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; + + 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: "", + }; + }, + ( + 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 { + try { + const res = await fetch(this.path(Qiniu.ListModelPath), { + method: "GET", + headers: { + ...getHeaders(), + }, + }); + + const resJson = (await res.json()) as QiniuListModelResponse; + const chatModels = resJson.data; + console.log("[Models]", chatModels); + + if (chatModels?.length) { + let seq = 1000; + return chatModels.map((m) => ({ + name: m.id, + available: true, + sorted: seq++, + provider: { + id: "qiniu", + providerName: "Qiniu", + providerType: "qiniu", + sorted: 16, + }, + })); + } + } catch (e) { + console.log("[Qiniu models]", e); + } + + return DEFAULT_MODELS.filter((m) => m.provider?.id === "qiniu").map( + (m) => ({ + ...m, + available: true, + }), + ) as LLMModel[]; + } +} diff --git a/app/components/settings.tsx b/app/components/settings.tsx index 881c12caeb3..cb4154e72df 100644 --- a/app/components/settings.tsx +++ b/app/components/settings.tsx @@ -75,6 +75,7 @@ import { ChatGLM, DeepSeek, SiliconFlow, + Qiniu, AI302, } from "../constant"; import { Prompt, SearchService, usePromptStore } from "../store/prompt"; @@ -1361,6 +1362,46 @@ export function Settings() { ); + const qiniuConfigComponent = accessStore.provider === + ServiceProvider.Qiniu && ( + <> + + + accessStore.update( + (access) => (access.qiniuUrl = e.currentTarget.value), + ) + } + > + + + { + accessStore.update( + (access) => (access.qiniuApiKey = e.currentTarget.value), + ); + }} + /> + + + ); + const stabilityConfigComponent = accessStore.provider === ServiceProvider.Stability && ( <> @@ -1459,44 +1500,44 @@ export function Settings() { ); - const ai302ConfigComponent = accessStore.provider === ServiceProvider["302.AI"] && ( + const ai302ConfigComponent = accessStore.provider === + ServiceProvider["302.AI"] && ( <> + + accessStore.update( + (access) => (access.ai302Url = e.currentTarget.value), + ) } - > - - accessStore.update( - (access) => (access.ai302Url = e.currentTarget.value), - ) - } - > - - - { - accessStore.update( - (access) => (access.ai302ApiKey = e.currentTarget.value), - ); - }} - /> - - + > + + + { + accessStore.update( + (access) => (access.ai302ApiKey = e.currentTarget.value), + ); + }} + /> + + ); return ( @@ -1863,6 +1904,7 @@ export function Settings() { {XAIConfigComponent} {chatglmConfigComponent} {siliconflowConfigComponent} + {qiniuConfigComponent} {ai302ConfigComponent} )} diff --git a/app/config/server.ts b/app/config/server.ts index 14175eadc8c..1b3a1e5c702 100644 --- a/app/config/server.ts +++ b/app/config/server.ts @@ -92,6 +92,9 @@ declare global { AI302_URL?: string; AI302_API_KEY?: string; + QINIU_URL?: string; + QINIU_API_KEY?: string; + // custom template for preprocessing user input DEFAULT_INPUT_TEMPLATE?: string; @@ -168,6 +171,7 @@ export const getServerSideConfig = () => { const isChatGLM = !!process.env.CHATGLM_API_KEY; const isSiliconFlow = !!process.env.SILICONFLOW_API_KEY; const isAI302 = !!process.env.AI302_API_KEY; + const isQiniu = !!process.env.QINIU_API_KEY; // const apiKeyEnvVar = process.env.OPENAI_API_KEY ?? ""; // const apiKeys = apiKeyEnvVar.split(",").map((v) => v.trim()); // const randomIndex = Math.floor(Math.random() * apiKeys.length); @@ -255,6 +259,10 @@ export const getServerSideConfig = () => { ai302Url: process.env.AI302_URL, ai302ApiKey: getApiKey(process.env.AI302_API_KEY), + isQiniu, + qiniuUrl: process.env.QINIU_URL, + qiniuApiKey: getApiKey(process.env.QINIU_API_KEY), + gtmId: process.env.GTM_ID, gaId: process.env.GA_ID || DEFAULT_GA_ID, diff --git a/app/constant.ts b/app/constant.ts index db9842d6027..863fe528cde 100644 --- a/app/constant.ts +++ b/app/constant.ts @@ -38,6 +38,8 @@ export const SILICONFLOW_BASE_URL = "https://api.siliconflow.cn"; export const AI302_BASE_URL = "https://api.302.ai"; +export const QINIU_BASE_URL = "https://api.qnaigc.com"; + export const CACHE_URL_PREFIX = "/api/cache"; export const UPLOAD_URL = `${CACHE_URL_PREFIX}/upload`; @@ -74,6 +76,7 @@ export enum ApiPath { ChatGLM = "/api/chatglm", DeepSeek = "/api/deepseek", SiliconFlow = "/api/siliconflow", + Qiniu = "/api/qiniu", "302.AI" = "/api/302ai", } @@ -133,6 +136,7 @@ export enum ServiceProvider { ChatGLM = "ChatGLM", DeepSeek = "DeepSeek", SiliconFlow = "SiliconFlow", + Qiniu = "Qiniu", "302.AI" = "302.AI", } @@ -160,6 +164,7 @@ export enum ModelProvider { ChatGLM = "ChatGLM", DeepSeek = "DeepSeek", SiliconFlow = "SiliconFlow", + Qiniu = "Qiniu", "302.AI" = "302.AI", } @@ -278,6 +283,12 @@ export const AI302 = { ListModelPath: "v1/models?llm=1", }; +export const Qiniu = { + ExampleEndpoint: QINIU_BASE_URL, + ChatPath: "v1/chat/completions", + ListModelPath: "v1/models", +}; + export const DEFAULT_INPUT_TEMPLATE = `{{input}}`; // input / time / model / lang // export const DEFAULT_SYSTEM_TEMPLATE = ` // You are ChatGPT, a large language model trained by {{ServiceProvider}}. @@ -493,7 +504,7 @@ export const VISION_MODEL_REGEXES = [ /o3/, /o4-mini/, /grok-4/i, - /gpt-5/ + /gpt-5/, ]; export const EXCLUDE_VISION_MODEL_REGEXES = [/claude-3-5-haiku-20241022/]; @@ -561,7 +572,7 @@ const googleModels = [ "gemini-2.0-pro-exp", "gemini-2.0-pro-exp-02-05", "gemini-2.5-pro-preview-06-05", - "gemini-2.5-pro" + "gemini-2.5-pro", ]; const anthropicModels = [ @@ -717,6 +728,8 @@ const siliconflowModels = [ "Pro/deepseek-ai/DeepSeek-V3", ]; +const qiniuModels = ["deepseek-v3"]; + const ai302Models = [ "deepseek-chat", "gpt-4o", @@ -909,6 +922,17 @@ export const DEFAULT_MODELS = [ sorted: 15, }, })), + ...qiniuModels.map((name) => ({ + name, + available: true, + sorted: seq++, + provider: { + id: "qiniu", + providerName: "Qiniu", + providerType: "qiniu", + sorted: 16, + }, + })), ] as const; export const CHAT_PAGE_SIZE = 15; diff --git a/app/locales/cn.ts b/app/locales/cn.ts index 2cb7dd1e535..42a367b4677 100644 --- a/app/locales/cn.ts +++ b/app/locales/cn.ts @@ -507,6 +507,17 @@ const cn = { SubTitle: "样例:", }, }, + Qiniu: { + ApiKey: { + Title: "接口密钥", + SubTitle: "使用自定义 Qiniu API Key", + Placeholder: "Qiniu API Key", + }, + Endpoint: { + Title: "接口地址", + SubTitle: "样例:", + }, + }, Stability: { ApiKey: { Title: "接口密钥", diff --git a/app/locales/en.ts b/app/locales/en.ts index a6d1919045c..47feb5e6366 100644 --- a/app/locales/en.ts +++ b/app/locales/en.ts @@ -491,6 +491,17 @@ const en: LocaleType = { SubTitle: "Example: ", }, }, + Qiniu: { + ApiKey: { + Title: "Qiniu API Key", + SubTitle: "Use a custom Qiniu API Key", + Placeholder: "Qiniu API Key", + }, + Endpoint: { + Title: "Endpoint Address", + SubTitle: "Example: ", + }, + }, Stability: { ApiKey: { Title: "Stability API Key", diff --git a/app/store/access.ts b/app/store/access.ts index fd55fbdd3d1..40346669325 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, + QINIU_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_QINIU_URL = isApp ? QINIU_BASE_URL : ApiPath.Qiniu; + const DEFAULT_ACCESS_STATE = { accessCode: "", useCustomConfig: false, @@ -139,6 +142,10 @@ const DEFAULT_ACCESS_STATE = { ai302Url: DEFAULT_AI302_URL, ai302ApiKey: "", + // qiniu + qiniuUrl: DEFAULT_QINIU_URL, + qiniuApiKey: "", + // server config needCode: true, hideUserApiKey: false, @@ -226,6 +233,10 @@ export const useAccessStore = createPersistStore( return ensure(get(), ["siliconflowApiKey"]); }, + isValidQiniu() { + return ensure(get(), ["qiniuApiKey"]); + }, + isAuthorized() { this.fetch(); @@ -245,6 +256,7 @@ export const useAccessStore = createPersistStore( this.isValidXAI() || this.isValidChatGLM() || this.isValidSiliconFlow() || + this.isValidQiniu() || !this.enabledAccessControl() || (this.enabledAccessControl() && ensure(get(), ["accessCode"])) );