A comprehensive example demonstrating Langfuse integration with LLM APIs (OpenAI) in a FastAPI application. This project showcases all major Langfuse features including tracing, monitoring, scoring, prompt management, and session tracking.
- π Automatic LLM Call Tracing: Every LLM interaction is automatically traced
- π Session Tracking: Track conversations across multiple interactions
- β User Feedback & Scoring: Collect multi-dimensional feedback
- π Prompt Template Management: Manage and use prompt templates
- π€ Auto-Evaluation: LLM-based evaluation of generations
- π Custom Event Logging: Log custom events and metadata
- π° Cost & Token Tracking: Monitor usage and costs
- π·οΈ Metadata & Tagging: Rich metadata support for better organization
langfuse-test/
βββ app.py # Main FastAPI server with Langfuse integration
βββ config.py # Configuration management
βββ test_client.py # Example client demonstrating all features
βββ requirements.txt # Python dependencies
βββ .env.example # Environment variables template
βββ .gitignore # Git ignore rules
βββ README.md # This file
# Create virtual environment
python3 -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
# Install dependencies
pip install -r requirements.txtCopy .env.example to .env and add your API keys:
cp .env.example .envThen edit .env with your actual keys:
# Langfuse Configuration
LANGFUSE_SECRET_KEY=your-langfuse-secret-key
LANGFUSE_PUBLIC_KEY=your-langfuse-public-key
LANGFUSE_HOST=https://cloud.langfuse.com
# OpenAI Configuration
OPENAI_API_KEY=your-openai-api-key
# Server Configuration
SERVER_HOST=0.0.0.0
SERVER_PORT=8000.env file to Git. It's included in .gitignore.
# Activate virtual environment if not already activated
source venv/bin/activate
# Run the server
uvicorn app:app --reload --host 0.0.0.0 --port 8000
# Or simply: python app.pyThe server will start at http://localhost:8000
API Documentation: http://localhost:8000/docs
In a new terminal:
# Activate virtual environment
source venv/bin/activate
# Run the demo
python test_client.py
# Or run a stress test (generates more data)
python test_client.py stress 20GET /- Health checkPOST /api/v1/chat- Chat completion with tracingPOST /api/v1/feedback- Submit feedback for a tracePOST /api/v1/prompt-completion- Use prompt templatesPOST /api/v1/evaluate- Auto-evaluate generationsGET /api/v1/sessions/{session_id}- Get session infoPOST /api/v1/event- Log custom events
response = await client.post("/api/v1/chat", json={
"messages": [
{"role": "user", "content": "Hello!"}
],
"model": "gpt-3.5-turbo",
"temperature": 0.7,
"session_id": "unique-session-id",
"user_id": "user-123",
"metadata": {"feature": "chat"}
})response = await client.post("/api/v1/feedback", json={
"trace_id": "trace-id-from-chat",
"score": 0.9,
"comment": "Great response!",
"name": "user-satisfaction"
})Every LLM call is automatically traced with:
- Input/output messages
- Token usage
- Latency metrics
- Model parameters
- User and session IDs
- Track multiple interactions in a session
- Analyze conversation flow
- Understand user journeys
Multiple scoring dimensions:
- User satisfaction
- Accuracy
- Helpfulness
- Style
- Custom metrics
- Template-based prompts
- Variable substitution
- Version control for prompts
- Real-time monitoring
- Cost tracking
- Performance metrics
- Error tracking
- Go to Langfuse Dashboard
- Navigate to your project
- View:
- Traces: Detailed LLM interactions
- Sessions: Conversation flows
- Users: User analytics
- Scores: Feedback metrics
- Analytics: Usage statistics
- New Endpoints: Add to
app.pywith@observe()decorator - Custom Scoring: Use
langfuse.score()with custom names - Events: Log with
langfuse.event()for custom tracking - Metadata: Add to any trace for better filtering
- Use Session IDs: Group related interactions
- Add Metadata: Include context for better analysis
- Score Consistently: Use standard score names
- Handle Errors: Wrap in try-catch with error logging
- Flush on Shutdown: Ensure
langfuse.flush()is called
- Connection Error: Ensure server is running
- API Key Issues: Check
.envfile and key validity - Import Errors: Verify virtual environment is activated
- Rate Limits: Add retry logic for production
Set DEBUG=true in .env for detailed logging
This example project is provided for educational purposes.