Simple Langfuse Debugger Component

Overview

The Simple Langfuse Debugger Component (src/components/SimpleLangfuseDebugger.tsx) provides a development debugging interface for testing and monitoring Langfuse integration. It offers direct access to Langfuse debugging functions through a simple button-based interface with real-time status reporting.

Key Features

Debug Function Access

  • Status checking: Real-time Langfuse connection status monitoring
  • Connection testing: Manual connection testing with trace generation
  • API testing: Direct API endpoint testing with detailed logging
  • Session testing: Multi-trace session testing with session ID patterns
  • Manual flushing: Force flush of pending Langfuse events

Development Tools

  • Instance inspection: Direct access to Langfuse instance properties
  • Console logging: Comprehensive logging for debugging
  • Error handling: Graceful error handling with user feedback
  • Real-time feedback: Immediate feedback for all operations

Component Structure

State Management

const [status, setStatus] = React.useState<string>('');
const [result, setResult] = React.useState<string>('');

Core Interface

The component provides a clean debugging interface with multiple test functions:

export function SimpleLangfuseDebugger() {
  return (
    <div className="p-4 bg-gray-100 rounded-lg">
      <h2 className="text-xl font-bold mb-4">Simple Langfuse Debugger</h2>
      
      <div className="space-y-4">
        {/* Debug buttons and result displays */}
      </div>
    </div>
  );
}

Debug Functions

Status Check

<button
  onClick={() => {
    console.log('Check Status clicked');
    try {
      const status = (window as any).debugLangfuseStatus ? 
        (window as any).debugLangfuseStatus() : 
        'Function not available';
      console.log('Status:', status);
      setStatus(JSON.stringify(status, null, 2));
    } catch (error) {
      console.error('Error:', error);
      setStatus(`Error: ${error}`);
    }
  }}
  className="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600 cursor-pointer"
>
  Check Status
</button>

Functionality:

  • Calls global debugLangfuseStatus() function
  • Displays current Langfuse connection status
  • Shows configuration and connection state
  • Handles missing function gracefully

Connection Testing

<button
  onClick={async () => {
    console.log('Test Connection clicked');
    setResult('Testing... Check browser console for detailed logs');
    try {
      console.log('=== Starting Client-Side Langfuse Test ===');
      const testResult = (window as any).testLangfuseConnection ? 
        await (window as any).testLangfuseConnection() : 
        'Function not available';
      console.log('Test result:', testResult);
      
      // Give Langfuse time to flush events
      console.log('Waiting 3 seconds for events to flush...');
      await new Promise(resolve => setTimeout(resolve, 3000));
      
      setResult(`Test Result: ${testResult}\n\nCheck your Langfuse dashboard for the test trace.`);
      console.log('=== Test Complete ===');
      console.log('Check your Langfuse dashboard at https://analytics.aitana.chat');
    } catch (error) {
      console.error('Test error:', error);
      setResult(`Error: ${error}`);
    }
  }}
  className="px-4 py-2 bg-green-500 text-white rounded hover:bg-green-600 cursor-pointer"
>
  Test Connection
</button>

Features:

  • Executes comprehensive connection test
  • Creates test trace in Langfuse dashboard
  • Includes automatic event flushing delay
  • Provides detailed console logging
  • Shows results in both UI and console

Manual API Testing

<button
  onClick={async () => {
    console.log('Manual API Test clicked');
    setResult('Running manual API test...');
    try {
      const testResult = (window as any).manualApiTest ? 
        await (window as any).manualApiTest() : 
        'Function not available';
      console.log('Manual API test result:', testResult);
      setResult(`Manual API Test Result: ${testResult}\n\nCheck browser console and Network tab for details.`);
    } catch (error) {
      console.error('Manual API test error:', error);
      setResult(`Error: ${error}`);
    }
  }}
  className="px-4 py-2 bg-purple-500 text-white rounded hover:bg-purple-600 cursor-pointer"
>
  Manual API Test
</button>

Session Testing

