How to beginner · 3 min read

How to use Langfuse decorators

Quick answer
Use Langfuse decorators like @observe() to automatically trace AI calls in your Python functions. Initialize a Langfuse client with your API keys, then decorate your functions to capture inputs, outputs, and metadata seamlessly.

PREREQUISITES

  • Python 3.8+
  • Langfuse account with API keys
  • pip install langfuse

Setup

Install the langfuse package and set your API keys as environment variables. This enables the Langfuse client to authenticate and send telemetry data.

bash
pip install langfuse

Step by step

Initialize the Langfuse client with your public_key and secret_key. Use the @observe() decorator on any function to automatically trace its calls, inputs, and outputs.

python
import os
from langfuse import Langfuse
from langfuse.decorators import observe

# Initialize Langfuse client
langfuse = Langfuse(
    public_key=os.environ["LANGFUSE_PUBLIC_KEY"],
    secret_key=os.environ["LANGFUSE_SECRET_KEY"],
    host="https://cloud.langfuse.com"
)

@observe()
def generate_response(prompt: str) -> str:
    # Simulate an AI call or any function you want to trace
    response = f"Echo: {prompt}"
    return response

if __name__ == "__main__":
    result = generate_response("Hello, Langfuse!")
    print(result)
output
Echo: Hello, Langfuse!

Common variations

You can customize the @observe() decorator with parameters like name to label traces or use it on async functions. Langfuse also supports auto-tracing for OpenAI clients via a drop-in replacement.

python
import asyncio
from langfuse import Langfuse
from langfuse.decorators import observe

langfuse = Langfuse(
    public_key=os.environ["LANGFUSE_PUBLIC_KEY"],
    secret_key=os.environ["LANGFUSE_SECRET_KEY"],
    host="https://cloud.langfuse.com"
)

@observe(name="async_generate")
async def async_generate_response(prompt: str) -> str:
    await asyncio.sleep(0.1)  # simulate async work
    return f"Async echo: {prompt}"

async def main():
    result = await async_generate_response("Hello async Langfuse")
    print(result)

if __name__ == "__main__":
    asyncio.run(main())
output
Async echo: Hello async Langfuse

Troubleshooting

  • If you see no traces in the Langfuse dashboard, verify your LANGFUSE_PUBLIC_KEY and LANGFUSE_SECRET_KEY environment variables are set correctly.
  • Ensure network connectivity to https://cloud.langfuse.com.
  • Use @observe() only on functions that return serializable data.

Key Takeaways

  • Initialize Langfuse client with your public and secret keys before using decorators.
  • Use @observe() to automatically trace function inputs and outputs.
  • Decorators support async functions and custom trace naming.
  • Check environment variables and network access if traces don’t appear.
  • Langfuse simplifies AI call observability with minimal code changes.
Verified 2026-04
Verify ↗