Langfuse database setup
Quick answer
To set up a Langfuse database, install the langfuse Python package, configure your database connection string in the Langfuse client, and initialize it with your API keys. Use Langfuse to automatically trace and store AI call data in your database for observability and analysis.
PREREQUISITES
Python 3.8+Langfuse account with API keyspip install langfuseAccess to a supported database (PostgreSQL, MySQL, SQLite, etc.)
Setup
Install the langfuse Python package and set your environment variables for API keys. Prepare your database connection string (DSN) for Langfuse to store trace data.
pip install langfuse Step by step
Initialize the Langfuse client with your public and secret keys and configure the database connection string. Use the client to trace AI calls, which will be saved in your database.
import os
from langfuse import Langfuse
# Set environment variables before running this script:
# export LANGFUSE_PUBLIC_KEY=os.environ["LANGFUSE_PUBLIC_KEY"]
# export LANGFUSE_SECRET_KEY=os.environ["LANGFUSE_SECRET_KEY"]
langfuse = Langfuse(
public_key=os.environ["LANGFUSE_PUBLIC_KEY"],
secret_key=os.environ["LANGFUSE_SECRET_KEY"],
host="https://cloud.langfuse.com",
database_url="postgresql://user:password@localhost:5432/langfuse_db" # Example DSN
)
# Example function to trace an AI call
@langfuse.observe()
def call_ai_model(prompt: str) -> str:
# Simulate AI call
response = f"Response to: {prompt}"
return response
result = call_ai_model("Hello Langfuse")
print("AI response:", result) output
AI response: Response to: Hello Langfuse
Common variations
- Use async functions with
@langfuse.observe()for asynchronous AI calls. - Configure different database backends by changing the
database_urlparameter (e.g., MySQL, SQLite). - Integrate Langfuse with OpenAI or other AI SDKs by wrapping their calls with
@observe()decorators.
import asyncio
@langfuse.observe()
async def async_call_ai(prompt: str) -> str:
await asyncio.sleep(0.1) # Simulate async call
return f"Async response to: {prompt}"
async def main():
response = await async_call_ai("Async Langfuse")
print(response)
asyncio.run(main()) output
Async response to: Async Langfuse
Troubleshooting
- If you see connection errors, verify your
database_urland network access to the database. - Ensure your
LANGFUSE_PUBLIC_KEYandLANGFUSE_SECRET_KEYenvironment variables are set correctly. - Check Langfuse logs for detailed error messages and enable debug logging if needed.
Key Takeaways
- Install and configure the langfuse Python package with your API keys and database URL.
- Use the @observe() decorator to automatically trace AI calls and store data in your database.
- Support for multiple databases allows flexible backend choices for Langfuse observability.
- Async and sync AI calls can both be traced seamlessly with Langfuse.
- Verify environment variables and database connectivity to avoid common setup issues.