Skip to content

Docs pattern os.getenv("OPENROUTER_API_KEY", "") defeats the built-in env fallback #591

Description

@rajarshidattapy

Description

The SDK already resolves api_key from OPENROUTER_API_KEY at request time (utils/security.py:79-80, called from basesdk.py:195 and every operation's security_source=). Passing api_key explicitly short-circuits that fallback — get_security_from_env returns the supplied value unchanged if it is not None.

~119 doc snippets pass api_key=os.getenv("OPENROUTER_API_KEY", ""). When the env var is unset, that yields Security(api_key="") — not None — so the fallback is skipped and the client sends an empty Authorization: Bearer header. The user gets a 401 from the API instead of a local "no credentials" signal, and the misconfiguration is harder to diagnose than if nothing had been sent.

Two separate fixes:

  1. Docs: drop the os.getenv(...) wrapper from generated snippets; OpenRouter() alone picks up OPENROUTER_API_KEY. This is a gen.yaml / template change, not a hand-edit — the files are generated.
  2. Optional hardening: treat empty-string api_key as absent in sdk.py:190-196 so an explicit "" still falls through to the env var.

Secondary inconsistency: the sibling globals (http_referer, x_open_router_title, x_open_router_categories) resolve their env vars eagerly in __init__ via get_global_from_env, while api_key resolves lazily per-request. Behavior is equivalent; only the read location differs. Not worth changing on its own.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions