Rebuild and update project functionality
This commit is contained in:
70
app/api/qwen/chat/route.ts
Normal file
70
app/api/qwen/chat/route.ts
Normal file
@@ -0,0 +1,70 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { createQwenHeaders } from "../constants";
|
||||
|
||||
const DEFAULT_QWEN_ENDPOINT = "https://dashscope-intl.aliyuncs.com/compatible-mode/v1";
|
||||
|
||||
function normalizeEndpoint(raw?: string | null): string {
|
||||
const trimmed = (raw || "").trim();
|
||||
if (!trimmed) {
|
||||
return DEFAULT_QWEN_ENDPOINT;
|
||||
}
|
||||
|
||||
if (trimmed.endsWith("/chat/completions")) {
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
const cleaned = trimmed.replace(/\/$/, "");
|
||||
return `${cleaned}/chat/completions`;
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const body = await request.json().catch(() => ({}));
|
||||
const { endpoint, model, messages, stream } = body || {};
|
||||
const authorization = request.headers.get("authorization") || body?.authorization;
|
||||
|
||||
if (!authorization) {
|
||||
return NextResponse.json(
|
||||
{ error: "Authorization header required" },
|
||||
{ status: 401 }
|
||||
);
|
||||
}
|
||||
|
||||
const url = normalizeEndpoint(endpoint);
|
||||
const response = await fetch(url, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
...createQwenHeaders("application/json"),
|
||||
Authorization: authorization,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
model,
|
||||
messages,
|
||||
stream,
|
||||
}),
|
||||
});
|
||||
|
||||
const payload = await response.text();
|
||||
if (!response.ok) {
|
||||
return NextResponse.json(
|
||||
{ error: payload || response.statusText || "Qwen chat failed" },
|
||||
{ status: response.status }
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
const data = JSON.parse(payload);
|
||||
return NextResponse.json(data, { status: response.status });
|
||||
} catch {
|
||||
return NextResponse.json(
|
||||
{ error: payload || "Unexpected response format" },
|
||||
{ status: 502 }
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
return NextResponse.json(
|
||||
{ error: "internal_server_error", message: error instanceof Error ? error.message : "Qwen chat failed" },
|
||||
{ status: 500 }
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user