WithListeners
Author: Donghak Lee
Peer Review:
Proofread : Q0211
This is a part of LangChain Open Tutorial
Overview
This tutorial covers the implementation and usage of with_listeners() in Runnable.
with_listeners() binds lifecycle listeners to a Runnable, returning a new Runnable. This allows you to connect event listeners to the data flow, enabling tracking, analysis, and debugging during execution.
The with_listeners() function provides the ability to add event listeners to a Runnable object. Listeners are functions that are called when specific events occur, such as start, end, or error.
This function is useful in the following scenarios:
Logging the start and end of data processing
Triggering notifications on errors
Printing debugging information
Table of Contents
References
Environment Setup
Set up the environment. You may refer to Environment Setup for more details.
[Note]
langchain-opentutorialis a package that provides a set of easy-to-use environment setup, useful functions and utilities for tutorials.You can check out the
langchain-opentutorialfor more details.
You can alternatively set API keys such as OPENAI_API_KEY in a .env file and load them.
[Note] This is not necessary if you've already set the required API keys in previous steps.
with_listeners
with_listeners() takes a list of listener functions and returns a new Runnable object. Listener functions respond to start, end, and error events.
Using event listeners allows you to observe the data flow, and you can flexibly register them using with_listeners().
Here is an example implementation of the function.
You can also register events in the chain of LCEL using with_listeners().
with_alisteners
Bind asynchronous lifecycle listeners to a Runnable, returning a new Runnable.
on_start: Asynchronously called before the Runnable starts running. on_end: Asynchronously called after the Runnable finishes running. on_error: Asynchronously called if the Runnable throws an error.
The Run object contains information about the run, including its id, type, input, output, error, start_time, end_time, and any tags or metadata added to the run.
RootListenersTracer
You can directly bind RootListenersTracer to a Runnable using RunnableBinding to register event listeners. This is the internal code of with_listeners().
RootListenersTracer calls listeners on run start, end, and error.
Using tracers without LCEL
You can directly use on_llm_start() and on_llm_end() of RootListenersTracer to handle events.
Last updated