Skip to content

Commit c7c2c02

Browse files
authored
Merge pull request #5704 from ConnectAI-E/feature/xai
xAi support
2 parents 06f897f + 65bb962 commit c7c2c02

File tree

11 files changed

+444
-0
lines changed

11 files changed

+444
-0
lines changed

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

+3
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import { handle as alibabaHandler } from "../../alibaba";
1010
import { handle as moonshotHandler } from "../../moonshot";
1111
import { handle as stabilityHandler } from "../../stability";
1212
import { handle as iflytekHandler } from "../../iflytek";
13+
import { handle as xaiHandler } from "../../xai";
1314
import { handle as proxyHandler } from "../../proxy";
1415

1516
async function handle(
@@ -38,6 +39,8 @@ async function handle(
3839
return stabilityHandler(req, { params });
3940
case ApiPath.Iflytek:
4041
return iflytekHandler(req, { params });
42+
case ApiPath.XAI:
43+
return xaiHandler(req, { params });
4144
case ApiPath.OpenAI:
4245
return openaiHandler(req, { params });
4346
default:

app/api/auth.ts

+3
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,9 @@ export function auth(req: NextRequest, modelProvider: ModelProvider) {
9292
systemApiKey =
9393
serverConfig.iflytekApiKey + ":" + serverConfig.iflytekApiSecret;
9494
break;
95+
case ModelProvider.XAI:
96+
systemApiKey = serverConfig.xaiApiKey;
97+
break;
9598
case ModelProvider.GPT:
9699
default:
97100
if (req.nextUrl.pathname.includes("azure/deployments")) {

app/api/xai.ts

+128
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,128 @@
1+
import { getServerSideConfig } from "@/app/config/server";
2+
import {
3+
XAI_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 { isModelAvailableInServer } 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("[XAI 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.XAI);
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("[XAI] ", e);
37+
return NextResponse.json(prettyObject(e));
38+
}
39+
}
40+
41+
async function request(req: NextRequest) {
42+
const controller = new AbortController();
43+
44+
// alibaba use base url or just remove the path
45+
let path = `${req.nextUrl.pathname}`.replaceAll(ApiPath.XAI, "");
46+
47+
let baseUrl = serverConfig.xaiUrl || XAI_BASE_URL;
48+
49+
if (!baseUrl.startsWith("http")) {
50+
baseUrl = `https://${baseUrl}`;
51+
}
52+
53+
if (baseUrl.endsWith("/")) {
54+
baseUrl = baseUrl.slice(0, -1);
55+
}
56+
57+
console.log("[Proxy] ", path);
58+
console.log("[Base Url]", baseUrl);
59+
60+
const timeoutId = setTimeout(
61+
() => {
62+
controller.abort();
63+
},
64+
10 * 60 * 1000,
65+
);
66+
67+
const fetchUrl = `${baseUrl}${path}`;
68+
const fetchOptions: RequestInit = {
69+
headers: {
70+
"Content-Type": "application/json",
71+
Authorization: req.headers.get("Authorization") ?? "",
72+
},
73+
method: req.method,
74+
body: req.body,
75+
redirect: "manual",
76+
// @ts-ignore
77+
duplex: "half",
78+
signal: controller.signal,
79+
};
80+
81+
// #1815 try to refuse some request to some models
82+
if (serverConfig.customModels && req.body) {
83+
try {
84+
const clonedBody = await req.text();
85+
fetchOptions.body = clonedBody;
86+
87+
const jsonBody = JSON.parse(clonedBody) as { model?: string };
88+
89+
// not undefined and is false
90+
if (
91+
isModelAvailableInServer(
92+
serverConfig.customModels,
93+
jsonBody?.model as string,
94+
ServiceProvider.XAI as string,
95+
)
96+
) {
97+
return NextResponse.json(
98+
{
99+
error: true,
100+
message: `you are not allowed to use ${jsonBody?.model} model`,
101+
},
102+
{
103+
status: 403,
104+
},
105+
);
106+
}
107+
} catch (e) {
108+
console.error(`[XAI] filter`, e);
109+
}
110+
}
111+
try {
112+
const res = await fetch(fetchUrl, fetchOptions);
113+
114+
// to prevent browser prompt for credentials
115+
const newHeaders = new Headers(res.headers);
116+
newHeaders.delete("www-authenticate");
117+
// to disable nginx buffering
118+
newHeaders.set("X-Accel-Buffering", "no");
119+
120+
return new Response(res.body, {
121+
status: res.status,
122+
statusText: res.statusText,
123+
headers: newHeaders,
124+
});
125+
} finally {
126+
clearTimeout(timeoutId);
127+
}
128+
}

app/client/api.ts

+10
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ import { QwenApi } from "./platforms/alibaba";
2020
import { HunyuanApi } from "./platforms/tencent";
2121
import { MoonshotApi } from "./platforms/moonshot";
2222
import { SparkApi } from "./platforms/iflytek";
23+
import { XAIApi } from "./platforms/xai";
2324

2425
export const ROLES = ["system", "user", "assistant"] as const;
2526
export type MessageRole = (typeof ROLES)[number];
@@ -152,6 +153,9 @@ export class ClientApi {
152153
case ModelProvider.Iflytek:
153154
this.llm = new SparkApi();
154155
break;
156+
case ModelProvider.XAI:
157+
this.llm = new XAIApi();
158+
break;
155159
default:
156160
this.llm = new ChatGPTApi();
157161
}
@@ -239,6 +243,7 @@ export function getHeaders(ignoreHeaders: boolean = false) {
239243
const isAlibaba = modelConfig.providerName === ServiceProvider.Alibaba;
240244
const isMoonshot = modelConfig.providerName === ServiceProvider.Moonshot;
241245
const isIflytek = modelConfig.providerName === ServiceProvider.Iflytek;
246+
const isXAI = modelConfig.providerName === ServiceProvider.XAI;
242247
const isEnabledAccessControl = accessStore.enabledAccessControl();
243248
const apiKey = isGoogle
244249
? accessStore.googleApiKey
@@ -252,6 +257,8 @@ export function getHeaders(ignoreHeaders: boolean = false) {
252257
? accessStore.alibabaApiKey
253258
: isMoonshot
254259
? accessStore.moonshotApiKey
260+
: isXAI
261+
? accessStore.xaiApiKey
255262
: isIflytek
256263
? accessStore.iflytekApiKey && accessStore.iflytekApiSecret
257264
? accessStore.iflytekApiKey + ":" + accessStore.iflytekApiSecret
@@ -266,6 +273,7 @@ export function getHeaders(ignoreHeaders: boolean = false) {
266273
isAlibaba,
267274
isMoonshot,
268275
isIflytek,
276+
isXAI,
269277
apiKey,
270278
isEnabledAccessControl,
271279
};
@@ -328,6 +336,8 @@ export function getClientApi(provider: ServiceProvider): ClientApi {
328336
return new ClientApi(ModelProvider.Moonshot);
329337
case ServiceProvider.Iflytek:
330338
return new ClientApi(ModelProvider.Iflytek);
339+
case ServiceProvider.XAI:
340+
return new ClientApi(ModelProvider.XAI);
331341
default:
332342
return new ClientApi(ModelProvider.GPT);
333343
}

0 commit comments

Comments
 (0)