~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
"""Bind the ``openai_endpoint`` API key to the endpoint it was configured for.
``llm.openai_endpoint.api_key`` belongs to ``llm.openai_endpoint.url``. Any
code that points the provider at another URL for one call or one run (the
``custom_endpoint`` research overlay, ``get_llm(openai_endpoint_url=...)``,
and the ``create_settings_snapshot`` overrides that the Python API's
``settings_override=`` builds its snapshot from) goes through
:func:`bind_openai_endpoint_override`, which carries the stored key over
only when the new URL has the same origin (scheme, host, port).
The binding is idempotent: the first override records, under
``OPENAI_ENDPOINT_KEY_OWNER_MARKER``, the origin the key belongs to, and
every later binding compares against that record. Which origin is recorded
depends on the snapshot the first binding sees:
* no marker yet, no explicit key: the snapshot's own
``llm.openai_endpoint.url`` entry as stored in it — the envelope's
``"value"`` or the raw string — read before the override is written and
without applying ``LDR_*`` environment overrides (a value an earlier
environment pass wrote into the snapshot is read as is for the
decision); with no entry of its own — including on the documented
``settings_snapshot=None`` Python-API path — the same thread-settings-
context fallback the ``llm.openai_endpoint.api_key`` read uses, so the
key is always owned by the endpoint it was configured for rather than
by the provider default; a missing or empty entry records the provider
default. A value equal to a live ``LDR_LLM_OPENAI_ENDPOINT_URL`` is
never recorded, whichever source it came from — entry or fallback —
and the record then fails closed to "no owner" (see
:func:`_configured_openai_endpoint_url`);
* an explicit key (one named with the URL in the same call): the URL it
was named for; when that URL has no origin (``None``, ``""``,
whitespace), the URL the provider actually contacts after the write —
the current URL when none was named, the provider default for an
emptied URL, the env URL while ``LDR_LLM_OPENAI_ENDPOINT_URL`` pins an
envelope entry, and no owner (the key is withheld) for a whitespace-only
raw URL, which the provider cannot reach either;
* a marker already present: the marker, kept as is.
The marker is written by this module only. ``create_settings_snapshot``
refuses caller overrides of internal (``_``-prefixed) snapshot keys, and
:func:`_key_owner_url` trusts a marker only in the exact form
:func:`_owner_origin_url` records it in. A snapshot passed in another way
(``create_settings_snapshot(base_settings=...)``, ``settings_snapshot=``)
is trusted like any other snapshot: a canonical marker it carries is
honoured as the owner record.
The same first binding also records, under
``OPENAI_ENDPOINT_SAVED_URL_MARKER``, the origin of the snapshot's URL
entry as it stood before any override (the saved URL).
The recorded owner speaks for a key that came from the snapshot only. An
operator ``LDR_LLM_OPENAI_ENDPOINT_API_KEY`` is never authorised by it: an
env-supplied key follows exactly one origin, the one a plain ``get_llm()``
without overrides would send it to — that of
``LDR_LLM_OPENAI_ENDPOINT_URL`` when it is set, otherwise that of the saved
URL (see :func:`_key_may_follow`). No default URL is allowed in its own
right; a default is reached only when it is the saved URL. A key from the
snapshot additionally may go to the env URL's origin while that variable is
set (operator policy). These rules are evaluated at decision time and the
env origin is never recorded as a stored key's owner — not through
``LDR_LLM_OPENAI_ENDPOINT_URL`` directly and not through a value an
earlier environment pass wrote into the snapshot or the
thread-settings-context fallback surfaced, which the binder's recording
path drops from the record whichever source it came from — so the env
rules expire with the variables.
Kept free of provider and langchain imports so the settings overlay helpers
in ``utilities.type_utils`` can use it.
"""
from loguru import logger
from ..settings.manager import check_env_setting
from ..utilities.url_utils import endpoint_origin, same_endpoint_origin
from .thread_settings import get_setting_from_snapshot
OPENAI_ENDPOINT_URL_SETTING = "llm.openai_endpoint.url"
OPENAI_ENDPOINT_API_KEY_SETTING = "llm.openai_endpoint.api_key"
# The URL the provider uses when ``llm.openai_endpoint.url`` is unset/empty.
OPENAI_ENDPOINT_DEFAULT_BASE_URL = "https://api.openai.com/v1"
# Snapshot entry recording which origin ``llm.openai_endpoint.api_key`` belongs
# to once the URL has been overridden. Leading underscore like ``_username``:
# run metadata, not a user setting.
OPENAI_ENDPOINT_KEY_OWNER_MARKER = "_openai_endpoint_key_owner_url"
# Snapshot entry recording the origin of the snapshot's own
# ``llm.openai_endpoint.url`` entry as it was before the first override (the
# saved URL). An env-supplied key with no env URL follows this origin only.
OPENAI_ENDPOINT_SAVED_URL_MARKER = "_openai_endpoint_saved_url_origin"
def effective_openai_endpoint_url(settings_snapshot=None):
"""The URL the ``openai_endpoint`` provider would contact for this snapshot.
Mirrors ``CustomOpenAIEndpointProvider.create_llm``: a missing or empty
value falls back to the provider default; any other value (including a
whitespace-only one) is used as is and normalised later. An operator-set
``LDR_LLM_OPENAI_ENDPOINT_URL`` environment override becomes the
effective value here (environment values are operator policy), so the
stored key is kept for the env URL while it is set — see
:func:`_key_may_follow`.
"""
url = get_setting_from_snapshot(
"llm.openai_endpoint.url", None, settings_snapshot=settings_snapshot
)
if not url:
return OPENAI_ENDPOINT_DEFAULT_BASE_URL
return url
def _configured_openai_endpoint_url(settings_snapshot, *, for_record=False):
"""The configured ``llm.openai_endpoint.url``: where the stored key belongs.
Resolved from the same sources, in the same order, as the API-key read
(:func:`get_setting_from_snapshot`): the snapshot's own
``llm.openai_endpoint.url`` entry first, then the thread-settings-
context fallback of that lookup — which is where a snapshot-less
caller's (``settings_snapshot=None``, or a snapshot without its own
entry) configured URL lives. Key and owner must come from the same
source: a key read through the fallback whose owner resolved from the
snapshot dict alone would be withheld from its own endpoint and
authorised for the provider default instead.
Two deliberate differences from a plain ``get_setting_from_snapshot``
read of that key:
* The entry is read exactly as it sits in ``settings_snapshot`` at
call time: the ``"value"`` of an envelope, or the raw string. That
is the stored, configured URL for a snapshot built from the settings
database (``get_all_settings(include_environment_overrides=False)``),
and the already-overridden URL for a snapshot an earlier write
changed — which is why the binder records the owner before it
writes. A transient ``LDR_LLM_OPENAI_ENDPOINT_URL`` is never
consulted for it: an environment value is policy only while it is
set and must never permanently re-own the key. The environment is
NOT stripped from the entry itself: a snapshot built with
``include_environment_overrides=True`` or passed through
``apply_environment_overrides_to_snapshot`` already carries the env
URL as its value, and that is what this returns — for a decision.
For a record (``for_record=True``) such a value is dropped like the
fallback's (below), whichever source it came from.
* A missing or empty entry falls back to the provider default (the URL
the provider contacts unconfigured). A default is reached only here
— when it *is* the URL the provider contacts — never in its own
right.
The thread-settings-context fallback may surface the live
``LDR_LLM_OPENAI_ENDPOINT_URL`` (a context built on the settings
managers applies ``LDR_*`` overrides on read), and an earlier
environment pass may have written that value into the entry itself.
Either is fine for a live decision — :func:`_key_may_follow`'s env
rule grants exactly its origin while the variable is set and nothing
after — but never for a record, which would outlive the variable: the
binder's recording path (``for_record=True``) drops a value equal to
the live ``LDR_LLM_OPENAI_ENDPOINT_URL``, whichever source it came
from, and gets ``""`` ("no owner", failing closed) for it; the
provider default must not stand in either, or the default origin
would be granted in its own right. The drop is keyed on a LIVE
(non-empty) env URL: an empty configured value is not the env value
and records the provider default below. A value that merely shares
the env URL's origin is not the env value and is recorded as is (it
is the stored value a context reports).
"""
raw = None
if (
isinstance(settings_snapshot, dict)
and OPENAI_ENDPOINT_URL_SETTING in settings_snapshot
):
raw = settings_snapshot[OPENAI_ENDPOINT_URL_SETTING]
if isinstance(raw, dict) and "value" in raw:
raw = raw["value"]
else:
# No entry of its own: the same fallback the key read uses —
# ``get_setting_from_snapshot``'s thread-settings-context lookup.
raw = get_setting_from_snapshot(
OPENAI_ENDPOINT_URL_SETTING,
None,
settings_snapshot=settings_snapshot,
)
if not isinstance(raw, str):
raw = None
if for_record:
# A record outlives ``LDR_LLM_OPENAI_ENDPOINT_URL``: a value equal
# to the live env URL is transient policy, never stored
# configuration, so the recording path drops it whichever source
# it came from — the thread-settings-context fallback surfacing
# it, or an earlier environment pass writing it into the entry —
# and fails closed to "no owner" (see the docstring). The test is
# against a LIVE (non-empty) env URL only: ``check_env_setting``
# reports unset and empty alike, so without it an empty configured
# URL would be dropped whenever no env URL is set — and a missing
# or empty value records the provider default below.
env_url = _env_openai_endpoint_url()
if env_url and raw == env_url:
return ""
if not raw:
return OPENAI_ENDPOINT_DEFAULT_BASE_URL
return raw
def _env_openai_endpoint_key():
"""The operator's ``LDR_LLM_OPENAI_ENDPOINT_API_KEY`` while it is set."""
return (check_env_setting(OPENAI_ENDPOINT_API_KEY_SETTING) or "").strip()
def _key_is_env_supplied(settings_snapshot):
"""Whether the key a read of ``settings_snapshot`` yields is the env key.
With ``LDR_LLM_OPENAI_ENDPOINT_API_KEY`` set, an envelope read applies
it, a missing entry resolves outside the snapshot, and
``apply_environment_overrides_to_snapshot`` writes it into raw entries.
Only a raw entry holding some other value (an explicit key the binder
wrote, or the cleared ``""``) is not the env key. Fails toward "env"
on anything else.
"""
env_key = _env_openai_endpoint_key()
if not env_key:
return False
if (
not isinstance(settings_snapshot, dict)
or OPENAI_ENDPOINT_API_KEY_SETTING not in settings_snapshot
):
return True
entry = settings_snapshot[OPENAI_ENDPOINT_API_KEY_SETTING]
if isinstance(entry, dict):
return True
return str(entry or "").strip() == env_key
def _saved_openai_endpoint_url(settings_snapshot, *, for_record=False):
"""The snapshot's saved ``llm.openai_endpoint.url``, before any override.
The binder records it under ``OPENAI_ENDPOINT_SAVED_URL_MARKER`` the
first time it rewrites the snapshot, from the URL entry as it stood
then (:func:`_configured_openai_endpoint_url`: the settings-database
or default value for a snapshot built from the settings, the same
thread-settings-context fallback the key read uses when there is no
snapshot entry — or no snapshot at all —, the provider default for a
missing or empty entry). A recorded value is trusted only in the
canonical form :func:`_owner_origin_url` writes. Before any binding
the URL entry has not been overridden and is read directly. A
snapshot that carries a key-owner marker but no saved-URL record
fails closed to "no saved URL": the entry may already hold an
override, and the owner marker may name a call's URL.
``for_record=True`` is the binder's recording path: the recorded saved
URL must outlive ``LDR_LLM_OPENAI_ENDPOINT_URL`` without ever steering
an env-supplied key to the env URL's former origin, so a value equal
to the live env URL is not recorded, whichever source it came from
(:func:`_configured_openai_endpoint_url`). Such a record is ``""``,
which means no known saved URL and withholds an env-supplied key (fail
closed) — unlike an empty ``llm.openai_endpoint.url`` entry, which
resolves to the provider default.
"""
if isinstance(settings_snapshot, dict):
if OPENAI_ENDPOINT_SAVED_URL_MARKER in settings_snapshot:
saved = settings_snapshot.get(OPENAI_ENDPOINT_SAVED_URL_MARKER)
if not isinstance(saved, str):
return ""
return saved if saved == _owner_origin_url(saved) else ""
if OPENAI_ENDPOINT_KEY_OWNER_MARKER in settings_snapshot:
return ""
return _configured_openai_endpoint_url(
settings_snapshot, for_record=for_record
)
def _env_openai_endpoint_url():
"""The operator's ``LDR_LLM_OPENAI_ENDPOINT_URL`` while it is set.
Read live at decision time through ``check_env_setting`` (an empty
variable counts as unset) and never recorded anywhere: the policy
lasts only as long as the variable.
"""
return check_env_setting(OPENAI_ENDPOINT_URL_SETTING) or ""
def _key_owner_url(settings_snapshot, *, for_record=False):
"""The URL a snapshot-supplied ``llm.openai_endpoint.api_key`` belongs to.
A marker present in the snapshot is trusted when, and only when, it is
in the canonical ``scheme://host:port`` form :func:`_owner_origin_url`
writes — whichever way the snapshot arrived (binder-written in this
process, or carried in a ``base_settings=`` / ``settings_snapshot=``
the caller passed). Any other value fails closed to "no owner". With
no marker the owner is the configured URL
(:func:`_configured_openai_endpoint_url`): the snapshot's entry as
stored in it, else the same thread-settings-context fallback the key
read uses — so on the ``settings_snapshot=None`` Python-API path the
key is owned by the endpoint it was configured for, not by the
provider default. The binder never consults ``LDR_LLM_OPENAI_ENDPOINT_URL``
directly; a value equal to a live one is used for decisions but never
recorded, whichever source it came from (``for_record=True``, see
:func:`_configured_openai_endpoint_url`).
This owner never authorises an env-supplied key; see
:func:`_key_may_follow`.
"""
if (
isinstance(settings_snapshot, dict)
and OPENAI_ENDPOINT_KEY_OWNER_MARKER in settings_snapshot
):
owner = settings_snapshot.get(OPENAI_ENDPOINT_KEY_OWNER_MARKER)
if not isinstance(owner, str):
return ""
return owner if owner == _owner_origin_url(owner) else ""
return _configured_openai_endpoint_url(
settings_snapshot, for_record=for_record
)
def _owner_origin_url(url):
"""Record the comparison origin without retaining other URL components."""
origin = endpoint_origin(url)
if origin is None:
return ""
scheme, host, port = origin
if ":" in host:
host = f"[{host}]"
return f"{scheme}://{host}:{port}"
def _key_may_follow(target_url, owner, settings_snapshot):
"""Whether the key ``settings_snapshot`` yields may be sent to ``target_url``.
An env-supplied key (``LDR_LLM_OPENAI_ENDPOINT_API_KEY``, see
:func:`_key_is_env_supplied`) follows exactly one origin, the one a
plain ``get_llm()`` on the snapshot would send it to: that of
``LDR_LLM_OPENAI_ENDPOINT_URL`` when it is set, otherwise that of the
saved ``llm.openai_endpoint.url`` (:func:`_saved_openai_endpoint_url`
— an empty ``llm.openai_endpoint.url`` entry is the provider default
there; a dropped saved record means no known saved URL and the key is
withheld). ``owner`` — which may name a call's URL — does not speak
for it, and no default URL is allowed in its own right.
Any other key may go to ``target_url`` when it shares ``owner``'s
origin (scheme, host, port), or when ``target_url`` is on the origin
of a currently-set ``LDR_LLM_OPENAI_ENDPOINT_URL``: environment values
are operator policy while they are set.
Both rules are evaluated here, live, and are never recorded as
ownership — once a variable is gone its rule no longer applies.
"""
env_url = _env_openai_endpoint_url()
if _key_is_env_supplied(settings_snapshot):
return same_endpoint_origin(
target_url, env_url or _saved_openai_endpoint_url(settings_snapshot)
)
if same_endpoint_origin(target_url, owner):
return True
return bool(env_url) and same_endpoint_origin(target_url, env_url)
def resolve_openai_endpoint_override_key(endpoint_url, settings_snapshot=None):
"""Decide whether the stored ``openai_endpoint`` key may go to ``endpoint_url``.
Returns:
``(key, withheld)``: ``key`` is the key the snapshot yields
(stored, or the operator's env key) when ``endpoint_url`` is an
origin that key may follow (see :func:`_key_may_follow`: an env
key follows the env URL, or with none the saved URL; a
stored key follows its owner's origin or a currently-set env
URL's), otherwise ``""``.
``withheld`` is True when a stored key exists but the key is not
sent.
"""
stored_key = get_setting_from_snapshot(
"llm.openai_endpoint.api_key", "", settings_snapshot=settings_snapshot
)
stored_key = str(stored_key or "").strip()
if _key_may_follow(
endpoint_url, _key_owner_url(settings_snapshot), settings_snapshot
):
return stored_key, False
return "", bool(stored_key)
def bind_openai_endpoint_override(
snapshot, endpoint_url=None, explicit_key=None, *, keep_envelope=False
):
"""Point ``snapshot`` at ``endpoint_url`` and keep the API key bound, in place.
Args:
snapshot: The settings snapshot dict to modify.
endpoint_url: The new ``llm.openai_endpoint.url``, or ``None`` to
keep the current URL and only re-check an earlier binding.
explicit_key: A key that belongs to the (new) URL; bound as is.
keep_envelope: Write the URL into an existing ``{"value": ...}``
envelope (as the runtime-settings overlay does) instead of
replacing the entry with the raw string.
The first binding records, under ``OPENAI_ENDPOINT_KEY_OWNER_MARKER``,
the origin the key belongs to (the module docstring lists which origin
each snapshot shape records): without an explicit key, the snapshot's
URL entry as stored in it — or the thread-settings-context fallback
the key read uses when there is no entry — read before the override is
written and without the environment applied (a value equal to a live
``LDR_LLM_OPENAI_ENDPOINT_URL`` is dropped from the record rather than
written down, whichever source it came from); with one, the URL it
was named for, or the URL the provider contacts after the write when
that URL has no origin.
It also records the saved URL's origin under
``OPENAI_ENDPOINT_SAVED_URL_MARKER``. Later bindings, including the
re-check ``get_llm`` runs on every ``openai_endpoint`` call,
compare against that origin rather than the snapshot's current one.
That makes binding idempotent, and it stops a key that
``apply_environment_overrides_to_snapshot`` writes back from following
the overridden URL. An env-supplied key is checked against the env
URL (or, with none set, the recorded saved URL) and never against the
recorded owner; a stored key is additionally kept for a currently-set
``LDR_LLM_OPENAI_ENDPOINT_URL`` (operator policy). The env origin is
never recorded as a stored key's owner. See :func:`_key_may_follow`.
Clearing is final for that snapshot: the key is not kept anywhere, so
binding back to the owner's origin later does not bring it back (fail
closed). A run that needs it again starts from a fresh snapshot.
The cleared key is written as a raw ``""``, never into an envelope:
envelope reads apply ``LDR_*`` environment overrides, which would bring
the stored key back. An explicit key is written raw too, and
``apply_environment_overrides_to_snapshot`` leaves a raw key under an
owner marker in place, so the env key is not swapped in under a
record that names another origin. That includes a cleared ``""``: a
slot the binder emptied stays empty for that snapshot even when an
``LDR_LLM_OPENAI_ENDPOINT_API_KEY`` is set later.
Returns:
True when a stored key was withheld because the origins differ.
"""
explicit_key = explicit_key.strip() if isinstance(explicit_key, str) else ""
# Decision-time and recorded values are distinguished on purpose (see
# ``_configured_openai_endpoint_url``): ``owner`` speaks for this
# call's keep/clear check below, while ``recorded_owner`` and
# ``saved_url`` are written into marker records that outlive a
# transient ``LDR_LLM_OPENAI_ENDPOINT_URL`` an earlier environment
# pass or the thread-settings-context fallback may surface. A record
# naming that value would re-own the key to the env origin after the
# variable is gone, so the recording path drops it, whichever source
# it came from (failing closed to "no owner"). Nothing is lost at
# decision time by that: any authority the transient value carries is
# re-granted live by ``_key_may_follow``'s env rule for exactly as
# long as the variable is set.
owner = _key_owner_url(snapshot)
recorded_owner = _key_owner_url(snapshot, for_record=True)
# Read before the write, like ``owner``: the saved URL is the entry as
# it stood before this (or any earlier) override.
saved_url = _owner_origin_url(
_saved_openai_endpoint_url(snapshot, for_record=True)
)
if endpoint_url is not None:
if keep_envelope:
from ..utilities.type_utils import overlay_snapshot_value
overlay_snapshot_value(
snapshot, OPENAI_ENDPOINT_URL_SETTING, endpoint_url
)
else:
snapshot[OPENAI_ENDPOINT_URL_SETTING] = endpoint_url
# The provider's actual destination after the write (an env override on
# an envelope entry can pin it).
new_url = effective_openai_endpoint_url(snapshot)
if explicit_key:
snapshot[OPENAI_ENDPOINT_API_KEY_SETTING] = explicit_key
# The call's key belongs to the URL it was named for. When that URL
# has no origin — none named, or an emptied/blank one — it belongs
# to where the provider actually goes after the write: the current
# URL when none was named, the provider default for an emptied URL,
# the env URL when an ``LDR_LLM_OPENAI_ENDPOINT_URL`` pins an
# envelope entry, and no owner for a whitespace-only raw URL.
key_owner = (
endpoint_url
if endpoint_origin(endpoint_url) is not None
else new_url
)
snapshot[OPENAI_ENDPOINT_KEY_OWNER_MARKER] = _owner_origin_url(
key_owner
)
snapshot[OPENAI_ENDPOINT_SAVED_URL_MARKER] = saved_url
return False
if (
endpoint_url is None
and OPENAI_ENDPOINT_KEY_OWNER_MARKER not in snapshot
):
# Nothing was overridden; the stored key belongs to the stored URL.
return False
snapshot[OPENAI_ENDPOINT_KEY_OWNER_MARKER] = _owner_origin_url(
recorded_owner
)
snapshot[OPENAI_ENDPOINT_SAVED_URL_MARKER] = saved_url
if _key_may_follow(new_url, owner, snapshot):
return False
stored_key = get_setting_from_snapshot(
"llm.openai_endpoint.api_key", "", settings_snapshot=snapshot
)
snapshot[OPENAI_ENDPOINT_API_KEY_SETTING] = ""
if str(stored_key or "").strip():
logger.warning(
"The configured llm.openai_endpoint.api_key is not sent to an "
"endpoint override on a different origin (scheme, host or "
"port); the call proceeds without it."
)
return True
return False