Images + TTS

This commit is contained in:
Zebratic committed 2026-02-27 21:18:44 +01:00
1 parent 6195553845
commit b5928cd270
40 files changed
+4869 -427

No files matched your search

+1554 -3
View File
File diff suppressed because it is too large. Load diff
+3
View File
@@ -39,7 +39,10 @@
"pino-pretty": "^13.0.0",
"react": "^19.1.0",
"react-dom": "^19.1.0",
"react-markdown": "^10.1.0",
"recharts": "^3.7.0",
"rehype-highlight": "^7.0.2",
"remark-gfm": "^4.0.1",
"sonner": "^2.0.3",
"tailwind-merge": "^3.3.0",
"zod": "^3.25.20"
+46 -1
View File
@@ -207,6 +207,51 @@ async function main() {
providerModelId: "sonar-reasoning-pro",
priority: 0,
},
// Image generation models
{
logicalModelId: "gpt-image-1",
providerId: "openai",
providerModelId: "gpt-image-1",
priority: 0,
modelType: "image",
},
{
logicalModelId: "dall-e-3",
providerId: "openai",
providerModelId: "dall-e-3",
priority: 0,
modelType: "image",
},
{
logicalModelId: "dall-e-2",
providerId: "openai",
providerModelId: "dall-e-2",
priority: 0,
modelType: "image",
},
// Audio TTS models
{
logicalModelId: "tts-1",
providerId: "openai",
providerModelId: "tts-1",
priority: 0,
modelType: "audio",
},
{
logicalModelId: "tts-1-hd",
providerId: "openai",
providerModelId: "tts-1-hd",
priority: 0,
modelType: "audio",
},
// Grok image model
{
logicalModelId: "grok-2-image",
providerId: "grok",
providerModelId: "grok-2-image",
priority: 0,
modelType: "image",
},
];
for (const mapping of mappings) {
@@ -218,7 +263,7 @@ async function main() {
},
{
$setOnInsert: { _id: crypto.randomUUID(), createdAt: now },
$set: { ...mapping, enabled: true, updatedAt: now },
$set: { ...mapping, enabled: true, modelType: mapping.modelType ?? "chat", updatedAt: now },
},
{ upsert: true },
);
+1 -1
View File
@@ -1,6 +1,6 @@
export default function AuthLayout({ children }: { children: React.ReactNode }) {
return (
<div className="flex min-h-screen items-center justify-center bg-muted/40 p-4">
<div className="flex min-h-screen items-center justify-center bg-background p-4">
<div className="w-full max-w-md">{children}</div>
</div>
);
+2 -2
View File
@@ -46,9 +46,9 @@ function LoginForm() {
}
return (
<div className="rounded-lg border bg-card p-8 shadow-sm">
<div className="w-full max-w-md rounded-lg border bg-card p-5 shadow-sm sm:p-8">
<div className="mb-6 text-center">
<h1 className="text-2xl font-bold">Sign In</h1>
<h1 className="text-xl font-bold sm:text-2xl">Sign In</h1>
<p className="mt-1 text-sm text-muted-foreground">Enter your credentials to continue</p>
</div>
+2 -2
View File
@@ -56,9 +56,9 @@ export default function RegisterPage() {
}
return (
<div className="rounded-lg border bg-card p-8 shadow-sm">
<div className="w-full max-w-md rounded-lg border bg-card p-5 shadow-sm sm:p-8">
<div className="mb-6 text-center">
<h1 className="text-2xl font-bold">Create Account</h1>
<h1 className="text-xl font-bold sm:text-2xl">Create Account</h1>
<p className="mt-1 text-sm text-muted-foreground">Get started with LLM Proxy</p>
</div>
+2 -2
View File
@@ -9,11 +9,11 @@ export default async function AdminLayout({ children }: { children: React.ReactN
if (session.user.role !== "ADMIN") redirect("/dashboard");
return (
<div className="flex h-screen">
<div className="flex h-[100dvh]">
<Sidebar variant="admin" />
<div className="flex flex-1 flex-col overflow-hidden">
<Header />
<main className="flex-1 overflow-y-auto p-6">{children}</main>
<main className="flex-1 overflow-y-auto p-4 pt-16 md:p-6 md:pt-6">{children}</main>
</div>
</div>
);
+6 -6
View File
@@ -16,10 +16,10 @@ export default async function AdminOverview() {
]);
const stats = [
{ title: "Total Users", value: userCount, icon: Users },
{ title: "Active Providers", value: providerCount, icon: Server },
{ title: "Active Provider Keys", value: providerKeyCount, icon: Key },
{ title: "Requests Today", value: todayLogs, icon: Activity },
{ title: "Total Users", value: userCount, icon: Users, color: "text-blue-400" },
{ title: "Active Providers", value: providerCount, icon: Server, color: "text-cyan-400" },
{ title: "Active Provider Keys", value: providerKeyCount, icon: Key, color: "text-violet-400" },
{ title: "Requests Today", value: todayLogs, icon: Activity, color: "text-emerald-400" },
];
return (
@@ -27,10 +27,10 @@ export default async function AdminOverview() {
<h1 className="text-2xl font-bold">Admin Overview</h1>
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
{stats.map((stat) => (
<Card key={stat.title}>
<Card key={stat.title} className="border-white/[0.06] bg-white/[0.02]">
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">{stat.title}</CardTitle>
<stat.icon className="h-4 w-4 text-muted-foreground" />
<stat.icon className={`h-4 w-4 ${stat.color}`} />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">{stat.value}</div>
@@ -0,0 +1,295 @@
import { NextResponse } from "next/server";
import { z } from "zod";
import { getSession } from "@/lib/auth-helpers";
import { db } from "@/lib/db";
import { logger } from "@/lib/logger";
import { checkRateLimit } from "@/server/services/rate-limiter";
import { resolveModelRouteCandidates } from "@/server/services/model-router";
import { logUsage } from "@/server/services/usage-logger";
import { ApiError, internalError, modelNotFound, rateLimitExceeded } from "@/lib/api-error";
import { sseHeaders } from "@/server/services/streaming";
import type { UnifiedChatRequest } from "@/types/unified-request";
const imagePartSchema = z.object({
type: z.literal("image_url"),
image_url: z.object({
url: z.string().min(1),
detail: z.enum(["auto", "low", "high"]).optional(),
}),
});
const messageSchema = z.object({
content: z.string().trim().min(1),
images: z.array(imagePartSchema).max(10).optional(),
model: z.string().min(1).optional(),
});
function shouldRetry(error: ApiError) {
return error.statusCode === 429 || (error.statusCode >= 500 && error.statusCode < 600);
}
export async function GET(
_req: Request,
{ params }: { params: Promise<{ conversationId: string }> },
) {
const session = await getSession();
if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
const { conversationId } = await params;
const conversation = await db.chatConversation.findUnique({ where: { id: conversationId } });
if (!conversation || (conversation as Record<string, unknown>).userId !== session.user.id) {
return NextResponse.json({ error: "Not found" }, { status: 404 });
}
const messages = await db.chatMessage.findMany({
where: { conversationId },
orderBy: { createdAt: "asc" },
take: 500,
});
return NextResponse.json({ data: messages });
}
export async function POST(
req: Request,
{ params }: { params: Promise<{ conversationId: string }> },
) {
const session = await getSession();
if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
const { conversationId } = await params;
const conversation = await db.chatConversation.findUnique({ where: { id: conversationId } });
if (!conversation || (conversation as Record<string, unknown>).userId !== session.user.id) {
return NextResponse.json({ error: "Not found" }, { status: 404 });
}
let body: unknown;
try {
body = await req.json();
} catch {
return NextResponse.json({ error: "Invalid JSON" }, { status: 400 });
}
const parsed = messageSchema.safeParse(body);
if (!parsed.success) {
return NextResponse.json({ error: parsed.error.errors[0]?.message ?? "Invalid input" }, { status: 400 });
}
const conv = conversation as Record<string, unknown>;
const modelId = parsed.data.model || (conv.model as string) || "";
if (!modelId) {
return NextResponse.json({ error: "No model selected" }, { status: 400 });
}
if (modelId !== conv.model) {
await db.chatConversation.update({ where: { id: conversationId }, data: { model: modelId } });
}
// Save user message (store images as JSON array alongside text content)
const userMsgData: Record<string, unknown> = {
conversationId,
role: "user",
content: parsed.data.content,
};
if (parsed.data.images?.length) {
userMsgData.images = parsed.data.images;
}
const userMsg = await db.chatMessage.create({ data: userMsgData });
// Get history for context
const history = await db.chatMessage.findMany({
where: { conversationId },
orderBy: { createdAt: "asc" },
take: 50,
});
// Resolve API key and rate limit
const [apiKeys, subscription] = await Promise.all([
db.userApiKey.findMany({
where: { userId: session.user.id },
orderBy: { createdAt: "asc" },
select: { id: true, status: true, dailyRequestLimit: true, dailyTokenLimit: true, softCostLimitCents: true },
}),
db.subscription.findUnique({
where: { userId: session.user.id },
include: { plan: true },
}),
]);
type ApiKeyRow = {
id: string;
status?: string | null;
dailyRequestLimit?: number | null;
dailyTokenLimit?: number | null;
softCostLimitCents?: number | null;
};
const apiKey = (apiKeys as ApiKeyRow[]).find((k) => !k.status || k.status === "ACTIVE") ?? null;
if (!apiKey) {
return NextResponse.json({ error: "Create a user API key first in Dashboard > API Keys." }, { status: 400 });
}
const sub = subscription as { plan?: { dailyRequestLimit?: number | null; dailyTokenLimit?: number | null } } | null;
if (!sub?.plan) {
return NextResponse.json({ error: "No active subscription plan found." }, { status: 403 });
}
const limits = {
dailyRequests: apiKey.dailyRequestLimit ?? sub.plan.dailyRequestLimit ?? null,
dailyTokens: apiKey.dailyTokenLimit ?? sub.plan.dailyTokenLimit ?? null,
dailyCostCents: apiKey.softCostLimitCents ?? null,
};
const rateLimit = await checkRateLimit(apiKey.id, limits);
if (!rateLimit.allowed) {
return rateLimitExceeded(rateLimit.reason!, rateLimit.retryAfter!);
}
const routes = await resolveModelRouteCandidates(modelId);
if (routes.length === 0) {
return modelNotFound(modelId).toResponse();
}
type HistoryRow = { role: string; content: string; images?: Array<{ type: "image_url"; image_url: { url: string; detail?: string } }> };
const chatMessages: UnifiedChatRequest["messages"] = (history as HistoryRow[]).map((m) => {
if (m.images?.length) {
return {
role: m.role as "user" | "assistant" | "system",
content: [
{ type: "text" as const, text: m.content },
...m.images.map((img) => ({
type: "image_url" as const,
image_url: { url: img.image_url.url, detail: img.image_url.detail as "auto" | "low" | "high" | undefined },
})),
],
};
}
return {
role: m.role as "user" | "assistant" | "system",
content: m.content,
};
});
const unifiedReq: UnifiedChatRequest = {
model: modelId,
messages: chatMessages,
stream: true,
};
const startedAt = Date.now();
let lastApiError: ApiError | null = null;
for (const route of routes) {
try {
const providerStream = await route.adapter.chatCompletionStream(unifiedReq, route.ctx);
// Build a transform that:
// 1. Passes SSE chunks to the client
// 2. Accumulates the full text and usage for DB persistence after stream ends
const encoder = new TextEncoder();
const decoder = new TextDecoder();
let fullText = "";
let tokensIn = 0;
let tokensOut = 0;
const outputStream = new ReadableStream<Uint8Array>({
async start(controller) {
// Send the userMessage id as the first custom SSE event
controller.enqueue(
encoder.encode(`event: meta\ndata: ${JSON.stringify({ userMessageId: userMsg.id, providerId: route.providerId })}\n\n`),
);
const reader = providerStream.getReader();
try {
while (true) {
const { done, value } = await reader.read();
if (done) break;
// Forward raw SSE chunk to client
controller.enqueue(value);
// Parse to accumulate text and usage
const text = decoder.decode(value, { stream: true });
for (const line of text.split("\n")) {
if (!line.startsWith("data: ") || line === "data: [DONE]") continue;
try {
const json = JSON.parse(line.slice(6));
const delta = json.choices?.[0]?.delta;
if (delta?.content) fullText += delta.content;
if (json.usage) {
tokensIn = json.usage.prompt_tokens ?? tokensIn;
tokensOut = json.usage.completion_tokens ?? tokensOut;
}
} catch {
// skip
}
}
}
} catch (err) {
logger.error(err, "Stream read error");
}
// Stream done — persist assistant message and log usage
const latencyMs = Date.now() - startedAt;
const assistantMsg = await db.chatMessage.create({
data: {
conversationId,
role: "assistant",
content: fullText,
model: modelId,
providerId: route.providerId,
tokensIn,
tokensOut,
},
});
// Auto-title on first exchange
if ((history as unknown[]).length <= 1) {
const autoTitle = parsed.data.content.slice(0, 60) + (parsed.data.content.length > 60 ? "..." : "");
await db.chatConversation.update({ where: { id: conversationId }, data: { title: autoTitle } });
}
await db.chatConversation.update({ where: { id: conversationId }, data: {} });
// Send final meta event with saved message info
controller.enqueue(
encoder.encode(
`event: done\ndata: ${JSON.stringify({ assistantMessageId: assistantMsg.id, tokensIn, tokensOut })}\n\n`,
),
);
controller.close();
logUsage({
userId: session.user.id,
userApiKeyId: apiKey.id,
providerId: route.providerId,
providerApiKeyId: route.providerApiKeyId,
logicalModelId: route.logicalModelId,
providerModelId: route.providerModelId,
statusCode: 200,
tokensIn,
tokensOut,
latencyMs,
streamed: true,
promptText: chatMessages.map((m) => {
const text = typeof m.content === "string" ? m.content : Array.isArray(m.content) ? m.content.filter((p) => p.type === "text").map((p) => (p as { text: string }).text).join("") : "";
return `${m.role}: ${text}`;
}).join("\n"),
responseText: fullText,
loggingMode: "preview",
}).catch((err) => logger.error(err, "Failed to log chat streaming usage"));
},
});
return new Response(outputStream, { status: 200, headers: sseHeaders() });
} catch (error) {
if (error instanceof ApiError) {
lastApiError = error;
if (shouldRetry(error)) continue;
return error.toResponse();
}
logger.error(error, "Unhandled chat error");
}
}
if (lastApiError) return lastApiError.toResponse();
return internalError().toResponse();
}
@@ -0,0 +1,50 @@
import { NextResponse } from "next/server";
import { getSession } from "@/lib/auth-helpers";
import { db } from "@/lib/db";
export async function PATCH(
req: Request,
{ params }: { params: Promise<{ conversationId: string }> },
) {
const session = await getSession();
if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
const { conversationId } = await params;
const conversation = await db.chatConversation.findUnique({ where: { id: conversationId } });
if (!conversation || (conversation as Record<string, unknown>).userId !== session.user.id) {
return NextResponse.json({ error: "Not found" }, { status: 404 });
}
let body: Record<string, unknown> = {};
try {
body = (await req.json()) as Record<string, unknown>;
} catch {
return NextResponse.json({ error: "Invalid JSON" }, { status: 400 });
}
const data: Record<string, unknown> = {};
if (typeof body.title === "string") data.title = body.title.trim();
if (typeof body.model === "string") data.model = body.model.trim();
const updated = await db.chatConversation.update({ where: { id: conversationId }, data });
return NextResponse.json({ data: updated });
}
export async function DELETE(
_req: Request,
{ params }: { params: Promise<{ conversationId: string }> },
) {
const session = await getSession();
if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
const { conversationId } = await params;
const conversation = await db.chatConversation.findUnique({ where: { id: conversationId } });
if (!conversation || (conversation as Record<string, unknown>).userId !== session.user.id) {
return NextResponse.json({ error: "Not found" }, { status: 404 });
}
await db.chatMessage.deleteMany({ where: { conversationId } });
await db.chatConversation.delete({ where: { id: conversationId } });
return NextResponse.json({ ok: true });
}
@@ -0,0 +1,84 @@
import { NextResponse } from "next/server";
import { z } from "zod";
import { getSession } from "@/lib/auth-helpers";
import { db } from "@/lib/db";
/**
* Save messages to a conversation without triggering LLM generation.
* Used by image/audio generation flows where the generation happens
* via dedicated endpoints but messages still need to be persisted.
*/
const messageEntrySchema = z.object({
role: z.enum(["user", "assistant"]),
content: z.string(),
model: z.string().optional(),
providerId: z.string().optional(),
images: z.array(z.unknown()).optional(),
generatedImages: z.array(z.unknown()).optional(),
audioB64: z.string().optional(),
audioContentType: z.string().optional(),
});
const schema = z.object({
messages: z.array(messageEntrySchema).min(1).max(10),
});
export async function POST(
req: Request,
{ params }: { params: Promise<{ conversationId: string }> },
) {
const session = await getSession();
if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
const { conversationId } = await params;
const conversation = await db.chatConversation.findUnique({ where: { id: conversationId } });
if (!conversation || (conversation as Record<string, unknown>).userId !== session.user.id) {
return NextResponse.json({ error: "Not found" }, { status: 404 });
}
let body: unknown;
try {
body = await req.json();
} catch {
return NextResponse.json({ error: "Invalid JSON" }, { status: 400 });
}
const parsed = schema.safeParse(body);
if (!parsed.success) {
return NextResponse.json({ error: parsed.error.errors[0]?.message ?? "Invalid input" }, { status: 400 });
}
const saved = [];
for (const msg of parsed.data.messages) {
const data: Record<string, unknown> = {
conversationId,
role: msg.role,
content: msg.content,
};
if (msg.model) data.model = msg.model;
if (msg.providerId) data.providerId = msg.providerId;
if (msg.images) data.images = msg.images;
if (msg.generatedImages) data.generatedImages = msg.generatedImages;
if (msg.audioB64) data.audioB64 = msg.audioB64;
if (msg.audioContentType) data.audioContentType = msg.audioContentType;
const created = await db.chatMessage.create({ data });
saved.push(created);
}
// Auto-title on first messages
const existingCount = await db.chatMessage.count({ where: { conversationId } });
if (existingCount <= parsed.data.messages.length + 1) {
const userMsg = parsed.data.messages.find((m) => m.role === "user");
if (userMsg) {
const autoTitle = userMsg.content.slice(0, 60) + (userMsg.content.length > 60 ? "..." : "");
await db.chatConversation.update({ where: { id: conversationId }, data: { title: autoTitle } });
}
}
// Touch updatedAt
await db.chatConversation.update({ where: { id: conversationId }, data: {} });
return NextResponse.json({ data: saved });
}
+41
View File
@@ -0,0 +1,41 @@
import { NextResponse } from "next/server";
import { getSession } from "@/lib/auth-helpers";
import { db } from "@/lib/db";
export async function GET() {
const session = await getSession();
if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
const conversations = await db.chatConversation.findMany({
where: { userId: session.user.id },
orderBy: { updatedAt: "desc" },
take: 100,
});
return NextResponse.json({ data: conversations });
}
export async function POST(req: Request) {
const session = await getSession();
if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
let body: Record<string, unknown> = {};
try {
body = (await req.json()) as Record<string, unknown>;
} catch {
// empty body is fine
}
const title = typeof body.title === "string" && body.title.trim() ? body.title.trim() : "New chat";
const model = typeof body.model === "string" && body.model.trim() ? body.model.trim() : "";
const conversation = await db.chatConversation.create({
data: {
userId: session.user.id,
title,
model,
},
});
return NextResponse.json({ data: conversation }, { status: 201 });
}
+124
View File
@@ -0,0 +1,124 @@
import { NextResponse } from "next/server";
import { z } from "zod";
import { getSession } from "@/lib/auth-helpers";
import { db } from "@/lib/db";
import { logger } from "@/lib/logger";
import { checkRateLimit } from "@/server/services/rate-limiter";
import { resolveModelRouteCandidates } from "@/server/services/model-router";
import { logUsage } from "@/server/services/usage-logger";
import { ApiError, internalError, modelNotFound, rateLimitExceeded } from "@/lib/api-error";
const schema = z.object({
model: z.string().min(1),
input: z.string().trim().min(1).max(4096),
voice: z.enum(["alloy", "ash", "ballad", "coral", "echo", "fable", "onyx", "nova", "sage", "shimmer"]).optional().default("alloy"),
speed: z.number().min(0.25).max(4).optional(),
});
export async function POST(req: Request) {
const session = await getSession();
if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
let body: unknown;
try {
body = await req.json();
} catch {
return NextResponse.json({ error: "Invalid JSON" }, { status: 400 });
}
const parsed = schema.safeParse(body);
if (!parsed.success) {
return NextResponse.json({ error: parsed.error.errors[0]?.message ?? "Invalid input" }, { status: 400 });
}
const payload = parsed.data;
const [apiKeys, subscription] = await Promise.all([
db.userApiKey.findMany({
where: { userId: session.user.id },
orderBy: { createdAt: "asc" },
select: { id: true, status: true, dailyRequestLimit: true, dailyTokenLimit: true, softCostLimitCents: true },
}),
db.subscription.findUnique({
where: { userId: session.user.id },
include: { plan: true },
}),
]);
type ApiKeyRow = { id: string; status?: string | null; dailyRequestLimit?: number | null; dailyTokenLimit?: number | null; softCostLimitCents?: number | null };
const apiKey = (apiKeys as ApiKeyRow[]).find((k) => !k.status || k.status === "ACTIVE") ?? null;
if (!apiKey) return NextResponse.json({ error: "Create a user API key first." }, { status: 400 });
const sub = subscription as { plan?: { dailyRequestLimit?: number | null; dailyTokenLimit?: number | null } } | null;
if (!sub?.plan) return NextResponse.json({ error: "No active plan." }, { status: 403 });
const limits = {
dailyRequests: apiKey.dailyRequestLimit ?? sub.plan.dailyRequestLimit ?? null,
dailyTokens: apiKey.dailyTokenLimit ?? sub.plan.dailyTokenLimit ?? null,
dailyCostCents: apiKey.softCostLimitCents ?? null,
};
const rateLimit = await checkRateLimit(apiKey.id, limits);
if (!rateLimit.allowed) return rateLimitExceeded(rateLimit.reason!, rateLimit.retryAfter!);
const routes = await resolveModelRouteCandidates(payload.model);
if (routes.length === 0) return modelNotFound(payload.model).toResponse();
const startedAt = Date.now();
let lastApiError: ApiError | null = null;
for (const route of routes) {
if (!route.adapter.audioSpeech) continue;
try {
const audioBuffer = await route.adapter.audioSpeech(
{
model: payload.model,
input: payload.input,
voice: payload.voice,
response_format: "mp3",
speed: payload.speed,
},
route.ctx,
);
const latencyMs = Date.now() - startedAt;
logUsage({
userId: session.user.id,
userApiKeyId: apiKey.id,
providerId: route.providerId,
providerApiKeyId: route.providerApiKeyId,
logicalModelId: route.logicalModelId,
providerModelId: route.providerModelId,
statusCode: 200,
tokensIn: 0,
tokensOut: 0,
latencyMs,
streamed: false,
promptText: payload.input,
loggingMode: "preview",
}).catch((err) => logger.error(err, "Failed to log audio speech usage"));
// Return audio as base64
const b64 = Buffer.from(audioBuffer).toString("base64");
return NextResponse.json({
providerId: route.providerId,
model: payload.model,
audio: {
b64: b64,
contentType: "audio/mpeg",
},
});
} catch (error) {
if (error instanceof ApiError) {
lastApiError = error;
if (error.statusCode === 429 || error.statusCode >= 500) continue;
return error.toResponse();
}
logger.error(error, "Unhandled audio speech error");
}
}
if (lastApiError) return lastApiError.toResponse();
return internalError().toResponse();
}
+126
View File
@@ -0,0 +1,126 @@
import { NextResponse } from "next/server";
import { z } from "zod";
import { getSession } from "@/lib/auth-helpers";
import { db } from "@/lib/db";
import { logger } from "@/lib/logger";
import { checkRateLimit } from "@/server/services/rate-limiter";
import { resolveModelRouteCandidates } from "@/server/services/model-router";
import { logUsage } from "@/server/services/usage-logger";
import { ApiError, internalError, modelNotFound, rateLimitExceeded } from "@/lib/api-error";
const schema = z.object({
model: z.string().min(1),
prompt: z.string().trim().min(1).max(4000),
size: z.enum(["1024x1024", "1024x1792", "1792x1024", "256x256", "512x512"]).optional(),
quality: z.enum(["auto", "high", "medium", "low", "standard", "hd"]).optional(),
style: z.enum(["vivid", "natural"]).optional(),
n: z.number().int().min(1).max(4).optional(),
});
export async function POST(req: Request) {
const session = await getSession();
if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
let body: unknown;
try {
body = await req.json();
} catch {
return NextResponse.json({ error: "Invalid JSON" }, { status: 400 });
}
const parsed = schema.safeParse(body);
if (!parsed.success) {
return NextResponse.json({ error: parsed.error.errors[0]?.message ?? "Invalid input" }, { status: 400 });
}
const payload = parsed.data;
const [apiKeys, subscription] = await Promise.all([
db.userApiKey.findMany({
where: { userId: session.user.id },
orderBy: { createdAt: "asc" },
select: { id: true, status: true, dailyRequestLimit: true, dailyTokenLimit: true, softCostLimitCents: true },
}),
db.subscription.findUnique({
where: { userId: session.user.id },
include: { plan: true },
}),
]);
type ApiKeyRow = { id: string; status?: string | null; dailyRequestLimit?: number | null; dailyTokenLimit?: number | null; softCostLimitCents?: number | null };
const apiKey = (apiKeys as ApiKeyRow[]).find((k) => !k.status || k.status === "ACTIVE") ?? null;
if (!apiKey) return NextResponse.json({ error: "Create a user API key first." }, { status: 400 });
const sub = subscription as { plan?: { dailyRequestLimit?: number | null; dailyTokenLimit?: number | null } } | null;
if (!sub?.plan) return NextResponse.json({ error: "No active plan." }, { status: 403 });
const limits = {
dailyRequests: apiKey.dailyRequestLimit ?? sub.plan.dailyRequestLimit ?? null,
dailyTokens: apiKey.dailyTokenLimit ?? sub.plan.dailyTokenLimit ?? null,
dailyCostCents: apiKey.softCostLimitCents ?? null,
};
const rateLimit = await checkRateLimit(apiKey.id, limits);
if (!rateLimit.allowed) return rateLimitExceeded(rateLimit.reason!, rateLimit.retryAfter!);
const routes = await resolveModelRouteCandidates(payload.model);
if (routes.length === 0) return modelNotFound(payload.model).toResponse();
const startedAt = Date.now();
let lastApiError: ApiError | null = null;
for (const route of routes) {
if (!route.adapter.imageGeneration) continue;
try {
const result = await route.adapter.imageGeneration(
{
prompt: payload.prompt,
model: payload.model,
n: payload.n,
size: payload.size,
quality: payload.quality,
style: payload.style,
},
route.ctx,
);
const latencyMs = Date.now() - startedAt;
logUsage({
userId: session.user.id,
userApiKeyId: apiKey.id,
providerId: route.providerId,
providerApiKeyId: route.providerApiKeyId,
logicalModelId: route.logicalModelId,
providerModelId: route.providerModelId,
statusCode: 200,
tokensIn: 0,
tokensOut: 0,
latencyMs,
streamed: false,
promptText: payload.prompt,
loggingMode: "preview",
}).catch((err) => logger.error(err, "Failed to log image generation usage"));
return NextResponse.json({
providerId: route.providerId,
model: payload.model,
images: result.data.map((d) => ({
b64_json: d.b64_json,
url: d.url,
revised_prompt: d.revised_prompt,
})),
});
} catch (error) {
if (error instanceof ApiError) {
lastApiError = error;
if (error.statusCode === 429 || error.statusCode >= 500) continue;
return error.toResponse();
}
logger.error(error, "Unhandled image generation error");
}
}
if (lastApiError) return lastApiError.toResponse();
return internalError().toResponse();
}
+165
View File
@@ -0,0 +1,165 @@
import { NextResponse } from "next/server";
import { z } from "zod";
import { getSession } from "@/lib/auth-helpers";
import { db } from "@/lib/db";
import { logger } from "@/lib/logger";
import { checkRateLimit } from "@/server/services/rate-limiter";
import { resolveModelRouteCandidates } from "@/server/services/model-router";
import { ApiError, internalError, modelNotFound, rateLimitExceeded } from "@/lib/api-error";
import { sseHeaders } from "@/server/services/streaming";
import type { UnifiedChatRequest } from "@/types/unified-request";
const imagePartSchema = z.object({
type: z.literal("image_url"),
image_url: z.object({
url: z.string().min(1),
detail: z.enum(["auto", "low", "high"]).optional(),
}),
});
const schema = z.object({
model: z.string().min(1),
message: z.string().trim().min(1),
images: z.array(imagePartSchema).max(10).optional(),
history: z
.array(z.object({
role: z.enum(["user", "assistant"]),
content: z.string(),
images: z.array(imagePartSchema).optional(),
}))
.max(50)
.optional(),
});
function shouldRetry(error: ApiError) {
return error.statusCode === 429 || (error.statusCode >= 500 && error.statusCode < 600);
}
export async function POST(req: Request) {
const session = await getSession();
if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
let body: unknown;
try {
body = await req.json();
} catch {
return NextResponse.json({ error: "Invalid JSON" }, { status: 400 });
}
const parsed = schema.safeParse(body);
if (!parsed.success) {
return NextResponse.json({ error: parsed.error.errors[0]?.message ?? "Invalid input" }, { status: 400 });
}
const payload = parsed.data;
const [apiKeys, subscription] = await Promise.all([
db.userApiKey.findMany({
where: { userId: session.user.id },
orderBy: { createdAt: "asc" },
select: { id: true, status: true, dailyRequestLimit: true, dailyTokenLimit: true, softCostLimitCents: true },
}),
db.subscription.findUnique({
where: { userId: session.user.id },
include: { plan: true },
}),
]);
type ApiKeyRow = { id: string; status?: string | null; dailyRequestLimit?: number | null; dailyTokenLimit?: number | null; softCostLimitCents?: number | null };
const apiKey = (apiKeys as ApiKeyRow[]).find((k) => !k.status || k.status === "ACTIVE") ?? null;
if (!apiKey) return NextResponse.json({ error: "Create a user API key first." }, { status: 400 });
const sub = subscription as { plan?: { dailyRequestLimit?: number | null; dailyTokenLimit?: number | null } } | null;
if (!sub?.plan) return NextResponse.json({ error: "No active plan." }, { status: 403 });
const limits = {
dailyRequests: apiKey.dailyRequestLimit ?? sub.plan.dailyRequestLimit ?? null,
dailyTokens: apiKey.dailyTokenLimit ?? sub.plan.dailyTokenLimit ?? null,
dailyCostCents: apiKey.softCostLimitCents ?? null,
};
const rateLimit = await checkRateLimit(apiKey.id, limits);
if (!rateLimit.allowed) return rateLimitExceeded(rateLimit.reason!, rateLimit.retryAfter!);
const routes = await resolveModelRouteCandidates(payload.model);
if (routes.length === 0) return modelNotFound(payload.model).toResponse();
const messages: UnifiedChatRequest["messages"] = [];
for (const m of payload.history ?? []) {
if (m.images?.length) {
messages.push({
role: m.role,
content: [
{ type: "text", text: m.content },
...m.images.map((img) => ({
type: "image_url" as const,
image_url: { url: img.image_url.url, detail: img.image_url.detail as "auto" | "low" | "high" | undefined },
})),
],
});
} else {
messages.push({ role: m.role, content: m.content });
}
}
if (payload.images?.length) {
messages.push({
role: "user",
content: [
{ type: "text", text: payload.message },
...payload.images.map((img) => ({
type: "image_url" as const,
image_url: { url: img.image_url.url, detail: img.image_url.detail as "auto" | "low" | "high" | undefined },
})),
],
});
} else {
messages.push({ role: "user", content: payload.message });
}
const unifiedReq: UnifiedChatRequest = { model: payload.model, messages, stream: true };
let lastApiError: ApiError | null = null;
for (const route of routes) {
try {
const providerStream = await route.adapter.chatCompletionStream(unifiedReq, route.ctx);
const encoder = new TextEncoder();
const decoder = new TextDecoder();
const outputStream = new ReadableStream<Uint8Array>({
async start(controller) {
// Send provider info as first event
controller.enqueue(
encoder.encode(`event: meta\ndata: ${JSON.stringify({ providerId: route.providerId })}\n\n`),
);
const reader = providerStream.getReader();
try {
while (true) {
const { done, value } = await reader.read();
if (done) break;
controller.enqueue(value);
}
} catch (err) {
logger.error(err, "Incognito stream read error");
}
// No DB writes or usage logging in incognito
controller.enqueue(encoder.encode(`event: done\ndata: {}\n\n`));
controller.close();
},
});
return new Response(outputStream, { status: 200, headers: sseHeaders() });
} catch (error) {
if (error instanceof ApiError) {
lastApiError = error;
if (shouldRetry(error)) continue;
return error.toResponse();
}
logger.error(error, "Unhandled incognito stream error");
}
}
if (lastApiError) return lastApiError.toResponse();
return internalError().toResponse();
}
+58
View File
@@ -0,0 +1,58 @@
import { NextResponse } from "next/server";
import { getSession } from "@/lib/auth-helpers";
import { db } from "@/lib/db";
interface Preferences {
defaultModel?: string;
favouriteModels?: string[];
}
export async function GET() {
const session = await getSession();
if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
const pref = await db.userPreference.findUnique({ where: { userId: session.user.id } });
const data: Preferences = pref
? {
defaultModel: (pref as Record<string, unknown>).defaultModel as string | undefined,
favouriteModels: (pref as Record<string, unknown>).favouriteModels as string[] | undefined,
}
: { defaultModel: "", favouriteModels: [] };
return NextResponse.json({ data });
}
export async function PUT(req: Request) {
const session = await getSession();
if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
let body: Record<string, unknown>;
try {
body = (await req.json()) as Record<string, unknown>;
} catch {
return NextResponse.json({ error: "Invalid JSON" }, { status: 400 });
}
const existing = await db.userPreference.findUnique({ where: { userId: session.user.id } });
const data: Record<string, unknown> = {};
if (typeof body.defaultModel === "string") data.defaultModel = body.defaultModel;
if (Array.isArray(body.favouriteModels)) {
data.favouriteModels = (body.favouriteModels as unknown[]).filter(
(m): m is string => typeof m === "string",
);
}
if (existing) {
const updated = await db.userPreference.update({
where: { id: (existing as Record<string, unknown>).id as string },
data,
});
return NextResponse.json({ data: updated });
}
const created = await db.userPreference.create({
data: { userId: session.user.id, ...data },
});
return NextResponse.json({ data: created }, { status: 201 });
}
+32 -9
View File
@@ -34,21 +34,43 @@ export async function GET() {
const session = await getSession();
if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
// Get providers that have at least one ACTIVE key
const providersWithKeys = await db.providerApiKey.findMany({
where: { status: "ACTIVE" },
select: { providerId: true },
});
const activeProviderIds = new Set(
(providersWithKeys as Array<{ providerId: string }>).map((k) => k.providerId),
);
// Also check provider is enabled
const enabledProviders = await db.provider.findMany({
where: { enabled: true },
select: { id: true },
});
const enabledProviderIds = new Set(
(enabledProviders as Array<{ id: string }>).map((p) => p.id),
);
const mappings = (await db.modelMapping.findMany({
where: { enabled: true },
select: { logicalModelId: true, providerId: true, priority: true },
select: { logicalModelId: true, providerId: true, priority: true, modelType: true },
orderBy: [{ logicalModelId: "asc" }, { priority: "asc" }],
})) as Array<{ logicalModelId: string; providerId: string }>;
})) as Array<{ logicalModelId: string; providerId: string; modelType?: string }>;
const byModel = new Map<string, string>();
const byModel = new Map<string, { providerId: string; modelType: string }>();
for (const row of mappings) {
if (!byModel.has(row.logicalModelId)) {
byModel.set(row.logicalModelId, row.providerId);
if (
!byModel.has(row.logicalModelId) &&
activeProviderIds.has(row.providerId) &&
enabledProviderIds.has(row.providerId)
) {
byModel.set(row.logicalModelId, { providerId: row.providerId, modelType: row.modelType ?? "chat" });
}
}
return NextResponse.json({
data: [...byModel.entries()].map(([id, providerId]) => ({ id, providerId })),
data: [...byModel.entries()].map(([id, info]) => ({ id, providerId: info.providerId, modelType: info.modelType })),
});
}
@@ -140,7 +162,8 @@ export async function POST(req: Request) {
try {
const result = await route.adapter.chatCompletion(unifiedReq, route.ctx);
const latencyMs = Date.now() - startedAt;
const assistantText = result.choices[0]?.message.content ?? "";
const rawContent = result.choices[0]?.message.content;
const assistantText = typeof rawContent === "string" ? rawContent : "";
logUsage({
userId: session.user.id,
@@ -154,7 +177,7 @@ export async function POST(req: Request) {
tokensOut: result.usage?.completion_tokens ?? 0,
latencyMs,
streamed: false,
promptText: messages.map((m) => `${m.role}: ${m.content ?? ""}`).join("\n"),
promptText: messages.map((m) => `${m.role}: ${typeof m.content === "string" ? m.content : ""}`).join("\n"),
responseText: assistantText,
loggingMode: "preview",
}).catch((err) => logger.error(err, "Failed to log playground usage"));
@@ -183,7 +206,7 @@ export async function POST(req: Request) {
tokensOut: 0,
latencyMs,
streamed: false,
promptText: messages.map((m) => `${m.role}: ${m.content ?? ""}`).join("\n"),
promptText: messages.map((m) => `${m.role}: ${typeof m.content === "string" ? m.content : ""}`).join("\n"),
loggingMode: "hash_only",
}).catch(() => {});
+9
View File
@@ -0,0 +1,9 @@
import { redirect } from "next/navigation";
import { getSession } from "@/lib/auth-helpers";
export default async function ChatLayout({ children }: { children: React.ReactNode }) {
const session = await getSession();
if (!session) redirect("/login");
return <>{children}</>;
}
File diff suppressed because it is too large. Load diff
+3 -3
View File
@@ -120,10 +120,10 @@ export default function ApiKeysPage() {
return (
<div className="space-y-6">
<div className="flex items-center justify-between">
<div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
<div>
<h1 className="text-2xl font-bold">API Keys</h1>
<p className="text-muted-foreground">Manage your API keys for accessing the LLM Proxy</p>
<h1 className="text-xl font-bold sm:text-2xl">API Keys</h1>
<p className="text-sm text-muted-foreground">Manage your API keys for accessing the LLM Proxy</p>
</div>
<Dialog
open={createOpen}
+2 -2
View File
@@ -8,11 +8,11 @@ export default async function DashboardLayout({ children }: { children: React.Re
if (!session) redirect("/login");
return (
<div className="flex h-screen">
<div className="flex h-[100dvh]">
<Sidebar variant="dashboard" />
<div className="flex flex-1 flex-col overflow-hidden">
<Header />
<main className="flex-1 overflow-y-auto p-6">{children}</main>
<main className="flex-1 overflow-y-auto p-4 pt-16 md:p-6 md:pt-6">{children}</main>
</div>
</div>
);
+9 -5
View File
@@ -72,21 +72,25 @@ export default async function DashboardOverview() {
title: "Active API Keys",
value: apiKeyCount,
icon: Key,
color: "text-blue-400",
},
{
title: "Requests Today",
value: todayLogs._count,
icon: Activity,
color: "text-cyan-400",
},
{
title: "Tokens Today",
value: ((todayLogs._sum.tokensIn ?? 0) + (todayLogs._sum.tokensOut ?? 0)).toLocaleString(),
icon: AlertCircle,
color: "text-violet-400",
},
{
title: "Cost Today",
value: `$${((todayLogs._sum.costCents ?? 0) / 100).toFixed(4)}`,
icon: Coins,
color: "text-emerald-400",
},
];
@@ -99,16 +103,16 @@ export default async function DashboardOverview() {
</p>
</div>
<Card>
<Card className="border-white/[0.06] bg-white/[0.02]">
<CardHeader className="pb-3">
<CardTitle className="flex items-center gap-2 text-base">
<BookOpen className="h-4 w-4" />
<BookOpen className="h-4 w-4 text-blue-400" />
API Documentation
</CardTitle>
</CardHeader>
<CardContent className="flex flex-wrap items-center gap-3">
<p className="text-sm text-muted-foreground">Open guides, endpoint reference, and live API testing.</p>
<Button asChild size="sm">
<Button asChild size="sm" className="bg-blue-500 text-white hover:bg-blue-400">
<Link href="/docs">Open Docs</Link>
</Button>
</CardContent>
@@ -116,10 +120,10 @@ export default async function DashboardOverview() {
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
{stats.map((stat) => (
<Card key={stat.title}>
<Card key={stat.title} className="border-white/[0.06] bg-white/[0.02]">
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
<CardTitle className="text-sm font-medium">{stat.title}</CardTitle>
<stat.icon className="h-4 w-4 text-muted-foreground" />
<stat.icon className={`h-4 w-4 ${stat.color}`} />
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">{stat.value}</div>
+3 -3
View File
@@ -130,8 +130,8 @@ export default function PlaygroundPage() {
<p className="text-muted-foreground">Test any mapped model directly from your dashboard.</p>
</div>
<div className="grid gap-6 lg:grid-cols-[340px_minmax(0,1fr)]">
<Card className="h-fit">
<div className="grid gap-6 lg:grid-cols-[300px_minmax(0,1fr)]">
<Card className="h-fit border-white/[0.06] bg-white/[0.02]">
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Sparkles className="h-4 w-4" />
@@ -200,7 +200,7 @@ export default function PlaygroundPage() {
</CardContent>
</Card>
<Card className="flex min-h-[640px] flex-col">
<Card className="flex min-h-[400px] flex-col border-white/[0.06] bg-white/[0.02] lg:min-h-[640px]">
<CardHeader>
<CardTitle>Chat</CardTitle>
<CardDescription>
+60 -50
View File
@@ -8,31 +8,11 @@ export default async function UsagePage() {
const session = await getSession();
if (!session) return null;
// Last 30 days aggregates
// Last 30 days
const thirtyDaysAgo = new Date();
thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
const aggregates = await db.usageAggregateDaily.findMany({
where: {
userId: session.user.id,
date: { gte: thirtyDaysAgo },
userApiKeyId: null, // user-level aggregates
},
orderBy: { date: "desc" },
take: 30,
});
const totals = aggregates.reduce(
(acc, row) => ({
requests: acc.requests + row.totalRequests,
tokensIn: acc.tokensIn + row.totalTokensIn,
tokensOut: acc.tokensOut + row.totalTokensOut,
cost: acc.cost + row.totalCostCents,
}),
{ requests: 0, tokensIn: 0, tokensOut: 0, cost: 0 },
);
const [providerStats, modelStats, apiKeyStats, apiKeys] = await Promise.all([
const [providerStats, modelStats, apiKeyStats, apiKeys, allLogs] = await Promise.all([
db.requestLog.groupBy({
by: ["providerId"],
where: {
@@ -73,19 +53,51 @@ export default async function UsagePage() {
where: { userId: session.user.id },
select: { id: true, keyPrefix: true },
}),
db.requestLog.findMany({
where: {
userId: session.user.id,
createdAt: { gte: thirtyDaysAgo },
softDeleted: false,
},
select: { tokensIn: true, tokensOut: true, costCents: true, createdAt: true },
orderBy: { createdAt: "asc" },
}),
]);
// Compute totals and daily breakdown from raw request logs
type LogRow = { tokensIn: number; tokensOut: number; costCents: number; createdAt: Date | string };
const logs = allLogs as LogRow[];
const totals = logs.reduce(
(acc, row) => ({
requests: acc.requests + 1,
tokensIn: acc.tokensIn + (row.tokensIn ?? 0),
tokensOut: acc.tokensOut + (row.tokensOut ?? 0),
cost: acc.cost + (row.costCents ?? 0),
}),
{ requests: 0, tokensIn: 0, tokensOut: 0, cost: 0 },
);
// Group logs by day for daily chart
const dailyMap = new Map<string, { requests: number; tokensIn: number; tokensOut: number; cost: number }>();
for (const row of logs) {
const d = new Date(row.createdAt).toLocaleDateString();
const existing = dailyMap.get(d) ?? { requests: 0, tokensIn: 0, tokensOut: 0, cost: 0 };
existing.requests += 1;
existing.tokensIn += row.tokensIn ?? 0;
existing.tokensOut += row.tokensOut ?? 0;
existing.cost += row.costCents ?? 0;
dailyMap.set(d, existing);
}
const keyPrefixMap = new Map(apiKeys.map((k) => [k.id, k.keyPrefix]));
const chartDaily = aggregates
.slice()
.reverse()
.map((row) => ({
date: new Date(row.date).toLocaleDateString(),
requests: row.totalRequests,
tokensIn: row.totalTokensIn,
tokensOut: row.totalTokensOut,
cost: Number((row.totalCostCents / 100).toFixed(4)),
}));
const chartDaily = [...dailyMap.entries()].map(([date, data]) => ({
date,
requests: data.requests,
tokensIn: data.tokensIn,
tokensOut: data.tokensOut,
cost: Number((data.cost / 100).toFixed(4)),
}));
const chartProviders = providerStats.map((row) => ({
name: row.providerId,
@@ -122,33 +134,33 @@ export default async function UsagePage() {
</div>
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
<Card>
<Card className="border-white/[0.06] bg-white/[0.02]">
<CardHeader className="pb-2">
<CardTitle className="text-sm font-medium">Total Requests</CardTitle>
<CardTitle className="text-sm font-medium text-blue-400">Total Requests</CardTitle>
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">{totals.requests.toLocaleString()}</div>
</CardContent>
</Card>
<Card>
<Card className="border-white/[0.06] bg-white/[0.02]">
<CardHeader className="pb-2">
<CardTitle className="text-sm font-medium">Input Tokens</CardTitle>
<CardTitle className="text-sm font-medium text-cyan-400">Input Tokens</CardTitle>
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">{totals.tokensIn.toLocaleString()}</div>
</CardContent>
</Card>
<Card>
<Card className="border-white/[0.06] bg-white/[0.02]">
<CardHeader className="pb-2">
<CardTitle className="text-sm font-medium">Output Tokens</CardTitle>
<CardTitle className="text-sm font-medium text-violet-400">Output Tokens</CardTitle>
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">{totals.tokensOut.toLocaleString()}</div>
</CardContent>
</Card>
<Card>
<Card className="border-white/[0.06] bg-white/[0.02]">
<CardHeader className="pb-2">
<CardTitle className="text-sm font-medium">Total Cost</CardTitle>
<CardTitle className="text-sm font-medium text-emerald-400">Total Cost</CardTitle>
</CardHeader>
<CardContent>
<div className="text-2xl font-bold">${(totals.cost / 100).toFixed(4)}</div>
@@ -161,7 +173,7 @@ export default async function UsagePage() {
<CardTitle>Daily Breakdown</CardTitle>
</CardHeader>
<CardContent>
{aggregates.length === 0 ? (
{chartDaily.length === 0 ? (
<p className="text-sm text-muted-foreground">No usage data yet.</p>
) : (
<Table>
@@ -172,18 +184,16 @@ export default async function UsagePage() {
<TableHead>Tokens In</TableHead>
<TableHead>Tokens Out</TableHead>
<TableHead>Cost</TableHead>
<TableHead>Errors</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{aggregates.map((row) => (
<TableRow key={row.id}>
<TableCell>{new Date(row.date).toLocaleDateString()}</TableCell>
<TableCell>{row.totalRequests.toLocaleString()}</TableCell>
<TableCell>{row.totalTokensIn.toLocaleString()}</TableCell>
<TableCell>{row.totalTokensOut.toLocaleString()}</TableCell>
<TableCell>${(row.totalCostCents / 100).toFixed(4)}</TableCell>
<TableCell>{row.totalErrors}</TableCell>
{[...chartDaily].reverse().map((row) => (
<TableRow key={row.date}>
<TableCell>{row.date}</TableCell>
<TableCell>{row.requests.toLocaleString()}</TableCell>
<TableCell>{row.tokensIn.toLocaleString()}</TableCell>
<TableCell>{row.tokensOut.toLocaleString()}</TableCell>
<TableCell>${row.cost.toFixed(4)}</TableCell>
</TableRow>
))}
</TableBody>
+1 -1
View File
@@ -6,7 +6,7 @@ import { KeySelector } from "@/components/docs/key-selector";
export default function DocsLayout({ children }: { children: React.ReactNode }) {
return (
<DocsAuthProvider>
<main className="mx-auto min-h-screen w-full max-w-7xl px-6 py-8">
<main className="mx-auto min-h-screen w-full max-w-7xl px-4 py-6 sm:px-6 sm:py-8">
<div className="mb-6 flex items-center justify-between">
<Link href="/" className="text-sm font-semibold">
LLM Proxy
+25 -20
View File
@@ -1,26 +1,33 @@
@import "tailwindcss";
@theme inline {
--color-background: hsl(230 26% 8%);
--color-foreground: hsl(210 40% 96%);
--color-card: hsl(230 24% 11%);
--color-card-foreground: hsl(210 40% 96%);
--color-popover: hsl(230 24% 11%);
--color-popover-foreground: hsl(210 40% 96%);
--color-primary: hsl(188 100% 62%);
--color-primary-foreground: hsl(220 40% 8%);
--color-secondary: hsl(230 20% 17%);
--color-secondary-foreground: hsl(210 40% 96%);
--color-muted: hsl(230 18% 16%);
--color-muted-foreground: hsl(220 18% 72%);
--color-accent: hsl(230 20% 20%);
--color-accent-foreground: hsl(210 40% 96%);
--color-destructive: hsl(2 79% 60%);
--color-background: hsl(220 16% 4%);
--color-foreground: hsl(210 20% 95%);
--color-card: hsl(220 16% 7%);
--color-card-foreground: hsl(210 20% 95%);
--color-popover: hsl(220 16% 7%);
--color-popover-foreground: hsl(210 20% 95%);
--color-primary: hsl(213 94% 58%);
--color-primary-foreground: hsl(0 0% 100%);
--color-secondary: hsl(220 14% 12%);
--color-secondary-foreground: hsl(210 20% 95%);
--color-muted: hsl(220 14% 11%);
--color-muted-foreground: hsl(220 10% 55%);
--color-accent: hsl(220 14% 14%);
--color-accent-foreground: hsl(210 20% 95%);
--color-destructive: hsl(0 72% 55%);
--color-destructive-foreground: hsl(0 0% 98%);
--color-border: hsl(230 20% 24%);
--color-input: hsl(230 20% 24%);
--color-ring: hsl(188 100% 62%);
--color-border: hsl(220 14% 14%);
--color-input: hsl(220 14% 14%);
--color-ring: hsl(213 94% 58%);
--radius: 0.5rem;
--color-chart-blue: hsl(213 94% 58%);
--color-chart-cyan: hsl(187 85% 53%);
--color-chart-violet: hsl(258 80% 65%);
--color-chart-emerald: hsl(160 72% 47%);
--color-chart-amber: hsl(38 92% 55%);
--color-chart-rose: hsl(347 77% 60%);
}
@layer base {
@@ -34,7 +41,5 @@
min-height: 100vh;
background-color: var(--color-background);
color: var(--color-foreground);
background-image: radial-gradient(circle at 10% 10%, hsl(188 100% 62% / 0.08), transparent 25%),
radial-gradient(circle at 90% 20%, hsl(260 90% 65% / 0.08), transparent 30%);
}
}
+20 -21
View File
@@ -67,23 +67,22 @@ export default async function Home() {
return (
<main className="relative min-h-screen overflow-hidden bg-background text-foreground">
<div className="pointer-events-none absolute inset-0 opacity-70">
<div className="absolute -left-40 top-0 h-96 w-96 rounded-full bg-cyan-500/15 blur-3xl" />
<div className="absolute right-0 top-40 h-[28rem] w-[28rem] rounded-full bg-indigo-500/20 blur-3xl" />
<div className="absolute bottom-0 left-1/3 h-80 w-80 rounded-full bg-violet-500/15 blur-3xl" />
<div className="pointer-events-none absolute inset-0">
<div className="absolute -left-40 top-0 h-[500px] w-[500px] rounded-full bg-blue-500/[0.07] blur-[120px]" />
<div className="absolute right-0 top-40 h-[400px] w-[400px] rounded-full bg-blue-600/[0.05] blur-[120px]" />
</div>
<div className="relative mx-auto flex w-full max-w-6xl flex-col px-6 pb-16 pt-8 md:px-10">
<header className="mb-16 flex items-center justify-between rounded-2xl border border-white/10 bg-black/30 px-5 py-3 backdrop-blur-xl">
<div className="relative mx-auto flex w-full max-w-6xl flex-col px-4 pb-16 pt-6 sm:px-6 md:px-10">
<header className="mb-16 flex items-center justify-between rounded-2xl border border-white/[0.06] bg-white/[0.02] px-5 py-3 backdrop-blur-xl">
<div className="flex items-center gap-2 text-sm font-medium">
<Sparkles className="h-4 w-4 text-cyan-300" />
<Sparkles className="h-4 w-4 text-blue-400" />
<span className="tracking-wide">LLM Proxy</span>
</div>
<div className="flex items-center gap-2">
<Button asChild variant="ghost" className="text-muted-foreground hover:text-foreground">
<Link href="/login">Login</Link>
</Button>
<Button asChild className="bg-cyan-400 text-black hover:bg-cyan-300">
<Button asChild className="bg-blue-500 text-white hover:bg-blue-400">
<Link href={session?.user ? "/dashboard" : "/register"}>
{session?.user ? "Open Dashboard" : "Get Started"}
</Link>
@@ -92,10 +91,10 @@ export default async function Home() {
</header>
<section className="mb-14">
<Badge className="mb-5 border-cyan-300/30 bg-cyan-300/10 text-cyan-200" variant="outline">
<Badge className="mb-5 border-blue-400/30 bg-blue-500/10 text-blue-300" variant="outline">
OpenAI-Compatible Multi-Provider Gateway
</Badge>
<h1 className="max-w-4xl text-4xl font-semibold leading-tight tracking-tight md:text-6xl">
<h1 className="max-w-4xl text-3xl font-semibold leading-tight tracking-tight sm:text-4xl md:text-6xl">
One key. Every model. One clean API.
</h1>
<p className="mt-5 max-w-2xl text-base text-muted-foreground md:text-lg">
@@ -103,16 +102,16 @@ export default async function Home() {
ship faster without juggling multiple integrations.
</p>
<div className="mt-8 flex flex-wrap items-center gap-3">
<Button asChild size="lg" className="bg-cyan-400 text-black hover:bg-cyan-300">
<Button asChild size="lg" className="bg-blue-500 text-white hover:bg-blue-400">
<Link href={session?.user ? "/dashboard" : "/register"}>
Start Building
<ArrowRight className="h-4 w-4" />
</Link>
</Button>
<Button asChild size="lg" variant="outline" className="border-white/20 bg-white/5 hover:bg-white/10">
<Button asChild size="lg" variant="outline" className="border-white/[0.08] bg-white/[0.03] hover:bg-white/[0.06]">
<Link href="/docs">Read API Docs</Link>
</Button>
<Button asChild size="lg" variant="outline" className="border-white/20 bg-white/5 hover:bg-white/10">
<Button asChild size="lg" variant="outline" className="border-white/[0.08] bg-white/[0.03] hover:bg-white/[0.06]">
<Link href="/v1/models">View Models API</Link>
</Button>
</div>
@@ -120,7 +119,7 @@ export default async function Home() {
<section className="mb-14 grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
{stats.map((item) => (
<Card key={item.label} className="border-white/10 bg-white/5 backdrop-blur-sm">
<Card key={item.label} className="border-white/[0.06] bg-white/[0.02]">
<CardContent className="p-5">
<p className="text-xs uppercase tracking-[0.18em] text-muted-foreground">{item.label}</p>
<p className="mt-2 text-2xl font-semibold">{item.value}</p>
@@ -129,13 +128,13 @@ export default async function Home() {
))}
</section>
<section className="mb-14 rounded-3xl border border-white/10 bg-white/5 p-6 backdrop-blur-sm md:p-8">
<section className="mb-14 rounded-3xl border border-white/[0.06] bg-white/[0.02] p-6 md:p-8">
<p className="mb-4 text-xs uppercase tracking-[0.2em] text-muted-foreground">Providers</p>
<div className="grid gap-3 sm:grid-cols-2 md:grid-cols-3">
{providers.map((provider) => (
<div
key={provider}
className="rounded-xl border border-white/10 bg-black/20 px-4 py-3 text-sm text-foreground/90"
className="rounded-xl border border-white/[0.06] bg-white/[0.02] px-4 py-3 text-sm text-foreground/90"
>
{provider}
</div>
@@ -146,15 +145,15 @@ export default async function Home() {
<section className="mb-14">
<div className="mb-6 flex items-center justify-between">
<h2 className="text-2xl font-semibold md:text-3xl">Everything you need to ship faster</h2>
<Badge variant="outline" className="border-white/15 bg-white/5 text-muted-foreground">
<Badge variant="outline" className="border-white/[0.08] bg-white/[0.03] text-muted-foreground">
Modern API SaaS
</Badge>
</div>
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
{features.map((feature) => (
<Card key={feature.title} className="border-white/10 bg-black/25">
<Card key={feature.title} className="border-white/[0.06] bg-white/[0.02]">
<CardContent className="p-6">
<feature.icon className="mb-4 h-5 w-5 text-cyan-300" />
<feature.icon className="mb-4 h-5 w-5 text-blue-400" />
<h3 className="mb-2 text-base font-semibold">{feature.title}</h3>
<p className="text-sm text-muted-foreground">{feature.description}</p>
</CardContent>
@@ -163,13 +162,13 @@ export default async function Home() {
</div>
</section>
<section className="rounded-3xl border border-cyan-300/20 bg-gradient-to-r from-cyan-400/15 via-indigo-400/10 to-violet-400/15 p-8 text-center">
<section className="rounded-3xl border border-blue-500/20 bg-gradient-to-r from-blue-500/[0.08] to-blue-600/[0.04] p-8 text-center">
<h3 className="text-2xl font-semibold md:text-3xl">Stop fighting limits. Start shipping continuously.</h3>
<p className="mx-auto mt-3 max-w-2xl text-muted-foreground">
Connect once, route everywhere, and manage usage from a single dark-first control plane.
</p>
<div className="mt-6 flex justify-center gap-3">
<Button asChild size="lg" className="bg-cyan-400 text-black hover:bg-cyan-300">
<Button asChild size="lg" className="bg-blue-500 text-white hover:bg-blue-400">
<Link href={session?.user ? "/dashboard" : "/register"}>Launch Dashboard</Link>
</Button>
<Button asChild size="lg" variant="ghost" className="text-muted-foreground hover:text-foreground">
+143 -80
View File
@@ -1,6 +1,18 @@
"use client";
import { Bar, BarChart, CartesianGrid, Line, LineChart, ResponsiveContainer, Tooltip, XAxis, YAxis } from "recharts";
import {
Area,
AreaChart,
Bar,
BarChart,
CartesianGrid,
Cell,
Legend,
ResponsiveContainer,
Tooltip,
XAxis,
YAxis,
} from "recharts";
interface ProviderRow {
name: string;
@@ -15,6 +27,28 @@ interface DailyRow {
cost: number;
}
const PALETTE = [
"#3b82f6",
"#22d3ee",
"#8b5cf6",
"#34d399",
"#f59e0b",
"#f43f5e",
"#6366f1",
"#14b8a6",
];
const tooltipStyle = {
borderRadius: 12,
border: "1px solid rgba(255,255,255,0.06)",
backgroundColor: "hsl(220 16% 7%)",
boxShadow: "0 8px 32px rgba(0,0,0,0.5)",
};
const tooltipItemStyle = { color: "hsl(220 10% 80%)" };
const tooltipLabelStyle = { color: "hsl(220 10% 55%)", marginBottom: 4 };
const axisTick = { fill: "hsl(220 10% 45%)", fontSize: 12 };
export function AdminAnalyticsCharts({
providers,
daily,
@@ -38,87 +72,116 @@ export function AdminAnalyticsCharts({
return (
<div className="grid gap-6 lg:grid-cols-2">
<div className="h-80 rounded-xl border bg-linear-to-b from-card to-card/30 p-4 shadow-sm">
<h3 className="mb-4 text-sm font-semibold tracking-tight">Requests by Provider</h3>
<ResponsiveContainer width="100%" height="90%">
<BarChart data={providers}>
<CartesianGrid strokeDasharray="3 3" stroke="hsl(var(--border))" vertical={false} />
<XAxis dataKey="name" tickLine={false} axisLine={false} />
<YAxis tickLine={false} axisLine={false} tickFormatter={(value) => numberFormatter.format(value)} />
<Tooltip
contentStyle={{
borderRadius: 10,
borderColor: "hsl(var(--border))",
backgroundColor: "hsl(var(--card))",
}}
formatter={(value, name) =>
name === "cost"
? [currencyFormatter.format(toNumber(value)), "Cost"]
: [numberFormatter.format(toNumber(value)), "Requests"]
}
/>
<Bar dataKey="requests" fill="hsl(var(--primary))" radius={[8, 8, 0, 0]} />
</BarChart>
</ResponsiveContainer>
{/* Provider bar chart with individual colors */}
<div className="rounded-2xl border border-white/[0.06] bg-white/[0.02] p-5">
<h3 className="mb-1 text-sm font-semibold">Requests by Provider</h3>
<p className="mb-4 text-xs text-muted-foreground">Total requests per provider (30 days)</p>
<div className="h-72">
<ResponsiveContainer width="100%" height="100%">
<BarChart data={providers}>
<CartesianGrid strokeDasharray="3 3" stroke="rgba(255,255,255,0.04)" vertical={false} />
<XAxis dataKey="name" tickLine={false} axisLine={false} tick={axisTick} />
<YAxis tickLine={false} axisLine={false} tick={axisTick} tickFormatter={(value) => numberFormatter.format(value)} />
<Tooltip
contentStyle={tooltipStyle}
labelStyle={tooltipLabelStyle}
itemStyle={tooltipItemStyle}
cursor={{ fill: "rgba(255,255,255,0.02)" }}
formatter={(value, name) =>
name === "cost"
? [currencyFormatter.format(toNumber(value)), "Cost"]
: [numberFormatter.format(toNumber(value)), "Requests"]
}
/>
<Bar dataKey="requests" radius={[6, 6, 0, 0]}>
{providers.map((_, index) => (
<Cell key={index} fill={PALETTE[index % PALETTE.length]} />
))}
</Bar>
</BarChart>
</ResponsiveContainer>
</div>
</div>
<div className="h-80 rounded-xl border bg-linear-to-b from-card to-card/30 p-4 shadow-sm">
<h3 className="mb-4 text-sm font-semibold tracking-tight">Daily Requests / Errors / Cost</h3>
<ResponsiveContainer width="100%" height="90%">
<LineChart data={daily}>
<CartesianGrid strokeDasharray="3 3" stroke="hsl(var(--border))" vertical={false} />
<XAxis dataKey="date" tickLine={false} axisLine={false} />
<YAxis
yAxisId="left"
tickLine={false}
axisLine={false}
tickFormatter={(value) => numberFormatter.format(value)}
/>
<YAxis
yAxisId="right"
orientation="right"
tickLine={false}
axisLine={false}
tickFormatter={(value) => currencyFormatter.format(value)}
/>
<Tooltip
contentStyle={{
borderRadius: 10,
borderColor: "hsl(var(--border))",
backgroundColor: "hsl(var(--card))",
}}
formatter={(value, name) =>
name === "cost"
? [currencyFormatter.format(toNumber(value)), "Cost"]
: [numberFormatter.format(toNumber(value)), name === "errors" ? "Errors" : "Requests"]
}
/>
<Line
yAxisId="left"
type="monotone"
dataKey="requests"
stroke="hsl(var(--primary))"
strokeWidth={2}
dot={false}
/>
<Line
yAxisId="left"
type="monotone"
dataKey="errors"
stroke="#ef4444"
strokeWidth={2}
dot={false}
/>
<Line
yAxisId="right"
type="monotone"
dataKey="cost"
stroke="#22c55e"
strokeWidth={2}
dot={false}
/>
</LineChart>
</ResponsiveContainer>
{/* Daily area chart with requests, errors, cost */}
<div className="rounded-2xl border border-white/[0.06] bg-white/[0.02] p-5">
<h3 className="mb-1 text-sm font-semibold">Daily Overview</h3>
<p className="mb-4 text-xs text-muted-foreground">Requests, errors, and cost over time</p>
<div className="h-72">
<ResponsiveContainer width="100%" height="100%">
<AreaChart data={daily}>
<defs>
<linearGradient id="adminReqFill" x1="0" y1="0" x2="0" y2="1">
<stop offset="0%" stopColor="#3b82f6" stopOpacity={0.25} />
<stop offset="100%" stopColor="#3b82f6" stopOpacity={0} />
</linearGradient>
<linearGradient id="adminErrFill" x1="0" y1="0" x2="0" y2="1">
<stop offset="0%" stopColor="#f43f5e" stopOpacity={0.2} />
<stop offset="100%" stopColor="#f43f5e" stopOpacity={0} />
</linearGradient>
<linearGradient id="adminCostFill" x1="0" y1="0" x2="0" y2="1">
<stop offset="0%" stopColor="#34d399" stopOpacity={0.2} />
<stop offset="100%" stopColor="#34d399" stopOpacity={0} />
</linearGradient>
</defs>
<CartesianGrid strokeDasharray="3 3" stroke="rgba(255,255,255,0.04)" vertical={false} />
<XAxis dataKey="date" tickLine={false} axisLine={false} tick={axisTick} />
<YAxis
yAxisId="left"
tickLine={false}
axisLine={false}
tick={axisTick}
tickFormatter={(value) => numberFormatter.format(value)}
/>
<YAxis
yAxisId="right"
orientation="right"
tickLine={false}
axisLine={false}
tick={axisTick}
tickFormatter={(value) => currencyFormatter.format(value)}
/>
<Tooltip
contentStyle={tooltipStyle}
labelStyle={tooltipLabelStyle}
itemStyle={tooltipItemStyle}
formatter={(value, name) =>
name === "Cost"
? [currencyFormatter.format(toNumber(value)), "Cost"]
: [numberFormatter.format(toNumber(value)), name === "Errors" ? "Errors" : "Requests"]
}
/>
<Legend iconType="circle" wrapperStyle={{ fontSize: 12, paddingTop: 8 }} />
<Area
yAxisId="left"
type="monotone"
dataKey="requests"
stroke="#3b82f6"
fill="url(#adminReqFill)"
strokeWidth={2}
name="Requests"
/>
<Area
yAxisId="left"
type="monotone"
dataKey="errors"
stroke="#f43f5e"
fill="url(#adminErrFill)"
strokeWidth={2}
name="Errors"
/>
<Area
yAxisId="right"
type="monotone"
dataKey="cost"
stroke="#34d399"
fill="url(#adminCostFill)"
strokeWidth={2}
name="Cost"
/>
</AreaChart>
</ResponsiveContainer>
</div>
</div>
</div>
);
+15 -13
View File
@@ -191,12 +191,12 @@ export function ProviderManagement() {
return (
<div className="space-y-6">
<div className="flex items-center justify-between">
<div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
<div>
<h1 className="text-2xl font-bold">Provider Management</h1>
<p className="text-muted-foreground">Manage ingested provider keys and routing readiness.</p>
<h1 className="text-xl font-bold sm:text-2xl">Provider Management</h1>
<p className="text-sm text-muted-foreground">Manage ingested provider keys and routing readiness.</p>
</div>
<div className="flex items-center gap-2 rounded-lg border bg-muted/20 p-1">
<div className="flex items-center gap-2 self-start rounded-lg border bg-muted/20 p-1">
<button
onClick={() => setTab("providers")}
className={cn(
@@ -219,7 +219,7 @@ export function ProviderManagement() {
</div>
{tab === "providers" ? (
<div className="grid gap-6 lg:grid-cols-[380px_minmax(0,1fr)]">
<div className="grid gap-6 lg:grid-cols-[320px_minmax(0,1fr)]">
<Card>
<CardHeader>
<CardTitle>Providers</CardTitle>
@@ -309,13 +309,15 @@ export function ProviderManagement() {
{key.lastUsedAt ? formatDateTimeSafe(key.lastUsedAt, "Never") : "Never"}
</TableCell>
<TableCell className="text-sm">{formatDateTimeSafe(key.createdAt)}</TableCell>
<TableCell className="space-x-2">
<Button size="sm" variant="outline" onClick={() => toggleKeyStatus(key)}>
{key.status === "ACTIVE" ? "Disable" : "Enable"}
</Button>
<Button size="sm" variant="destructive" onClick={() => deleteKey(key)}>
Delete
</Button>
<TableCell>
<div className="flex gap-1.5">
<Button size="sm" variant="outline" onClick={() => toggleKeyStatus(key)}>
{key.status === "ACTIVE" ? "Disable" : "Enable"}
</Button>
<Button size="sm" variant="destructive" onClick={() => deleteKey(key)}>
Delete
</Button>
</div>
</TableCell>
</TableRow>
))}
@@ -326,7 +328,7 @@ export function ProviderManagement() {
</Card>
</div>
) : (
<div className="grid gap-6 lg:grid-cols-[minmax(0,1fr)_420px]">
<div className="grid gap-6 lg:grid-cols-[minmax(0,1fr)_380px]">
<Card>
<CardHeader>
<CardTitle>Ingest Provider Keys</CardTitle>
@@ -6,6 +6,7 @@ import {
Bar,
BarChart,
CartesianGrid,
Legend,
ResponsiveContainer,
Tooltip,
XAxis,
@@ -24,6 +25,24 @@ type ProviderPoint = {
requests: number;
};
const COLORS = {
blue: "#3b82f6",
cyan: "#22d3ee",
violet: "#8b5cf6",
emerald: "#34d399",
amber: "#f59e0b",
rose: "#f43f5e",
};
const tooltipStyle = {
borderRadius: 12,
border: "1px solid rgba(255,255,255,0.06)",
backgroundColor: "hsl(220 16% 7%)",
boxShadow: "0 8px 32px rgba(0,0,0,0.5)",
};
const tooltipItemStyle = { color: "hsl(220 10% 80%)" };
const tooltipLabelStyle = { color: "hsl(220 10% 55%)", marginBottom: 4 };
export function DashboardUsageGraphs({
trend,
providers,
@@ -41,7 +60,7 @@ export function DashboardUsageGraphs({
return (
<div className="grid gap-4 xl:grid-cols-3">
<div className="xl:col-span-2 rounded-2xl border bg-linear-to-br from-card to-card/30 p-5 shadow-sm">
<div className="xl:col-span-2 rounded-2xl border border-white/[0.06] bg-white/[0.02] p-5">
<div className="mb-4 flex items-center justify-between">
<div>
<p className="text-xs uppercase tracking-wider text-muted-foreground">Last 14 days</p>
@@ -49,7 +68,7 @@ export function DashboardUsageGraphs({
</div>
<div className="text-right">
<p className="text-xs text-muted-foreground">Total Cost</p>
<p className="text-sm font-semibold">
<p className="text-sm font-semibold text-emerald-400">
{currencyFormatter.format(trend.reduce((acc, point) => acc + point.cost, 0))}
</p>
</div>
@@ -60,43 +79,50 @@ export function DashboardUsageGraphs({
<AreaChart data={trend}>
<defs>
<linearGradient id="requestsFill" x1="0" y1="0" x2="0" y2="1">
<stop offset="5%" stopColor="hsl(var(--primary))" stopOpacity={0.35} />
<stop offset="95%" stopColor="hsl(var(--primary))" stopOpacity={0.03} />
<stop offset="0%" stopColor={COLORS.blue} stopOpacity={0.3} />
<stop offset="100%" stopColor={COLORS.blue} stopOpacity={0} />
</linearGradient>
<linearGradient id="tokensFill" x1="0" y1="0" x2="0" y2="1">
<stop offset="5%" stopColor="#06b6d4" stopOpacity={0.2} />
<stop offset="95%" stopColor="#06b6d4" stopOpacity={0.03} />
<stop offset="0%" stopColor={COLORS.cyan} stopOpacity={0.2} />
<stop offset="100%" stopColor={COLORS.cyan} stopOpacity={0} />
</linearGradient>
</defs>
<CartesianGrid strokeDasharray="3 3" vertical={false} stroke="hsl(var(--border))" />
<XAxis dataKey="date" tickLine={false} axisLine={false} />
<YAxis tickLine={false} axisLine={false} tickFormatter={(value) => numberFormatter.format(value)} />
<CartesianGrid strokeDasharray="3 3" vertical={false} stroke="rgba(255,255,255,0.04)" />
<XAxis dataKey="date" tickLine={false} axisLine={false} tick={{ fill: "hsl(220 10% 45%)", fontSize: 12 }} />
<YAxis tickLine={false} axisLine={false} tick={{ fill: "hsl(220 10% 45%)", fontSize: 12 }} tickFormatter={(value) => numberFormatter.format(value)} />
<Tooltip
contentStyle={{
borderRadius: 12,
borderColor: "hsl(var(--border))",
backgroundColor: "hsl(var(--card))",
}}
contentStyle={tooltipStyle}
labelStyle={tooltipLabelStyle}
itemStyle={tooltipItemStyle}
formatter={(value, key) => {
const numeric = typeof value === "number" ? value : Number(value);
if (key === "cost") return [currencyFormatter.format(numeric), "Cost"];
return [numberFormatter.format(numeric), key === "requests" ? "Requests" : "Tokens"];
}}
/>
<Legend iconType="circle" wrapperStyle={{ fontSize: 12, paddingTop: 8 }} />
<Area
type="monotone"
dataKey="requests"
stroke="hsl(var(--primary))"
stroke={COLORS.blue}
fill="url(#requestsFill)"
strokeWidth={2}
name="Requests"
/>
<Area
type="monotone"
dataKey="tokens"
stroke={COLORS.cyan}
fill="url(#tokensFill)"
strokeWidth={2}
name="Tokens"
/>
<Area type="monotone" dataKey="tokens" stroke="#06b6d4" fill="url(#tokensFill)" strokeWidth={2} />
</AreaChart>
</ResponsiveContainer>
</div>
</div>
<div className="rounded-2xl border bg-linear-to-br from-card to-card/30 p-5 shadow-sm">
<div className="rounded-2xl border border-white/[0.06] bg-white/[0.02] p-5">
<div className="mb-4">
<p className="text-xs uppercase tracking-wider text-muted-foreground">Distribution</p>
<h3 className="text-base font-semibold">Requests by Provider</h3>
@@ -105,18 +131,17 @@ export function DashboardUsageGraphs({
<div className="h-72">
<ResponsiveContainer width="100%" height="100%">
<BarChart data={providers} layout="vertical" margin={{ left: 6, right: 10 }}>
<CartesianGrid strokeDasharray="3 3" horizontal={false} stroke="hsl(var(--border))" />
<XAxis type="number" tickLine={false} axisLine={false} tickFormatter={(value) => numberFormatter.format(value)} />
<YAxis dataKey="name" type="category" tickLine={false} axisLine={false} width={90} />
<CartesianGrid strokeDasharray="3 3" horizontal={false} stroke="rgba(255,255,255,0.04)" />
<XAxis type="number" tickLine={false} axisLine={false} tick={{ fill: "hsl(220 10% 45%)", fontSize: 12 }} tickFormatter={(value) => numberFormatter.format(value)} />
<YAxis dataKey="name" type="category" tickLine={false} axisLine={false} width={90} tick={{ fill: "hsl(220 10% 55%)", fontSize: 12 }} />
<Tooltip
contentStyle={{
borderRadius: 12,
borderColor: "hsl(var(--border))",
backgroundColor: "hsl(var(--card))",
}}
contentStyle={tooltipStyle}
labelStyle={tooltipLabelStyle}
itemStyle={tooltipItemStyle}
formatter={(value) => [numberFormatter.format(Number(value)), "Requests"]}
cursor={{ fill: "rgba(255,255,255,0.02)" }}
/>
<Bar dataKey="requests" fill="hsl(var(--primary))" radius={[0, 8, 8, 0]} />
<Bar dataKey="requests" fill={COLORS.blue} radius={[0, 6, 6, 0]} />
</BarChart>
</ResponsiveContainer>
</div>
@@ -1,6 +1,20 @@
"use client";
import { Bar, BarChart, CartesianGrid, Line, LineChart, ResponsiveContainer, Tooltip, XAxis, YAxis } from "recharts";
import {
Area,
AreaChart,
Bar,
BarChart,
CartesianGrid,
Cell,
Legend,
Pie,
PieChart,
ResponsiveContainer,
Tooltip,
XAxis,
YAxis,
} from "recharts";
interface DailyPoint {
date: string;
@@ -17,6 +31,29 @@ interface BreakdownPoint {
cost: number;
}
const PALETTE = [
"#3b82f6",
"#22d3ee",
"#8b5cf6",
"#34d399",
"#f59e0b",
"#f43f5e",
"#6366f1",
"#14b8a6",
];
const tooltipStyle = {
borderRadius: 12,
border: "1px solid rgba(255,255,255,0.06)",
backgroundColor: "hsl(220 16% 7%)",
boxShadow: "0 8px 32px rgba(0,0,0,0.5)",
};
const tooltipItemStyle = { color: "hsl(220 10% 80%)" };
const tooltipLabelStyle = { color: "hsl(220 10% 55%)", marginBottom: 4 };
const axisTick = { fill: "hsl(220 10% 45%)", fontSize: 12 };
export function UsageBreakdownCharts({
daily,
providers,
@@ -44,118 +81,166 @@ export function UsageBreakdownCharts({
return (
<div className="grid gap-6 lg:grid-cols-2">
<div className="h-80 rounded-xl border bg-linear-to-b from-card to-card/30 p-4 shadow-sm">
<h3 className="mb-4 text-sm font-semibold tracking-tight">Daily Requests & Cost</h3>
<ResponsiveContainer width="100%" height="90%">
<LineChart data={daily}>
<CartesianGrid strokeDasharray="3 3" stroke="hsl(var(--border))" vertical={false} />
<XAxis dataKey="date" tickLine={false} axisLine={false} />
<YAxis
yAxisId="left"
tickLine={false}
axisLine={false}
tickFormatter={(value) => numberFormatter.format(value)}
/>
<YAxis
yAxisId="right"
orientation="right"
tickLine={false}
axisLine={false}
tickFormatter={(value) => currencyFormatter.format(value)}
/>
<Tooltip
contentStyle={{
borderRadius: 10,
borderColor: "hsl(var(--border))",
backgroundColor: "hsl(var(--card))",
}}
formatter={(value, name) =>
name === "cost"
? [currencyFormatter.format(toNumber(value)), "Cost"]
: [numberFormatter.format(toNumber(value)), "Requests"]
}
/>
<Line
yAxisId="left"
type="monotone"
dataKey="requests"
stroke="hsl(var(--primary))"
strokeWidth={2}
dot={false}
/>
<Line
yAxisId="right"
type="monotone"
dataKey="cost"
stroke="#22c55e"
strokeWidth={2}
dot={false}
/>
</LineChart>
</ResponsiveContainer>
{/* Daily Requests & Cost - Area chart */}
<div className="rounded-2xl border border-white/[0.06] bg-white/[0.02] p-5">
<h3 className="mb-1 text-sm font-semibold">Daily Requests & Cost</h3>
<p className="mb-4 text-xs text-muted-foreground">Last 30 days trend</p>
<div className="h-72">
<ResponsiveContainer width="100%" height="100%">
<AreaChart data={daily}>
<defs>
<linearGradient id="dailyReqFill" x1="0" y1="0" x2="0" y2="1">
<stop offset="0%" stopColor="#3b82f6" stopOpacity={0.25} />
<stop offset="100%" stopColor="#3b82f6" stopOpacity={0} />
</linearGradient>
<linearGradient id="dailyCostFill" x1="0" y1="0" x2="0" y2="1">
<stop offset="0%" stopColor="#34d399" stopOpacity={0.2} />
<stop offset="100%" stopColor="#34d399" stopOpacity={0} />
</linearGradient>
</defs>
<CartesianGrid strokeDasharray="3 3" stroke="rgba(255,255,255,0.04)" vertical={false} />
<XAxis dataKey="date" tickLine={false} axisLine={false} tick={axisTick} />
<YAxis
yAxisId="left"
tickLine={false}
axisLine={false}
tick={axisTick}
tickFormatter={(value) => numberFormatter.format(value)}
/>
<YAxis
yAxisId="right"
orientation="right"
tickLine={false}
axisLine={false}
tick={axisTick}
tickFormatter={(value) => currencyFormatter.format(value)}
/>
<Tooltip
contentStyle={tooltipStyle}
labelStyle={tooltipLabelStyle}
itemStyle={tooltipItemStyle}
formatter={(value, name) =>
name === "cost"
? [currencyFormatter.format(toNumber(value)), "Cost"]
: [numberFormatter.format(toNumber(value)), "Requests"]
}
/>
<Legend iconType="circle" wrapperStyle={{ fontSize: 12, paddingTop: 8 }} />
<Area
yAxisId="left"
type="monotone"
dataKey="requests"
stroke="#3b82f6"
fill="url(#dailyReqFill)"
strokeWidth={2}
name="Requests"
/>
<Area
yAxisId="right"
type="monotone"
dataKey="cost"
stroke="#34d399"
fill="url(#dailyCostFill)"
strokeWidth={2}
name="Cost"
/>
</AreaChart>
</ResponsiveContainer>
</div>
</div>
<div className="h-80 rounded-xl border bg-linear-to-b from-card to-card/30 p-4 shadow-sm">
<h3 className="mb-4 text-sm font-semibold tracking-tight">Top Providers</h3>
<ResponsiveContainer width="100%" height="90%">
<BarChart data={providers}>
<CartesianGrid strokeDasharray="3 3" stroke="hsl(var(--border))" vertical={false} />
<XAxis dataKey="name" tickLine={false} axisLine={false} />
<YAxis tickLine={false} axisLine={false} tickFormatter={(value) => numberFormatter.format(value)} />
<Tooltip
contentStyle={{
borderRadius: 10,
borderColor: "hsl(var(--border))",
backgroundColor: "hsl(var(--card))",
}}
formatter={(value, name) => [numberFormatter.format(toNumber(value)), name]}
/>
<Bar dataKey="requests" fill="hsl(var(--primary))" radius={[8, 8, 0, 0]} />
<Bar dataKey="tokens" fill="#8b5cf6" radius={[8, 8, 0, 0]} />
</BarChart>
</ResponsiveContainer>
{/* Top Providers - Horizontal bar + Pie */}
<div className="rounded-2xl border border-white/[0.06] bg-white/[0.02] p-5">
<h3 className="mb-1 text-sm font-semibold">Top Providers</h3>
<p className="mb-4 text-xs text-muted-foreground">Requests and tokens breakdown</p>
<div className="h-72">
<ResponsiveContainer width="100%" height="100%">
<BarChart data={providers}>
<CartesianGrid strokeDasharray="3 3" stroke="rgba(255,255,255,0.04)" vertical={false} />
<XAxis dataKey="name" tickLine={false} axisLine={false} tick={axisTick} />
<YAxis tickLine={false} axisLine={false} tick={axisTick} tickFormatter={(value) => numberFormatter.format(value)} />
<Tooltip
contentStyle={tooltipStyle}
labelStyle={tooltipLabelStyle}
itemStyle={tooltipItemStyle}
cursor={{ fill: "rgba(255,255,255,0.02)" }}
formatter={(value, name) => [numberFormatter.format(toNumber(value)), name]}
/>
<Legend iconType="circle" wrapperStyle={{ fontSize: 12, paddingTop: 8 }} />
<Bar dataKey="requests" fill="#3b82f6" radius={[6, 6, 0, 0]} name="Requests" />
<Bar dataKey="tokens" fill="#8b5cf6" radius={[6, 6, 0, 0]} name="Tokens" />
</BarChart>
</ResponsiveContainer>
</div>
</div>
<div className="h-80 rounded-xl border bg-linear-to-b from-card to-card/30 p-4 shadow-sm">
<h3 className="mb-4 text-sm font-semibold tracking-tight">Top Models</h3>
<ResponsiveContainer width="100%" height="90%">
<BarChart data={models}>
<CartesianGrid strokeDasharray="3 3" stroke="hsl(var(--border))" vertical={false} />
<XAxis dataKey="name" tickLine={false} axisLine={false} />
<YAxis tickLine={false} axisLine={false} tickFormatter={(value) => numberFormatter.format(value)} />
<Tooltip
contentStyle={{
borderRadius: 10,
borderColor: "hsl(var(--border))",
backgroundColor: "hsl(var(--card))",
}}
formatter={(value, name) => [numberFormatter.format(toNumber(value)), name]}
/>
<Bar dataKey="requests" fill="#06b6d4" radius={[8, 8, 0, 0]} />
<Bar dataKey="tokens" fill="#f97316" radius={[8, 8, 0, 0]} />
</BarChart>
</ResponsiveContainer>
{/* Top Models - Colorful bars */}
<div className="rounded-2xl border border-white/[0.06] bg-white/[0.02] p-5">
<h3 className="mb-1 text-sm font-semibold">Top Models</h3>
<p className="mb-4 text-xs text-muted-foreground">Usage by model</p>
<div className="h-72">
<ResponsiveContainer width="100%" height="100%">
<BarChart data={models} layout="vertical" margin={{ left: 10 }}>
<CartesianGrid strokeDasharray="3 3" stroke="rgba(255,255,255,0.04)" horizontal={false} />
<XAxis type="number" tickLine={false} axisLine={false} tick={axisTick} tickFormatter={(value) => numberFormatter.format(value)} />
<YAxis dataKey="name" type="category" tickLine={false} axisLine={false} width={120} tick={{ fill: "hsl(220 10% 55%)", fontSize: 11 }} />
<Tooltip
contentStyle={tooltipStyle}
labelStyle={tooltipLabelStyle}
itemStyle={tooltipItemStyle}
cursor={{ fill: "rgba(255,255,255,0.02)" }}
formatter={(value) => [numberFormatter.format(toNumber(value)), "Requests"]}
/>
<Bar dataKey="requests" radius={[0, 6, 6, 0]}>
{models.map((_, index) => (
<Cell key={index} fill={PALETTE[index % PALETTE.length]} />
))}
</Bar>
</BarChart>
</ResponsiveContainer>
</div>
</div>
<div className="h-80 rounded-xl border bg-linear-to-b from-card to-card/30 p-4 shadow-sm">
<h3 className="mb-4 text-sm font-semibold tracking-tight">Top API Keys</h3>
<ResponsiveContainer width="100%" height="90%">
<BarChart data={keys}>
<CartesianGrid strokeDasharray="3 3" stroke="hsl(var(--border))" vertical={false} />
<XAxis dataKey="name" tickLine={false} axisLine={false} />
<YAxis tickLine={false} axisLine={false} tickFormatter={(value) => numberFormatter.format(value)} />
<Tooltip
contentStyle={{
borderRadius: 10,
borderColor: "hsl(var(--border))",
backgroundColor: "hsl(var(--card))",
}}
formatter={(value, name) => [numberFormatter.format(toNumber(value)), name]}
/>
<Bar dataKey="requests" fill="#22c55e" radius={[8, 8, 0, 0]} />
<Bar dataKey="tokens" fill="#eab308" radius={[8, 8, 0, 0]} />
</BarChart>
</ResponsiveContainer>
{/* Top API Keys - Pie chart */}
<div className="rounded-2xl border border-white/[0.06] bg-white/[0.02] p-5">
<h3 className="mb-1 text-sm font-semibold">Top API Keys</h3>
<p className="mb-4 text-xs text-muted-foreground">Request distribution by key</p>
<div className="h-72">
<ResponsiveContainer width="100%" height="100%">
{keys.length > 0 ? (
<PieChart>
<Pie
data={keys}
dataKey="requests"
nameKey="name"
cx="50%"
cy="50%"
innerRadius={60}
outerRadius={100}
strokeWidth={0}
paddingAngle={3}
>
{keys.map((_, index) => (
<Cell key={index} fill={PALETTE[index % PALETTE.length]} />
))}
</Pie>
<Tooltip
contentStyle={tooltipStyle}
labelStyle={tooltipLabelStyle}
itemStyle={tooltipItemStyle}
formatter={(value) => [numberFormatter.format(toNumber(value)), "Requests"]}
/>
<Legend iconType="circle" wrapperStyle={{ fontSize: 12 }} />
</PieChart>
) : (
<BarChart data={[]}>
<text x="50%" y="50%" textAnchor="middle" fill="hsl(220 10% 45%)" fontSize={13}>
No data
</text>
</BarChart>
)}
</ResponsiveContainer>
</div>
</div>
</div>
);
+5 -5
View File
@@ -11,23 +11,23 @@ export function Header() {
const isAdminArea = pathname.startsWith("/admin");
return (
<header className="flex h-14 items-center justify-between border-b bg-card px-6">
<header className="hidden h-14 items-center justify-between border-b border-white/[0.06] bg-[hsl(220,16%,5%)] px-4 md:flex md:px-6">
<div>
{isAdminArea && (
<Link
href="/dashboard"
className="inline-flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground"
className="inline-flex items-center gap-1.5 text-sm text-muted-foreground transition-colors hover:text-foreground"
>
<ArrowLeft className="h-4 w-4" />
Dashboard
</Link>
)}
</div>
<div className="flex items-center gap-4">
<span className="text-sm text-muted-foreground">{session?.user.email}</span>
<div className="flex items-center gap-3">
<span className="max-w-[200px] truncate text-sm text-muted-foreground">{session?.user.email}</span>
<button
onClick={() => signOut({ callbackUrl: "/login" })}
className="flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground"
className="flex items-center gap-1.5 text-sm text-muted-foreground transition-colors hover:text-foreground"
>
<LogOut className="h-4 w-4" />
Sign out
+99 -59
View File
@@ -19,7 +19,11 @@ import {
TrendingUp,
Shield,
ArrowLeft,
Sparkles,
Menu,
X,
} from "lucide-react";
import { useEffect, useState } from "react";
interface NavItem {
label: string;
@@ -29,7 +33,7 @@ interface NavItem {
const dashboardNav: NavItem[] = [
{ label: "Overview", href: "/dashboard", icon: LayoutDashboard },
{ label: "Playground", href: "/dashboard/playground", icon: MessageSquare },
{ label: "Chat", href: "/chat", icon: MessageSquare },
{ label: "Docs", href: "/docs", icon: BookOpen },
{ label: "API Keys", href: "/dashboard/api-keys", icon: Key },
{ label: "Usage", href: "/dashboard/usage", icon: BarChart3 },
@@ -51,66 +55,102 @@ export function Sidebar({ variant }: { variant: "dashboard" | "admin" }) {
const { data: session } = useSession();
const items = variant === "admin" ? adminNav : dashboardNav;
const showAdminLink = variant === "dashboard" && session?.user.role === "ADMIN";
const [open, setOpen] = useState(false);
// Close on route change
useEffect(() => {
setOpen(false);
}, [pathname]);
return (
<aside className="flex h-full w-64 flex-col border-r bg-card">
<div className="flex h-14 items-center border-b px-6">
<Link href="/" className="text-lg font-bold">
LLM Proxy
</Link>
</div>
<nav className="flex-1 space-y-1 p-3">
{variant === "admin" && (
<>
<Link
href="/dashboard"
className="mb-2 flex items-center gap-3 rounded-md px-3 py-2 text-sm font-medium text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"
>
<ArrowLeft className="h-4 w-4" />
Back to Dashboard
</Link>
<div className="mb-2 border-t" />
</>
<>
{/* Mobile hamburger */}
<button
onClick={() => setOpen(true)}
className="fixed left-3 top-3 z-40 flex h-10 w-10 items-center justify-center rounded-lg border border-white/[0.06] bg-[hsl(220,16%,5%)] text-muted-foreground md:hidden"
aria-label="Open menu"
>
<Menu className="h-5 w-5" />
</button>
{/* Overlay */}
{open && (
<div className="fixed inset-0 z-40 bg-black/60 md:hidden" onClick={() => setOpen(false)} />
)}
{/* Sidebar */}
<aside
className={cn(
"fixed inset-y-0 left-0 z-50 flex w-64 flex-col border-r border-white/[0.06] bg-[hsl(220,16%,5%)] transition-transform duration-200 md:static md:translate-x-0",
open ? "translate-x-0" : "-translate-x-full",
)}
{items.map((item) => {
const isActive =
item.href === `/${variant === "admin" ? "admin" : "dashboard"}`
? pathname === item.href
: pathname.startsWith(item.href);
return (
<Link
key={item.href}
href={item.href}
className={cn(
"flex items-center gap-3 rounded-md px-3 py-2 text-sm font-medium transition-colors",
isActive
? "bg-primary text-primary-foreground"
: "text-muted-foreground hover:bg-muted hover:text-foreground",
)}
>
<item.icon className="h-4 w-4" />
{item.label}
</Link>
);
})}
{showAdminLink && (
<>
<div className="my-3 border-t" />
<Link
href="/admin"
className={cn(
"flex items-center gap-3 rounded-md px-3 py-2 text-sm font-medium transition-colors",
pathname.startsWith("/admin")
? "bg-primary text-primary-foreground"
: "text-muted-foreground hover:bg-muted hover:text-foreground",
)}
>
<Shield className="h-4 w-4" />
Admin Portal
</Link>
</>
)}
</nav>
</aside>
>
<div className="flex h-14 items-center justify-between border-b border-white/[0.06] px-4">
<Link href="/" className="flex items-center gap-2 text-sm font-medium">
<Sparkles className="h-4 w-4 text-blue-400" />
<span className="tracking-wide">LLM Proxy</span>
</Link>
<button
onClick={() => setOpen(false)}
className="flex h-8 w-8 items-center justify-center rounded-lg text-muted-foreground hover:text-foreground md:hidden"
aria-label="Close menu"
>
<X className="h-4 w-4" />
</button>
</div>
<nav className="flex-1 space-y-0.5 overflow-y-auto p-3">
{variant === "admin" && (
<>
<Link
href="/dashboard"
className="mb-2 flex items-center gap-3 rounded-lg px-3 py-2 text-sm font-medium text-muted-foreground transition-colors hover:bg-white/[0.04] hover:text-foreground"
>
<ArrowLeft className="h-4 w-4" />
Back to Dashboard
</Link>
<div className="mb-2 border-t border-white/[0.06]" />
</>
)}
{items.map((item) => {
const isActive =
item.href === `/${variant === "admin" ? "admin" : "dashboard"}`
? pathname === item.href
: pathname.startsWith(item.href);
return (
<Link
key={item.href}
href={item.href}
className={cn(
"flex items-center gap-3 rounded-lg px-3 py-2 text-sm font-medium transition-all",
isActive
? "bg-blue-500/15 text-blue-400"
: "text-muted-foreground hover:bg-white/[0.04] hover:text-foreground",
)}
>
<item.icon className={cn("h-4 w-4", isActive && "text-blue-400")} />
{item.label}
</Link>
);
})}
{showAdminLink && (
<>
<div className="my-3 border-t border-white/[0.06]" />
<Link
href="/admin"
className={cn(
"flex items-center gap-3 rounded-lg px-3 py-2 text-sm font-medium transition-all",
pathname.startsWith("/admin")
? "bg-blue-500/15 text-blue-400"
: "text-muted-foreground hover:bg-white/[0.04] hover:text-foreground",
)}
>
<Shield className="h-4 w-4" />
Admin Portal
</Link>
</>
)}
</nav>
</aside>
</>
);
}
+3
View File
@@ -417,4 +417,7 @@ export const db = {
requestLog: makeModel("requestLog", "request_logs"),
usageAggregateDaily: makeModel("usageAggregateDaily", "usage_aggregates_daily"),
ingestionBatch: makeModel("ingestionBatch", "ingestion_batches"),
chatConversation: makeModel("chatConversation", "chat_conversations"),
chatMessage: makeModel("chatMessage", "chat_messages"),
userPreference: makeModel("userPreference", "user_preferences"),
};
+12 -1
View File
@@ -1,8 +1,19 @@
import { z } from "zod";
const contentPartSchema = z.discriminatedUnion("type", [
z.object({ type: z.literal("text"), text: z.string() }),
z.object({
type: z.literal("image_url"),
image_url: z.object({
url: z.string(),
detail: z.enum(["auto", "low", "high"]).optional(),
}),
}),
]);
const chatMessageSchema = z.object({
role: z.enum(["system", "user", "assistant", "tool"]),
content: z.union([z.string(), z.null()]),
content: z.union([z.string(), z.array(contentPartSchema), z.null()]),
name: z.string().optional(),
tool_calls: z
.array(
+65 -1
View File
@@ -1,4 +1,7 @@
import type {
AudioSpeechRequest,
ImageGenerationRequest,
ImageGenerationResponse,
ProviderAdapter,
ProviderKeyContext,
ProviderKeyMetadata,
@@ -46,7 +49,6 @@ export abstract class OpenAICompatibleAdapter implements ProviderAdapter {
};
if (req.temperature !== undefined) body.temperature = req.temperature;
if (req.top_p !== undefined) body.top_p = req.top_p;
if (req.max_tokens !== undefined) body.max_tokens = req.max_tokens;
if (req.stop !== undefined) body.stop = req.stop;
if (req.presence_penalty !== undefined) body.presence_penalty = req.presence_penalty;
if (req.frequency_penalty !== undefined) body.frequency_penalty = req.frequency_penalty;
@@ -171,6 +173,68 @@ export abstract class OpenAICompatibleAdapter implements ProviderAdapter {
return (await response.json()) as UnifiedEmbeddingResponse;
}
async imageGeneration(req: ImageGenerationRequest, ctx: ProviderKeyContext): Promise<ImageGenerationResponse> {
const body: Record<string, unknown> = {
model: ctx.providerModelId,
prompt: req.prompt,
response_format: "b64_json",
};
if (req.n !== undefined) body.n = req.n;
if (req.size !== undefined) body.size = req.size;
if (req.quality !== undefined) body.quality = req.quality;
if (req.style !== undefined) body.style = req.style;
const response = await fetch(`${ctx.providerBaseUrl}/v1/images/generations`, {
method: "POST",
headers: this.buildHeaders(ctx),
body: JSON.stringify(body),
signal: AbortSignal.timeout(ctx.timeout),
});
if (!response.ok) {
const errorText = await response.text().catch(() => "Unknown error");
logger.error({ status: response.status, body: errorText, provider: this.id }, "Provider image generation error");
throw new ApiError(
response.status,
`Provider ${this.id} returned ${response.status}: ${errorText.slice(0, 200)}`,
"server_error",
"provider_error",
);
}
return (await response.json()) as ImageGenerationResponse;
}
async audioSpeech(req: AudioSpeechRequest, ctx: ProviderKeyContext): Promise<ArrayBuffer> {
const body: Record<string, unknown> = {
model: ctx.providerModelId,
input: req.input,
voice: req.voice,
};
if (req.response_format) body.response_format = req.response_format;
if (req.speed !== undefined) body.speed = req.speed;
const response = await fetch(`${ctx.providerBaseUrl}/v1/audio/speech`, {
method: "POST",
headers: this.buildHeaders(ctx),
body: JSON.stringify(body),
signal: AbortSignal.timeout(ctx.timeout),
});
if (!response.ok) {
const errorText = await response.text().catch(() => "Unknown error");
logger.error({ status: response.status, body: errorText, provider: this.id }, "Provider audio speech error");
throw new ApiError(
response.status,
`Provider ${this.id} returned ${response.status}: ${errorText.slice(0, 200)}`,
"server_error",
"provider_error",
);
}
return response.arrayBuffer();
}
async validateApiKey(key: string): Promise<ProviderKeyMetadata> {
try {
const response = await fetch(`${this.defaultBaseUrl}/v1/models`, {
+6 -1
View File
@@ -2,7 +2,7 @@ import { getMongoDb } from "@/lib/mongo";
import { decrypt } from "./encryption";
import { getAdapter } from "@/server/adapters";
import { DEFAULT_PROVIDER_TIMEOUT_MS } from "@/lib/constants";
import type { ProviderAdapter, ProviderKeyContext } from "@/types/provider";
import type { ModelType, ProviderAdapter, ProviderKeyContext } from "@/types/provider";
type ProviderDocument = {
_id: string;
@@ -27,6 +27,7 @@ type ModelMappingDocument = {
logicalModelId: string;
priority: number;
enabled: boolean;
modelType?: ModelType;
createdAt: Date;
};
@@ -37,6 +38,7 @@ export interface ResolvedRoute {
providerApiKeyId: string;
logicalModelId: string;
providerModelId: string;
modelType: ModelType;
}
const localRoundRobinByProvider = new Map<string, number>();
@@ -46,6 +48,7 @@ async function resolveRouteForMapping(
providerId: string;
providerModelId: string;
logicalModelId: string;
modelType?: ModelType;
provider: { baseUrl: string; config?: Record<string, unknown>; enabled: boolean };
},
): Promise<ResolvedRoute | null> {
@@ -89,6 +92,7 @@ async function resolveRouteForMapping(
providerApiKeyId: selectedKey._id,
logicalModelId: mapping.logicalModelId,
providerModelId: mapping.providerModelId,
modelType: mapping.modelType ?? "chat",
};
}
@@ -115,6 +119,7 @@ export async function resolveModelRouteCandidates(logicalModelId: string): Promi
providerId: mapping.providerId,
providerModelId: mapping.providerModelId,
logicalModelId: mapping.logicalModelId,
modelType: mapping.modelType,
provider: { baseUrl: provider.baseUrl, config: provider.config, enabled: provider.enabled },
});
if (route) candidates.push(route);
+2 -2
View File
@@ -26,7 +26,7 @@ interface RouteLogContext extends BaseRequestContext {
function summarizeChatPrompt(req: UnifiedChatRequest): string {
return req.messages
.map((message) => `${message.role}: ${message.content ?? ""}`)
.map((message) => `${message.role}: ${typeof message.content === "string" ? message.content : Array.isArray(message.content) ? message.content.filter((p) => p.type === "text").map((p) => (p as { text: string }).text).join("") : ""}`)
.join("\n")
.slice(0, 5000);
}
@@ -190,7 +190,7 @@ export async function handleChatCompletion(request: Request): Promise<Response>
latencyMs,
streamed: false,
promptText: summarizeChatPrompt(unifiedReq),
responseText: result.choices[0]?.message.content ?? undefined,
responseText: typeof result.choices[0]?.message.content === "string" ? result.choices[0].message.content : undefined,
loggingMode: "preview",
}).catch((err) => logger.error(err, "Failed to log usage"));
+26
View File
@@ -1,6 +1,30 @@
import type { UnifiedChatRequest, UnifiedCompletionRequest, UnifiedEmbeddingRequest } from "./unified-request";
import type { UnifiedChatResponse, UnifiedCompletionResponse, UnifiedEmbeddingResponse } from "./unified-response";
export type ModelType = "chat" | "image" | "audio";
export interface ImageGenerationRequest {
prompt: string;
model: string;
n?: number;
size?: string;
quality?: string;
style?: string;
}
export interface ImageGenerationResponse {
created: number;
data: Array<{ url?: string; b64_json?: string; revised_prompt?: string }>;
}
export interface AudioSpeechRequest {
model: string;
input: string;
voice: string;
response_format?: "mp3" | "opus" | "aac" | "flac" | "wav" | "pcm";
speed?: number;
}
export interface ProviderKeyContext {
decryptedKey: string;
providerModelId: string;
@@ -35,5 +59,7 @@ export interface ProviderAdapter {
completion?(req: UnifiedCompletionRequest, ctx: ProviderKeyContext): Promise<UnifiedCompletionResponse>;
embeddings?(req: UnifiedEmbeddingRequest, ctx: ProviderKeyContext): Promise<UnifiedEmbeddingResponse>;
imageGeneration?(req: ImageGenerationRequest, ctx: ProviderKeyContext): Promise<ImageGenerationResponse>;
audioSpeech?(req: AudioSpeechRequest, ctx: ProviderKeyContext): Promise<ArrayBuffer>;
listModels?(ctx: ProviderKeyContext): Promise<ProviderModelInfo[]>;
}
+16 -1
View File
@@ -1,6 +1,21 @@
export interface ChatMessageContentPartText {
type: "text";
text: string;
}
export interface ChatMessageContentPartImage {
type: "image_url";
image_url: {
url: string;
detail?: "auto" | "low" | "high";
};
}
export type ChatMessageContentPart = ChatMessageContentPartText | ChatMessageContentPartImage;
export interface ChatMessage {
role: "system" | "user" | "assistant" | "tool";
content: string | null;
content: string | ChatMessageContentPart[] | null;
name?: string;
tool_calls?: ToolCall[];
tool_call_id?: string;