Skip to content

Commit 0588b40

Browse files
feat: add AnyAPI provider
1 parent c3b8c15 commit 0588b40

11 files changed

Lines changed: 543 additions & 0 deletions

File tree

app/api/[provider]/[...path]/route.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ import { handle as xaiHandler } from "../../xai";
1616
import { handle as chatglmHandler } from "../../glm";
1717
import { handle as proxyHandler } from "../../proxy";
1818
import { handle as ai302Handler } from "../../302ai";
19+
import { handle as anyapiHandler } from "../../anyapi";
1920

2021
async function handle(
2122
req: NextRequest,
@@ -55,6 +56,8 @@ async function handle(
5556
return openaiHandler(req, { params });
5657
case ApiPath["302.AI"]:
5758
return ai302Handler(req, { params });
59+
case ApiPath.AnyAPI:
60+
return anyapiHandler(req, { params });
5861
default:
5962
return proxyHandler(req, { params });
6063
}

app/api/anyapi.ts

Lines changed: 124 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,124 @@
1+
import { getServerSideConfig } from "@/app/config/server";
2+
import {
3+
ANYAPI_BASE_URL,
4+
ApiPath,
5+
ModelProvider,
6+
ServiceProvider,
7+
} from "@/app/constant";
8+
import { prettyObject } from "@/app/utils/format";
9+
import { NextRequest, NextResponse } from "next/server";
10+
import { auth } from "@/app/api/auth";
11+
import { isModelNotavailableInServer } from "@/app/utils/model";
12+
13+
const serverConfig = getServerSideConfig();
14+
15+
export async function handle(
16+
req: NextRequest,
17+
{ params }: { params: { path: string[] } },
18+
) {
19+
console.log("[AnyAPI Route] params ", params);
20+
21+
if (req.method === "OPTIONS") {
22+
return NextResponse.json({ body: "OK" }, { status: 200 });
23+
}
24+
25+
const authResult = auth(req, ModelProvider.AnyAPI);
26+
if (authResult.error) {
27+
return NextResponse.json(authResult, {
28+
status: 401,
29+
});
30+
}
31+
32+
try {
33+
const response = await request(req);
34+
return response;
35+
} catch (e) {
36+
console.error("[AnyAPI] ", e);
37+
return NextResponse.json(prettyObject(e));
38+
}
39+
}
40+
41+
async function request(req: NextRequest) {
42+
const controller = new AbortController();
43+
44+
let path = `${req.nextUrl.pathname}`.replaceAll(ApiPath.AnyAPI, "");
45+
46+
let baseUrl = serverConfig.anyapiUrl || ANYAPI_BASE_URL;
47+
48+
if (!baseUrl.startsWith("http")) {
49+
baseUrl = `https://${baseUrl}`;
50+
}
51+
52+
if (baseUrl.endsWith("/")) {
53+
baseUrl = baseUrl.slice(0, -1);
54+
}
55+
56+
console.log("[Proxy] ", path);
57+
console.log("[Base Url]", baseUrl);
58+
59+
const timeoutId = setTimeout(
60+
() => {
61+
controller.abort();
62+
},
63+
10 * 60 * 1000,
64+
);
65+
66+
const fetchUrl = `${baseUrl}${path}`;
67+
const fetchOptions: RequestInit = {
68+
headers: {
69+
"Content-Type": "application/json",
70+
Authorization: req.headers.get("Authorization") ?? "",
71+
},
72+
method: req.method,
73+
body: req.body,
74+
redirect: "manual",
75+
// @ts-ignore
76+
duplex: "half",
77+
signal: controller.signal,
78+
};
79+
80+
// try to refuse some request to some models
81+
if (serverConfig.customModels && req.body) {
82+
try {
83+
const clonedBody = await req.text();
84+
fetchOptions.body = clonedBody;
85+
86+
const jsonBody = JSON.parse(clonedBody) as { model?: string };
87+
88+
if (
89+
isModelNotavailableInServer(
90+
serverConfig.customModels,
91+
jsonBody?.model as string,
92+
ServiceProvider.AnyAPI as string,
93+
)
94+
) {
95+
return NextResponse.json(
96+
{
97+
error: true,
98+
message: `you are not allowed to use ${jsonBody?.model} model`,
99+
},
100+
{
101+
status: 403,
102+
},
103+
);
104+
}
105+
} catch (e) {
106+
console.error(`[AnyAPI] filter`, e);
107+
}
108+
}
109+
try {
110+
const res = await fetch(fetchUrl, fetchOptions);
111+
112+
const newHeaders = new Headers(res.headers);
113+
newHeaders.delete("www-authenticate");
114+
newHeaders.set("X-Accel-Buffering", "no");
115+
116+
return new Response(res.body, {
117+
status: res.status,
118+
statusText: res.statusText,
119+
headers: newHeaders,
120+
});
121+
} finally {
122+
clearTimeout(timeoutId);
123+
}
124+
}

app/api/auth.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,9 @@ export function auth(req: NextRequest, modelProvider: ModelProvider) {
104104
case ModelProvider.SiliconFlow:
105105
systemApiKey = serverConfig.siliconFlowApiKey;
106106
break;
107+
case ModelProvider.AnyAPI:
108+
systemApiKey = serverConfig.anyapiApiKey;
109+
break;
107110
case ModelProvider.GPT:
108111
default:
109112
if (req.nextUrl.pathname.includes("azure/deployments")) {

app/client/api.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ import { XAIApi } from "./platforms/xai";
2525
import { ChatGLMApi } from "./platforms/glm";
2626
import { SiliconflowApi } from "./platforms/siliconflow";
2727
import { Ai302Api } from "./platforms/ai302";
28+
import { AnyAPIApi } from "./platforms/anyapi";
2829

2930
export const ROLES = ["system", "user", "assistant"] as const;
3031
export type MessageRole = (typeof ROLES)[number];
@@ -177,6 +178,9 @@ export class ClientApi {
177178
case ModelProvider["302.AI"]:
178179
this.llm = new Ai302Api();
179180
break;
181+
case ModelProvider.AnyAPI:
182+
this.llm = new AnyAPIApi();
183+
break;
180184
default:
181185
this.llm = new ChatGPTApi();
182186
}
@@ -270,6 +274,7 @@ export function getHeaders(ignoreHeaders: boolean = false) {
270274
const isSiliconFlow =
271275
modelConfig.providerName === ServiceProvider.SiliconFlow;
272276
const isAI302 = modelConfig.providerName === ServiceProvider["302.AI"];
277+
const isAnyAPI = modelConfig.providerName === ServiceProvider.AnyAPI;
273278
const isEnabledAccessControl = accessStore.enabledAccessControl();
274279
const apiKey = isGoogle
275280
? accessStore.googleApiKey
@@ -297,6 +302,8 @@ export function getHeaders(ignoreHeaders: boolean = false) {
297302
: ""
298303
: isAI302
299304
? accessStore.ai302ApiKey
305+
: isAnyAPI
306+
? accessStore.anyapiApiKey
300307
: accessStore.openaiApiKey;
301308
return {
302309
isGoogle,
@@ -312,6 +319,7 @@ export function getHeaders(ignoreHeaders: boolean = false) {
312319
isChatGLM,
313320
isSiliconFlow,
314321
isAI302,
322+
isAnyAPI,
315323
apiKey,
316324
isEnabledAccessControl,
317325
};
@@ -341,6 +349,7 @@ export function getHeaders(ignoreHeaders: boolean = false) {
341349
isChatGLM,
342350
isSiliconFlow,
343351
isAI302,
352+
isAnyAPI,
344353
apiKey,
345354
isEnabledAccessControl,
346355
} = getConfig();
@@ -393,6 +402,8 @@ export function getClientApi(provider: ServiceProvider): ClientApi {
393402
return new ClientApi(ModelProvider.SiliconFlow);
394403
case ServiceProvider["302.AI"]:
395404
return new ClientApi(ModelProvider["302.AI"]);
405+
case ServiceProvider.AnyAPI:
406+
return new ClientApi(ModelProvider.AnyAPI);
396407
default:
397408
return new ClientApi(ModelProvider.GPT);
398409
}

0 commit comments

Comments
 (0)