Runnable 组件生命周期监听器与使用场景
Runnable 生命周期监听器
1.1 监听机制演进
在 LangChain
框架中,Runnable
组件提供两种监控方案:
- 传统模式:通过
config
+callbacks
参数传递回调配置 - 增强模式:使用
with_listeners()
方法实现生命周期订阅
# 新旧方案对比调用
chain = my_chain.with_listeners(...) # 现代方案
chain = my_chain(config=..., callbacks=...) # 传统方案
1.2 事件订阅接口
with_listeners
参数规范
def lifecycle_handler(run_obj: Run, # 运行时上下文对象config: RunnableConfig # 执行配置快照
) -> None:""" 标准化事件处理函数 """
- 🔗 官方文档参考
- 💡大模型中转API推荐
- ✨中转使用教程
1.3 运行时元数据解析
元数据字段 | 类型 | 描述 |
---|---|---|
run_id | UUID | 全局唯一执行标识符 |
run_type | str | 组件类型 (chain/llm/tool) |
start_time | datetime | 事件触发时间戳(UTC标准) |
inputs | Dict[str, Any] | 结构化输入参数(自动序列化) |
error | Optional[Exception] | 异常堆栈信息(仅错误事件触发) |
1.4 示例代码
import timefrom langchain_core.runnables import RunnableLambda, RunnableConfig
from langchain_core.tracers.schemas import Rundef on_start(run_obj: Run, config: RunnableConfig) -> None:print("on_start")print("run_obj:", run_obj.inputs)print("config:", config)print("========================")def on_end(run_obj: Run, config: RunnableConfig) -> None:print("on_end")print("run_obj:", run_obj)print("config:", config)print("========================")def on_error(run_obj: Run, config: RunnableConfig) -> None:print("on_error")print("run_obj:", run_obj)print("config:", config)print("========================")runnable = RunnableLambda(lambda x: time.sleep(x))
chain = runnable.with_listeners(on_start=on_start, on_end=on_end, on_error=on_error)chain.invoke(2)
输出内容:
on_start
run_obj: {'input': 2}
config: {'configurable': {'name': 'xxx'}}
========================
on_end
run_obj: id=UUID('3479d7ab-3bc7-4c4c-9db9-aaaff0c1fd04') name='RunnableLambda' start_time=datetime.datetime(2024, 7, 6, 9, 24, 52, 820817, tzinfo=datetime.timezone.utc) run_type='chain' end_time=datetime.datetime(2024, 7, 6, 9, 24, 54, 821575, tzinfo=datetime.timezone.utc) extra={'metadata': {'name': 'xxx'}} error=None serialized={'lc': 1, 'type': 'not_implemented', 'id': ['langchain_core', 'runnables', 'base', 'RunnableLambda'], 'repr': 'RunnableLambda(lambda x: time.sleep(x))'} events=[{'name': 'start', 'time': datetime.datetime(2024, 7, 6, 9, 24, 52, 820817, tzinfo=datetime.timezone.utc)}, {'name': 'end', 'time': datetime.datetime(2024, 7, 6, 9, 24, 54, 821575, tzinfo=datetime.timezone.utc)}] inputs={'input': 2} outputs={'output': None} reference_example_id=None parent_run_id=None tags=[] child_runs=[] trace_id=UUID('3479d7ab-3bc7-4c4c-9db9-aaaff0c1fd04') dotted_order='20240706T092452820817Z3479d7ab-3bc7-4c4c-9db9-aaaff0c1fd04'
config: {'configurable': {'name': 'xxx'}}
========================
1.5. 资料推荐
- 🔗 官方文档参考
- 💡大模型中转API推荐
- ✨中转使用教程
🔥 核心优势
with_listeners 相比传统回调方案具备:
统一的事件参数签名
自动化的上下文注入
非侵入式的监控接入