From ce84f8ba7e14fc373e0ec410a062ac70d7032088 Mon Sep 17 00:00:00 2001 From: William FH <13333726+hinthornw@users.noreply.github.com> Date: Wed, 19 Mar 2025 12:05:06 -0700 Subject: [PATCH] Dereference run tree (#30377) --- libs/core/langchain_core/tracers/langchain.py | 8 +++++++- .../unit_tests/runnables/test_tracing_interops.py | 14 ++++++++------ 2 files changed, 15 insertions(+), 7 deletions(-) diff --git a/libs/core/langchain_core/tracers/langchain.py b/libs/core/langchain_core/tracers/langchain.py index 8a14ce1fc6e..9fdc76d9436 100644 --- a/libs/core/langchain_core/tracers/langchain.py +++ b/libs/core/langchain_core/tracers/langchain.py @@ -173,7 +173,13 @@ class LangChainTracer(BaseTracer): return chat_model_run def _persist_run(self, run: Run) -> None: - self.latest_run = run + # We want to free up more memory by avoiding keeping a reference to the + # whole nested run tree. + self.latest_run = Run.construct( + **run.dict(exclude={"child_runs", "inputs", "outputs"}), + inputs=run.inputs, + outputs=run.outputs, + ) def get_run_url(self) -> str: """Get the LangSmith root run URL. diff --git a/libs/core/tests/unit_tests/runnables/test_tracing_interops.py b/libs/core/tests/unit_tests/runnables/test_tracing_interops.py index d3635cb878f..fc99fbd0d56 100644 --- a/libs/core/tests/unit_tests/runnables/test_tracing_interops.py +++ b/libs/core/tests/unit_tests/runnables/test_tracing_interops.py @@ -445,11 +445,12 @@ def test_tree_is_constructed(parent_type: Literal["ls", "lc"]) -> None: metadata={"some_foo": "some_bar"}, tags=["afoo"], ): - if parent_type == "ls": - collected: dict[str, RunTree] = {} # noqa + collected: dict[str, RunTree] = {} # noqa - def collect_run(run: RunTree) -> None: - collected[str(run.id)] = run + def collect_run(run: RunTree) -> None: + collected[str(run.id)] = run + + if parent_type == "ls": @traceable def parent() -> str: @@ -459,7 +460,6 @@ def test_tree_is_constructed(parent_type: Literal["ls", "lc"]) -> None: parent(langsmith_extra={"on_end": collect_run, "run_id": rid}) == "foo" ) assert collected - run = collected.get(str(rid)) else: @@ -468,8 +468,10 @@ def test_tree_is_constructed(parent_type: Literal["ls", "lc"]) -> None: return child.invoke("foo") tracer = LangChainTracer() + tracer._persist_run = collect_run # type: ignore + assert parent.invoke(..., {"run_id": rid, "callbacks": [tracer]}) == "foo" # type: ignore - run = tracer.latest_run + run = collected.get(str(rid)) assert run is not None assert run.name == "parent"