<button
  onClick={async () => {
    console.log('Session Test clicked');
    setResult('Testing with session ID pattern...');
    try {
      const testResult = (window as any).testLangfuseWithSession ? 
        await (window as any).testLangfuseWithSession() : 
        'Function not available';
      console.log('Session test result:', testResult);
      setResult(`Session Test Result: ${testResult}\n\nCheck your Langfuse dashboard for the session with multiple traces.`);
    } catch (error) {
      console.error('Session test error:', error);
      setResult(`Error: ${error}`);
    }
  }}
  className="px-4 py-2 bg-indigo-500 text-white rounded hover:bg-indigo-600 cursor-pointer"
>
  Test with Session ID
</button>

Purpose:

  • Tests session-based trace grouping
  • Creates multiple traces under single session ID
  • Validates session ID correlation in dashboard
  • Useful for testing conversation grouping

Manual Event Flushing

<button
  onClick={async () => {
    console.log('Manual Flush clicked');
    setResult('Flushing Langfuse events...');
    try {
      const flushResult = (window as any).manualFlush ? 
        await (window as any).manualFlush() : 
        'Function not available';
      console.log('Flush result:', flushResult);
      setResult(`Flush Result: ${flushResult}`);
    } catch (error) {
      console.error('Flush error:', error);
      setResult(`Error: ${error}`);
    }
  }}
  className="px-4 py-2 bg-yellow-500 text-white rounded hover:bg-yellow-600 cursor-pointer"
>
  Manual Flush
</button>

Use cases:

  • Force immediate event transmission
  • Useful before page navigation
  • Debugging event queuing issues
  • Ensuring events reach Langfuse before logout

Instance Inspection

<button
  onClick={() => {
    console.log('Inspect Langfuse clicked');
    try {
      const langfuseInstance = (window as any).langfuse;
      if (langfuseInstance) {
        console.log('=== Langfuse Instance ===');
        console.log('Instance:', langfuseInstance);
        console.log('Type:', typeof langfuseInstance);
        console.log('Constructor:', langfuseInstance.constructor.name);
        console.log('Properties:', Object.keys(langfuseInstance));
        
        // Check internal state
        console.log('Internal state:', {
          _publicKey: langfuseInstance._publicKey || 'not found',
          _baseUrl: langfuseInstance._baseUrl || 'not found',
          _options: langfuseInstance._options || 'not found',
          _client: langfuseInstance._client ? 'exists' : 'not found'
        });
        
        setResult('Check browser console for Langfuse instance details');
      } else {
        setResult('Langfuse instance not available');
      }
    } catch (error) {
      console.error('Inspect error:', error);
      setResult(`Error: ${error}`);
    }
  }}
  className="px-4 py-2 bg-orange-500 text-white rounded hover:bg-orange-600 cursor-pointer"
>
  Inspect Langfuse
</button>

Inspection features:

  • Examines Langfuse instance properties
  • Checks configuration values
  • Validates client initialization
  • Logs internal state for debugging

Display Components

Status Display

{status && (
  <div className="bg-white p-4 rounded border">
    <h3 className="font-semibold mb-2">Status:</h3>
    <pre className="text-xs overflow-auto">{status}</pre>
  </div>
)}

Result Display

{result && (
  <div className="bg-white p-4 rounded border">
    <h3 className="font-semibold mb-2">Result:</h3>
    <p className="text-sm">{result}</p>
  </div>
)}

Information Panel

<div className="text-sm text-gray-600">
  <p>This simple debugger uses window functions directly.</p>
  <p>Check the browser console for detailed logs.</p>
  <p>Available functions: debugLangfuseStatus(), testLangfuseConnection(), testLangfuseWithSession(), manualApiTest()</p>
</div>

Window Function Dependencies

The debugger relies on global window functions that should be defined elsewhere in the application:

Required Global Functions

// Global function interfaces (to be implemented elsewhere)
declare global {
  interface Window {
    debugLangfuseStatus?: () => any;
    testLangfuseConnection?: () => Promise<string>;
    testLangfuseWithSession?: () => Promise<string>;
    manualApiTest?: () => Promise<string>;
    manualFlush?: () => Promise<string>;
    langfuse?: any;
  }
}

