102 lines
2.8 KiB
JavaScript
102 lines
2.8 KiB
JavaScript
import { getConfig } from "@/lib/config";
|
|
import { getProvider } from "@/lib/llm/provider";
|
|
import { reconstructionSchema } from "@/lib/reconstruction/schema";
|
|
|
|
const MAX_SCENARIO_LENGTH = 10000;
|
|
|
|
export async function POST(request) {
|
|
const startTime = Date.now();
|
|
let rawResponse = null;
|
|
|
|
try {
|
|
const body = await request.json();
|
|
|
|
if (!body.scenario || typeof body.scenario !== "string") {
|
|
return Response.json(
|
|
{ error: "Request must include a 'scenario' string field" },
|
|
{ status: 400 }
|
|
);
|
|
}
|
|
|
|
const trimmed = body.scenario.trim();
|
|
|
|
if (trimmed.length === 0) {
|
|
return Response.json(
|
|
{ error: "Scenario cannot be empty" },
|
|
{ status: 400 }
|
|
);
|
|
}
|
|
|
|
if (trimmed.length > MAX_SCENARIO_LENGTH) {
|
|
return Response.json(
|
|
{ error: `Scenario must be under ${MAX_SCENARIO_LENGTH} characters` },
|
|
{ status: 400 }
|
|
);
|
|
}
|
|
|
|
const configResult = getConfig();
|
|
if (!configResult.ok) {
|
|
return Response.json(
|
|
{ error: "Invalid server configuration" },
|
|
{ status: 500 }
|
|
);
|
|
}
|
|
|
|
const { OLLAMA_BASE_URL, OLLAMA_MODEL } = configResult.config;
|
|
const provider = getProvider();
|
|
|
|
// Attempt parse to capture raw for debugging
|
|
let reconstruction;
|
|
try {
|
|
reconstruction = await provider.generateReconstruction(trimmed, OLLAMA_MODEL);
|
|
} catch (e) {
|
|
return Response.json(
|
|
{
|
|
error: e.message || "Unknown server error",
|
|
responseDurationMs: Date.now() - startTime,
|
|
modelName: OLLAMA_MODEL,
|
|
validationStatus: "invalid",
|
|
},
|
|
{ status: 500 }
|
|
);
|
|
}
|
|
|
|
// Try to stringify for rawResponse display (safe even if it's already an object)
|
|
try {
|
|
rawResponse = JSON.stringify(reconstruction);
|
|
} catch {
|
|
rawResponse = String(reconstruction).slice(0, 2000);
|
|
}
|
|
|
|
const duration = Date.now() - startTime;
|
|
|
|
// Validate with Zod schema
|
|
const validationResult = reconstructionSchema.safeParse(reconstruction);
|
|
|
|
if (!validationResult.success) {
|
|
return Response.json({
|
|
reconstruction: null,
|
|
modelName: OLLAMA_MODEL,
|
|
responseDurationMs: duration,
|
|
validationStatus: "invalid",
|
|
rawResponse: rawResponse?.slice(0, 2000),
|
|
errors: validationResult.error.issues.map((i) => `${i.path.join(".")}: ${i.message}`),
|
|
});
|
|
}
|
|
|
|
return Response.json({
|
|
reconstruction: validationResult.data,
|
|
modelName: OLLAMA_MODEL,
|
|
responseDurationMs: duration,
|
|
validationStatus: "valid",
|
|
rawResponse: rawResponse?.slice(0, 2000),
|
|
});
|
|
} catch (e) {
|
|
const duration = Date.now() - startTime;
|
|
return Response.json(
|
|
{ error: e.message || "Unknown server error", responseDurationMs: duration },
|
|
{ status: 500 }
|
|
);
|
|
}
|
|
}
|