Add API routes to lighthouse

This commit is contained in:
Chandrapal Badshah
2025-04-27 14:13:07 +05:30
parent c310326d4c
commit 2be01adc2b
4 changed files with 125 additions and 2 deletions
+1 -1
View File
@@ -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;
}
};
+1 -1
View File
@@ -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,
+94
View File
@@ -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 });
}
}
+29
View File
@@ -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 },
);
}
}