Skip to content

feat(client): support organization API keys with api_key and project_id - #2074

Draft
marksalpeter wants to merge 9 commits into
mainfrom
mark/lfe-18172-update-sdks-to-support-multi-org-api-tokens
Draft

marksalpeter wants to merge 9 commits into
mainfrom
mark/lfe-18172-update-sdks-to-support-multi-org-api-tokens

Conversation

@marksalpeter

@marksalpeter marksalpeter commented Oct 29, 2026 •

Copy link
Copy Markdown

What does this PR do?

Implements the Python side of "RFC: SDK support for organization API keys" (LFE-18172). Organization and user API keys can write to many projects, so each client names its target project. The change only adds behavior: existing key-pair setups work as before.

New configuration: Langfuse(api_key=..., project_id=...), or the LANGFUSE_API_KEY and LANGFUSE_PROJECT_ID env vars.

  • The key authenticates as Authorization: Bearer <api_key> on OTLP exports and on the generated LangfuseAPI / AsyncLangfuseAPI clients.
  • Any secret works in either slot; the SDK doesn't check key formats.
    • An existing sk-lf-... secret works as api_key.
    • A new key works as secret_key with the project ID as public_key, over Basic auth. That's how older SDK versions use new keys.
  • Langfuse(...) raises ValueError for:
    • api_key combined with public_key / secret_key;
    • api_key without project_id;
    • project_id passed with a key pair.
  • Key-pair clients ignore LANGFUSE_PROJECT_ID, so one process can mix both kinds of client.
  • Explicit public_key / secret_key arguments take precedence over LANGFUSE_API_KEY.

Project header: API key clients send langfuse-project-id on every API request and span export. The server accepts it with or without the x- prefix. If additional_headers or httpx_client.headers sets either header name to a different project, init raises ValueError.

Routing: each client is selected by exactly one identifier.

Client created with Selected by
api_key + project_id get_client(project_id=...), langfuse_project_id=... on @observe functions and OpenAI calls, CallbackHandler(project_id=...)
public_key + secret_key get_client(public_key=...), langfuse_public_key=..., CallbackHandler(public_key=...), as today
  • Nested calls inherit the client chosen by the top-level @observe call.
  • With several clients and no identifier, or both identifiers, or one that matches no client, you get a disabled client and a warning.
  • The span processor's scope filter compares both fields, so clients on a shared TracerProvider export only their own spans.

No breaking changes in integrations: get_client() creates the default client when none exists. If that hits a credential misconfiguration, it logs the error and returns a disabled client instead of raising inside an OpenAI or LangChain call.

No project lookup: API key clients return the configured project_id from _get_project_id() without calling projects.get(). Trace and experiment URLs use it.

Hints:

  • A 403 span export logs a one-time hint to check project_id.
  • project_id combined with a custom span_exporter logs a warning that the exporter must send the header itself.

Notes for reviewers

  • Server dependency: the server doesn't yet accept a secret as a bearer token with langfuse-project-id. On langfuse main, Bearer still means a public key with scores-only access. The api_key path is covered by unit tests and works end to end once the server ships it.
  • Same project, different api_key: two clients reuse one instance, and the first key wins. That matches how the SDK already treats a reused public key.
  • 403 hint: comes from a logging.Filter on the OTLP exporter's logger, because the exporter doesn't return the status code. It never suppresses the record.
  • Intermittent e2e failure, not from this PR: see the PR comment. A server startup race sometimes leaves model prices unseeded, so 4 total_cost assertions in tests/e2e/test_decorators.py fail. main fails the same way.

Type of change

  • Bug fix
  • New feature
  • Breaking change
  • Refactor
  • Documentation update
  • Tooling, CI, or repo maintenance

Verification

