59 lines
1.5 KiB
TypeScript
59 lines
1.5 KiB
TypeScript
import { getDemoAssistantReply, type DemoChatTurn } from "@/lib/chat-demo/assistant";
|
|
|
|
type ReplyRequestBody = {
|
|
message?: unknown;
|
|
conversation?: unknown;
|
|
};
|
|
|
|
function parseConversation(value: unknown): DemoChatTurn[] {
|
|
if (!Array.isArray(value)) {
|
|
return [];
|
|
}
|
|
|
|
return value
|
|
.map((entry): DemoChatTurn | null => {
|
|
if (!entry || typeof entry !== "object") {
|
|
return null;
|
|
}
|
|
|
|
const role = (entry as { role?: unknown }).role;
|
|
const content = (entry as { content?: unknown }).content;
|
|
|
|
if ((role !== "user" && role !== "assistant") || typeof content !== "string") {
|
|
return null;
|
|
}
|
|
|
|
const trimmed = content.trim();
|
|
if (!trimmed) {
|
|
return null;
|
|
}
|
|
|
|
return {
|
|
role,
|
|
content: trimmed.slice(0, 1000),
|
|
};
|
|
})
|
|
.filter((entry): entry is DemoChatTurn => entry !== null)
|
|
.slice(-20);
|
|
}
|
|
|
|
export async function POST(request: Request) {
|
|
try {
|
|
const body = (await request.json()) as ReplyRequestBody;
|
|
const message = typeof body.message === "string" ? body.message.trim() : "";
|
|
|
|
if (!message) {
|
|
return Response.json({ error: "message_required" }, { status: 400 });
|
|
}
|
|
|
|
const result = await getDemoAssistantReply({
|
|
message: message.slice(0, 1000),
|
|
conversation: parseConversation(body.conversation),
|
|
});
|
|
|
|
return Response.json(result);
|
|
} catch {
|
|
return Response.json({ error: "invalid_payload" }, { status: 400 });
|
|
}
|
|
}
|