langfuse_service.py
Overview
The langfuse_service.py file is part of the InfiniFlow project and provides a service layer to interact with the TenantLangfuse database model. This service encapsulates operations related to managing Langfuse configuration keys for tenants, such as retrieving, updating, saving, and deleting Langfuse credentials. The service uses the Peewee ORM for database interactions and enforces atomic operations for data integrity.
The primary purpose of this file is to abstract and centralize all database-related logic concerning the Langfuse integration for tenants, ensuring consistent and safe modifications to the data.
Classes and Methods
TenantLangfuseService(CommonService)
This class extends from a generic CommonService and provides CRUD-related methods specific to TenantLangfuse model instances. It handles the retrieval, update, creation, and deletion of tenant-related Langfuse keys.
Class Attributes
model: Refers to theTenantLangfusePeewee model that this service operates on.
Methods
filter_by_tenant(cls, tenant_id)
Type: Class method
Decorator: @DB.connection_context() (ensures DB connection context)
Parameters:
tenant_id(int or str): Unique identifier of the tenant whose Langfuse keys are requested.
Returns:
A Peewee model instance containing the fields
tenant_id,host,secret_key, andpublic_keyif found.Returns
Noneif no matching record exists.
Description:
Fetches the Langfuse related keys for a given tenant. This method returns a Peewee model object with tenant-specific keys or None if the tenant does not exist.
Usage Example:
keys = TenantLangfuseService.filter_by_tenant(tenant_id=123)
if keys:
print(keys.host, keys.secret_key)
else:
print("No keys found for tenant")
filter_by_tenant_with_info(cls, tenant_id)
Type: Class method
Decorator: @DB.connection_context()
Parameters:
tenant_id(int or str): Tenant identifier.
Returns:
A dictionary with keys:
tenant_id,host,secret_key, andpublic_keyif found.Returns
Noneif no matching record is found.
Description:
Similar to filter_by_tenant but returns a dictionary instead of a Peewee model instance. This is useful when a dict representation is preferred for easier manipulation or serialization.
Usage Example:
keys_dict = TenantLangfuseService.filter_by_tenant_with_info(tenant_id=123)
if keys_dict:
print(keys_dict['host'], keys_dict['public_key'])
else:
print("No keys found for tenant")
update_by_tenant(cls, tenant_id, langfuse_keys)
Type: Class method
Parameters:
tenant_id(int or str): Tenant identifier.langfuse_keys(dict): Dictionary of Langfuse key-value pairs to update.
Returns:
Integer count of rows updated (should be 1 if successful, 0 if no matching tenant).
Description:
Updates the Langfuse keys for the specified tenant. This method automatically adds update_time and update_date timestamp fields to the update data before executing the database operation.
Note: This method is expected to be called within an atomic transaction context to maintain data integrity.
Usage Example:
update_data = {
"host": "new-host.example.com",
"secret_key": "new-secret",
"public_key": "new-public"
}
rows_updated = TenantLangfuseService.update_by_tenant(tenant_id=123, langfuse_keys=update_data)
print(f"Rows updated: {rows_updated}")
save(cls, **kwargs)
Type: Class method
Parameters:
**kwargs: Keyword arguments matching the fields of theTenantLangfusemodel.
Returns:
The newly created model instance.
Description:
Creates and saves a new TenantLangfuse record in the database. Automatically sets creation and update timestamps (create_time, create_date, update_time, update_date) based on the current datetime.
Usage Example:
new_tenant_keys = TenantLangfuseService.save(
tenant_id=123,
host="host.example.com",
secret_key="secret123",
public_key="public123"
)
print(new_tenant_keys.id)
delete_model(cls, langfuse_model)
Type: Class method
Parameters:
langfuse_model(TenantLangfuse model instance): The model instance to delete.
Returns:
None
Description:
Deletes the provided TenantLangfuse model instance from the database using Peewee's delete_instance() method.
Usage Example:
tenant_keys = TenantLangfuseService.filter_by_tenant(tenant_id=123)
if tenant_keys:
TenantLangfuseService.delete_model(tenant_keys)
Important Implementation Details
Atomicity:
The class docstring recommends that all status-modifying methods be wrapped within aDB.atomic()context manager. This ensures all database changes are atomic, preventing partial updates and maintaining data integrity.Database Connection Context:
The@DB.connection_context()decorator is used on query methods to manage database connections automatically, ensuring proper open/close cycles.Timestamps:
The service automatically manages timestamp fields (create_time,create_date,update_time,update_date) using utility functionscurrent_timestamp()anddatetime_format()to maintain consistent record-keeping.Error Handling:
Peewee'sDoesNotExistexception is handled gracefully in the filter methods to returnNonewhen no records are found.
Interaction with Other Components
Database Models:
Uses theTenantLangfusemodel fromapi.db.db_models, which represents tenant-specific Langfuse configuration keys.CommonService:
Inherits fromCommonServiceinapi.db.services.common_service, likely providing common database service utilities shared across other models.Utilities:
Utilizes timestamp-related utilities fromapi.utilsto handle date and time formatting consistently.Database Connection:
Uses theDBinstance fromapi.db.db_modelsto manage database connections and transaction contexts.
This service is typically used by higher-level API handlers or business logic components that need to read or mutate Langfuse credentials for tenants.
Mermaid Class Diagram
classDiagram
class TenantLangfuseService {
+model: TenantLangfuse
+filter_by_tenant(tenant_id)
+filter_by_tenant_with_info(tenant_id)
+update_by_tenant(tenant_id, langfuse_keys)
+save(**kwargs)
+delete_model(langfuse_model)
}
TenantLangfuseService --|> CommonService
Summary
langfuse_service.py provides a robust, atomic, and convenient service layer for managing tenant-specific Langfuse keys in the InfiniFlow system. It abstracts direct database operations into reusable methods, handling connection contexts, error cases, and timestamp management. This modular approach simplifies integration of Langfuse functionalities across the application and enforces clean, maintainable code practices.