Spaces:
Sleeping
Sleeping
v4.0: Fix /api/chat — call Gradio Space chatbot endpoint
Browse files123456789101112131415161718192021222324252627282930313233343536import { NextRequest, NextResponse } from "next/server";const API_URL = process.env.CLAUSEGUARD_API_URL || "https://gaurv007-clauseguard-api.hf.space";export async function POST(req: NextRequest) {try {const body = await req.json();const { message, session_id, history } = body;if (!message || !session_id) {return NextResponse.json({ error: "message and session_id are required" },{ status: 400 });}const response = await fetch(`${API_URL}/api/chat`, {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({ message, session_id, history: history || [] }),});if (!response.ok) {const err = await response.text().catch(() => "");throw new Error(err || `Backend error: ${response.status}`);}const result = await response.json();return NextResponse.json(result);} catch (error: any) {console.error("Chat error:", error.message);return NextResponse.json({ error: error.message || "Chat failed. Try again." },{ status: 500 });}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768import { 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 messageconst 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 resultconst 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 dataconst dataMatch = resultText.match(/event:\s*complete\s*\ndata:\s*(.+)/);if (!dataMatch) {// Check for errorconst 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 stringconst 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 });}
web/app/api/chat/route.ts+44-12