diff --git a/src/app/v1/audio/speech/route.ts b/src/app/v1/audio/speech/route.ts new file mode 100644 index 0000000..c55e825 --- /dev/null +++ b/src/app/v1/audio/speech/route.ts @@ -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 { + // 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 } + ); +}