import { z } from "zod"; import { withAuth } from "@/lib/api-auth"; import { apiError, handleApiError } from "@/lib/api-errors"; import { apiKeyValues } from "@/lib/api-keys"; import { ENGINE_PORT } from "@/lib/deploy-command"; import { getDeployment } from "@/lib/deployments"; export const dynamic = "force-dynamic"; const Body = z.object({ messages: z.array(z.object({ role: z.enum(["system", "user", "assistant"]), content: z.string().max(100_000) })).min(1).max(100), maxTokens: z.number().int().min(1).max(8192).default(256), }); /** * Smoke-test chat: forwards to the container's OpenAI-compatible API over the Docker network and * streams the server-sent events back unchanged. */ export const POST = withAuth>(async (req, { params }) => { try { const d = await getDeployment((await params).id); if (!d) return apiError(404, "not_found", "Deployment not found."); if (d.state !== "running" || !d.containerName) return apiError(409, "not_running", "The deployment isn't running."); const { messages, maxTokens } = Body.parse(await req.json()); // Any key works; keys added after the deployment started aren't known to it yet, so prefer the oldest. const [key] = d.options.requireApiKey ? await apiKeyValues() : []; const upstream = await fetch(`http://${d.containerName}:${ENGINE_PORT[d.engine]}/v1/chat/completions`, { method: "POST", headers: { "Content-Type": "application/json", ...(key ? { Authorization: `Bearer ${key}` } : {}) }, body: JSON.stringify({ model: d.repoId, messages, max_tokens: maxTokens, stream: true, stream_options: { include_usage: true } }), signal: req.signal, }).catch((err: Error) => { throw new Error(`Can't reach the deployment (${err.message}). The web app must be on the same Docker network.`); }); if (!upstream.ok || !upstream.body) { const text = await upstream.text().catch(() => ""); if (upstream.status === 401) return apiError(502, "upstream", "The model server rejected Kaname's API key. Restart the deployment to pick up changed keys."); return apiError(502, "upstream", `The model server answered ${upstream.status}: ${text.slice(0, 500)}`); } return new Response(upstream.body, { headers: { "Content-Type": "text/event-stream", "Cache-Control": "no-store" } }); } catch (err) { if (err instanceof Error && err.message.startsWith("Can't reach")) return apiError(502, "unreachable", err.message); return handleApiError(err); } });