File size: 2,406 Bytes
c146e54
 
d339e38
c146e54
 
 
 
d339e38
c146e54
d339e38
c146e54
d339e38
c146e54
 
 
 
d339e38
 
 
 
c146e54
 
d339e38
c146e54
 
d339e38
 
 
c146e54
 
d339e38
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c146e54
 
 
d339e38
c146e54
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
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 }
    );
  }
}