Skip to content

~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.

fix(metrics): isolate callbacks on shared LLMs (#7053)

LearningCircuitcb0da2c36b24
diff --git a/changelog.d/+shared-llm-callback-isolation.bugfix.md b/changelog.d/+shared-llm-callback-isolation.bugfix.md
new file mode 100644
index 0000000000..e036218ad6
--- /dev/null
+++ b/changelog.d/+shared-llm-callback-isolation.bugfix.md
@@ -0,0 +1 @@
+Token usage from a registered LLM now stays with the research and user that made each call. Each research's token callback is passed with that research's calls and is no longer stored on the model. A model that serves several runs or users is therefore invoked as it is and no longer modified: a registered model instance, or a model that a registered factory returns more than once, such as a cached or singleton model. It keeps its own state, such as a call counter, and other researches never fire that callback. A callback list or manager that a factory gives every model it builds is no longer extended in place, which had made later calls also write their token usage under earlier users' names. When a research ends, LDR now closes only a model that one of its built-in providers built for that research. A model that a registered factory returned is no longer closed, because it can be one cached or singleton model that other researches are still using. A factory that builds a new model with its own HTTP clients on every call, such as a `ChatOllama`, now has to close those clients itself, as the owner of a registered instance already did. `bind()` and `with_config()` on an LLM from `get_llm()` now return LDR's wrapper, as `bind_tools()` does, so calls through them record token usage, have `<think>` tags stripped and stop when the research is cancelled. A config bound with `with_config()` combines with each call's config as it does in LangChain, and like the wrapper itself, the result cannot be composed with `|`. Methods the wrapper does not define, such as `with_retry()` or `generate()`, reach the model without the token callback and record no token usage for the research. Wrapping a model for a research binds the cancellation scope only to LDR's own wrappers, never to the model or to objects the model holds. Token usage is also recorded when LLM rate limiting is enabled and the model has no callbacks of its own; the callback used to be stored on the rate-limiting wrapper, which never passes it to the model.
diff --git a/changelog.d/5854.misc.md b/changelog.d/5854.misc.md
index c8d3d40885..f21b098b27 100644
--- a/changelog.d/5854.misc.md
+++ b/changelog.d/5854.misc.md
@@ -1 +1 @@
-Notes AI routes now await model responses on the request event loop while their synchronous database work runs on worker threads. The background change-summary worker retains synchronous invocation. Model acquisition handles request cancellation so a late worker result receives a cleanup attempt instead of remaining cached and unused. Registered shared model instances remain caller-owned when wrapped or bound to tools; built-in and registered factory results retain close-after-use behavior. Cleanup remains best effort and provider-specific; synchronous cleanup and notes HTTP rate-limit storage checks run on worker threads. The async rate-limit wrapper now scrubs and wraps rate-limit errors; adaptive retry remains disabled in production. Part of #5854; addresses the shared-instance lifetime conflict in #6291.
+Notes AI routes now await model responses on the request event loop while their synchronous database work runs on worker threads. The background change-summary worker retains synchronous invocation. Model acquisition handles request cancellation so a late worker result receives a cleanup attempt instead of remaining cached and unused. Registered shared model instances remain caller-owned when wrapped or bound to tools; built-in provider results retain close-after-use behavior. Cleanup remains best effort and provider-specific; synchronous cleanup and notes HTTP rate-limit storage checks run on worker threads. The async rate-limit wrapper now scrubs and wraps rate-limit errors; adaptive retry remains disabled in production. Part of #5854; addresses the shared-instance lifetime conflict in #6291.
diff --git a/docs/CUSTOM_LLM_INTEGRATION.md b/docs/CUSTOM_LLM_INTEGRATION.md
index 091d263437..8e46cb5cc2 100644
--- a/docs/CUSTOM_LLM_INTEGRATION.md
+++ b/docs/CUSTOM_LLM_INTEGRATION.md
@@ -188,6 +188,12 @@ The LLM registry is thread-safe, allowing concurrent usage in multi-threaded app
Registered LLMs are available globally within the Python process. They persist until explicitly unregistered or the process ends.
+### Model Lifetime
+
+LDR never closes a model you register, whether you register the instance or a factory. A factory can return the same model, such as a cached or singleton one, to every research, so closing that model when one research ends would break the others. LDR closes only the models that its built-in providers build.
+
+Each research's token-counting callback is passed with that research's calls and is never stored on your model, so one instance can serve several researches and users. If your model holds HTTP clients of its own, as a `ChatOllama` does, you can build it once and return that instance from your factory. A factory that builds a new model on every call leaves closing those clients to you.
+
## Best Practices
1. **Consistent Naming**: Use clear, descriptive names for your custom LLMs
diff --git a/docs/developing/resource-cleanup.md b/docs/developing/resource-cleanup.md
index d7a0f1fd07..9f2fca0e85 100644
--- a/docs/developing/resource-cleanup.md
+++ b/docs/developing/resource-cleanup.md
@@ -111,7 +111,7 @@ Key invariants:
| You're holding | Do this |
| --- | --- |
-| A `ChatOllama` (raw or wrapped) | Call `wrapper.close()` in a `finally`, or pass to `safe_close(wrapper, "...")`. The wrapper chain handles both sync and async httpx clients. |
+| A `ChatOllama` (raw or wrapped) | Call `wrapper.close()` in a `finally`, or pass to `safe_close(wrapper, "...")`. The wrapper chain handles both sync and async httpx clients. A wrapper from `get_llm()` closes only a model that a built-in provider built; a registered instance or a registered factory's model stays open for whoever registered it (see `docs/CUSTOM_LLM_INTEGRATION.md`). |
| A search engine you constructed | `safe_close(engine, "...")` in `finally`. The engine's `close()` cascades into preview/content filters. |
| A holder class with an LLM | Add a `close()` method, gate the LLM close on `self._owns_llm`, document who calls it. Don't add `__del__`. |
| A long-lived service holder (news scheduler, etc.) | Wrap construction in `try/finally` at the cycle boundary. Don't store the LLM if you can recreate it cheaply. |
diff --git a/src/local_deep_research/advanced_search_system/strategies/langgraph_agent_strategy.py b/src/local_deep_research/advanced_search_system/strategies/langgraph_agent_strategy.py
index 5013f5509a..5da1ed6874 100644
--- a/src/local_deep_research/advanced_search_system/strategies/langgraph_agent_strategy.py
+++ b/src/local_deep_research/advanced_search_system/strategies/langgraph_agent_strategy.py
@@ -2004,12 +2004,14 @@ def _make_research_subtopic_tool(
# (config/llm_config.py) overrides bind_tools to re-wrap the
# bound model, so the wrapper's <think>-tag stripping survives
# the agent loop and runs on every model call here (fix #4804).
- # Scope note: other Runnable transforms still escape the wrapper
- # — with_config/bind/stream delegate via __getattr__ to the
- # unwrapped base model (silent, unstripped), and `|` raises
- # TypeError (the wrapper defines no __or__). None are on this
- # create_agent path. Closing that whole class would need a full
- # Runnable-subclass wrapper.
+ # Scope note: Runnable transforms other than bind_tools,
+ # with_structured_output, bind and with_config (which re-wrap)
+ # still escape the wrapper — with_retry/with_fallbacks delegate
+ # via __getattr__ to the unwrapped base model (silent,
+ # unstripped), stream() passes chunks on unstripped, and `|`
+ # raises TypeError (the wrapper defines no __or__). None are on
+ # this create_agent path. Closing that whole class would need a
+ # full Runnable-subclass wrapper.
agent = create_agent(
model=model,
tools=sub_tools,
@@ -3151,9 +3153,10 @@ class LangGraphAgentStrategy(BaseSearchStrategy):
# create_agent() calls model.bind_tools(); ProcessingLLMWrapper overrides
# bind_tools to re-wrap the bound model, so the wrapper's <think>-tag
# stripping survives the agent loop here (fix #4804). Other Runnable
- # transforms still escape the wrapper (with_config/bind/stream delegate
- # via __getattr__ unstripped; `|` raises TypeError, no __or__), but none
- # are on this create_agent path — see config/llm_config.py.
+ # transforms still escape the wrapper (with_retry/with_fallbacks
+ # delegate via __getattr__ unstripped; stream() passes chunks on
+ # unstripped; `|` raises TypeError, no __or__), but none are on this
+ # create_agent path — see config/llm_config.py.
try:
agent = create_agent(
model=self.model,
diff --git a/src/local_deep_research/config/llm_config.py b/src/local_deep_research/config/llm_config.py
index d04522d83d..a6e42d4b1b 100644
--- a/src/local_deep_research/config/llm_config.py
+++ b/src/local_deep_research/config/llm_config.py
@@ -1,7 +1,10 @@
from typing import Any
-from langchain_core.language_models import BaseChatModel
+from langchain_core.callbacks import BaseCallbackManager, CallbackManager
+from langchain_core.language_models import BaseChatModel, BaseLanguageModel
from langchain_core.messages import AIMessage
+from langchain_core.runnables import RunnableBinding, ensure_config
+from langchain_core.runnables.config import merge_configs
from loguru import logger
from ..llm import get_llm_from_registry, is_llm_registered
@@ -14,6 +17,7 @@ from ..utilities.search_utilities import remove_think_tags
# langchain install), the module must fail loudly here rather than start
# with an empty registry and confusing per-call errors.
from ..llm.providers import discover_providers # noqa: F401
+from ..llm.providers.auto_discovery import is_builtin_provider_factory
from ..llm.providers.base import normalize_provider
from .thread_settings import get_setting_from_snapshot
@@ -319,7 +323,13 @@ def get_llm(
provider=provider,
research_context=research_context,
settings_snapshot=settings_snapshot,
- owns_llm=not isinstance(custom_llm, BaseChatModel),
+ # LDR closes only a model it knows it built: a built-in
+ # provider's create_llm builds a new one on every call. A
+ # registered instance, or whatever a registered factory
+ # returns, can be serving other researches (a factory can
+ # return one cached or singleton model), so it stays with the
+ # code that registered it.
+ owns_llm=is_builtin_provider_factory(custom_llm),
)
# Validate the provider against the auto-discovered set — NOT a hardcoded
@@ -427,7 +437,82 @@ def _log_llm_error(error: Exception) -> None:
logger.warning(f"LLM Request - Failed with error: {safe_msg}")
+def _merge_callbacks(existing, added, *, inherit: bool = True):
+ """Return a callback manager holding *existing* plus *added*.
+
+ *existing* is never changed. It holds a call's callbacks: the ones its
+ caller passed, or the ones it inherits from an enclosing run such as a
+ LangGraph node. A caller can pass one handler list or
+ ``BaseCallbackManager`` to many calls, and an enclosing run's manager
+ serves all of its child runs, so adding to either in place could make
+ those other calls fire this research's token callback too, writing
+ their usage under this research's user and research id.
+
+ *existing* stays inheritable. With ``inherit=False`` the added handlers
+ see only the run the result is passed to, the way a model's own
+ ``callbacks`` field behaves, and child runs do not inherit them.
+
+ The result is a manager even when *existing* is a list. A
+ ``RunnableBinding`` merges a call's callbacks with the ones it binds,
+ which the call's callbacks can already hold (see
+ ``_with_research_callbacks``). LangChain's ``merge_configs`` adds each
+ handler once when either side is a manager, but joins two lists with
+ every handler from both.
+ """
+ added = list(added)
+ if isinstance(existing, BaseCallbackManager):
+ merged = existing.copy()
+ if merged is existing:
+ raise TypeError("A callback manager must support isolated copies")
+ else:
+ inherited = list(existing or [])
+ merged = CallbackManager(
+ handlers=inherited, inheritable_handlers=list(inherited)
+ )
+ for handler in added:
+ merged.add_handler(handler, inherit=inherit)
+ return merged
+
+
+def _config_receiver(runnable):
+ """Return the runnable that receives the config passed to *runnable*.
+
+ LDR's rate-limiting wrapper hands each call's arguments, the config
+ included, unchanged to the runnable it wraps.
+ """
+ seen = set()
+ while (
+ getattr(type(runnable), "_ldr_forwards_call_arguments", False)
+ and id(runnable) not in seen
+ ):
+ seen.add(id(runnable))
+ runnable = runnable.base_llm
+ return runnable
+
+
+def _starts_the_model_run(runnable) -> bool:
+ """Whether the config passed to *runnable* starts the model's own run.
+
+ A model starts its run with the config it is called with, and a
+ ``RunnableBinding``, which ``bind``, ``bind_tools`` and ``with_config``
+ return for a standard model, passes its merged config on to the
+ runnable it binds. Anything else is taken to start a run of its own
+ and run the model as a child of that run, as the chain that
+ ``with_structured_output`` returns does, or a chain like
+ ``prompt | self`` that a custom ``bind_tools`` returns.
+ """
+ while isinstance(runnable, RunnableBinding):
+ runnable = runnable.bound
+ return isinstance(runnable, BaseLanguageModel)
+
+
class ProcessingLLMWrapper:
+ # Token callbacks of the research this wrapper serves, passed with each
+ # call instead of stored on the model; see _with_research_callbacks.
+ # The class default keeps lookups away from __getattr__, which would
+ # otherwise ask the model.
+ _ldr_research_callbacks: tuple = ()
+
def __init__(
self,
base_llm,
@@ -437,9 +522,11 @@ class ProcessingLLMWrapper:
provider=None,
settings_snapshot=None,
structured_output: bool = False,
+ research_callbacks=(),
):
self.base_llm = base_llm
self._owns_llm = owns_llm
+ self._ldr_research_callbacks = tuple(research_callbacks)
# Cancellation scope: explicit id wins, otherwise the thread's
# search context is consulted per call (see _effective_research_id).
# Stored under both names — ``research_id`` for readability and
@@ -477,11 +564,13 @@ class ProcessingLLMWrapper:
downstream code can use ``response.content`` directly — do NOT add
per-site ``remove_think_tags`` / ``get_llm_response_text`` calls on
fresh ``invoke``/``ainvoke`` results; they are redundant and hide
- bugs. (Exceptions: ``.stream()``/``.astream()``, ``with_config``,
- ``bind`` and other Runnable transforms still bypass this wrapper via
- ``__getattr__``, as do injected/unwrapped LLMs — those may still need
- explicit handling. ``bind_tools`` is NOT an exception: it re-wraps so
- the stripper survives — see the ``bind_tools`` override below and #4804.)
+ bugs. (Exceptions: ``.stream()``/``.astream()`` pass chunks on
+ unstripped, Runnable transforms other than ``bind_tools``,
+ ``with_structured_output``, ``bind`` and ``with_config`` still
+ bypass this wrapper via ``__getattr__``, and injected/unwrapped LLMs
+ are not wrapped at all — those may still need explicit handling.
+ Those four are NOT exceptions: they re-wrap so the stripper survives
+ — see the ``bind_tools`` override below and #4804.)
A message keeps its object identity (only ``.content`` is rewritten,
so ``additional_kwargs``/``reasoning_content``/``tool_calls`` survive).
@@ -507,6 +596,66 @@ class ProcessingLLMWrapper:
def _log_llm_error(error: Exception) -> None:
_log_llm_error(error)
+ def _with_research_callbacks(self, args, kwargs):
+ """Return the call arguments with this research's callbacks added.
+
+ The callbacks go into the call's ``RunnableConfig`` (positional
+ argument two or ``config=``), so the model is invoked as it is and
+ never stores them. Any model can serve other researches and users:
+ a registered instance does, and so does a model that a registered
+ factory returns more than once, such as a cached or singleton
+ model.
+
+ Only the callbacks change: every other config key resolves as it
+ does for the same call without this wrapper. The config passed on
+ holds the caller's own keys rather than everything the call
+ inherits, plus the callbacks the call would use anyway: the
+ caller's, or those of an enclosing run such as a LangGraph node.
+ A ``RunnableBinding``, such as the result of ``with_config``, lets
+ its bound config win over an inherited one only when it is called
+ without a config. For a binding, the config passed on is therefore
+ its bound config already merged with the call's, as the binding
+ merges them, so the binding merging its bound config in again gives
+ the same values.
+
+ The handlers are not inheritable when that config starts the
+ model's own run (see ``_starts_the_model_run``), which matches a
+ model's own ``callbacks`` field: a run the model starts inside its
+ own run is not recorded as well. When the config starts a chain
+ instead, such as under ``with_structured_output`` or a custom
+ ``bind_tools`` that returns ``prompt | self``, the model call is a
+ child run, so the handlers are inheritable. If the model itself
+ invokes another runnable during that call, the handlers see that
+ inner run too and record its tokens as well.
+
+ Only the wrapper's own call methods add the callbacks: ``invoke``,
+ ``ainvoke``, ``stream``, ``astream``, ``batch`` and ``abatch``. The
+ wrappers that ``bind_tools``, ``with_structured_output``, ``bind``
+ and ``with_config`` return have the same methods and callbacks. A
+ call that leaves the wrapper through ``__getattr__`` reaches the
+ model without them, so its tokens are not recorded for the
+ research. That covers the other Runnable transforms, such as
+ ``with_retry`` and ``with_fallbacks``, and methods such as
+ ``generate`` and ``astream_events``.
+ """
+ if not self._ldr_research_callbacks:
+ return args, kwargs
+ positional = len(args) > 1
+ explicit = args[1] if positional else kwargs.get("config")
+ receiver = _config_receiver(self.base_llm)
+ if isinstance(receiver, RunnableBinding):
+ config = merge_configs(receiver.config, explicit)
+ else:
+ config = dict(explicit or {})
+ config["callbacks"] = _merge_callbacks(
+ ensure_config(config).get("callbacks"),
+ self._ldr_research_callbacks,
+ inherit=not _starts_the_model_run(receiver),
+ )
+ if positional:
+ return (args[0], config, *args[2:]), kwargs
+ return args, {**kwargs, "config": config}
+
def _effective_research_id(self):
"""Resolve the cancellation scope for this call.
@@ -964,6 +1113,7 @@ class ProcessingLLMWrapper:
# check_termination checkpoints) — no new HTTP request.
self._check_terminated()
try:
+ args, kwargs = self._with_research_callbacks(args, kwargs)
# When a cancellation scope is known, stream under the hood
# so a Stop mid-generation aborts within one chunk instead
# of waiting for the full response (minutes on slow local
@@ -997,6 +1147,7 @@ class ProcessingLLMWrapper:
# through __getattr__ to the base LLM and bypass think-tag stripping.
self._check_terminated()
try:
+ args, kwargs = self._with_research_callbacks(args, kwargs)
if (
self._effective_research_id() is not None
and self._stream_cancel_allowed()
@@ -1025,6 +1176,7 @@ class ProcessingLLMWrapper:
research_id = self._effective_research_id()
if research_id:
self._check_terminated(research_id)
+ args, kwargs = self._with_research_callbacks(args, kwargs)
gen = None
try:
gen = self.base_llm.stream(*args, **kwargs)
@@ -1052,6 +1204,7 @@ class ProcessingLLMWrapper:
research_id = self._effective_research_id()
if research_id:
self._check_terminated(research_id)
+ args, kwargs = self._with_research_callbacks(args, kwargs)
agen = None
try:
agen = self.base_llm.astream(*args, **kwargs)
@@ -1141,7 +1294,13 @@ class ProcessingLLMWrapper:
return results
def close(self):
- """Release owned clients; registered shared instances remain caller-owned."""
+ """Close the model's clients if this wrapper owns the model.
+
+ ``get_llm()`` gives a wrapper ownership only of a model that a
+ built-in provider built for it. A registered instance, or a model
+ that a registered factory returns, stays with the code that
+ registered it, since other researches can be using it.
+ """
if not self._owns_llm:
return
try:
@@ -1191,12 +1350,47 @@ class ProcessingLLMWrapper:
strip ``<think>`` tags.
"""
bound = self.base_llm.bind_tools(tools, **kwargs)
+ return self._rewrap(bound, structured_output=False)
+
+ def bind(self, **kwargs: Any) -> Any:
+ """Re-wrap like :meth:`bind_tools`.
+
+ ``langchain.agents.create_agent()`` calls ``model.bind(...)`` for an
+ agent without tools and runs the result. Without this override the
+ call would fall through ``__getattr__`` to the model, and the bound
+ model would skip the ``<think>`` stripping, the termination checks
+ and this research's token callbacks. Like this wrapper, the result
+ cannot be composed with ``|``.
+ """
+ return self._rewrap(self.base_llm.bind(**kwargs))
+
+ def with_config(self, config=None, **kwargs: Any) -> Any:
+ """Re-wrap like :meth:`bind`.
+
+ The bound config resolves with each call's config as it does in
+ LangChain: when the call passes no config, its keys win over those
+ inherited from an enclosing run. This research's token callbacks
+ run beside any callbacks it binds.
+ """
+ return self._rewrap(self.base_llm.with_config(config, **kwargs))
+
+ def _rewrap(self, runnable, *, structured_output=None):
+ """Wrap *runnable*, derived from this wrapper's model, the same way.
+
+ The new wrapper keeps this wrapper's ownership, cancellation scope,
+ provider, settings and research callbacks. It is a structured-output
+ wrapper if this one is, unless *structured_output* says otherwise.
+ """
+ if structured_output is None:
+ structured_output = self._ldr_structured_output
return ProcessingLLMWrapper(
- bound,
+ runnable,
owns_llm=self._owns_llm,
research_id=self._effective_research_id(),
provider=getattr(self, "_provider", None),
settings_snapshot=getattr(self, "_settings_snapshot", None),
+ structured_output=structured_output,
+ research_callbacks=self._ldr_research_callbacks,
)
def with_structured_output(self, schema, **kwargs: Any) -> Any:
@@ -1218,14 +1412,7 @@ class ProcessingLLMWrapper:
logger.debug(
"Structured-output scope propagation failed (non-critical)"
)
- return ProcessingLLMWrapper(
- bound,
- owns_llm=self._owns_llm,
- research_id=self._effective_research_id(),
- provider=getattr(self, "_provider", None),
- settings_snapshot=getattr(self, "_settings_snapshot", None),
- structured_output=True,
- )
+ return self._rewrap(bound, structured_output=True)
def wrap_llm_without_think_tags(
@@ -1239,10 +1426,24 @@ def wrap_llm_without_think_tags(
):
"""Wrap response processing and metrics with explicit resource ownership.
- Set ``owns_llm=False`` for a registered shared instance. Its registering
- caller remains responsible for closing it after all consumers are done.
+ Set ``owns_llm=False`` for a model the wrapper must not close.
+ ``get_llm()`` keeps ``True`` only for a model that a built-in provider
+ built for this call, and passes ``False`` for a registered instance and
+ for any model a registered factory returns: a factory can return the
+ same cached or singleton model on every call, and closing it when one
+ research ends would break the others. Whoever registered such a model
+ remains responsible for closing it after all consumers are done.
+
+ Ownership only decides who closes the model. Whether it owns the model
+ or not, this function writes nothing about the research onto the
+ model: the research's token callback is passed with each call, and the
+ cancellation scope is bound to LDR's wrappers only.
"""
+ # The model before any LDR wrapper. No research state lands on it or
+ # on anything it holds.
+ model = llm
+
# First apply rate limiting if enabled
from ..web_search_engines.rate_limiting.llm import (
create_rate_limited_llm_wrapper,
@@ -1253,7 +1454,7 @@ def wrap_llm_without_think_tags(
if get_setting_from_snapshot(
"rate_limiting.llm_enabled", False, settings_snapshot=settings_snapshot
):
- llm = create_rate_limited_llm_wrapper(llm, provider)
+ llm = create_rate_limited_llm_wrapper(model, provider)
# Set context_limit in research_context for overflow detection.
# This is needed for providers that go through the registered provider path
@@ -1282,33 +1483,32 @@ def wrap_llm_without_think_tags(
if provider:
token_callback.preset_provider = provider
# Try to extract model name from the LLM instance
- if hasattr(llm, "model_name"):
- token_callback.preset_model = llm.model_name
- elif hasattr(llm, "model"):
- token_callback.preset_model = llm.model
+ if hasattr(model, "model_name"):
+ token_callback.preset_model = model.model_name
+ elif hasattr(model, "model"):
+ token_callback.preset_model = model.model
callbacks.append(token_callback)
- # Add callbacks to the LLM if it supports them
- if callbacks and hasattr(llm, "callbacks"):
- if llm.callbacks is None:
- llm.callbacks = callbacks
- else:
- llm.callbacks.extend(callbacks)
-
wrapped = ProcessingLLMWrapper(
llm,
owns_llm=owns_llm,
research_id=research_id,
provider=provider,
settings_snapshot=settings_snapshot,
+ # The model can serve other researches and users, owned or not, so
+ # this research's callbacks travel in each call's RunnableConfig.
+ # The rate-limiting wrapper passes that config on to the model.
+ research_callbacks=callbacks,
)
if research_id is not None:
# Propagate the scope to inner wrappers (rate-limiting layer)
- # so direct uses of the inner instance also abort promptly.
+ # so direct uses of the inner instance also abort promptly. The
+ # walk stops at the model: it can be shared, and any model can
+ # hold shared objects under ``base_llm``.
try:
from ..llm.cancellation import bind_llm_to_research
- bind_llm_to_research(wrapped, research_id)
+ bind_llm_to_research(wrapped, research_id, stop_at=model)
except Exception:
logger.debug(
"Inner-wrapper scope propagation failed (non-critical)"
diff --git a/src/local_deep_research/llm/cancellation.py b/src/local_deep_research/llm/cancellation.py
index 4fe34a9dda..57fa1063d5 100644
--- a/src/local_deep_research/llm/cancellation.py
+++ b/src/local_deep_research/llm/cancellation.py
@@ -111,7 +111,9 @@ def _try_bind(target: Any, rid: str) -> None:
logger.debug("bind_llm_to_research: setattr refused", exc_info=True)
-def bind_llm_to_research(llm: Any, research_id: Optional[str]) -> Any:
+def bind_llm_to_research(
+ llm: Any, research_id: Optional[str], *, stop_at: Any = None
+) -> Any:
"""Attach *research_id* to an LLM wrapper chain (in place, chain-safe).
Sets ``_ldr_research_id`` on *llm* and, when present, on its
@@ -120,6 +122,12 @@ def bind_llm_to_research(llm: Any, research_id: Optional[str]) -> Any:
``None`` clears nothing — a falsy id leaves existing bindings intact
so rebinding with an empty value cannot silently drop cancellation.
+ *stop_at* names an object the binding must not reach. The walk stops
+ there, so neither that object nor anything below it is written. Pass
+ the model under LDR's wrappers: other researches can share it (a
+ registered instance, or a model a registered factory returns more than
+ once), or it can hold shared objects of its own.
+
Invariant: a bound wrapper must not outlive its run. The binding is
resolved per call (explicit id > binding > thread context), so
re-binding for the next run takes effect without reconstructing the
@@ -129,11 +137,13 @@ def bind_llm_to_research(llm: Any, research_id: Optional[str]) -> Any:
"""
if not research_id:
return llm
+ if stop_at is not None and llm is stop_at:
+ return llm
rid = str(research_id)
_try_bind(llm, rid)
# Propagate one level down so inner wrappers that are invoked
- # directly (e.g. via __getattr__ passthrough or shared instances)
- # see the same scope. Depth is bounded: each level sets a plain
+ # directly (e.g. via __getattr__ passthrough) see the same scope,
+ # down to *stop_at*. Depth is bounded: each level sets a plain
# attribute, never recursing.
try:
inner = getattr(llm, "base_llm", None)
@@ -142,7 +152,11 @@ def bind_llm_to_research(llm: Any, research_id: Optional[str]) -> Any:
"bind_llm_to_research: base_llm lookup failed", exc_info=True
)
return llm
- if inner is not None and getattr(inner, "_ldr_research_id", None) != rid:
+ if (
+ inner is not None
+ and inner is not stop_at
+ and getattr(inner, "_ldr_research_id", None) != rid
+ ):
_try_bind(inner, rid)
# One more level for the double-wrapped shape
# (Processing -> RateLimited -> ChatModel).
@@ -156,6 +170,7 @@ def bind_llm_to_research(llm: Any, research_id: Optional[str]) -> Any:
return llm
if (
inner_inner is not None
+ and inner_inner is not stop_at
and getattr(inner_inner, "_ldr_research_id", None) != rid
):
_try_bind(inner_inner, rid)
diff --git a/src/local_deep_research/llm/providers/auto_discovery.py b/src/local_deep_research/llm/providers/auto_discovery.py
index dccde6a7f2..1ceac8ec95 100644
--- a/src/local_deep_research/llm/providers/auto_discovery.py
+++ b/src/local_deep_research/llm/providers/auto_discovery.py
@@ -305,3 +305,28 @@ def get_provider_class(provider_key: str):
Provider class or None if not found
"""
return provider_discovery.get_provider_class(provider_key)
+
+
+_IMPLEMENTATIONS_PACKAGE = ".".join((__package__, "implementations"))
+
+
+def is_builtin_provider_factory(factory) -> bool:
+ """Whether *factory* is a built-in provider's ``create_llm``.
+
+ ``discover_providers()`` registers the ``create_llm`` classmethod of
+ each provider class defined in ``llm/providers/implementations``, and
+ every one of them builds a new model on each call. A factory registered
+ any other way, through ``register_llm()`` or the ``llms=`` argument of
+ the programmatic API, can return a model that other researches share,
+ such as a cached or singleton model.
+ """
+ provider_class = getattr(factory, "__self__", None)
+ if not (
+ isinstance(provider_class, type)
+ and issubclass(provider_class, BaseLLMProvider)
+ and provider_class.__module__.startswith(f"{_IMPLEMENTATIONS_PACKAGE}.")
+ ):
+ return False
+ return getattr(factory, "__func__", None) is getattr(
+ provider_class.create_llm, "__func__", None
+ )
diff --git a/src/local_deep_research/web_search_engines/rate_limiting/llm/wrapper.py b/src/local_deep_research/web_search_engines/rate_limiting/llm/wrapper.py
index 1590bfcc17..fd683e6f02 100644
--- a/src/local_deep_research/web_search_engines/rate_limiting/llm/wrapper.py
+++ b/src/local_deep_research/web_search_engines/rate_limiting/llm/wrapper.py
@@ -69,6 +69,12 @@ def create_rate_limited_llm_wrapper(base_llm, provider: Optional[str] = None):
class RateLimitedLLMWrapper:
"""Wrapper that adds rate limiting to LLM calls."""
+ # invoke, ainvoke, stream, astream, batch and abatch pass their
+ # arguments, the call's RunnableConfig included, to base_llm
+ # unchanged. ProcessingLLMWrapper relies on this to see which
+ # runnable receives that config (config/llm_config.py).
+ _ldr_forwards_call_arguments = True
+
def __init__(self, llm, provider_name: Optional[str] = None):
self.base_llm = llm
self.provider = provider_name
diff --git a/tests/config/test_llm_config_coverage.py b/tests/config/test_llm_config_coverage.py
index 5472bb01e5..512e2d141c 100644
--- a/tests/config/test_llm_config_coverage.py
+++ b/tests/config/test_llm_config_coverage.py
@@ -457,11 +457,14 @@ class TestWrapLlmWithoutThinkTags:
)
assert mock_callback.preset_model == "claude-3-opus"
- def test_callbacks_extended_when_existing(self):
- """If llm.callbacks already has entries, new callback is appended."""
+ def test_existing_callbacks_are_left_unchanged(self):
+ """The token callback goes with each call, never onto the model: a
+ factory can return the same model to every research, so the model's
+ own callbacks stay exactly as they were."""
existing_cb = MagicMock()
+ existing = [existing_cb]
llm = MagicMock()
- llm.callbacks = [existing_cb]
+ llm.callbacks = existing
llm.model_name = "m"
mock_counter = MagicMock()
@@ -482,9 +485,10 @@ class TestWrapLlmWithoutThinkTags:
wrap_llm_without_think_tags,
)
- wrap_llm_without_think_tags(llm, research_id=10)
- assert mock_callback in llm.callbacks
- assert existing_cb in llm.callbacks
+ wrapper = wrap_llm_without_think_tags(llm, research_id=10)
+ assert llm.callbacks is existing
+ assert existing == [existing_cb]
+ assert wrapper._ldr_research_callbacks == (mock_callback,)
def test_no_callbacks_when_no_research_id(self):
"""When research_id is None, no callbacks are attached."""
diff --git a/tests/config/test_llm_config_deep_coverage.py b/tests/config/test_llm_config_deep_coverage.py
index a650eeb12d..105e9217da 100644
--- a/tests/config/test_llm_config_deep_coverage.py
+++ b/tests/config/test_llm_config_deep_coverage.py
@@ -352,7 +352,12 @@ class TestGetLlmNameCleaning:
@pytest.mark.parametrize("factory_registration", [False, True])
def test_registered_model_cleanup_respects_ownership(factory_registration):
- """Shared registrations survive consumer cleanup, including tool binding.
+ """Registrations survive consumer cleanup, including tool binding.
+
+ LDR closes only a model that one of its built-in providers built. A
+ registered factory can return the same model to every consumer, so
+ what it returns stays with the code that registered it, as an instance
+ does.
A primary search engine lets the real policy precheck complete before
exercising registry ownership; missing search.tool correctly fails closed.
@@ -399,13 +404,8 @@ def test_registered_model_cleanup_respects_ownership(factory_registration):
bound = wrapper.bind_tools([])
assert bound.invoke("prompt").content == "answer"
bound.close()
- if not factory_registration:
- wrapper.close()
- assert wrapper.invoke("still usable").content == "answer"
-
- if factory_registration:
- assert len(models) == 2
- assert closed == models
- else:
- assert len(models) == 1
- assert closed == []
+ wrapper.close()
+ assert wrapper.invoke("still usable").content == "answer"
+
+ assert len(models) == (2 if factory_registration else 1)
+ assert closed == []
diff --git a/tests/integration/test_notes_release_concurrency.py b/tests/integration/test_notes_release_concurrency.py
index 615b13b494..8877234a42 100644
--- a/tests/integration/test_notes_release_concurrency.py
+++ b/tests/integration/test_notes_release_concurrency.py
@@ -28,6 +28,9 @@ from slowapi.middleware import SlowAPIMiddleware
from starlette.middleware.sessions import SessionMiddleware
from local_deep_research.llm import register_llm, unregister_llm
+from local_deep_research.llm.providers.implementations.ollama import (
+ OllamaProvider,
+)
from local_deep_research.research_library.notes.services.note_ai_service import (
NoteAIService,
)
@@ -39,6 +42,10 @@ pytestmark = [pytest.mark.integration, pytest.mark.asyncio]
DEADLINE = 10.0
PROVIDER = "release-concurrency-probe"
SUMMARY_URL = "/notes/api/notes/release-note/summarize"
+# The constructor the built-in Ollama provider builds its model with.
+OLLAMA_CHAT = (
+ "local_deep_research.llm.providers.implementations.ollama.ChatOllama"
+)
class _HeldOperation:
@@ -201,15 +208,24 @@ def harness(monkeypatch):
lambda self: {
"llm.provider": PROVIDER,
"llm.model": "local-test",
+ "llm.ollama.url": "http://127.0.0.1:11434",
"search.tool": "searxng",
"_username": self.username,
},
)
- def install_model(gate=None, mode="success", shared=False):
+ def install_model(gate=None, mode="success", registration="built-in"):
+ """Register the probe model as PROVIDER.
+
+ ``"built-in"`` registers a built-in provider's factory and has it
+ build the probe model instead of a ``ChatOllama``, so each request
+ gets a new model that LDR owns and closes. ``"instance"`` and
+ ``"singleton factory"`` register one model that every request
+ shares and that LDR must leave open.
+ """
state = SimpleNamespace(models=[], started=asyncio.Event())
- def factory(**kwargs):
+ def build(**kwargs):
model = _LocalModel()
model._gate = gate
model._mode = mode
@@ -217,7 +233,14 @@ def harness(monkeypatch):
state.models.append(model)
return model
- register_llm(PROVIDER, factory() if shared else factory)
+ if registration == "built-in":
+ monkeypatch.setattr(OLLAMA_CHAT, build)
+ register_llm(PROVIDER, OllamaProvider.create_llm)
+ elif registration == "instance":
+ register_llm(PROVIDER, build())
+ else:
+ singleton = build()
+ register_llm(PROVIDER, lambda **kwargs: singleton)
return state
@asynccontextmanager
@@ -276,8 +299,11 @@ async def test_owned_cleanup_preserves_responsiveness(harness, outcome):
assert model._closed, "request completed before cleanup finished"
-async def test_shared_model_remains_usable_after_consumer_cleanup(harness):
- state = harness.install_model(shared=True)
[email protected]("registration", ["instance", "singleton factory"])
+async def test_shared_model_remains_usable_after_consumer_cleanup(
+ harness, registration
+):
+ state = harness.install_model(registration=registration)
async with harness.connect() as client:
for _ in range(2):
response = await client.post(SUMMARY_URL, json={})
diff --git a/tests/llm/test_provider_adapter_contracts.py b/tests/llm/test_provider_adapter_contracts.py
index 6a8ce30a3d..01d57e585c 100644
--- a/tests/llm/test_provider_adapter_contracts.py
+++ b/tests/llm/test_provider_adapter_contracts.py
@@ -45,18 +45,24 @@ database writer.
"""
import ast
+import asyncio
+import functools
import inspect
import re
import sys
import threading
-from contextlib import ExitStack
+from contextlib import ExitStack, contextmanager
from pathlib import Path
from types import SimpleNamespace
+from typing import Any
from unittest.mock import MagicMock, patch
import pytest
+from langchain_core.callbacks import BaseCallbackHandler, CallbackManager
from langchain_core.language_models.fake_chat_models import FakeListChatModel
+from langchain_core.runnables import RunnableLambda, ensure_config
from loguru import logger as loguru_logger
+from pydantic import Field
from local_deep_research.llm.providers import discover_providers
from local_deep_research.llm.providers.base import normalize_provider
@@ -844,7 +850,7 @@ def _run_in_worker_thread(fn):
return box.get("value")
-def _wrap_for(llm, research_id, username):
+def _wrap_for(llm, research_id, username, *, owns_llm=False):
from local_deep_research.config.llm_config import (
wrap_llm_without_think_tags,
)
@@ -853,6 +859,7 @@ def _wrap_for(llm, research_id, username):
llm,
research_id=research_id,
provider="ollama",
+ owns_llm=owns_llm,
research_context={
"username": username,
"user_password": f"pw-{username}",
@@ -861,14 +868,143 @@ def _wrap_for(llm, research_id, username):
)
+_METRICS_WRITER = "local_deep_research.database.thread_metrics.metrics_writer"
+
+
+def _written(writer):
+ return [call.args[:2] for call in writer.write_token_metrics.mock_calls]
+
+
+@contextmanager
+def _registered(provider, llm):
+ from local_deep_research.llm import register_llm, unregister_llm
+
+ register_llm(provider, llm)
+ try:
+ yield
+ finally:
+ unregister_llm(provider)
+
+
+def _get_llm_for(provider, username, **snapshot_overrides):
+ """The production dispatch: registry lookup, then the shared wrap."""
+ from local_deep_research.config.llm_config import get_llm
+
+ return get_llm(
+ provider=provider,
+ model_name="test-model",
+ username=username,
+ research_id=f"res-{username}",
+ research_context={
+ "username": username,
+ "user_password": f"pw-{username}",
+ },
+ settings_snapshot=_snapshot(**snapshot_overrides),
+ )
+
+
+class _Recorder(BaseCallbackHandler):
+ """A caller's own handler: counts the model runs it sees."""
+
+ def __init__(self):
+ self.started = 0
+ self.completed = 0
+
+ def on_chat_model_start(self, serialized, messages, **kwargs):
+ self.started += 1
+
+ def on_llm_end(self, response, **kwargs):
+ self.completed += 1
+
+
+class _ToolCallingFake(FakeListChatModel):
+ """Accepts ``bind_tools``, which ``with_structured_output`` also uses."""
+
+ def bind_tools(self, tools, **kwargs):
+ return self.bind(tools=tools, **kwargs)
+
+
+class _DelegatingFake(FakeListChatModel):
+ """Keeps another model under ``base_llm``, like the rate-limiting
+ wrapper example in docs/CUSTOM_LLM_INTEGRATION.md."""
+
+ base_llm: Any = None
+
+
+class _ChainToolFake(FakeListChatModel):
+ """``bind_tools`` returns a chain, as a custom model's ``prompt | self``
+ would, so the model call is a child run of that chain."""
+
+ def bind_tools(self, tools, **kwargs):
+ return RunnableLambda(lambda value: value) | self
+
+
+class _NestingFake(FakeListChatModel):
+ """Answers with an inner model that it runs as a child of its own run,
+ the way a routing model that traces its inner call would. The child
+ gets the run's inheritable handlers, as ``ParentRunManager.get_child``
+ gives a chain's child runs."""
+
+ inner: Any = None
+
+ def _call(self, messages, stop=None, run_manager=None, **kwargs):
+ child = CallbackManager(handlers=[], parent_run_id=run_manager.run_id)
+ child.set_handlers(run_manager.inheritable_handlers)
+ return self.inner.invoke(messages, {"callbacks": child}).content
+
+
+class _ConfigRecorder(FakeListChatModel):
+ """Records the config each call hands the model."""
+
+ received: list = Field(default_factory=list)
+
+ def invoke(self, input, config=None, **kwargs):
+ self.received.append(ensure_config(config))
+ return super().invoke(input, config, **kwargs)
+
+ def stream(self, input, config=None, **kwargs):
+ self.received.append(ensure_config(config))
+ return super().stream(input, config, **kwargs)
+
+
+class _ClosableModel(FakeListChatModel):
+ """Holds clients of its own, like ``ChatOllama``: ``_close_base_llm``
+ calls its ``close()``, and a closed model cannot answer."""
+
+ closed: bool = False
+
+ def close(self):
+ self.closed = True
+
+ def _call(self, *args, **kwargs):
+ assert not self.closed, "a closed model was used"
+ return super()._call(*args, **kwargs)
+
+ def _stream(self, *args, **kwargs):
+ assert not self.closed, "a closed model was used"
+ yield from super()._stream(*args, **kwargs)
+
+
+_LOOKUP_TOOL = {
+ "type": "function",
+ "function": {
+ "name": "lookup",
+ "parameters": {"type": "object", "properties": {}},
+ },
+}
+
+
class TestTokenCallbackOwnership:
- """A registered LLM *instance* is shared; its callbacks must not be.
+ """A registered LLM can be shared; its callbacks must not be.
``register_llm(name, llm_instance, username=...)`` (the programmatic
API) stores the instance itself — and a registration made without a
- username lands in the shared namespace, resolving for every user.
- ``wrap_llm_without_think_tags`` then does
- ``llm.callbacks.extend([token_callback])`` on that shared object.
+ username lands in the shared namespace, resolving for every user. A
+ registered factory can share too: it can return the same model on
+ every call (a singleton, or a cached builder), or give every model it
+ builds one callback list or manager. Each research's token callback
+ travels with that research's calls, so the model is invoked as it is,
+ keeps its own state, and never collects another research's callback.
"""
def test_the_callback_fires_and_writes_for_its_own_research(self):
@@ -892,21 +1028,345 @@ class TestTokenCallbackOwnership:
]
assert written == [("alice", "res-alice")]
- @pytest.mark.xfail(
- strict=True,
- reason=(
- "DEFECT (#5794 mechanism): wrap_llm_without_think_tags mutates "
- "the LLM instance (llm.callbacks.extend) and nothing ever "
- "detaches. A registered BaseChatModel instance is reused across "
- "researches and — for a username-less registration, which lands "
- "in the shared namespace — across users, so every later call "
- "also fires the earlier research's callback and writes that "
- "call's tokens under the earlier user's name and research_id. "
- "The callback carries its owner only via research_context; "
- "get_llm resolves a username but never plumbs it into "
- "wrap_llm_without_think_tags."
- ),
+ def test_shared_registry_instance_isolated_through_get_llm(self):
+ from local_deep_research.config.llm_config import get_llm
+ from local_deep_research.llm import register_llm, unregister_llm
+
+ provider = "shared-callback-isolation-test"
+ shared = FakeListChatModel(responses=["a", "b"])
+ register_llm(provider, shared)
+ try:
+ wrappers = {}
+ for username in ("alice", "bob"):
+ wrappers[username] = get_llm(
+ provider=provider,
+ model_name="test-model",
+ username=username,
+ research_id=f"res-{username}",
+ research_context={
+ "username": username,
+ "user_password": f"pw-{username}",
+ },
+ settings_snapshot=_snapshot(),
+ )
+
+ writer = MagicMock()
+ with patch(
+ "local_deep_research.database.thread_metrics.metrics_writer",
+ writer,
+ ):
+ _run_in_worker_thread(lambda: wrappers["bob"].invoke("hi"))
+
+ assert [
+ call.args[:2] for call in writer.write_token_metrics.mock_calls
+ ] == [("bob", "res-bob")]
+ # The caller's own instance is invoked, never a copy.
+ assert wrappers["alice"].base_llm is shared
+ assert wrappers["bob"].base_llm is shared
+ assert not shared.callbacks
+ assert getattr(shared, "_ldr_research_id", None) is None
+ finally:
+ unregister_llm(provider)
+
+ def test_a_registered_instance_keeps_its_own_state_across_researches(
+ self,
+ ):
+ """``quick_summary(llms={...})`` registers the caller's model and
+ gives every run a research id. The caller's model must be the one
+ invoked: FakeListChatModel's response cursor ``i`` is rebound on
+ each call, like a monitor's ``call_count += 1``, so it only
+ advances on the registered instance if no copy is made."""
+ shared = FakeListChatModel(responses=["first", "second", "third"])
+ provider = "shared-state-test"
+ with _registered(provider, shared):
+ alice = _get_llm_for(provider, "alice")
+ bob = _get_llm_for(provider, "bob")
+ writer = MagicMock()
+ with patch(_METRICS_WRITER, writer):
+ replies = [
+ _run_in_worker_thread(lambda: alice.invoke("x")).content,
+ _run_in_worker_thread(lambda: bob.invoke("y")).content,
+ ]
+
+ assert replies == ["first", "second"]
+ assert shared.i == 2
+ assert _written(writer) == [("alice", "res-alice"), ("bob", "res-bob")]
+
+ @pytest.mark.parametrize("container", ["list", "manager"])
+ def test_a_factory_sharing_a_callback_container_keeps_it_unchanged(
+ self, container
+ ):
+ """A factory can derive each model from one configured template.
+ ``model_copy()`` shares the template's callback list or manager, so
+ adding Alice's token callback to it in place would make Bob's later
+ call write under Alice's name too."""
+ user_handler = _Recorder()
+ callbacks = (
+ CallbackManager([user_handler])
+ if container == "manager"
+ else [user_handler]
+ )
+ template = FakeListChatModel(responses=["a"], callbacks=callbacks)
+ shared_callbacks = template.callbacks
+
+ def factory(model_name, temperature, settings_snapshot):
+ return template.model_copy()
+
+ provider = "factory-callback-isolation-test"
+ with _registered(provider, factory):
+ _get_llm_for(provider, "alice")
+ bob = _get_llm_for(provider, "bob")
+ writer = MagicMock()
+ with patch(_METRICS_WRITER, writer):
+ _run_in_worker_thread(lambda: bob.invoke("hi"))
+
+ assert _written(writer) == [("bob", "res-bob")]
+ # Positive control: the shared container still served the call.
+ assert user_handler.completed == 1
+ handlers = (
+ shared_callbacks.handlers
+ if container == "manager"
+ else shared_callbacks
+ )
+ assert handlers == [user_handler]
+
+ @pytest.mark.parametrize(
+ "rate_limited", [False, True], ids=["direct", "rate-limited"]
)
+ @pytest.mark.parametrize("builder", ["singleton", "lru_cache"])
+ def test_a_factory_returning_one_model_keeps_it_unchanged(
+ self, builder, rate_limited
+ ):
+ """A factory can return the same model on every call, for instance
+ a local model it loads once. If a research's token callback were
+ stored on that model, Bob's call would also fire Alice's callback
+ and write Bob's usage under Alice's name and research id."""
+ user_handler = _Recorder()
+ built = []
+
+ def build():
+ model = FakeListChatModel(
+ responses=["a", "b"], callbacks=[user_handler]
+ )
+ built.append((model, model.callbacks))
+ return model
+
+ if builder == "singleton":
+ singleton = build()
+
+ def factory(**kwargs):
+ return singleton
+
+ else:
+
+ @functools.lru_cache(maxsize=None)
+ def cached_build(model_name, temperature):
+ return build()
+
+ def factory(model_name, temperature, settings_snapshot):
+ return cached_build(model_name, temperature)
+
+ provider = f"one-model-factory-{builder}-test"
+ settings = {"rate_limiting.llm_enabled": rate_limited}
+ with _registered(provider, factory):
+ alice = _get_llm_for(provider, "alice", **settings)
+ bob = _get_llm_for(provider, "bob", **settings)
+ writer = MagicMock()
+ with patch(_METRICS_WRITER, writer):
+ _run_in_worker_thread(lambda: alice.invoke("x"))
+ _run_in_worker_thread(lambda: bob.invoke("y"))
+
+ # Positive controls: one model served both researches, behind the
+ # rate-limiting layer when it is on, and its own handler still ran.
+ assert len(built) == 1
+ model, own_callbacks = built[0]
+ expected_layer = (
+ "RateLimitedLLMWrapper" if rate_limited else "FakeListChatModel"
+ )
+ assert type(bob.base_llm).__name__ == expected_layer
+ assert user_handler.completed == 2
+ assert _written(writer) == [("alice", "res-alice"), ("bob", "res-bob")]
+ assert model.callbacks is own_callbacks
+ assert own_callbacks == [user_handler]
+ assert getattr(model, "_ldr_research_id", None) is None
+
+ def test_a_factory_building_a_model_per_call_records_each_call_once(
+ self,
+ ):
+ """The usual factory, like a built-in provider's ``create_llm``,
+ builds a new model per call. Nothing is stored on that model
+ either, and the research's usage is still recorded once per call."""
+ built = []
+
+ def factory(model_name, temperature, settings_snapshot):
+ model = FakeListChatModel(responses=["a", "b"])
+ built.append(model)
+ return model
+
+ provider = "model-per-call-factory-test"
+ with _registered(provider, factory):
+ alice = _get_llm_for(provider, "alice")
+ writer = MagicMock()
+ with patch(_METRICS_WRITER, writer):
+ _run_in_worker_thread(lambda: alice.invoke("x"))
+ _run_in_worker_thread(lambda: alice.invoke("y"))
+
+ assert len(built) == 1
+ assert alice.base_llm is built[0]
+ assert _written(writer) == [("alice", "res-alice")] * 2
+ assert not built[0].callbacks
+
+ @pytest.mark.parametrize("registration", ["instance", "factory"])
+ def test_rows_are_written_with_llm_rate_limiting_enabled(
+ self, registration
+ ):
+ """The rate-limiting wrapper calls the model without its own
+ attributes, so a callback stored on that wrapper never fires."""
+
+ def factory(model_name, temperature, settings_snapshot):
+ return FakeListChatModel(responses=["a"])
+
+ registered = (
+ FakeListChatModel(responses=["a"])
+ if registration == "instance"
+ else factory
+ )
+ provider = "rate-limited-callback-test"
+ with _registered(provider, registered):
+ alice = _get_llm_for(
+ provider, "alice", **{"rate_limiting.llm_enabled": True}
+ )
+ writer = MagicMock()
+ with patch(_METRICS_WRITER, writer):
+ _run_in_worker_thread(lambda: alice.invoke("hi"))
+
+ # Positive control: the rate-limiting layer is in the chain and
+ # still carries the research's cancellation scope.
+ assert type(alice.base_llm).__name__ == "RateLimitedLLMWrapper"
+ assert alice.base_llm._ldr_research_id == "res-alice"
+ assert _written(writer) == [("alice", "res-alice")]
+ # The call's config carried the callback through that layer; the
+ # model itself was left as it was.
+ assert not alice.base_llm.base_llm.callbacks
+
+ @pytest.mark.parametrize(
+ "path",
+ [
+ "ainvoke",
+ "stream",
+ "astream",
+ "batch",
+ "bind_tools",
+ "with_structured_output",
+ "bind",
+ "with_config",
+ ],
+ )
+ def test_every_call_path_writes_one_row_for_its_own_research(self, path):
+ model = _ToolCallingFake(responses=["ok"])
+ bob = _wrap_for(model, "res-bob", "bob")
+ tool = {
+ "type": "function",
+ "function": {
+ "name": "lookup",
+ "parameters": {"type": "object", "properties": {}},
+ },
+ }
+ schema = {
+ "title": "Answer",
+ "type": "object",
+ "properties": {"text": {"type": "string"}},
+ }
+
+ async def _astream():
+ return [chunk async for chunk in bob.astream("hi")]
+
+ calls = {
+ "ainvoke": lambda: asyncio.run(bob.ainvoke("hi")),
+ "stream": lambda: list(bob.stream("hi")),
+ "astream": lambda: asyncio.run(_astream()),
+ "batch": lambda: bob.batch(["hi"]),
+ "bind_tools": lambda: bob.bind_tools([tool]).invoke("hi"),
+ "with_structured_output": lambda: bob.with_structured_output(
+ schema
+ ).invoke("hi"),
+ "bind": lambda: bob.bind(stop=["never"]).invoke("hi"),
+ "with_config": lambda: bob.with_config(run_name="bob").invoke("hi"),
+ }
+ writer = MagicMock()
+ with patch(_METRICS_WRITER, writer):
+ _run_in_worker_thread(calls[path])
+
+ assert _written(writer) == [("bob", "res-bob")]
+ assert not model.callbacks
+ assert getattr(model, "_ldr_research_id", None) is None
+
+ def test_callbacks_of_an_enclosing_run_still_see_the_model_call(self):
+ """The research callback joins the config the model would inherit
+ (from a LangGraph node, say). It must not replace that config."""
+ outer = _Recorder()
+ alice = _wrap_for(
+ FakeListChatModel(responses=["a"]), "res-alice", "alice"
+ )
+ chain = RunnableLambda(lambda text: alice.invoke(text))
+ writer = MagicMock()
+ with patch(_METRICS_WRITER, writer):
+ _run_in_worker_thread(
+ lambda: chain.invoke("hi", {"callbacks": [outer]})
+ )
+
+ assert (outer.started, outer.completed) == (1, 1)
+ assert _written(writer) == [("alice", "res-alice")]
+
+ def test_with_config_keeps_the_callbacks_it_binds(self):
+ """``with_config(callbacks=...)`` re-wraps; the bound callbacks and
+ the research callback both see the model call."""
+ bound = _Recorder()
+ alice = _wrap_for(
+ FakeListChatModel(responses=["a"]), "res-alice", "alice"
+ )
+ configured = alice.with_config(callbacks=[bound])
+ writer = MagicMock()
+ with patch(_METRICS_WRITER, writer):
+ _run_in_worker_thread(lambda: configured.invoke("hi"))
+
+ assert (bound.started, bound.completed) == (1, 1)
+ assert _written(writer) == [("alice", "res-alice")]
+
+ def test_an_agent_without_tools_runs_the_model_through_bind(self):
+ """``create_agent()`` calls ``model.bind(...)`` when the agent has no
+ tools, and runs what it returns. That model call must still strip
+ ``<think>`` tags and record the research's token usage, as the
+ ``bind_tools`` path does for an agent with tools."""
+ from langchain.agents import create_agent
+
+ model = FakeListChatModel(responses=["<think>plan</think>answer"])
+ alice = _wrap_for(model, "res-alice", "alice")
+ agent = create_agent(model=alice, tools=[])
+ writer = MagicMock()
+ with patch(_METRICS_WRITER, writer):
+ result = _run_in_worker_thread(
+ lambda: agent.invoke(
+ {"messages": [{"role": "user", "content": "hi"}]}
+ )
+ )
+
+ assert result["messages"][-1].content == "answer"
+ assert _written(writer) == [("alice", "res-alice")]
+ assert not model.callbacks
+
+ @pytest.mark.parametrize(
+ "owns_llm", [True, False], ids=["owned", "registered"]
+ )
+ def test_the_cancellation_scope_stays_on_the_wrappers(self, owns_llm):
+ inner = FakeListChatModel(responses=["inner"])
+ model = _DelegatingFake(responses=["outer"], base_llm=inner)
+ wrapped = _wrap_for(model, "res-alice", "alice", owns_llm=owns_llm)
+
+ assert wrapped._ldr_research_id == "res-alice"
+ assert getattr(model, "_ldr_research_id", None) is None
+ assert getattr(inner, "_ldr_research_id", None) is None
+
def test_a_second_users_call_does_not_write_under_the_first_user(self):
writer = MagicMock()
shared = FakeListChatModel(responses=["a", "b", "c", "d"])
@@ -924,6 +1384,52 @@ class TestTokenCallbackOwnership:
call.args[:2] for call in writer.write_token_metrics.mock_calls
]
assert written == [("bob", "res-bob")]
+ assert not shared.callbacks
+ assert getattr(shared, "_ldr_research_id", None) is None
+
+ def test_unscoped_call_does_not_reuse_an_earlier_research_callback(self):
+ writer = MagicMock()
+ shared = FakeListChatModel(responses=["a", "b"])
+
+ _wrap_for(shared, "res-alice", "alice")
+ unscoped = _wrap_for(shared, None, "bob")
+
+ with patch(
+ "local_deep_research.database.thread_metrics.metrics_writer",
+ writer,
+ ):
+ _run_in_worker_thread(lambda: unscoped.invoke("hi"))
+
+ writer.write_token_metrics.assert_not_called()
+ assert not shared.callbacks
+
+ def test_registered_callback_manager_keeps_its_handlers(self):
+ class Recorder(BaseCallbackHandler):
+ def __init__(self):
+ self.completed = 0
+
+ def on_llm_end(self, response, **kwargs):
+ self.completed += 1
+
+ user_handler = Recorder()
+ manager = CallbackManager([user_handler])
+ shared = FakeListChatModel(responses=["a", "b"], callbacks=manager)
+ alice = _wrap_for(shared, "res-alice", "alice")
+ bob = _wrap_for(shared, "res-bob", "bob")
+ writer = MagicMock()
+
+ with patch(
+ "local_deep_research.database.thread_metrics.metrics_writer",
+ writer,
+ ):
+ _run_in_worker_thread(lambda: alice.invoke("first"))
+ _run_in_worker_thread(lambda: bob.invoke("second"))
+
+ assert user_handler.completed == 2
+ assert manager.handlers == [user_handler]
+ assert [
+ call.args[:2] for call in writer.write_token_metrics.mock_calls
+ ] == [("alice", "res-alice"), ("bob", "res-bob")]
def test_no_callback_is_attached_without_a_research_id(self):
"""Metrics are opt-in per research: no research_id, no listener on
@@ -932,3 +1438,235 @@ class TestTokenCallbackOwnership:
_wrap_for(shared, None, "alice")
assert not shared.callbacks
+
+ @pytest.mark.parametrize("path", ["invoke", "stream"])
+ @pytest.mark.parametrize(
+ "call_config",
+ [None, {"metadata": {"k": "call"}}],
+ ids=["no-config", "explicit-config"],
+ )
+ def test_with_config_resolves_as_in_langchain_inside_an_enclosing_run(
+ self, path, call_config
+ ):
+ """Called without a config inside an enclosing run, a binding's
+ bound config wins over the one the call inherits; called with one,
+ the call's config is merged over it. Adding the research callback
+ must leave every key as ``model.with_config(...)`` resolves it."""
+ bound = {
+ "metadata": {"k": "bound"},
+ "configurable": {"c": "bound"},
+ "recursion_limit": 55,
+ }
+ enclosing = {
+ "metadata": {"k": "outer"},
+ "configurable": {"c": "outer"},
+ "recursion_limit": 77,
+ }
+ args = ("hi",) if call_config is None else ("hi", call_config)
+
+ def call(runnable):
+ if path == "stream":
+ return lambda _: list(runnable.stream(*args))
+ return lambda _: runnable.invoke(*args)
+
+ def resolved(model):
+ config = model.received[-1]
+ return (
+ config["metadata"]["k"],
+ config["configurable"]["c"],
+ config["recursion_limit"],
+ )
+
+ plain = _ConfigRecorder(responses=["a"])
+ RunnableLambda(call(plain.with_config(**bound))).invoke("x", enclosing)
+ model = _ConfigRecorder(responses=["a"])
+ alice = _wrap_for(model, "res-alice", "alice").with_config(**bound)
+ writer = MagicMock()
+ with patch(_METRICS_WRITER, writer):
+ _run_in_worker_thread(
+ lambda: RunnableLambda(call(alice)).invoke("x", enclosing)
+ )
+
+ if call_config is None:
+ # Positive control: LangChain's own precedence for a binding.
+ assert resolved(plain) == ("bound", "bound", 55)
+ assert resolved(model) == resolved(plain)
+ assert _written(writer) == [("alice", "res-alice")]
+
+ @pytest.mark.parametrize("returned", ["binding", "chain"])
+ def test_a_tool_bound_model_records_each_call_once(self, returned):
+ """``bind_tools`` usually returns a ``RunnableBinding``, which hands
+ the call's config to the model's own run. A custom model can return
+ a chain instead, which runs the model as a child run. Either way
+ each call writes one row."""
+ fake = _ToolCallingFake if returned == "binding" else _ChainToolFake
+ alice = _wrap_for(fake(responses=["ok"]), "res-alice", "alice")
+ bound = alice.bind_tools([_LOOKUP_TOOL])
+ writer = MagicMock()
+ with patch(_METRICS_WRITER, writer):
+ _run_in_worker_thread(lambda: bound.invoke("hi"))
+ _run_in_worker_thread(lambda: list(bound.stream("hi")))
+
+ assert _written(writer) == [("alice", "res-alice")] * 2
+
+ @pytest.mark.parametrize("returned", ["binding", "chain"])
+ def test_an_agent_with_tools_records_its_model_call_once(self, returned):
+ """``create_agent()`` runs what the model's ``bind_tools`` returns,
+ whether that is a ``RunnableBinding`` or a chain."""
+ from langchain.agents import create_agent
+ from langchain_core.tools import tool
+
+ @tool
+ def lookup(query: str) -> str:
+ """Look a query up."""
+ return "found"
+
+ fake = _ToolCallingFake if returned == "binding" else _ChainToolFake
+ model = fake(responses=["<think>plan</think>answer"])
+ agent = create_agent(
+ model=_wrap_for(model, "res-alice", "alice"), tools=[lookup]
+ )
+ writer = MagicMock()
+ with patch(_METRICS_WRITER, writer):
+ result = _run_in_worker_thread(
+ lambda: agent.invoke(
+ {"messages": [{"role": "user", "content": "hi"}]}
+ )
+ )
+
+ assert result["messages"][-1].content == "answer"
+ assert _written(writer) == [("alice", "res-alice")]
+ assert not model.callbacks
+
+ def test_a_model_running_an_inner_model_records_one_row(self):
+ """A model can answer by running another model as a child of its own
+ run, as a router does. Like the model's own ``callbacks``, the
+ research callback sees only the model's own run, so one call writes
+ one row, not one per model."""
+ inner = FakeListChatModel(responses=["inner answer"])
+ model = _NestingFake(
+ responses=["unused"], inner=inner, disable_streaming=True
+ )
+ alice = _wrap_for(model, "res-alice", "alice")
+ writer = MagicMock()
+ with patch(_METRICS_WRITER, writer):
+ reply = _run_in_worker_thread(lambda: alice.invoke("hi"))
+
+ # Positive control: the inner model produced the answer.
+ assert reply.content == "inner answer"
+ assert _written(writer) == [("alice", "res-alice")]
+
+
+class TestModelOwnership:
+ """LDR closes only the models that its built-in providers build.
+
+ When a research ends, ``safe_close(system.model)`` in
+ ``api/research_functions.py`` closes its LLM. A built-in provider
+ builds a new model on every ``get_llm()`` call, so that releases only
+ this research's clients. A registered instance, or a model that a
+ registered factory returns, can serve other researches at the same
+ time, because a factory can return one cached or singleton model.
+ """
+
+ def test_a_built_in_provider_model_is_closed_when_its_research_ends(
+ self,
+ ):
+ from local_deep_research.utilities.resource_utils import safe_close
+
+ url = {"llm.ollama.url": "http://127.0.0.1:11434"}
+ alice = _get_llm_for("ollama", "alice", **url)
+ bob = _get_llm_for("ollama", "bob", **url)
+ model = alice.base_llm
+ try:
+ # Positive controls: a real client, and one per research.
+ assert type(model).__name__ == "ChatOllama"
+ assert bob.base_llm is not model
+
+ safe_close(alice, "system LLM")
+
+ assert model._client._client.is_closed
+ assert model._async_client._client.is_closed
+ assert not bob.base_llm._client._client.is_closed
+ finally:
+ safe_close(bob, "system LLM")
+
+ @pytest.mark.parametrize(
+ "registration",
+ ["instance", "singleton factory", "lru_cache factory", "new per call"],
+ )
+ def test_ldr_never_closes_a_registered_model(self, registration):
+ """Ending Alice's research must leave Bob's research able to use
+ the model. LDR cannot tell a factory that returns one model from
+ one that builds a new model per call, so it closes neither."""
+ from local_deep_research.utilities.resource_utils import safe_close
+
+ built = []
+
+ def build():
+ model = _ClosableModel(responses=["a", "b"])
+ built.append(model)
+ return model
+
+ if registration == "instance":
+ registered = build()
+ elif registration == "singleton factory":
+ singleton = build()
+
+ def registered(model_name, temperature, settings_snapshot):
+ return singleton
+
+ elif registration == "lru_cache factory":
+
+ @functools.lru_cache(maxsize=None)
+ def cached_build(model_name, temperature):
+ return build()
+
+ def registered(model_name, temperature, settings_snapshot):
+ return cached_build(model_name, temperature)
+
+ else:
+
+ def registered(model_name, temperature, settings_snapshot):
+ return build()
+
+ provider = "registered-model-ownership-test"
+ with _registered(provider, registered):
+ alice = _get_llm_for(provider, "alice")
+ bob = _get_llm_for(provider, "bob")
+ writer = MagicMock()
+ with patch(_METRICS_WRITER, writer):
+ safe_close(alice, "system LLM")
+ reply = _run_in_worker_thread(lambda: bob.invoke("hi"))
+
+ assert len(built) == (2 if registration == "new per call" else 1)
+ assert reply.content == "a"
+ assert not any(model.closed for model in built)
+
+ def test_only_built_in_provider_factories_count_as_built_in(self):
+ from local_deep_research.llm import get_llm_from_registry
+ from local_deep_research.llm.providers.auto_discovery import (
+ is_builtin_provider_factory,
+ )
+ from local_deep_research.llm.providers.implementations.ollama import (
+ OllamaProvider,
+ )
+
+ discovered = discover_providers()
+ assert discovered
+ for key in discovered:
+ registered = get_llm_from_registry(normalize_provider(key))
+ assert is_builtin_provider_factory(registered), key
+
+ class CachingOllamaProvider(OllamaProvider):
+ """A user's subclass, defined outside LDR's providers."""
+
+ def factory(model_name, temperature, settings_snapshot):
+ return FakeListChatModel(responses=["a"])
+
+ assert not is_builtin_provider_factory(CachingOllamaProvider.create_llm)
+ assert not is_builtin_provider_factory(OllamaProvider.is_available)
+ assert not is_builtin_provider_factory(factory)
+ assert not is_builtin_provider_factory(MagicMock())
+ assert not is_builtin_provider_factory(
+ FakeListChatModel(responses=["a"])
+ )