2025-12-04 23:44:00 +09:00
|
|
|
import { getLangfuseClient } from '@/lib/langfuse';
|
2025-12-04 22:56:59 +09:00
|
|
|
import { randomUUID } from 'crypto';
|
2025-12-04 23:44:00 +09:00
|
|
|
import { z } from 'zod';
|
|
|
|
|
|
|
|
|
|
const saveSchema = z.object({
|
|
|
|
|
filename: z.string().min(1).max(255),
|
|
|
|
|
format: z.enum(['drawio', 'png', 'svg']),
|
|
|
|
|
sessionId: z.string().min(1).max(200).optional(),
|
|
|
|
|
});
|
2025-12-04 22:56:59 +09:00
|
|
|
|
|
|
|
|
export async function POST(req: Request) {
|
2025-12-04 23:44:00 +09:00
|
|
|
const langfuse = getLangfuseClient();
|
|
|
|
|
if (!langfuse) {
|
2025-12-04 22:56:59 +09:00
|
|
|
return Response.json({ success: true, logged: false });
|
|
|
|
|
}
|
|
|
|
|
|
2025-12-04 23:44:00 +09:00
|
|
|
// Validate input
|
|
|
|
|
let data;
|
|
|
|
|
try {
|
|
|
|
|
data = saveSchema.parse(await req.json());
|
|
|
|
|
} catch {
|
|
|
|
|
return Response.json({ success: false, error: 'Invalid input' }, { status: 400 });
|
|
|
|
|
}
|
2025-12-04 22:56:59 +09:00
|
|
|
|
2025-12-04 23:44:00 +09:00
|
|
|
const { filename, format, sessionId } = data;
|
2025-12-04 22:56:59 +09:00
|
|
|
|
|
|
|
|
try {
|
|
|
|
|
const timestamp = new Date().toISOString();
|
|
|
|
|
|
2025-12-04 23:44:00 +09:00
|
|
|
// Find the most recent chat trace for this session to attach the save flag
|
2025-12-04 22:56:59 +09:00
|
|
|
const tracesResponse = await langfuse.api.trace.list({
|
|
|
|
|
sessionId,
|
|
|
|
|
limit: 1,
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
const traces = tracesResponse.data || [];
|
|
|
|
|
const latestTrace = traces[0];
|
|
|
|
|
|
|
|
|
|
if (latestTrace) {
|
2025-12-04 23:44:00 +09:00
|
|
|
// Add a score to the existing trace to flag that user saved
|
2025-12-04 22:56:59 +09:00
|
|
|
await langfuse.api.ingestion.batch({
|
|
|
|
|
batch: [
|
|
|
|
|
{
|
2025-12-04 23:44:00 +09:00
|
|
|
type: 'score-create',
|
2025-12-04 22:56:59 +09:00
|
|
|
id: randomUUID(),
|
|
|
|
|
timestamp,
|
|
|
|
|
body: {
|
|
|
|
|
id: randomUUID(),
|
|
|
|
|
traceId: latestTrace.id,
|
2025-12-04 23:44:00 +09:00
|
|
|
name: 'diagram-saved',
|
|
|
|
|
value: 1,
|
|
|
|
|
comment: `User saved diagram as ${filename}.${format}`,
|
2025-12-04 22:56:59 +09:00
|
|
|
},
|
|
|
|
|
},
|
|
|
|
|
],
|
|
|
|
|
});
|
|
|
|
|
}
|
2025-12-04 23:44:00 +09:00
|
|
|
// If no trace found, skip logging (user hasn't chatted yet)
|
2025-12-04 22:56:59 +09:00
|
|
|
|
2025-12-04 23:44:00 +09:00
|
|
|
return Response.json({ success: true, logged: !!latestTrace });
|
2025-12-04 22:56:59 +09:00
|
|
|
} catch (error) {
|
|
|
|
|
console.error('Langfuse save error:', error);
|
2025-12-04 23:44:00 +09:00
|
|
|
return Response.json({ success: false, error: 'Failed to log save' }, { status: 500 });
|
2025-12-04 22:56:59 +09:00
|
|
|
}
|
|
|
|
|
}
|