fix(core): honor enabled=false in nested tracing (#31986)

Co-authored-by: Mason Daugherty <mason@langchain.dev>
Co-authored-by: Mason Daugherty <github@mdrxy.com>
This commit is contained in:
William FH
2025-09-09 13:12:17 -07:00
committed by GitHub
parent a35ee49f37
commit f1d44d0f9d
2 changed files with 14 additions and 3 deletions

View File

@@ -8,7 +8,7 @@ from datetime import datetime, timezone
from typing import TYPE_CHECKING, Any, Optional, Union from typing import TYPE_CHECKING, Any, Optional, Union
from uuid import UUID from uuid import UUID
from langsmith import Client from langsmith import Client, get_tracing_context
from langsmith import run_trees as rt from langsmith import run_trees as rt
from langsmith import utils as ls_utils from langsmith import utils as ls_utils
from tenacity import ( from tenacity import (
@@ -113,6 +113,8 @@ class LangChainTracer(BaseTracer):
super()._start_trace(run) super()._start_trace(run)
if run.ls_client is None: if run.ls_client is None:
run.ls_client = self.client run.ls_client = self.client
if get_tracing_context().get("enabled") is False:
run.extra["__disabled"] = True
def on_chat_model_start( def on_chat_model_start(
self, self,
@@ -205,6 +207,8 @@ class LangChainTracer(BaseTracer):
def _persist_run_single(self, run: Run) -> None: def _persist_run_single(self, run: Run) -> None:
"""Persist a run.""" """Persist a run."""
if run.extra.get("__disabled"):
return
try: try:
run.extra["runtime"] = get_runtime_environment() run.extra["runtime"] = get_runtime_environment()
run.tags = self._get_tags(run) run.tags = self._get_tags(run)
@@ -218,6 +222,8 @@ class LangChainTracer(BaseTracer):
def _update_run_single(self, run: Run) -> None: def _update_run_single(self, run: Run) -> None:
"""Update a run.""" """Update a run."""
if run.extra.get("__disabled"):
return
try: try:
run.patch(exclude_inputs=run.extra.get("inputs_is_truthy", False)) run.patch(exclude_inputs=run.extra.get("inputs_is_truthy", False))
except Exception as e: except Exception as e:

View File

@@ -57,15 +57,20 @@ def test_tracing_context() -> None:
) )
@RunnableLambda @RunnableLambda
def my_function(a: int) -> int: def my_lambda(a: int) -> int:
return a + 1 return a + 1
@RunnableLambda
def my_function(a: int) -> int:
with tracing_context(enabled=False):
return my_lambda.invoke(a)
name = uuid.uuid4().hex name = uuid.uuid4().hex
project_name = f"Some project {name}" project_name = f"Some project {name}"
with tracing_context(project_name=project_name, client=mock_client_, enabled=True): with tracing_context(project_name=project_name, client=mock_client_, enabled=True):
assert my_function.invoke(1) == 2 assert my_function.invoke(1) == 2
posts = _get_posts(mock_client_) posts = _get_posts(mock_client_)
assert posts assert len(posts) == 1
assert all(post["session_name"] == project_name for post in posts) assert all(post["session_name"] == project_name for post in posts)