import { Langfuse } from "langfuse";
let langfuseInstance: Langfuse | null = null;
/**
* Get or create Langfuse instance singleton
*/
export function getLangfuse(env: Env): Langfuse | null {
// Check if Langfuse is configured
if (!(env as any).LANGFUSE_PUBLIC_KEY || !(env as any).LANGFUSE_SECRET_KEY) {
console.warn('Langfuse not configured - tracing disabled');
return null;
}
if (!langfuseInstance) {
langfuseInstance = new Langfuse({
publicKey: (env as any).LANGFUSE_PUBLIC_KEY,
secretKey: (env as any).LANGFUSE_SECRET_KEY,
baseUrl: (env as any).LANGFUSE_BASE_URL || "https://cloud.langfuse.com",
// Cloudflare Workers specific settings
flushAt: 1, // Flush immediately due to short-lived Workers
fetchRetryCount: 0, // Don't retry in Workers context
});
}
return langfuseInstance;
}
/**
* Flush Langfuse events (call before response)
*/
export async function flushLangfuse(): Promise<void> {
if (langfuseInstance) {
try {
await langfuseInstance.flushAsync();
} catch (error) {
console.error('Error flushing Langfuse:', error);
}
}
}
/**
* Shutdown Langfuse (call on cleanup)
*/
export async function shutdownLangfuse(): Promise<void> {
if (langfuseInstance) {
try {
await langfuseInstance.shutdownAsync();
langfuseInstance = null;
} catch (error) {
console.error('Error shutting down Langfuse:', error);
}
}
}