OpenAI-compatible client with mock fallback, tool-calling loop, and /assistant UI. Tools map to /api/v1/ endpoints per ADR 0006 direct-tools decision.
53 lines
1.2 KiB
TypeScript
53 lines
1.2 KiB
TypeScript
import { z } from "zod";
|
|
import { apiError, apiJson } from "@/lib/api-handler";
|
|
import { resolveApiAuth } from "@/lib/api-auth";
|
|
import { isLlmConfigured } from "@/lib/llm";
|
|
import { runAgentChat } from "@/modules/agent/server/run";
|
|
|
|
const chatInput = z.object({
|
|
messages: z
|
|
.array(
|
|
z.object({
|
|
role: z.enum(["user", "assistant"]),
|
|
content: z.string().trim().min(1).max(8000),
|
|
}),
|
|
)
|
|
.min(1)
|
|
.max(40),
|
|
});
|
|
|
|
export async function POST(request: Request) {
|
|
const auth = await resolveApiAuth(request);
|
|
if (!auth) {
|
|
return apiError("Unauthorized", 401);
|
|
}
|
|
|
|
let body: unknown;
|
|
try {
|
|
body = await request.json();
|
|
} catch {
|
|
return apiError("Invalid JSON body", 400);
|
|
}
|
|
|
|
const parsed = chatInput.safeParse(body);
|
|
if (!parsed.success) {
|
|
return apiError(parsed.error.issues[0]?.message ?? "Validation error", 400);
|
|
}
|
|
|
|
try {
|
|
const result = await runAgentChat({
|
|
messages: parsed.data.messages,
|
|
request,
|
|
});
|
|
|
|
return apiJson({
|
|
...result,
|
|
configured: isLlmConfigured(),
|
|
provider: isLlmConfigured() ? "openai" : "mock",
|
|
});
|
|
} catch (err) {
|
|
const message = err instanceof Error ? err.message : "Agent request failed";
|
|
return apiError(message, 502);
|
|
}
|
|
}
|