TypeError
TypeError: __init__() got an unexpected keyword argument 'api_key'
Stack trace
Traceback (most recent call last):
File "app.py", line 10, in <module>
client = LangfuseOpenAI(api_key=os.environ['OPENAI_API_KEY']) # TypeError here
TypeError: __init__() got an unexpected keyword argument 'api_key' Why it happens
Langfuse's OpenAI drop-in replacement client does not accept the 'api_key' parameter in its constructor, unlike the official OpenAI SDK. Passing 'api_key' causes a TypeError because the constructor signature differs. This happens when developers assume identical initialization parameters between Langfuse and OpenAI clients.
Detection
Detect this error by catching TypeError exceptions during client initialization and verifying if 'api_key' is passed as a parameter to Langfuse's client constructor.
Causes & fixes
Passing 'api_key' parameter to Langfuse OpenAI client constructor which does not accept it.
Remove the 'api_key' argument from the Langfuse client initialization and instead set the API key via environment variables or Langfuse-specific configuration.
Confusing Langfuse client initialization with OpenAI SDK v1+ initialization patterns.
Refer to Langfuse documentation for correct client instantiation and avoid using OpenAI SDK constructor parameters directly.
Not setting environment variable 'OPENAI_API_KEY' before initializing Langfuse client.
Ensure 'OPENAI_API_KEY' is set in the environment before running the application so Langfuse client can read it automatically.
Code: broken vs fixed
import os
from langfuse import LangfuseOpenAI
client = LangfuseOpenAI(api_key=os.environ['OPENAI_API_KEY']) # TypeError here
response = client.chat.completions.create(model="gpt-4o-mini", messages=[{"role": "user", "content": "Hello"}])
print(response.choices[0].message.content) import os
from langfuse import LangfuseOpenAI
# Removed api_key argument; rely on environment variable OPENAI_API_KEY
client = LangfuseOpenAI()
response = client.chat.completions.create(model="gpt-4o-mini", messages=[{"role": "user", "content": "Hello"}])
print(response.choices[0].message.content) # Fixed initialization Workaround
If you cannot remove 'api_key' immediately, wrap the client initialization in try/except TypeError and fallback to initializing without parameters, ensuring environment variables are set.
Prevention
Always consult Langfuse's official docs for client initialization patterns and avoid assuming OpenAI SDK constructor compatibility; use environment variables for API keys.