Python
以下概述了使用 python 构建时”拆分”跟踪的常见原因。使用 asyncio 进行上下文传播
在 Python 版本 < 3.11 中使用异步调用(尤其是流式传输)时,您可能会遇到跟踪嵌套问题。这是因为 Python 的asyncio 仅在版本 3.11 中添加了传递上下文的完整支持。
原因
LangChain 和 LangSmith SDK 使用 contextvars 隐式传播跟踪信息。在 Python 3.11 及更高版本中,这可以无缝工作。但是,在早期版本(3.8、3.9、3.10)中,asyncio 任务缺乏适当的 contextvar 支持,这可能导致断开的跟踪。
解决方法
- 升级 Python 版本(推荐) 如果可能,升级到 Python 3.11 或更高版本以实现自动上下文传播。
-
手动上下文传播 如果升级不是选项,您需要手动传播跟踪上下文。方法因您的设置而异:
a) 使用 LangGraph 或 LangChain 将父
config传递给子调用:b) 直接使用 LangSmith 直接传递运行树:c) Combining Decorated Code with LangGraph/LangChain Use a combination of techniques for manual handoff:
Context propagation using threading
It’s common to start tracing and want to apply some parallelism on child tasks all within a single trace. Python’s stdlibThreadPoolExecutor by default breaks tracing.
Why
Python’s contextvars start empty within new threads. Here are two approaches to handle maintain trace contiguity:To resolve
-
Using LangSmith’s ContextThreadPoolExecutor
LangSmith provides a
ContextThreadPoolExecutorthat automatically handles context propagation: -
Manually providing the parent run tree
Alternatively, you can manually pass the parent run tree to the inner function:
get_current_run_tree() to obtain the current run tree and pass it to the inner function using the langsmith_extra parameter.
Both methods ensure that the inner function calls are correctly aggregated under the initial trace stack, even when executed in separate threads.