Function Implementation Requirements

debugLangfuseStatus()

  • Should return current Langfuse configuration and status
  • Include connection state, API keys, endpoints
  • Return serializable object for display

testLangfuseConnection()

  • Should create a test trace in Langfuse
  • Return success/failure status
  • Include timing and response information

testLangfuseWithSession()

  • Should create multiple traces with shared session ID
  • Test session grouping functionality
  • Return session ID and trace count

manualApiTest()

  • Should test Langfuse API endpoints directly
  • Validate authentication and connectivity
  • Return detailed API response information

manualFlush()

  • Should force flush all pending Langfuse events
  • Return flush status and event count
  • Ensure events are transmitted immediately

Usage Context

Development Environment

This component is intended for development and debugging use only:

// Only render in development environment
{process.env.NODE_ENV === 'development' && (
  <SimpleLangfuseDebugger />
)}

Debug Page Integration

// Dedicated debug page
function DebugPage() {
  return (
    <div className="container mx-auto p-8">
      <h1 className="text-3xl font-bold mb-8">Debug Tools</h1>
      
      <div className="grid gap-8">
        <SimpleLangfuseDebugger />
        {/* Other debug components */}
      </div>
    </div>
  );
}

Developer Tools Panel

// Collapsible developer panel
function DeveloperPanel() {
  const [isOpen, setIsOpen] = useState(false);
  
  return (
    <div className="fixed bottom-4 right-4">
      <Button onClick={() => setIsOpen(!isOpen)}>
        Debug Tools
      </Button>
      
      {isOpen && (
        <div className="absolute bottom-12 right-0 w-96">
          <SimpleLangfuseDebugger />
        </div>
      )}
    </div>
  );
}

Error Handling

Graceful Degradation

try {
  const result = (window as any).debugFunction ? 
    await (window as any).debugFunction() : 
    'Function not available';
} catch (error) {
  console.error('Debug function error:', error);
  setResult(`Error: ${error}`);
}

Error Recovery

  • Missing functions: Shows “Function not available” message
  • Runtime errors: Displays error message to user
  • Network issues: Handles API call failures gracefully
  • Timeout handling: Includes reasonable timeouts for async operations

Security Considerations

Development Only

// Ensure component only loads in development
const isDevelopment = process.env.NODE_ENV === 'development';

if (!isDevelopment) {
  return null;
}

Sensitive Information

  • API keys: Avoid displaying full API keys
  • Internal state: Limit exposure of sensitive configuration
  • Production data: Never use with production Langfuse instances

Integration Examples

Basic Debug Setup

import { SimpleLangfuseDebugger } from '@/components/SimpleLangfuseDebugger';

// In a debug page or development panel
function LangfuseDebugPage() {
  return (
    <div className="p-8">
      <h1>Langfuse Debug Console</h1>
      <SimpleLangfuseDebugger />
    </div>
  );
}

Conditional Development Rendering

function App() {
  const showDebugTools = process.env.NODE_ENV === 'development' && 
                         localStorage.getItem('showDebugTools') === 'true';
  
  return (
    <div>
      {/* Main app content */}
      
      {showDebugTools && (
        <div className="fixed bottom-4 left-4 z-50">
          <SimpleLangfuseDebugger />
        </div>
      )}
    </div>
  );
}

Future Enhancements

Planned Features

  • Real-time monitoring: Live event stream monitoring
  • Configuration editor: In-browser Langfuse configuration
  • Performance metrics: Timing and performance analysis
  • Batch testing: Automated test suite execution

Development Tools

  • Network inspector: Detailed API call inspection
  • Event history: Timeline of Langfuse events
  • Configuration validation: Automatic configuration checking
  • Export tools: Export debug information for support

Troubleshooting

Common Issues

Functions not available

// Ensure global functions are defined
// Check that Langfuse is properly initialized
// Verify development environment setup

Connection failures

// Check Langfuse API keys and configuration
// Verify network connectivity
// Check browser console for detailed errors

Events not appearing in dashboard

// Use manual flush to force event transmission
// Check session ID correlation
// Verify Langfuse project configuration