DocsObservabilityFeaturesMetadata

Metadata

Traces and observations (see Langfuse Data Model) can be enriched with metadata to better understand your users, application, and experiments. Metadata can be added to traces in the form of arbitrary JSON.

Metadata updates are merged based on the top-level key. We strongly discourage writing the same key multiple times within your instrumentation.

When using the @observe() decorator:

from langfuse import observe, get_client
 
langfuse = get_client()
 
@observe()
def process_data():
    # Access the client and update the current trace metadata
 
    # Add metadata to the trace level
    langfuse.update_current_trace(
        metadata={"source": "api", "version": "1.2.3"}
    )
 
    # Add metadata to the current span level
    langfuse.update_current_span(
        metadata={"processing_stage": "initial"}
    )
 
    # Process data...
    return result

When creating spans directly:

from langfuse import get_client
 
langfuse = get_client()
 
# Add metadata at trace level
with langfuse.start_as_current_span(
    name="process-request"
) as root_span:
    # Add metadata to the trace
    root_span.update_trace(metadata={"request_id": "req_12345"})
 
    # Add metadata to the current span
    root_span.update(metadata={"stage": "parsing"})
 
    # Create a child span with metadata
    with root_span.start_as_current_generation(
        name="generate-response",
        model="gpt-4o",
        metadata={"temperature": 0.7, "max_tokens": 1000}
    ) as gen:
        # Update metadata later if needed
        gen.update(metadata={"completion_type": "creative"})

You can add new keys to the metadata object by continuously updating the entity. We strongly discourage writing the same top-level key multiple times as this will produce an undefined behaviour.

with langfuse.start_as_current_span(name="operation") as span:
    # First write
    span.update(metadata={"status": "started"})
 
    # Additional key - will be merged with previous metadata
    span.update(metadata={"error": "Failed to process"})
 
    # Final metadata will be {"status": "started", "error": "Failed to process"}

GitHub Discussions

Was this page helpful?