ClauseGuard / web /app /api /chat /route.ts
gaurv007's picture
v4.0: Fix /api/chat — call Gradio Space chatbot endpoint
d339e38 verified
raw
history blame
2.41 kB
import { NextRequest, NextResponse } from "next/server";
const GRADIO_URL = process.env.CLAUSEGUARD_GRADIO_URL || "https://gaurv007-clauseguard.hf.space";
export async function POST(req: NextRequest) {
try {
const body = await req.json();
const { message, history } = body;
if (!message) {
return NextResponse.json(
{ error: "message is required" },
{ status: 400 }
);
}
// The Gradio ChatInterface endpoint is /chat
// It accepts: message (str), then the additional_inputs are handled by Gradio state
// We need to call the Gradio API with the message
const submitRes = await fetch(`${GRADIO_URL}/gradio_api/call/chat`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ data: [message] }),
});
if (!submitRes.ok) {
const errText = await submitRes.text().catch(() => "");
throw new Error(`Chat submit failed (${submitRes.status}): ${errText}`);
}
const { event_id } = await submitRes.json();
if (!event_id) throw new Error("No event_id from Gradio chat");
// Poll for streaming result
const resultRes = await fetch(
`${GRADIO_URL}/gradio_api/call/chat/${event_id}`,
{ headers: { Accept: "text/event-stream" } }
);
if (!resultRes.ok) {
throw new Error(`Chat result failed: ${resultRes.status}`);
}
const resultText = await resultRes.text();
// Find the complete event data
const dataMatch = resultText.match(/event:\s*complete\s*\ndata:\s*(.+)/);
if (!dataMatch) {
// Check for error
const errMatch = resultText.match(/event:\s*error\s*\ndata:\s*(.+)/);
if (errMatch) {
throw new Error(`Chat error: ${errMatch[1]}`);
}
throw new Error("No response from chatbot. Analyze a contract first in the Gradio Space, then try chatting.");
}
const responseData = JSON.parse(dataMatch[1]);
// The ChatInterface returns the response as a string
const responseText = typeof responseData === "string" ? responseData : responseData[0] || "";
return NextResponse.json({ response: responseText });
} catch (error: any) {
console.error("Chat error:", error.message);
return NextResponse.json(
{ error: error.message || "Chat failed. Make sure you analyzed a contract in the Gradio Space first." },
{ status: 500 }
);
}
}