diff --git a/README.md b/README.md index 2e45c7120fa..dd944fc33f4 100644 --- a/README.md +++ b/README.md @@ -375,6 +375,14 @@ SiliconFlow API URL. 302.AI API URL. +### `ANYAPI_API_KEY` (optional) + +AnyAPI API Key. + +### `ANYAPI_URL` (optional) + +AnyAPI API URL. + ## Requirements NodeJS >= 18, Docker >= 20 diff --git a/README_CN.md b/README_CN.md index f4c441ad006..cc29dbcc2e8 100644 --- a/README_CN.md +++ b/README_CN.md @@ -292,6 +292,14 @@ SiliconFlow API URL. 302.AI API URL. +### `ANYAPI_API_KEY` (optional) + +AnyAPI API Key. + +### `ANYAPI_URL` (optional) + +AnyAPI API URL. + ## 开发 点击下方按钮,开始二次开发: diff --git a/app/api/[provider]/[...path]/route.ts b/app/api/[provider]/[...path]/route.ts index e8af34f29f8..52cf166e9ef 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 anyapiHandler } from "../../anyapi"; async function handle( req: NextRequest, @@ -55,6 +56,8 @@ async function handle( return openaiHandler(req, { params }); case ApiPath["302.AI"]: return ai302Handler(req, { params }); + case ApiPath.AnyAPI: + return anyapiHandler(req, { params }); default: return proxyHandler(req, { params }); } diff --git a/app/api/anyapi.ts b/app/api/anyapi.ts new file mode 100644 index 00000000000..104f0b040a9 --- /dev/null +++ b/app/api/anyapi.ts @@ -0,0 +1,127 @@ +import { getServerSideConfig } from "@/app/config/server"; +import { + ANYAPI_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("[AnyAPI Route] params ", params); + + if (req.method === "OPTIONS") { + return NextResponse.json({ body: "OK" }, { status: 200 }); + } + + const authResult = auth(req, ModelProvider.AnyAPI); + if (authResult.error) { + return NextResponse.json(authResult, { + status: 401, + }); + } + + try { + const response = await request(req); + return response; + } catch (e) { + console.error("[AnyAPI] ", e); + return NextResponse.json(prettyObject(e)); + } +} + +async function request(req: NextRequest) { + const controller = new AbortController(); + + let path = `${req.nextUrl.pathname}`.replaceAll(ApiPath.AnyAPI, ""); + + let baseUrl = serverConfig.anyapiUrl || ANYAPI_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.AnyAPI as string, + ) + ) { + return NextResponse.json( + { + error: true, + message: `you are not allowed to use ${jsonBody?.model} model`, + }, + { + status: 403, + }, + ); + } + } catch (e) { + console.error(`[AnyAPI] 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); + } +} \ No newline at end of file diff --git a/app/api/auth.ts b/app/api/auth.ts index 8c78c70c865..1bf3b79e927 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.AnyAPI: + systemApiKey = serverConfig.anyapiApiKey; + break; case ModelProvider.GPT: default: if (req.nextUrl.pathname.includes("azure/deployments")) { diff --git a/app/client/api.ts b/app/client/api.ts index f60b0e2ad71..4a2e51683b8 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 { AnyAPIApi } from "./platforms/anyapi"; 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.AnyAPI: + this.llm = new AnyAPIApi(); + break; default: this.llm = new ChatGPTApi(); } @@ -270,6 +274,8 @@ export function getHeaders(ignoreHeaders: boolean = false) { const isSiliconFlow = modelConfig.providerName === ServiceProvider.SiliconFlow; const isAI302 = modelConfig.providerName === ServiceProvider["302.AI"]; + const isAnyAPI = + modelConfig.providerName === ServiceProvider.AnyAPI; const isEnabledAccessControl = accessStore.enabledAccessControl(); const apiKey = isGoogle ? accessStore.googleApiKey @@ -297,6 +303,8 @@ export function getHeaders(ignoreHeaders: boolean = false) { : "" : isAI302 ? accessStore.ai302ApiKey + : isAnyAPI + ? accessStore.anyapiApiKey : accessStore.openaiApiKey; return { isGoogle, @@ -312,6 +320,7 @@ export function getHeaders(ignoreHeaders: boolean = false) { isChatGLM, isSiliconFlow, isAI302, + isAnyAPI, apiKey, isEnabledAccessControl, }; @@ -341,6 +350,7 @@ export function getHeaders(ignoreHeaders: boolean = false) { isChatGLM, isSiliconFlow, isAI302, + isAnyAPI, apiKey, isEnabledAccessControl, } = getConfig(); @@ -393,6 +403,8 @@ export function getClientApi(provider: ServiceProvider): ClientApi { return new ClientApi(ModelProvider.SiliconFlow); case ServiceProvider["302.AI"]: return new ClientApi(ModelProvider["302.AI"]); + case ServiceProvider.AnyAPI: + return new ClientApi(ModelProvider.AnyAPI); default: return new ClientApi(ModelProvider.GPT); } diff --git a/app/client/platforms/anyapi.ts b/app/client/platforms/anyapi.ts new file mode 100644 index 00000000000..5ac0f3b76f8 --- /dev/null +++ b/app/client/platforms/anyapi.ts @@ -0,0 +1,280 @@ +"use client"; + +import { + ApiPath, + ANYAPI_BASE_URL, + DEFAULT_MODELS, + AnyAPI, +} 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 AnyAPIListModelResponse { + object: string; + data: Array<{ + id: string; + object: string; + root: string; + }>; +} + +export class AnyAPIApi implements LLMApi { + private disableListModels = false; + + path(path: string): string { + const accessStore = useAccessStore.getState(); + + let baseUrl = ""; + + if (accessStore.useCustomConfig) { + baseUrl = accessStore.anyapiUrl; + } + + if (baseUrl.length === 0) { + const isApp = !!getClientConfig()?.isApp; + const apiPath = ApiPath.AnyAPI; + baseUrl = isApp ? ANYAPI_BASE_URL : apiPath; + } + + if (baseUrl.endsWith("/")) { + baseUrl = baseUrl.slice(0, baseUrl.length - 1); + } + if ( + !baseUrl.startsWith("http") && + !baseUrl.startsWith(ApiPath.AnyAPI) + ) { + 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(AnyAPI.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, + // parseSSE + (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: "", + }; + }, + // processToolMessage + ( + 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(AnyAPI.ListModelPath), { + method: "GET", + headers: { + ...getHeaders(), + }, + }); + + const resJson = (await res.json()) as AnyAPIListModelResponse; + const chatModels = resJson.data; + console.log("[Models]", chatModels); + + if (!chatModels) { + return []; + } + + let seq = 1000; + return chatModels.map((m) => ({ + name: m.id, + available: true, + sorted: seq++, + provider: { + id: "anyapi", + providerName: "AnyAPI", + providerType: "anyapi", + sorted: 16, + }, + })); + } +} \ No newline at end of file diff --git a/app/components/settings.tsx b/app/components/settings.tsx index 881c12caeb3..8c036445251 100644 --- a/app/components/settings.tsx +++ b/app/components/settings.tsx @@ -76,6 +76,7 @@ import { DeepSeek, SiliconFlow, AI302, + AnyAPI, } from "../constant"; import { Prompt, SearchService, usePromptStore } from "../store/prompt"; import { ErrorBoundary } from "./error"; @@ -1498,6 +1499,45 @@ export function Settings() { ); + const anyapiConfigComponent = accessStore.provider === ServiceProvider.AnyAPI && ( + <> + + + accessStore.update( + (access) => (access.anyapiUrl = e.currentTarget.value), + ) + } + > + + + { + accessStore.update( + (access) => (access.anyapiApiKey = e.currentTarget.value), + ); + }} + /> + + + ); return ( @@ -1864,6 +1904,7 @@ export function Settings() { {chatglmConfigComponent} {siliconflowConfigComponent} {ai302ConfigComponent} + {anyapiConfigComponent} )} diff --git a/app/config/server.ts b/app/config/server.ts index 14175eadc8c..53b9194fd5e 100644 --- a/app/config/server.ts +++ b/app/config/server.ts @@ -92,6 +92,10 @@ declare global { AI302_URL?: string; AI302_API_KEY?: string; + // anyapi only + ANYAPI_URL?: string; + ANYAPI_API_KEY?: string; + // custom template for preprocessing user input DEFAULT_INPUT_TEMPLATE?: string; @@ -168,6 +172,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 isAnyAPI = !!process.env.ANYAPI_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 +260,10 @@ export const getServerSideConfig = () => { ai302Url: process.env.AI302_URL, ai302ApiKey: getApiKey(process.env.AI302_API_KEY), + isAnyAPI, + anyapiUrl: process.env.ANYAPI_URL, + anyapiApiKey: getApiKey(process.env.ANYAPI_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..e2b456e381b 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 ANYAPI_BASE_URL = "https://api.anyapi.ai"; + export const CACHE_URL_PREFIX = "/api/cache"; export const UPLOAD_URL = `${CACHE_URL_PREFIX}/upload`; @@ -75,6 +77,7 @@ export enum ApiPath { DeepSeek = "/api/deepseek", SiliconFlow = "/api/siliconflow", "302.AI" = "/api/302ai", + AnyAPI = "/api/anyapi", } export enum SlotID { @@ -134,6 +137,7 @@ export enum ServiceProvider { DeepSeek = "DeepSeek", SiliconFlow = "SiliconFlow", "302.AI" = "302.AI", + AnyAPI = "AnyAPI", } // Google API safety settings, see https://ai.google.dev/gemini-api/docs/safety-settings @@ -161,6 +165,7 @@ export enum ModelProvider { DeepSeek = "DeepSeek", SiliconFlow = "SiliconFlow", "302.AI" = "302.AI", + AnyAPI = "AnyAPI", } export const Stability = { @@ -278,6 +283,12 @@ export const AI302 = { ListModelPath: "v1/models?llm=1", }; +export const AnyAPI = { + ExampleEndpoint: ANYAPI_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}}. @@ -742,6 +753,18 @@ const ai302Models = [ "gemini-2.5-pro", ]; +const anyapiModels = [ + "openai/gpt-4o", + "openai/gpt-4o-mini", + "anthropic/claude-sonnet-4-20250514", + "anthropic/claude-opus-4-20250514", + "google/gemini-2.5-pro", + "google/gemini-2.5-flash", + "meta/llama-4-maverick", + "deepseek/deepseek-v3", + "deepseek/deepseek-r1", +]; + let seq = 1000; // 内置的模型序号生成器从1000开始 export const DEFAULT_MODELS = [ ...openaiModels.map((name) => ({ @@ -909,6 +932,17 @@ export const DEFAULT_MODELS = [ sorted: 15, }, })), + ...anyapiModels.map((name) => ({ + name, + available: true, + sorted: seq++, + provider: { + id: "anyapi", + providerName: "AnyAPI", + providerType: "anyapi", + sorted: 16, + }, + })), ] as const; export const CHAT_PAGE_SIZE = 15; diff --git a/app/locales/cn.ts b/app/locales/cn.ts index 2cb7dd1e535..70e1290911b 100644 --- a/app/locales/cn.ts +++ b/app/locales/cn.ts @@ -549,6 +549,17 @@ const cn = { SubTitle: "样例:", }, }, + AnyAPI: { + ApiKey: { + Title: "接口密钥", + SubTitle: "使用自定义 AnyAPI API Key", + Placeholder: "AnyAPI API Key", + }, + Endpoint: { + Title: "接口地址", + SubTitle: "样例:", + }, + }, }, Model: "模型 (model)", diff --git a/app/locales/en.ts b/app/locales/en.ts index a6d1919045c..3f5cfbac5b8 100644 --- a/app/locales/en.ts +++ b/app/locales/en.ts @@ -554,6 +554,17 @@ const en: LocaleType = { SubTitle: "Example: ", }, }, + AnyAPI: { + ApiKey: { + Title: "AnyAPI API Key", + SubTitle: "Use a custom AnyAPI API Key", + Placeholder: "AnyAPI API Key", + }, + Endpoint: { + Title: "Endpoint Address", + SubTitle: "Example: ", + }, + }, }, Model: "Model", diff --git a/app/store/access.ts b/app/store/access.ts index fd55fbdd3d1..900b8f8585f 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, + ANYAPI_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_ANYAPI_URL = isApp ? ANYAPI_BASE_URL : ApiPath.AnyAPI; + const DEFAULT_ACCESS_STATE = { accessCode: "", useCustomConfig: false, @@ -139,6 +142,10 @@ const DEFAULT_ACCESS_STATE = { ai302Url: DEFAULT_AI302_URL, ai302ApiKey: "", + // anyapi + anyapiUrl: DEFAULT_ANYAPI_URL, + anyapiApiKey: "", + // server config needCode: true, hideUserApiKey: false, @@ -226,6 +233,10 @@ export const useAccessStore = createPersistStore( return ensure(get(), ["siliconflowApiKey"]); }, + isValidAnyAPI() { + return ensure(get(), ["anyapiApiKey"]); + }, + isAuthorized() { this.fetch(); @@ -245,6 +256,7 @@ export const useAccessStore = createPersistStore( this.isValidXAI() || this.isValidChatGLM() || this.isValidSiliconFlow() || + this.isValidAnyAPI() || !this.enabledAccessControl() || (this.enabledAccessControl() && ensure(get(), ["accessCode"])) );