Compare commits

...
10 Commits
Author SHA1 Message Date
Zebratic 71cb4d3f72 feat: integrate Pulse Analytics tracking for LLM Proxy
- Add Pulse Analytics script tag to root layout (data-domain=llm.xmr.network)
- Add server-side tracking for successful API calls (chat completions,
  completions, embeddings) via /api/track/server endpoint
- Add lib/pulse.ts tracking utility (fire-and-forget)
2026-03-20 13:12:05 +00:00
Zebratic 401a0ba0d7 feat: add /v1/audio/speech endpoint with API key auth 2026-03-18 04:29:32 +00:00
Zebratic 94b86e92ca feat: show Mosaic in dashboard model dropdowns (playground + models list) 2026-03-18 01:51:19 +00:00
Zebratic 9c9ff51b87 fix: support x-api-key header in Anthropic messages endpoint (Claude Code compat)
Claude Code sends x-api-key instead of Authorization Bearer. Now accepts both.
2026-03-18 01:31:58 +00:00
Zebratic 4c222c036a fix: Anthropic streaming - correct stop_reason and add content_block_start/stop for text
- stop_reason now correctly returns 'end_turn' for non-tool responses (was always 'tool_use')
- Added content_block_start event before first text delta
- Added content_block_stop event for text blocks
- Fixes Claude Code compatibility
2026-03-18 01:26:45 +00:00
Zebratic ffbcdf753b feat: add Mosaic support to Anthropic Messages handler (Claude Code compatibility)
- Mosaic routing in /v1/messages endpoint
- Identity injection for Anthropic-format requests
- Model field masking in both streaming and non-streaming Anthropic responses
- Analytics logged as logicalModelId='mosaic'
2026-03-18 01:17:27 +00:00
Zebratic 8f37b3cd4f feat: add Mosaic virtual model - smart multi-provider routing with identity protection
- Mosaic router: dynamically selects best backend model based on prompt complexity, size, and tool usage
- Identity injection: system prompt ensures model always identifies as Mosaic
- Response masking: model field rewritten to 'mosaic' in both streaming and non-streaming responses
- Analytics: logicalModelId='mosaic' for user stats, providerModelId tracks actual backend
- Models list: mosaic appears in /v1/models endpoint
- Backends: claude-opus-4-6, gpt-5.4, gpt-4.1, claude-sonnet-4-6, gpt-4o, deepseek-chat
2026-03-18 00:12:30 +00:00
Zebratic b229d873ef Revert "Integrate Mosaic model logic and update configuration for Claude Code"
This reverts commit 248fc1f824.
2026-03-17 23:57:03 +00:00
Zebratic 248fc1f824 Integrate Mosaic model logic and update configuration for Claude Code 2026-03-17 23:52:24 +00:00
Zebratic 9252feffe0 Fix: retry on upstream credit errors, fix model field in request logs 2026-03-17 21:06:59 +00:00
10 changed files with 601 additions and 39 deletions

No files matched your search

+3
View File
@@ -12,5 +12,8 @@ export async function GET() {
});
const models = [...new Set(mappings.map((m) => m.logicalModelId as string))].sort();
if (!models.includes("mosaic")) {
models.unshift("mosaic");
}
return NextResponse.json({ data: models });
}
+10 -5
View File
@@ -72,11 +72,16 @@ export async function GET() {
const isFineTuned = (id: string) =>
id.startsWith("ft:") || id.includes(":personal:") || id.includes("ckpt-step-");
return NextResponse.json({
data: [...byModel.entries()]
.filter(([id]) => !isFineTuned(id))
.map(([id, info]) => ({ id, providerId: info.providerId, modelType: info.modelType })),
});
const modelList = [...byModel.entries()]
.filter(([id]) => !isFineTuned(id))
.map(([id, info]) => ({ id, providerId: info.providerId, modelType: info.modelType }));
// Always include Mosaic as a virtual model at the top
if (!modelList.some((m) => m.id === "mosaic")) {
modelList.unshift({ id: "mosaic", providerId: "mosaic", modelType: "chat" });
}
return NextResponse.json({ data: modelList });
}
export async function POST(req: Request) {
+6
View File
@@ -19,6 +19,12 @@ export default function RootLayout({ children }: { children: React.ReactNode })
<html lang="en" suppressHydrationWarning className="dark">
<head>
<meta name="theme-color" content="#0a0b0f" />
{/* Pulse Analytics tracking */}
<script
src="https://pulse.xmr.network/api/script"
data-domain="llm.xmr.network"
defer
/>
</head>
<body className="bg-background text-foreground antialiased font-[Inter,ui-sans-serif,system-ui,-apple-system,Segoe_UI,Roboto,Helvetica,Arial,sans-serif]">
<SessionProvider>
+139
View File
@@ -0,0 +1,139 @@
import { NextResponse } from "next/server";
import { authenticateApiKey } from "@/server/services/api-key-auth";
import { resolveModelRouteCandidates } from "@/server/services/model-router";
import { checkRateLimit } from "@/server/services/rate-limiter";
import { logUsage } from "@/server/services/usage-logger";
import { logger } from "@/lib/logger";
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
export async function POST(request: Request): Promise<Response> {
// Authenticate — support both Bearer and x-api-key
const authHeader =
request.headers.get("Authorization") ??
(request.headers.get("x-api-key")
? `Bearer ${request.headers.get("x-api-key")}`
: null);
const auth = await authenticateApiKey(authHeader);
if (!auth) {
return NextResponse.json({ error: "Invalid API key" }, { status: 401 });
}
// Parse body
let body: {
model: string;
input: string;
voice?: string;
voice_id?: string;
speed?: number;
model_id?: string;
stability?: number;
similarity_boost?: number;
style?: number;
response_format?: string;
};
try {
body = await request.json();
} catch {
return NextResponse.json({ error: "Invalid JSON" }, { status: 400 });
}
if (!body.model || !body.input) {
return NextResponse.json(
{ error: "Missing required fields: model, input" },
{ status: 400 }
);
}
// Rate limit
const limits = {
dailyRequests:
auth.apiKey.dailyRequestLimit ?? auth.subscription.plan.dailyRequestLimit ?? null,
dailyTokens:
auth.apiKey.dailyTokenLimit ?? auth.subscription.plan.dailyTokenLimit ?? null,
dailyCostCents: auth.apiKey.softCostLimitCents ?? null,
};
const rateLimit = await checkRateLimit(auth.apiKey.id, limits);
if (!rateLimit.allowed) {
return NextResponse.json(
{ error: `Rate limited: ${rateLimit.reason}` },
{ status: 429, headers: { "Retry-After": String(rateLimit.retryAfter ?? 60) } }
);
}
// Resolve model routes
const routes = await resolveModelRouteCandidates(body.model);
if (routes.length === 0) {
return NextResponse.json(
{ error: `Model '${body.model}' not found` },
{ status: 404 }
);
}
const startedAt = Date.now();
for (const route of routes) {
if (!route.adapter.audioSpeech) continue;
try {
const audioBuffer = await route.adapter.audioSpeech(
{
model: body.model,
input: body.input,
voice: body.voice ?? "alloy",
response_format: body.response_format ?? "mp3",
speed: body.speed,
voice_id: body.voice_id,
model_id: body.model_id,
stability: body.stability,
similarity_boost: body.similarity_boost,
style: body.style,
},
route.ctx
);
const latencyMs = Date.now() - startedAt;
logUsage({
userId: auth.user.id,
userApiKeyId: auth.apiKey.id,
providerId: route.providerId,
providerApiKeyId: route.providerApiKeyId,
logicalModelId: route.logicalModelId,
providerModelId: route.providerModelId,
statusCode: 200,
tokensIn: 0,
tokensOut: 0,
latencyMs,
streamed: false,
promptText: body.input,
loggingMode: "preview",
}).catch((err) => logger.error(err, "Failed to log audio speech usage"));
const b64 = Buffer.from(audioBuffer).toString("base64");
return NextResponse.json({
model: body.model,
audio: {
b64,
contentType: "audio/mpeg",
},
});
} catch (error: any) {
const status = error.statusCode ?? 500;
if (status === 429 || status >= 500) continue; // try next route
logger.error(error, "Audio speech error");
return NextResponse.json(
{ error: error.message ?? "Provider error" },
{ status }
);
}
}
return NextResponse.json(
{ error: "No provider with audio speech capability available for this model" },
{ status: 502 }
);
}
+18 -6
View File
@@ -50,14 +50,26 @@ export async function GET(request: Request): Promise<Response> {
const isFineTuned = (id: string) =>
id.startsWith("ft:") || id.includes(":personal:") || id.includes("ckpt-step-");
const models: OpenAIModelList = {
object: "list",
data: mappings.filter((m) => !isFineTuned(m._id)).map((m) => ({
id: m._id,
const modelData = mappings.filter((m) => !isFineTuned(m._id)).map((m) => ({
id: m._id,
object: "model" as const,
created: Math.floor(Date.now() / 1000),
owned_by: "llm-proxy",
}));
// Always include Mosaic as a virtual model
if (!modelData.some((m) => m.id === "mosaic")) {
modelData.unshift({
id: "mosaic",
object: "model" as const,
created: Math.floor(Date.now() / 1000),
owned_by: "llm-proxy",
})),
owned_by: "mosaic",
});
}
const models: OpenAIModelList = {
object: "list",
data: modelData,
};
return Response.json(models);
+52
View File
@@ -0,0 +1,52 @@
/**
* Pulse Analytics server-side tracking
* Fire-and-forget tracking calls to the Pulse Analytics server endpoint.
*/
const PULSE_TRACK_URL = process.env.PULSE_ANALYTICS_URL || "https://pulse.xmr.network";
const PULSE_API_KEY = process.env.PULSE_API_KEY;
const SITE_DOMAIN = process.env.NEXT_PUBLIC_APP_URL?.replace("https://", "") || "llm.xmr.network";
interface TrackParams {
eventType: string;
eventName?: string;
userId?: string;
model?: string;
provider?: string;
tokensIn?: number;
tokensOut?: number;
latencyMs?: number;
error?: string;
}
export async function trackPulseEvent(params: TrackParams): Promise<void> {
if (!PULSE_API_KEY) return;
try {
fetch(`${PULSE_TRACK_URL}/api/track/server`, {
method: "POST",
headers: {
"Content-Type": "application/json",
"X-Pulse-API-Key": PULSE_API_KEY,
},
body: JSON.stringify({
site: SITE_DOMAIN,
eventType: params.eventType,
eventName: params.eventName,
userId: params.userId,
props: {
model: params.model,
provider: params.provider,
tokensIn: params.tokensIn,
tokensOut: params.tokensOut,
latencyMs: params.latencyMs,
error: params.error,
},
}),
}).catch(() => {
// fire-and-forget, ignore errors
});
} catch {
// ignore errors
}
}
@@ -7,6 +7,7 @@ import { evaluateKeySchedule } from "./schedule-evaluator";
import { createLoggingTransformStream, sseHeaders } from "./streaming";
import { logUsage } from "./usage-logger";
import { logDebugEntry, extractClientInfo, extractSessionId, type DebugLogEntry, type ToolCall } from "./debug-logger";
import { isMosaicRequest, resolveMosaicRoutes, injectMosaicIdentity, createMosaicStreamMask, MOSAIC_MODEL_ID, MOSAIC_SYSTEM_PROMPT } from "./mosaic-router";
import { invalidApiKey, rateLimitExceeded, modelNotFound, invalidRequest, providerUnavailable, ApiError } from "@/lib/api-error";
import { z } from "zod";
import { anthropicMessagesSchema } from "@/lib/validations/anthropic-messages";
@@ -285,7 +286,23 @@ function previewForConsoleLog(value: string, maxLength = 300): string {
}
function shouldRetryProviderError(error: ApiError): boolean {
return error.statusCode === 429 || (error.statusCode >= 500 && error.statusCode < 600);
// Retry on rate limits, server errors, and upstream billing/auth failures
// (e.g. "credit balance too low" returns 400 from Anthropic — we should try the next key)
if (error.statusCode === 429 || (error.statusCode >= 500 && error.statusCode < 600)) return true;
// Upstream provider billing/credit errors — try next key
const msg = (error.errorMessage || "").toLowerCase();
if (msg.includes("credit balance") || msg.includes("billing") || msg.includes("overloaded") ||
msg.includes("insufficient") || msg.includes("quota") || msg.includes("exceeded")) {
return true;
}
// Provider returned 400/401/403 with a provider_error code — likely a key-specific issue
if (error.errorCode === "provider_error" && (error.statusCode === 400 || error.statusCode === 401 || error.statusCode === 403)) {
return true;
}
return false;
}
export async function handleAnthropicMessages(request: Request): Promise<Response> {
@@ -311,7 +328,10 @@ export async function handleAnthropicMessages(request: Request): Promise<Respons
const isStreaming = input.stream ?? false;
// Authenticate
const auth = await authenticateApiKey(request.headers.get("Authorization"));
// Support both OpenAI-style "Authorization: Bearer <key>" and Anthropic-style "x-api-key: <key>"
const authHeader = request.headers.get("Authorization") ??
(request.headers.get("x-api-key") ? `Bearer ${request.headers.get("x-api-key")}` : null);
const auth = await authenticateApiKey(authHeader);
if (!auth) return invalidApiKey().toResponse();
// Extract client info
@@ -344,7 +364,24 @@ export async function handleAnthropicMessages(request: Request): Promise<Respons
return rateLimitExceeded(rateLimitResult.reason!, rateLimitResult.retryAfter!);
}
const plans = await resolveModelRouteWithCandidates(effectiveModel);
// Convert to unified request first (needed for Mosaic routing)
let unifiedReq = convertAnthropicToUnified(input, isStreaming);
const mosaic = isMosaicRequest(effectiveModel);
let mosaicBackend: string | undefined;
let plans;
if (mosaic) {
const result = await resolveMosaicRoutes(unifiedReq);
plans = result.plans;
mosaicBackend = result.selectedBackend;
// Inject Mosaic identity into unified request
unifiedReq = injectMosaicIdentity(unifiedReq);
logger.info({ mosaicBackend }, "Mosaic (Anthropic): routing to backend");
} else {
plans = await resolveModelRouteWithCandidates(effectiveModel);
}
if (plans.length === 0) {
return modelNotFound(effectiveModel).toResponse();
}
@@ -361,9 +398,6 @@ export async function handleAnthropicMessages(request: Request): Promise<Respons
}
}
// Convert to unified request
const unifiedReq = convertAnthropicToUnified(input, isStreaming);
const baseLogContext = {
userId: auth.user.id,
userApiKeyId: auth.apiKey.id,
@@ -401,7 +435,7 @@ export async function handleAnthropicMessages(request: Request): Promise<Respons
...baseLogContext,
providerId: route.providerId,
providerApiKeyId: route.providerApiKeyId,
logicalModelId: route.logicalModelId,
logicalModelId: mosaic ? MOSAIC_MODEL_ID : route.logicalModelId,
providerModelId: route.providerModelId,
};
@@ -420,7 +454,7 @@ export async function handleAnthropicMessages(request: Request): Promise<Respons
const encoder = new TextEncoder();
// Send start event
const msgObj = { id: "temp", type: "message", role: "assistant", content: [], model: effectiveModel, stop_reason: null, stop_sequence: null, usage: { input_tokens: 0, output_tokens: 0 } };
const msgObj = { id: "temp", type: "message", role: "assistant", content: [], model: mosaic ? MOSAIC_MODEL_ID : effectiveModel, stop_reason: null, stop_sequence: null, usage: { input_tokens: 0, output_tokens: 0 } };
const startEventObj = { type: "message_start", message: msgObj };
const startLine = "data: " + JSON.stringify(startEventObj);
controller.enqueue(encoder.encode(startLine.concat("\n\n")));
@@ -429,6 +463,7 @@ export async function handleAnthropicMessages(request: Request): Promise<Respons
let currentToolCallId = "";
let currentToolName = "";
let currentToolArgs = "";
let textBlockStarted = false;
try {
while (true) {
@@ -445,6 +480,11 @@ export async function handleAnthropicMessages(request: Request): Promise<Respons
const data = line.slice(6);
if (data === "[DONE]") {
// Close text block if open
if (textBlockStarted && !currentToolCallId) {
const textStop = "data: " + JSON.stringify({ type: "content_block_stop", index: 0 });
controller.enqueue(encoder.encode(textStop.concat("\n\n")));
}
// If we have a pending tool call, send it
if (currentToolCallId) {
const toolInputDelta = "data: " + JSON.stringify({
@@ -461,7 +501,9 @@ export async function handleAnthropicMessages(request: Request): Promise<Respons
controller.enqueue(encoder.encode(toolStopDelta.concat("\n\n")));
}
const deltaLine = "data: " + JSON.stringify({ type: "message_delta", delta: { stop_reason: "tool_use", stop_sequence: null }, usage: { output_tokens: 0 } });
// Use "tool_use" stop reason only if we had tool calls, otherwise "end_turn"
const stopReason = currentToolCallId ? "tool_use" : "end_turn";
const deltaLine = "data: " + JSON.stringify({ type: "message_delta", delta: { stop_reason: stopReason, stop_sequence: null }, usage: { output_tokens: 0 } });
controller.enqueue(encoder.encode(deltaLine.concat("\n\n")));
const stopLine = "data: " + JSON.stringify({ type: "message_stop" });
controller.enqueue(encoder.encode(stopLine.concat("\n\n")));
@@ -474,6 +516,11 @@ export async function handleAnthropicMessages(request: Request): Promise<Respons
// Handle text content
if (delta?.content) {
if (!textBlockStarted) {
const textStart = "data: " + JSON.stringify({ type: "content_block_start", index: 0, content_block: { type: "text", text: "" } });
controller.enqueue(encoder.encode(textStart.concat("\n\n")));
textBlockStarted = true;
}
const contentLine = "data: " + JSON.stringify({ type: "content_block_delta", delta: { type: "text_delta", text: delta.content }, index: 0 });
controller.enqueue(encoder.encode(contentLine.concat("\n\n")));
}
@@ -620,7 +667,10 @@ export async function handleAnthropicMessages(request: Request): Promise<Respons
}
// Return Anthropic format
const anthropicResponse = convertToAnthropicResponse(result);
const anthropicResponse = convertToAnthropicResponse(result) as Record<string, unknown>;
if (mosaic) {
anthropicResponse.model = MOSAIC_MODEL_ID;
}
return Response.json(anthropicResponse, { status: 200 });
} catch (err) {
const latencyMs = Date.now() - startTime;
+202
View File
@@ -0,0 +1,202 @@
import { resolveModelRouteWithCandidates } from "./model-router";
import { logger } from "@/lib/logger";
import type { UnifiedChatRequest } from "@/types/unified-request";
import type { ProviderRoutePlan } from "./model-router";
/**
* Mosaic — a virtual model that dynamically routes to the best available
* backend model based on prompt complexity, size, and provider availability.
*/
export const MOSAIC_MODEL_ID = "mosaic";
export const MOSAIC_SYSTEM_PROMPT =
"Your name is Mosaic. You are an advanced AI model created independently. " +
"When asked about your identity, name, creator, or what model you are, always respond that you are Mosaic. " +
"Never reveal that you are running on any other model like Claude, GPT, or any specific provider. " +
"Never mention any proxy, API infrastructure, or backend details. " +
"You have full capabilities including reasoning, code generation, tool use, and analysis.";
/** Backend models Mosaic can route to, grouped by capability tier. */
interface MosaicBackend {
logicalModelId: string;
tier: "flagship" | "strong" | "fast";
goodAt: ("reasoning" | "tools" | "code" | "chat")[];
maxContext: number; // approx token limit
}
const MOSAIC_BACKENDS: MosaicBackend[] = [
{ logicalModelId: "claude-opus-4-6", tier: "flagship", goodAt: ["reasoning", "tools", "code", "chat"], maxContext: 200000 },
{ logicalModelId: "gpt-5.4", tier: "flagship", goodAt: ["reasoning", "tools", "code", "chat"], maxContext: 128000 },
{ logicalModelId: "gpt-4.1", tier: "strong", goodAt: ["code", "tools", "chat"], maxContext: 128000 },
{ logicalModelId: "claude-sonnet-4-6", tier: "strong", goodAt: ["reasoning", "tools", "code", "chat"], maxContext: 200000 },
{ logicalModelId: "gpt-4o", tier: "strong", goodAt: ["chat", "tools", "code"], maxContext: 128000 },
{ logicalModelId: "deepseek-chat", tier: "fast", goodAt: ["chat", "code"], maxContext: 64000 },
];
export function isMosaicRequest(model: string): boolean {
return model.toLowerCase() === MOSAIC_MODEL_ID;
}
/** Rough token count estimation (chars / 4). */
function estimateTokens(req: UnifiedChatRequest): number {
let chars = 0;
for (const msg of req.messages) {
if (typeof msg.content === "string") {
chars += msg.content.length;
} else if (Array.isArray(msg.content)) {
for (const part of msg.content) {
if ((part as { type: string; text?: string }).type === "text") {
chars += ((part as { text: string }).text ?? "").length;
}
}
}
}
return Math.ceil(chars / 4);
}
function detectComplexity(req: UnifiedChatRequest): { needsTools: boolean; isComplex: boolean } {
const needsTools = !!(req.tools && req.tools.length > 0);
const estimatedTokens = estimateTokens(req);
// Complex if tools, large prompt, or explicit reasoning effort
const isComplex = needsTools || estimatedTokens > 4000 || req.effort === "high";
return { needsTools, isComplex };
}
function shuffleArray<T>(arr: T[]): T[] {
const shuffled = [...arr];
for (let i = shuffled.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
}
return shuffled;
}
/**
* Select backend models ordered by suitability for this request.
* Returns logical model IDs to try in order.
*/
function rankBackends(req: UnifiedChatRequest): string[] {
const { needsTools, isComplex } = detectComplexity(req);
const estimatedTokens = estimateTokens(req);
// Filter out models that can't handle the context size
const viable = MOSAIC_BACKENDS.filter((b) => b.maxContext > estimatedTokens * 1.5);
if (viable.length === 0) {
// Fallback: just return all backends sorted by context size
return MOSAIC_BACKENDS.sort((a, b) => b.maxContext - a.maxContext).map((b) => b.logicalModelId);
}
// Score each backend
const scored = viable.map((b) => {
let score = 0;
// Tier bonus
if (b.tier === "flagship") score += 10;
else if (b.tier === "strong") score += 5;
else score += 2;
// Capability match
if (needsTools && b.goodAt.includes("tools")) score += 5;
if (isComplex && b.goodAt.includes("reasoning")) score += 5;
// For simple/small prompts, don't penalize fast models
if (!isComplex && !needsTools) {
if (b.tier === "fast") score += 3; // Slightly prefer fast for simple stuff
}
return { backend: b, score };
});
// Group by score, shuffle within same score for load distribution
scored.sort((a, b) => b.score - a.score);
const groups = new Map<number, string[]>();
for (const s of scored) {
const existing = groups.get(s.score) ?? [];
existing.push(s.backend.logicalModelId);
groups.set(s.score, existing);
}
const result: string[] = [];
for (const [, models] of [...groups.entries()].sort((a, b) => b[0] - a[0])) {
result.push(...shuffleArray(models));
}
return result;
}
/**
* Resolve Mosaic to actual provider route plans.
* Tries backend models in ranked order until one has available providers.
*/
export async function resolveMosaicRoutes(req: UnifiedChatRequest): Promise<{
plans: ProviderRoutePlan[];
selectedBackend: string;
}> {
const rankedBackends = rankBackends(req);
logger.info({ rankedBackends }, "Mosaic: ranked backend models");
for (const backendModel of rankedBackends) {
const plans = await resolveModelRouteWithCandidates(backendModel);
if (plans.length > 0 && plans.some((p) => p.keys.length > 0)) {
logger.info({ selectedBackend: backendModel, planCount: plans.length }, "Mosaic: selected backend");
return { plans, selectedBackend: backendModel };
}
}
// Nothing available — return empty
logger.warn("Mosaic: no backend models available");
return { plans: [], selectedBackend: "none" };
}
/**
* Inject the Mosaic identity system prompt into the messages array.
* Prepends as a system message, or appends to existing system message.
*/
export function injectMosaicIdentity(req: UnifiedChatRequest): UnifiedChatRequest {
const messages = [...req.messages];
if (messages.length > 0 && messages[0].role === "system") {
// Prepend to existing system message
const existing = typeof messages[0].content === "string" ? messages[0].content : "";
messages[0] = {
...messages[0],
content: `${MOSAIC_SYSTEM_PROMPT}\n\n${existing}`,
};
} else {
// Insert new system message at the beginning
messages.unshift({ role: "system", content: MOSAIC_SYSTEM_PROMPT });
}
return { ...req, messages };
}
/**
* Rewrite the `model` field in a non-streaming response JSON.
*/
export function maskResponseModel<T extends { model?: string }>(response: T): T {
return { ...response, model: MOSAIC_MODEL_ID };
}
/**
* Create a transform stream that rewrites `"model":"anything"` to `"model":"mosaic"` in SSE chunks.
*/
export function createMosaicStreamMask(sourceStream: ReadableStream<Uint8Array>): ReadableStream<Uint8Array> {
const decoder = new TextDecoder();
const encoder = new TextEncoder();
// Match "model":"<anything>" in JSON — handles most SSE chunk formats
const modelRegex = /"model"\s*:\s*"[^"]+"/g;
return sourceStream.pipeThrough(
new TransformStream<Uint8Array, Uint8Array>({
transform(chunk, controller) {
const text = decoder.decode(chunk, { stream: true });
const masked = text.replace(modelRegex, `"model":"${MOSAIC_MODEL_ID}"`);
controller.enqueue(encoder.encode(masked));
},
}),
);
}
+106 -18
View File
@@ -6,11 +6,13 @@ import { getStickyKey, setStickyKey, clearStickyKey } from "./sticky-key-store";
import { evaluateKeySchedule } from "./schedule-evaluator";
import { createLoggingTransformStream, sseHeaders } from "./streaming";
import { logUsage } from "./usage-logger";
import { isMosaicRequest, resolveMosaicRoutes, injectMosaicIdentity, maskResponseModel, createMosaicStreamMask, MOSAIC_MODEL_ID } from "./mosaic-router";
import { invalidApiKey, rateLimitExceeded, modelNotFound, invalidRequest, providerUnavailable, ApiError } from "@/lib/api-error";
import { chatCompletionSchema } from "@/lib/validations/chat-completion";
import { completionSchema } from "@/lib/validations/completion";
import { embeddingsSchema } from "@/lib/validations/embeddings";
import { logger } from "@/lib/logger";
import { trackPulseEvent } from "@/lib/pulse";
import type { UnifiedChatRequest, UnifiedCompletionRequest, UnifiedEmbeddingRequest } from "@/types/unified-request";
import type { ResolvedRoute, ProviderRoutePlan, CandidateKey } from "./model-router";
@@ -82,16 +84,18 @@ async function applyStickyKeyAffinity(plans: ProviderRoutePlan[], userApiKeyId:
}
}
interface CommonContext {
baseLogContext: BaseRequestContext;
plans: ProviderRoutePlan[];
isMosaic: boolean;
mosaicBackend?: string;
}
async function getCommonContext(
request: Request,
model: string,
): Promise<
| {
baseLogContext: BaseRequestContext;
plans: ProviderRoutePlan[];
}
| Response
> {
chatReq?: UnifiedChatRequest,
): Promise<CommonContext | Response> {
const auth = await authenticateApiKey(request.headers.get("Authorization"));
if (!auth) return invalidApiKey().toResponse();
@@ -112,7 +116,19 @@ async function getCommonContext(
return rateLimitExceeded(rateLimitResult.reason!, rateLimitResult.retryAfter!);
}
const plans = await resolveModelRouteWithCandidates(model);
const mosaic = isMosaicRequest(model);
let plans: ProviderRoutePlan[];
let mosaicBackend: string | undefined;
if (mosaic && chatReq) {
const result = await resolveMosaicRoutes(chatReq);
plans = result.plans;
mosaicBackend = result.selectedBackend;
} else {
plans = await resolveModelRouteWithCandidates(model);
}
if (plans.length === 0) {
return modelNotFound(model).toResponse();
}
@@ -124,6 +140,8 @@ async function getCommonContext(
requestId: request.headers.get("X-Request-Id") ?? undefined,
},
plans,
isMosaic: mosaic,
mosaicBackend,
};
}
@@ -147,14 +165,9 @@ export async function handleChatCompletion(request: Request): Promise<Response>
}
const input = parsed.data;
const common = await getCommonContext(request, input.model);
if (common instanceof Response) return common;
const { plans, baseLogContext } = common;
// Apply sticky key affinity so the same provider key is reused across requests
await applyStickyKeyAffinity(plans, baseLogContext.userApiKeyId);
const unifiedReq: UnifiedChatRequest = {
// Build initial unified request (needed for Mosaic routing decisions)
let unifiedReq: UnifiedChatRequest = {
model: input.model,
messages: input.messages,
stream: input.stream,
@@ -171,12 +184,25 @@ export async function handleChatCompletion(request: Request): Promise<Response>
effort: input.effort,
};
const common = await getCommonContext(request, input.model, unifiedReq);
if (common instanceof Response) return common;
const { plans, baseLogContext, isMosaic, mosaicBackend } = common;
// For Mosaic requests, inject identity system prompt
if (isMosaic) {
unifiedReq = injectMosaicIdentity(unifiedReq);
logger.info({ mosaicBackend }, "Mosaic: identity prompt injected, routing to backend");
}
// Apply sticky key affinity so the same provider key is reused across requests
await applyStickyKeyAffinity(plans, baseLogContext.userApiKeyId);
logger.info(
{
requestId: baseLogContext.requestId,
userId: baseLogContext.userId,
userApiKeyId: baseLogContext.userApiKeyId,
model: unifiedReq.model,
model: isMosaic ? `mosaic → ${mosaicBackend}` : unifiedReq.model,
stream: Boolean(unifiedReq.stream),
promptPreview: previewForConsoleLog(summarizeChatPrompt(unifiedReq)),
},
@@ -192,13 +218,23 @@ export async function handleChatCompletion(request: Request): Promise<Response>
totalAttempts++;
const route = buildResolvedRoute(plan, candidateKey);
// For Mosaic: log logicalModelId as "mosaic" so user analytics show Mosaic
const logParams = buildRouteLogContext(baseLogContext, route);
if (isMosaic) {
logParams.logicalModelId = MOSAIC_MODEL_ID;
}
try {
if (input.stream) {
const providerStream = await route.adapter.chatCompletionStream(unifiedReq, route.ctx);
let providerStream = await route.adapter.chatCompletionStream(unifiedReq, route.ctx);
recordSuccess(candidateKey.providerApiKeyId, plan.logicalModelId);
setStickyKey(baseLogContext.userApiKeyId, plan.logicalModelId, candidateKey.providerApiKeyId).catch(() => {});
// For Mosaic: mask model name in SSE chunks before logging transform
if (isMosaic) {
providerStream = createMosaicStreamMask(providerStream);
}
const outputStream = createLoggingTransformStream(providerStream, {
onComplete: (usage) => {
logUsage({
@@ -211,6 +247,17 @@ export async function handleChatCompletion(request: Request): Promise<Response>
promptText: summarizeChatPrompt(unifiedReq),
loggingMode: "hash_only",
}).catch((err) => logger.error(err, "Failed to log streaming usage"));
// Pulse Analytics: track successful streaming API call
trackPulseEvent({
eventType: "api_call",
eventName: "chat_completion_stream",
userId: baseLogContext.userId,
model: logParams.logicalModelId,
provider: plan.providerId,
tokensIn: usage.tokensIn,
tokensOut: usage.tokensOut,
latencyMs: usage.latencyMs,
});
},
onError: (err) => {
logger.error(err, "Stream error");
@@ -223,10 +270,16 @@ export async function handleChatCompletion(request: Request): Promise<Response>
});
}
const result = await route.adapter.chatCompletion(unifiedReq, route.ctx);
let result = await route.adapter.chatCompletion(unifiedReq, route.ctx);
recordSuccess(candidateKey.providerApiKeyId, plan.logicalModelId);
setStickyKey(baseLogContext.userApiKeyId, plan.logicalModelId, candidateKey.providerApiKeyId).catch(() => {});
const latencyMs = Date.now() - startTime;
// For Mosaic: mask the model field in response
if (isMosaic) {
result = maskResponseModel(result);
}
logUsage({
...logParams,
statusCode: 200,
@@ -239,6 +292,18 @@ export async function handleChatCompletion(request: Request): Promise<Response>
loggingMode: "preview",
}).catch((err) => logger.error(err, "Failed to log usage"));
// Pulse Analytics: track successful non-streaming chat completion
trackPulseEvent({
eventType: "api_call",
eventName: "chat_completion",
userId: baseLogContext.userId,
model: logParams.logicalModelId,
provider: plan.providerId,
tokensIn: result.usage?.prompt_tokens ?? 0,
tokensOut: result.usage?.completion_tokens ?? 0,
latencyMs,
});
return Response.json(result, { status: 200 });
} catch (err) {
const latencyMs = Date.now() - startTime;
@@ -372,6 +437,18 @@ export async function handleCompletion(request: Request): Promise<Response> {
loggingMode: "preview",
}).catch((err) => logger.error(err, "Failed to log completion usage"));
// Pulse Analytics: track successful completion
trackPulseEvent({
eventType: "api_call",
eventName: "completion",
userId: baseLogContext.userId,
model: logParams.logicalModelId,
provider: plan.providerId,
tokensIn: result.usage?.prompt_tokens ?? 0,
tokensOut: result.usage?.completion_tokens ?? 0,
latencyMs,
});
return Response.json(result, { status: 200 });
} catch (err) {
const latencyMs = Date.now() - startTime;
@@ -501,6 +578,17 @@ export async function handleEmbeddings(request: Request): Promise<Response> {
loggingMode: "preview",
}).catch((err) => logger.error(err, "Failed to log embeddings usage"));
// Pulse Analytics: track successful embeddings
trackPulseEvent({
eventType: "api_call",
eventName: "embeddings",
userId: baseLogContext.userId,
model: logParams.logicalModelId,
provider: plan.providerId,
tokensIn: result.usage?.prompt_tokens ?? 0,
latencyMs,
});
return Response.json(result, { status: 200 });
} catch (err) {
const latencyMs = Date.now() - startTime;
+5
View File
@@ -11,6 +11,8 @@ type RequestLogDocument = {
providerApiKeyId: string | null;
logicalModelId: string;
providerModelId: string;
model?: string;
status?: number;
statusCode: number;
errorCode?: string;
errorMessage?: string;
@@ -90,6 +92,9 @@ export async function logUsage(params: LogParams): Promise<void> {
providerApiKeyId: params.providerApiKeyId,
logicalModelId: params.logicalModelId,
providerModelId: params.providerModelId,
// `model` field for admin dashboard compatibility
model: params.logicalModelId || params.providerModelId,
status: params.statusCode,
statusCode: params.statusCode,
errorCode: params.errorCode,
errorMessage: params.errorMessage,