From 2be01adc2bf4d6eafa5636208363f8393348ff1c Mon Sep 17 00:00:00 2001 From: Chandrapal Badshah <12944530+Chan9390@users.noreply.github.com> Date: Sun, 27 Apr 2025 14:13:07 +0530 Subject: [PATCH] Add API routes to lighthouse --- ui/actions/lighthouse/lighthouse.ts | 2 +- ui/app/(prowler)/lighthouse/chat.tsx | 2 +- ui/app/api/lighthouse/analyst/route.ts | 94 ++++++++++++++++++++++++++ ui/app/api/lighthouse/cache/route.ts | 29 ++++++++ 4 files changed, 125 insertions(+), 2 deletions(-) create mode 100644 ui/app/api/lighthouse/analyst/route.ts create mode 100644 ui/app/api/lighthouse/cache/route.ts diff --git a/ui/actions/lighthouse/lighthouse.ts b/ui/actions/lighthouse/lighthouse.ts index 92f6bcf738..34a3dafeb5 100644 --- a/ui/actions/lighthouse/lighthouse.ts +++ b/ui/actions/lighthouse/lighthouse.ts @@ -94,7 +94,7 @@ export const getLighthouseConfig = async () => { const data = await response.json(); return data; } catch (error) { - console.error("[Server] Error in getAIConfiguration:", error); + console.error("[Server] Error in getLighthouseConfig:", error); return undefined; } }; diff --git a/ui/app/(prowler)/lighthouse/chat.tsx b/ui/app/(prowler)/lighthouse/chat.tsx index 01412ba275..fbbc68e22a 100644 --- a/ui/app/(prowler)/lighthouse/chat.tsx +++ b/ui/app/(prowler)/lighthouse/chat.tsx @@ -14,7 +14,7 @@ interface SuggestedAction { export default function Chat() { const { messages, input, handleSubmit, handleInputChange, append, status } = useChat({ - api: "/analyst", + api: "/api/lighthouse/analyst", credentials: "same-origin", experimental_throttle: 100, sendExtraMessageFields: true, diff --git a/ui/app/api/lighthouse/analyst/route.ts b/ui/app/api/lighthouse/analyst/route.ts new file mode 100644 index 0000000000..8207120a9f --- /dev/null +++ b/ui/app/api/lighthouse/analyst/route.ts @@ -0,0 +1,94 @@ +import { LangChainAdapter, Message } from "ai"; + +import { getLighthouseConfig } from "@/actions/lighthouse/lighthouse"; +import { getCachedDataSection } from "@/lib/lighthouse/cache"; +import { + convertLangChainMessageToVercelMessage, + convertVercelMessageToLangChainMessage, +} from "@/lib/lighthouse/utils"; +import { initLighthouseWorkflow } from "@/lib/lighthouse/workflow"; + +export async function POST(req: Request) { + try { + const { + messages, + }: { + messages: Message[]; + } = await req.json(); + + if (!messages) { + return Response.json({ error: "No messages provided" }, { status: 400 }); + } + + // Create a new array for processed messages + const processedMessages = [...messages]; + + // Get AI configuration to access business context + const aiConfig = await getLighthouseConfig(); + const businessContext = aiConfig?.data?.attributes?.business_context; + + // Get cached data + const cachedData = await getCachedDataSection(); + + // Add context messages at the beginning + const contextMessages: Message[] = []; + + // Add business context if available + if (businessContext) { + contextMessages.push({ + id: "business-context", + role: "assistant", + content: `Business Context Information:\n${businessContext}`, + }); + } + + // Add cached data if available + if (cachedData) { + contextMessages.push({ + id: "cached-data", + role: "assistant", + content: cachedData, + }); + } + + // Insert all context messages at the beginning + processedMessages.unshift(...contextMessages); + + const app = await initLighthouseWorkflow(); + + const agentStream = app.streamEvents( + { + messages: processedMessages + .filter( + (message: Message) => + message.role === "user" || message.role === "assistant", + ) + .map(convertVercelMessageToLangChainMessage), + }, + { + streamMode: ["values", "messages", "custom"], + version: "v2", + }, + ); + + const stream = new ReadableStream({ + async start(controller) { + for await (const { event, data, tags } of agentStream) { + if (event === "on_chat_model_stream") { + if (data.chunk.content && !!tags && tags.includes("supervisor")) { + const chunk = data.chunk; + const aiMessage = convertLangChainMessageToVercelMessage(chunk); + controller.enqueue(aiMessage); + } + } + } + controller.close(); + }, + }); + + return LangChainAdapter.toDataStreamResponse(stream); + } catch (error) { + console.error("Error in POST request:", error); + return Response.json({ error: "An error occurred" }, { status: 500 }); + } +} diff --git a/ui/app/api/lighthouse/cache/route.ts b/ui/app/api/lighthouse/cache/route.ts new file mode 100644 index 0000000000..99d167cd68 --- /dev/null +++ b/ui/app/api/lighthouse/cache/route.ts @@ -0,0 +1,29 @@ +import { NextResponse } from "next/server"; + +import { createCache, getCurrentUserId } from "@/lib/lighthouse/cache"; + +export async function POST() { + try { + // Get the current user ID + const userId = await getCurrentUserId(); + + // Initialize the cache + await createCache(userId); + + return NextResponse.json({ + success: true, + message: "Cache created successfully", + timestamp: new Date().toISOString(), + }); + } catch (error) { + console.error("Error creating cache:", error); + + return NextResponse.json( + { + success: false, + message: `Failed to create cache: ${error instanceof Error ? error.message : "Unknown error"}`, + }, + { status: 500 }, + ); + } +}