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'
This commit is contained in:
Zebratic committed 2026-03-18 01:17:27 +00:00
1 parent 8f37b3cd4f
commit ffbcdf753b
1 file changed
+25 -7
@@ -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";
@@ -360,7 +361,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();
}
@@ -377,9 +395,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,
@@ -417,7 +432,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,
};
@@ -436,7 +451,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")));
@@ -636,7 +651,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;