uv run --frozen ruff format --check .
uv run --frozen ruff check .
uv run --frozen mypy langfuse --no-error-summary
uv run --frozen pytest -n auto --dist worksteal tests/unit
uv run --frozen pytest -n 4 --dist worksteal tests/e2e -m "not serial_e2e"
uv run --frozen pytest tests/e2e -m "serial_e2e"
  • Unit: 1055 passed. 26 tests in tests/unit/test_prompt.py error locally because LANGFUSE_PUBLIC_KEY isn't set; they error the same way on main.
  • E2E: 134 parallel and 9 serial passed on the previous head (1f606ce3) against a local server (CI's compose file, image 4 = v4.86.0) with seeded model prices. These exercise the key-pair path, which the latest commit doesn't touch: it only removes the key-format checks.

Checklist

  • I self-reviewed the diff using code_review.md.
  • I added or updated tests for behavior changes.
  • I updated docs, examples, or .env.template if needed.
  • I did not hand-edit generated files; if generated files changed, I used the upstream regeneration path.
  • I did not commit secrets or credentials.

🤖 Generated with Claude Code

https://claude.ai/code/session_016PExPf2jnm8CPvdxKYmfqt

Organization API keys can write to any project in their organization, so
each request has to name its target project in the x-langfuse-project-id
header. Add a project_id argument (env LANGFUSE_PROJECT_ID) to Langfuse()
and identify a client by (public_key, project_id) everywhere:

- LangfuseResourceManager instances are keyed by the pair, so a second
  client on the same org key for another project no longer silently
  reuses the first client's setup.
- Tracer scope attributes carry project_id and LangfuseSpanProcessor
  filters on both, so two clients sharing an org key never export each
  other's spans.
- get_client() and @observe accept project_id / langfuse_project_id; an
  org key shared by several clients without a project_id resolves to a
  disabled client.

The header is sent on OTLP exports and on the generated API clients (so a
caller-provided httpx_client sends it too). A conflicting project header
in additional_headers or httpx_client.headers raises ValueError at init.
A configured project_id is used for trace and experiment URLs without
calling projects.get(). A custom span_exporter with project_id warns that
the exporter must set the header, and a 403 span export logs a one-time
hint to set LANGFUSE_PROJECT_ID.

Project API keys leave project_id unset, so their behavior is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016PExPf2jnm8CPvdxKYmfqt

marksalpeter commented Oct 29, 2026 •

Copy link
Copy Markdown
Author

CLA gate was failing on aaff525 ("CLA missing or unavailable").

Resolved: the CLA is now signed (license/cla passes), and CLA gate reports "CLA verified." on aaff525. No rewrite of the commit was needed.


Generated by Claude Code

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016PExPf2jnm8CPvdxKYmfqt
Add an api_key argument and LANGFUSE_API_KEY env var for Langfuse API
keys (lf_<cuid>). They authenticate as a bearer token, replace the
public/secret key pair, and require project_id. The key format is
checked locally, so a key pair value passed as api_key (or the reverse)
fails at construction with instructions.

API key clients have no public key: get_client(project_id=...) and
@observe(langfuse_project_id=...) select them, while key pair clients
keep being selected by public key.

Send the project as langfuse-project-id, the header the server's
authorization layer reads.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016PExPf2jnm8CPvdxKYmfqt
@marksalpeter marksalpeter changed the title feat(client): support organization API keys with project_id feat(client): support organization API keys with api_key and project_id Nov 24, 2026

marksalpeter commented Nov 24, 2026 •

Copy link
Copy Markdown
Author

E2E shard 2 tests on Python 3.13 fails intermittently in 4 tests in tests/e2e/test_decorators.py:

  • test_nested_observations
  • test_nested_observations_with_non_parentheses_decorator
  • test_concurrent_decorator_executions
  • test_decorated_class_and_instance_methods

Each one fails on assert level_3_observation.total_cost > 0, with total_cost returned as None. This isn't caused by this PR: plain main fails the same way against the same server.

Root cause: a startup race in the server (langfuse/langfuse). I reproduced it locally with CI's compose file and the image tagged 4, which is currently v4.86.0.

  • At startup, the worker seeds the default model prices with a query that reads models.scope.
  • That column comes from migration 20261120120000_add_model_scope_organization, which the web container applies.
  • If the worker gets there first, seeding fails and isn't retried. In my run the worker failed at 10:11:31.317 and the migration finished at 10:11:31.819. The worker logged:
    Error upserting default model prices ... column m.scope does not exist
    
  • The result is that only 3 of 87 models have pricing tiers, so gpt-4o-mini generations get no cost. Whether the race goes the worker's way changes from run to run, which is why it's intermittent.

Verified:

  • On this branch and on main, the 4 tests fail 3 out of 3 times against the unseeded server.
  • After docker compose restart langfuse-worker, the worker logs Finished upserting default model prices, 199 of 207 models have pricing tiers, and all 4 tests pass.

Fix: the worker's price seeding should wait for migrations or retry; that belongs in langfuse/langfuse. Until then, this repo's CI could restart langfuse-worker after the health check. I haven't changed CI in this PR.


Generated by Claude Code

Key pairs belong to one project, so an explicit project_id with
public_key/secret_key now raises ValueError, and key pair clients
ignore LANGFUSE_PROJECT_ID. A client is then selected by exactly one
identifier: project_id for API key clients, public_key for key pairs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016PExPf2jnm8CPvdxKYmfqt
Mark public_key/secret_key and their env vars as deprecated in favor of
api_key, shorten the api_key/project_id docs, and validate project
headers inside _get_credentials. Drop the get_client branch for several
matches, which one identifier per client makes unreachable.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016PExPf2jnm8CPvdxKYmfqt
@langfuse-ai-gate-approver

langfuse-ai-gate-approver Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

AI review gate — Draft pull request — AI review not started

  • Cursor Bugbot does not review draft pull requests, so the gate cannot pass yet.

What to do:

  • Mark the pull request Ready for review. Bugbot then reviews it.
  • The bot re-runs this gate automatically when you mark the pull request ready or the review lands; or comment /ai-gate check.

Configuration: the repository's .github/ai-gate.yml on the base branch (the defaults without one).

History (latest 5 heads, newest first)

  • 9868e4273986 gate pending — Draft pull request — AI review not started
  • 1f606ce3a03d gate pending — Draft pull request — AI review not started
  • 67e60911fc99 gate pending — Draft pull request — AI review not started

…angChain

Add langfuse_project_id to OpenAI calls and project_id to the LangChain
CallbackHandler, so API key clients can be selected outside @observe.

get_client() now warns and returns a disabled client when given both
public_key and project_id. A credential misconfiguration found while
get_client() creates the default client is logged instead of raised,
so integrations never fail the user's call; Langfuse(...) still raises.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016PExPf2jnm8CPvdxKYmfqt
Per the revised RFC, key formats are interchangeable: an existing
sk-lf- secret works as api_key (bearer with project_id), and a new key
works as secret_key with the project ID as public_key (Basic auth), so
older SDKs can use new keys. Drop the lf_ prefix checks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016PExPf2jnm8CPvdxKYmfqt

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants