langfuse_app.py
Overview
The langfuse_app.py file implements a set of Flask API endpoints for managing Langfuse API keys associated with different tenants in a multi-tenant system. It provides functionality to create, update, retrieve, and delete Langfuse API keys securely while validating these keys against the Langfuse service.
This file integrates with the Flask web framework, Flask-Login for user authentication, and the Langfuse Python SDK to interact with Langfuse APIs. It also uses internal database models and services to persist tenant-specific Langfuse credentials.
Detailed Explanation
Flask Routes and Their Functionality
The file defines three HTTP API endpoints under the /api_key path with methods POST/PUT, GET, and DELETE. All routes require the user to be authenticated (@login_required) and use a request validation decorator (@validate_request) to ensure required parameters are present.
1. set_api_key()
Purpose
Handles creating or updating the Langfuse API keys (secret key, public key, host) for the currently logged-in tenant.
HTTP Method
POST and PUT
URL
/api_key
Parameters (JSON payload)
secret_key(string): The Langfuse secret API key.public_key(string): The Langfuse public API key.host(string): The Langfuse host URL.
Returns
On success: JSON object containing the stored Langfuse keys.
On failure: JSON error message indicating missing fields or invalid keys.
Behavior
Extracts the three required keys from the request JSON.
Validates all fields are present.
Instantiates a Langfuse client and checks if the keys are valid by calling
auth_check().If valid, checks if the tenant already has keys stored:
If not, saves new keys.
If yes, updates existing keys.
Uses database transactions (
DB.atomic()) to ensure atomicity.Handles any exceptions with a server error response.
Example Usage (cURL)
curl -X POST /api_key \
-H "Content-Type: application/json" \
-d '{"secret_key": "sk_123", "public_key": "pk_123", "host": "https://api.langfuse.com"}' \
-b "session_cookie=..."
2. get_api_key()
Purpose
Retrieves the stored Langfuse API keys for the current tenant, validating them and fetching associated project information from Langfuse.
HTTP Method
GET
URL
/api_key
Parameters
None required in the request body.
Returns
On success: JSON object containing stored Langfuse keys along with the project ID and project name fetched from Langfuse.
If no keys are stored: JSON message stating no records found.
If keys are invalid: JSON error message.
Handles exceptions from Langfuse API and server errors gracefully.
Behavior
Queries the database for the tenant's Langfuse keys.
Instantiates Langfuse client and validates credentials.
Calls Langfuse API to get the first project associated with the keys.
Attaches project ID and name to the response data.
Example Usage (cURL)
curl -X GET /api_key -b "session_cookie=..."
3. delete_api_key()
Purpose
Deletes the stored Langfuse API keys for the current tenant.
HTTP Method
DELETE
URL
/api_key
Parameters
None required in the request body.
Returns
On success: JSON boolean
true.If no keys found: JSON message stating no records found.
Handles server errors gracefully.
Behavior
Looks up the tenant's Langfuse keys in the database.
If found, deletes the record within an atomic transaction.
Returns success or error response accordingly.
Example Usage (cURL)
curl -X DELETE /api_key -b "session_cookie=..."
Important Implementation Details
Authentication & Authorization: Routes are secured with
@login_required, ensuring only authenticated users can manage API keys.Request Validation: Decorator
@validate_requestchecks for required fields in requests, improving robustness.Langfuse Integration: Uses the Langfuse Python SDK (
Langfuseclass) to validate keys and fetch project info.Database Transactions: Employs
DB.atomic()context manager for safe, atomic database writes.Error Handling: Uses helper functions (
get_error_data_result,get_json_result,server_error_response) to provide consistent API responses and handle exceptions.Tenant Isolation: All operations are scoped to the current tenant via
current_user.idto isolate data per tenant.
Interactions with Other System Components
LangfuseSDK: Core interaction for authentication checks and project retrieval.TenantLangfuseService: Database service layer that abstracts CRUD operations on Langfuse key records tied to tenants.DBModel: Manages database transactions.Flask-Login(current_user): Provides tenant context based on authenticated session.Utility functions: Standardized API response generation and error handling.
Mermaid Class Diagram
classDiagram
class LangfuseApp {
+set_api_key()
+get_api_key()
+delete_api_key()
}
class TenantLangfuseService {
+filter_by_tenant(tenant_id)
+filter_by_tenant_with_info(tenant_id)
+save(**langfuse_keys)
+update_by_tenant(tenant_id, langfuse_keys)
+delete_model(langfuse_entry)
}
class Langfuse {
+__init__(public_key, secret_key, host)
+auth_check() bool
+api
}
class DB {
+atomic()
}
LangfuseApp --> TenantLangfuseService : uses
LangfuseApp --> Langfuse : instantiates
LangfuseApp --> DB : uses atomic transaction
Summary
The langfuse_app.py module provides a clean, secure, and robust interface for tenants to manage their Langfuse API keys within the InfiniFlow system. It ensures keys are validated before storage and enables retrieval of project metadata, fostering smooth integration with the Langfuse platform. The file demonstrates best practices in API design, error handling, and multi-tenant data isolation.