How to install Langfuse Python SDK
Quick answer
Install the Langfuse Python SDK using
pip install langfuse. Then, initialize the client in your Python code with your API keys from environment variables using Langfuse(public_key=..., secret_key=...).PREREQUISITES
Python 3.8+Langfuse API keys (public and secret)pip install langfuse
Setup
Install the Langfuse Python SDK via pip and set your API keys as environment variables for secure access.
pip install langfuse Step by step
Use the following Python code to initialize the Langfuse client and send a simple trace event.
import os
from langfuse import Langfuse
# Initialize Langfuse client with API keys from environment variables
langfuse = Langfuse(
public_key=os.environ["LANGFUSE_PUBLIC_KEY"],
secret_key=os.environ["LANGFUSE_SECRET_KEY"],
host="https://cloud.langfuse.com"
)
# Example function to trace
@langfuse.observe()
def greet(name: str) -> str:
return f"Hello, {name}!"
# Call the function
print(greet("World")) output
Hello, World!
Common variations
You can use the @observe() decorator to trace multiple functions or use langfuse_context for context management. The SDK supports custom hosts if you run a self-hosted Langfuse instance.
from langfuse.decorators import observe, langfuse_context
@observe()
def add(a: int, b: int) -> int:
return a + b
with langfuse_context():
result = add(3, 4)
print(result) output
7
Troubleshooting
- If you see authentication errors, verify your
LANGFUSE_PUBLIC_KEYandLANGFUSE_SECRET_KEYenvironment variables are set correctly. - Ensure network connectivity to
https://cloud.langfuse.comor your custom host. - Use
pip show langfuseto confirm the SDK is installed.
Key Takeaways
- Install Langfuse SDK with
pip install langfuseand set API keys via environment variables. - Use
Langfuse(public_key=..., secret_key=...)to initialize the client in Python. - Leverage
@observe()decorator to trace function calls automatically. - Check environment variables and network access if authentication or connectivity issues arise.