*   [](/v0.2/)
*   [How-to guides](/v0.2/docs/how_to/)
*   LangChain Expression Language Cheatsheet

On this page

LangChain Expression Language Cheatsheet
========================================

This is a quick reference for all the most important LCEL primitives. For more advanced usage see the [LCEL how-to guides](/v0.2/docs/how_to/#langchain-expression-language-lcel) and the [full API reference](https://api.python.langchain.com/en/latest/runnables/langchain_core.runnables.base.Runnable.html).

### Invoke a runnable[​](#invoke-a-runnable "Direct link to Invoke a runnable")

#### [Runnable.invoke()](https://api.python.langchain.com/en/latest/runnables/langchain_core.runnables.base.Runnable.html#langchain_core.runnables.base.Runnable.invoke) / [Runnable.ainvoke()](https://api.python.langchain.com/en/latest/runnables/langchain_core.runnables.base.Runnable.html#langchain_core.runnables.base.Runnable.ainvoke)[​](#runnableinvoke--runnableainvoke "Direct link to runnableinvoke--runnableainvoke")

    from langchain_core.runnables import RunnableLambdarunnable = RunnableLambda(lambda x: str(x))runnable.invoke(5)# Async variant:# await runnable.ainvoke(5)

**API Reference:**[RunnableLambda](https://api.python.langchain.com/en/latest/runnables/langchain_core.runnables.base.RunnableLambda.html)

    '5'

### Batch a runnable[​](#batch-a-runnable "Direct link to Batch a runnable")

#### [Runnable.batch()](https://api.python.langchain.com/en/latest/runnables/langchain_core.runnables.base.Runnable.html#langchain_core.runnables.base.Runnable.batch) / [Runnable.abatch()](https://api.python.langchain.com/en/latest/runnables/langchain_core.runnables.base.Runnable.html#langchain_core.runnables.base.Runnable.abatch)[​](#runnablebatch--runnableabatch "Direct link to runnablebatch--runnableabatch")

    from langchain_core.runnables import RunnableLambdarunnable = RunnableLambda(lambda x: str(x))runnable.batch([7, 8, 9])# Async variant:# await runnable.abatch([7, 8, 9])

**API Reference:**[RunnableLambda](https://api.python.langchain.com/en/latest/runnables/langchain_core.runnables.base.RunnableLambda.html)

    ['7', '8', '9']

### Stream a runnable[​](#stream-a-runnable "Direct link to Stream a runnable")

#### [Runnable.stream()](https://api.python.langchain.com/en/latest/runnables/langchain_core.runnables.base.Runnable.html#langchain_core.runnables.base.Runnable.stream) / [Runnable.astream()](https://api.python.langchain.com/en/latest/runnables/langchain_core.runnables.base.Runnable.html#langchain_core.runnables.base.Runnable.astream)[​](#runnablestream--runnableastream "Direct link to runnablestream--runnableastream")

    from langchain_core.runnables import RunnableLambdadef func(x):    for y in x:        yield str(y)runnable = RunnableLambda(func)for chunk in runnable.stream(range(5)):    print(chunk)# Async variant:# async for chunk in await runnable.astream(range(5)):#     print(chunk)

**API Reference:**[RunnableLambda](https://api.python.langchain.com/en/latest/runnables/langchain_core.runnables.base.RunnableLambda.html)

    01234

### Compose runnables[​](#compose-runnables "Direct link to Compose runnables")

#### Pipe operator `|`[​](#pipe-operator- "Direct link to pipe-operator-")

    from langchain_core.runnables import RunnableLambdarunnable1 = RunnableLambda(lambda x: {"foo": x})runnable2 = RunnableLambda(lambda x: [x] * 2)chain = runnable1 | runnable2chain.invoke(2)

**API Reference:**[RunnableLambda](https://api.python.langchain.com/en/latest/runnables/langchain_core.runnables.base.RunnableLambda.html)

    [{'foo': 2}, {'foo': 2}]

### Invoke runnables in parallel[​](#invoke-runnables-in-parallel "Direct link to Invoke runnables in parallel")

#### [RunnableParallel](https://api.python.langchain.com/en/latest/runnables/langchain_core.runnables.base.RunnableParallel.html)[​](#runnableparallel "Direct link to runnableparallel")

    from langchain_core.runnables import RunnableLambda, RunnableParallelrunnable1 = RunnableLambda(lambda x: {"foo": x})runnable2 = RunnableLambda(lambda x: [x] * 2)chain = RunnableParallel(first=runnable1, second=runnable2)chain.invoke(2)

**API Reference:**[RunnableLambda](https://api.python.langchain.com/en/latest/runnables/langchain_core.runnables.base.RunnableLambda.html) | [RunnableParallel](https://api.python.langchain.com/en/latest/runnables/langchain_core.runnables.base.RunnableParallel.html)

    {'first': {'foo': 2}, 'second': [2, 2]}

### Turn any function into a runnable[​](#turn-any-function-into-a-runnable "Direct link to Turn any function into a runnable")

#### [RunnableLambda](https://api.python.langchain.com/en/latest/runnables/langchain_core.runnables.base.RunnableLambda.html)[​](#runnablelambda "Direct link to runnablelambda")

    from langchain_core.runnables import RunnableLambdadef func(x):    return x + 5runnable = RunnableLambda(func)runnable.invoke(2)

**API Reference:**[RunnableLambda](https://api.python.langchain.com/en/latest/runnables/langchain_core.runnables.base.RunnableLambda.html)

    7

### Merge input and output dicts[​](#merge-input-and-output-dicts "Direct link to Merge input and output dicts")

#### [RunnablePassthrough.assign](https://api.python.langchain.com/en/latest/runnables/langchain_core.runnables.passthrough.RunnablePassthrough.html)[​](#runnablepassthroughassign "Direct link to runnablepassthroughassign")

    from langchain_core.runnables import RunnableLambda, RunnablePassthroughrunnable1 = RunnableLambda(lambda x: x["foo"] + 7)chain = RunnablePassthrough.assign(bar=runnable1)chain.invoke({"foo": 10})

**API Reference:**[RunnableLambda](https://api.python.langchain.com/en/latest/runnables/langchain_core.runnables.base.RunnableLambda.html) | [RunnablePassthrough](https://api.python.langchain.com/en/latest/runnables/langchain_core.runnables.passthrough.RunnablePassthrough.html)

    {'foo': 10, 'bar': 17}

### Include input dict in output dict[​](#include-input-dict-in-output-dict "Direct link to Include input dict in output dict")

#### [RunnablePassthrough](https://api.python.langchain.com/en/latest/runnables/langchain_core.runnables.passthrough.RunnablePassthrough.html)[​](#runnablepassthrough "Direct link to runnablepassthrough")

    from langchain_core.runnables import (    RunnableLambda,    RunnableParallel,    RunnablePassthrough,)runnable1 = RunnableLambda(lambda x: x["foo"] + 7)chain = RunnableParallel(bar=runnable1, baz=RunnablePassthrough())chain.invoke({"foo": 10})

**API Reference:**[RunnableLambda](https://api.python.langchain.com/en/latest/runnables/langchain_core.runnables.base.RunnableLambda.html) | [RunnableParallel](https://api.python.langchain.com/en/latest/runnables/langchain_core.runnables.base.RunnableParallel.html) | [RunnablePassthrough](https://api.python.langchain.com/en/latest/runnables/langchain_core.runnables.passthrough.RunnablePassthrough.html)

    {'bar': 17, 'baz': {'foo': 10}}

### Add default invocation args[​](#add-default-invocation-args "Direct link to Add default invocation args")

#### [Runnable.bind](https://api.python.langchain.com/en/latest/runnables/langchain_core.runnables.base.Runnable.html#langchain_core.runnables.base.Runnable.bind)[​](#runnablebind "Direct link to runnablebind")

    from typing import Optionalfrom langchain_core.runnables import RunnableLambdadef func(main_arg: dict, other_arg: Optional[str] = None) -> dict:    if other_arg:        return {**main_arg, **{"foo": other_arg}}    return main_argrunnable1 = RunnableLambda(func)bound_runnable1 = runnable1.bind(other_arg="bye")bound_runnable1.invoke({"bar": "hello"})

**API Reference:**[RunnableLambda](https://api.python.langchain.com/en/latest/runnables/langchain_core.runnables.base.RunnableLambda.html)

    {'bar': 'hello', 'foo': 'bye'}

### Add fallbacks[​](#add-fallbacks "Direct link to Add fallbacks")

#### [Runnable.with\_fallbacks](https://api.python.langchain.com/en/latest/runnables/langchain_core.runnables.base.Runnable.html#langchain_core.runnables.base.Runnable.with_fallbacks)[​](#runnablewith_fallbacks "Direct link to runnablewith_fallbacks")

    from langchain_core.runnables import RunnableLambdarunnable1 = RunnableLambda(lambda x: x + "foo")runnable2 = RunnableLambda(lambda x: str(x) + "foo")chain = runnable1.with_fallbacks([runnable2])chain.invoke(5)

**API Reference:**[RunnableLambda](https://api.python.langchain.com/en/latest/runnables/langchain_core.runnables.base.RunnableLambda.html)

    '5foo'

### Add retries[​](#add-retries "Direct link to Add retries")

#### [Runnable.with\_retry](https://api.python.langchain.com/en/latest/runnables/langchain_core.runnables.base.Runnable.html#langchain_core.runnables.base.Runnable.with_retry)[​](#runnablewith_retry "Direct link to runnablewith_retry")

    from langchain_core.runnables import RunnableLambdacounter = -1def func(x):    global counter    counter += 1    print(f"attempt with {counter=}")    return x / counterchain = RunnableLambda(func).with_retry(stop_after_attempt=2)chain.invoke(2)

**API Reference:**[RunnableLambda](https://api.python.langchain.com/en/latest/runnables/langchain_core.runnables.base.RunnableLambda.html)

    attempt with counter=0attempt with counter=1

    2.0

### Configure runnable execution[​](#configure-runnable-execution "Direct link to Configure runnable execution")

#### [RunnableConfig](https://api.python.langchain.com/en/latest/runnables/langchain_core.runnables.config.RunnableConfig.html)[​](#runnableconfig "Direct link to runnableconfig")

    from langchain_core.runnables import RunnableLambda, RunnableParallelrunnable1 = RunnableLambda(lambda x: {"foo": x})runnable2 = RunnableLambda(lambda x: [x] * 2)runnable3 = RunnableLambda(lambda x: str(x))chain = RunnableParallel(first=runnable1, second=runnable2, third=runnable3)chain.invoke(7, config={"max_concurrency": 2})

**API Reference:**[RunnableLambda](https://api.python.langchain.com/en/latest/runnables/langchain_core.runnables.base.RunnableLambda.html) | [RunnableParallel](https://api.python.langchain.com/en/latest/runnables/langchain_core.runnables.base.RunnableParallel.html)

    {'first': {'foo': 7}, 'second': [7, 7], 'third': '7'}

### Add default config to runnable[​](#add-default-config-to-runnable "Direct link to Add default config to runnable")

#### [Runnable.with\_config](https://api.python.langchain.com/en/latest/runnables/langchain_core.runnables.base.Runnable.html#langchain_core.runnables.base.Runnable.with_config)[​](#runnablewith_config "Direct link to runnablewith_config")

    from langchain_core.runnables import RunnableLambda, RunnableParallelrunnable1 = RunnableLambda(lambda x: {"foo": x})runnable2 = RunnableLambda(lambda x: [x] * 2)runnable3 = RunnableLambda(lambda x: str(x))chain = RunnableParallel(first=runnable1, second=runnable2, third=runnable3)configured_chain = chain.with_config(max_concurrency=2)chain.invoke(7)

**API Reference:**[RunnableLambda](https://api.python.langchain.com/en/latest/runnables/langchain_core.runnables.base.RunnableLambda.html) | [RunnableParallel](https://api.python.langchain.com/en/latest/runnables/langchain_core.runnables.base.RunnableParallel.html)

    {'first': {'foo': 7}, 'second': [7, 7], 'third': '7'}

### Make runnable attributes configurable[​](#make-runnable-attributes-configurable "Direct link to Make runnable attributes configurable")

#### [Runnable.with\_configurable\_fields](https://api.python.langchain.com/en/latest/runnables/langchain_core.runnables.base.RunnableSerializable.html#langchain_core.runnables.base.RunnableSerializable.configurable_fields)[​](#runnablewith_configurable_fields "Direct link to runnablewith_configurable_fields")

    from typing import Any, Optionalfrom langchain_core.runnables import (    ConfigurableField,    RunnableConfig,    RunnableSerializable,)class FooRunnable(RunnableSerializable[dict, dict]):    output_key: str    def invoke(        self, input: Any, config: Optional[RunnableConfig] = None, **kwargs: Any    ) -> list:        return self._call_with_config(self.subtract_seven, input, config, **kwargs)    def subtract_seven(self, input: dict) -> dict:        return {self.output_key: input["foo"] - 7}runnable1 = FooRunnable(output_key="bar")configurable_runnable1 = runnable1.configurable_fields(    output_key=ConfigurableField(id="output_key"))configurable_runnable1.invoke(    {"foo": 10}, config={"configurable": {"output_key": "not bar"}})

**API Reference:**[ConfigurableField](https://api.python.langchain.com/en/latest/runnables/langchain_core.runnables.utils.ConfigurableField.html) | [RunnableConfig](https://api.python.langchain.com/en/latest/runnables/langchain_core.runnables.config.RunnableConfig.html) | [RunnableSerializable](https://api.python.langchain.com/en/latest/runnables/langchain_core.runnables.base.RunnableSerializable.html)

    {'not bar': 3}

    configurable_runnable1.invoke({"foo": 10})

    {'bar': 3}

### Make chain components configurable[​](#make-chain-components-configurable "Direct link to Make chain components configurable")

#### [Runnable.with\_configurable\_alternatives](https://api.python.langchain.com/en/latest/runnables/langchain_core.runnables.base.RunnableSerializable.html#langchain_core.runnables.base.RunnableSerializable.configurable_alternatives)[​](#runnablewith_configurable_alternatives "Direct link to runnablewith_configurable_alternatives")

    from typing import Any, Optionalfrom langchain_core.runnables import RunnableConfig, RunnableLambda, RunnableParallelclass ListRunnable(RunnableSerializable[Any, list]):    def invoke(        self, input: Any, config: Optional[RunnableConfig] = None, **kwargs: Any    ) -> list:        return self._call_with_config(self.listify, input, config, **kwargs)    def listify(self, input: Any) -> list:        return [input]class StrRunnable(RunnableSerializable[Any, str]):    def invoke(        self, input: Any, config: Optional[RunnableConfig] = None, **kwargs: Any    ) -> list:        return self._call_with_config(self.strify, input, config, **kwargs)    def strify(self, input: Any) -> str:        return str(input)runnable1 = RunnableLambda(lambda x: {"foo": x})configurable_runnable = ListRunnable().configurable_alternatives(    ConfigurableField(id="second_step"), default_key="list", string=StrRunnable())chain = runnable1 | configurable_runnablechain.invoke(7, config={"configurable": {"second_step": "string"}})

**API Reference:**[RunnableConfig](https://api.python.langchain.com/en/latest/runnables/langchain_core.runnables.config.RunnableConfig.html) | [RunnableLambda](https://api.python.langchain.com/en/latest/runnables/langchain_core.runnables.base.RunnableLambda.html) | [RunnableParallel](https://api.python.langchain.com/en/latest/runnables/langchain_core.runnables.base.RunnableParallel.html)

    "{'foo': 7}"

    chain.invoke(7)

    [{'foo': 7}]

### Build a chain dynamically based on input[​](#build-a-chain-dynamically-based-on-input "Direct link to Build a chain dynamically based on input")

    from langchain_core.runnables import RunnableLambda, RunnableParallelrunnable1 = RunnableLambda(lambda x: {"foo": x})runnable2 = RunnableLambda(lambda x: [x] * 2)chain = RunnableLambda(lambda x: runnable1 if x > 6 else runnable2)chain.invoke(7)

**API Reference:**[RunnableLambda](https://api.python.langchain.com/en/latest/runnables/langchain_core.runnables.base.RunnableLambda.html) | [RunnableParallel](https://api.python.langchain.com/en/latest/runnables/langchain_core.runnables.base.RunnableParallel.html)

    {'foo': 7}

    chain.invoke(5)

    [5, 5]

### Generate a stream of events[​](#generate-a-stream-of-events "Direct link to Generate a stream of events")

#### [Runnable.astream\_events](https://api.python.langchain.com/en/latest/runnables/langchain_core.runnables.base.Runnable.html#langchain_core.runnables.base.Runnable.astream_events)[​](#runnableastream_events "Direct link to runnableastream_events")

    # | echo: falseimport nest_asyncionest_asyncio.apply()

    from langchain_core.runnables import RunnableLambda, RunnableParallelrunnable1 = RunnableLambda(lambda x: {"foo": x}, name="first")async def func(x):    for _ in range(5):        yield xrunnable2 = RunnableLambda(func, name="second")chain = runnable1 | runnable2async for event in chain.astream_events("bar", version="v2"):    print(f"event={event['event']} | name={event['name']} | data={event['data']}")

**API Reference:**[RunnableLambda](https://api.python.langchain.com/en/latest/runnables/langchain_core.runnables.base.RunnableLambda.html) | [RunnableParallel](https://api.python.langchain.com/en/latest/runnables/langchain_core.runnables.base.RunnableParallel.html)

    event=on_chain_start | name=RunnableSequence | data={'input': 'bar'}event=on_chain_start | name=first | data={}event=on_chain_stream | name=first | data={'chunk': {'foo': 'bar'}}event=on_chain_start | name=second | data={}event=on_chain_end | name=first | data={'output': {'foo': 'bar'}, 'input': 'bar'}event=on_chain_stream | name=second | data={'chunk': {'foo': 'bar'}}event=on_chain_stream | name=RunnableSequence | data={'chunk': {'foo': 'bar'}}event=on_chain_stream | name=second | data={'chunk': {'foo': 'bar'}}event=on_chain_stream | name=RunnableSequence | data={'chunk': {'foo': 'bar'}}event=on_chain_stream | name=second | data={'chunk': {'foo': 'bar'}}event=on_chain_stream | name=RunnableSequence | data={'chunk': {'foo': 'bar'}}event=on_chain_stream | name=second | data={'chunk': {'foo': 'bar'}}event=on_chain_stream | name=RunnableSequence | data={'chunk': {'foo': 'bar'}}event=on_chain_stream | name=second | data={'chunk': {'foo': 'bar'}}event=on_chain_stream | name=RunnableSequence | data={'chunk': {'foo': 'bar'}}event=on_chain_end | name=second | data={'output': {'foo': 'bar'}, 'input': {'foo': 'bar'}}event=on_chain_end | name=RunnableSequence | data={'output': {'foo': 'bar'}}

### Yield batched outputs as they complete[​](#yield-batched-outputs-as-they-complete "Direct link to Yield batched outputs as they complete")

#### [Runnable.batch\_as\_completed](https://api.python.langchain.com/en/latest/runnables/langchain_core.runnables.base.Runnable.html#langchain_core.runnables.base.Runnable.batch_as_completed) / [Runnable.abatch\_as\_completed](https://api.python.langchain.com/en/latest/runnables/langchain_core.runnables.base.Runnable.html#langchain_core.runnables.base.Runnable.abatch_as_completed)[​](#runnablebatch_as_completed--runnableabatch_as_completed "Direct link to runnablebatch_as_completed--runnableabatch_as_completed")

    import timefrom langchain_core.runnables import RunnableLambda, RunnableParallelrunnable1 = RunnableLambda(lambda x: time.sleep(x) or print(f"slept {x}"))for idx, result in runnable1.batch_as_completed([5, 1]):    print(idx, result)# Async variant:# async for idx, result in runnable1.abatch_as_completed([5, 1]):#     print(idx, result)

**API Reference:**[RunnableLambda](https://api.python.langchain.com/en/latest/runnables/langchain_core.runnables.base.RunnableLambda.html) | [RunnableParallel](https://api.python.langchain.com/en/latest/runnables/langchain_core.runnables.base.RunnableParallel.html)

    slept 11 Noneslept 50 None

### Return subset of output dict[​](#return-subset-of-output-dict "Direct link to Return subset of output dict")

#### [Runnable.pick](https://api.python.langchain.com/en/latest/runnables/langchain_core.runnables.base.Runnable.html#langchain_core.runnables.base.Runnable.pick)[​](#runnablepick "Direct link to runnablepick")

    from langchain_core.runnables import RunnableLambda, RunnablePassthroughrunnable1 = RunnableLambda(lambda x: x["baz"] + 5)chain = RunnablePassthrough.assign(foo=runnable1).pick(["foo", "bar"])chain.invoke({"bar": "hi", "baz": 2})

**API Reference:**[RunnableLambda](https://api.python.langchain.com/en/latest/runnables/langchain_core.runnables.base.RunnableLambda.html) | [RunnablePassthrough](https://api.python.langchain.com/en/latest/runnables/langchain_core.runnables.passthrough.RunnablePassthrough.html)

    {'foo': 7, 'bar': 'hi'}

### Declaratively make a batched version of a runnable[​](#declaratively-make-a-batched-version-of-a-runnable "Direct link to Declaratively make a batched version of a runnable")

#### [Runnable.map](https://api.python.langchain.com/en/latest/runnables/langchain_core.runnables.base.Runnable.html#langchain_core.runnables.base.Runnable.map)[​](#runnablemap "Direct link to runnablemap")

    from langchain_core.runnables import RunnableLambdarunnable1 = RunnableLambda(lambda x: list(range(x)))runnable2 = RunnableLambda(lambda x: x + 5)chain = runnable1 | runnable2.map()chain.invoke(3)

**API Reference:**[RunnableLambda](https://api.python.langchain.com/en/latest/runnables/langchain_core.runnables.base.RunnableLambda.html)

    [5, 6, 7]

### Get a graph representation of a runnable[​](#get-a-graph-representation-of-a-runnable "Direct link to Get a graph representation of a runnable")

#### [Runnable.get\_graph](https://api.python.langchain.com/en/latest/runnables/langchain_core.runnables.base.Runnable.html#langchain_core.runnables.base.Runnable.get_graph)[​](#runnableget_graph "Direct link to runnableget_graph")

    from langchain_core.runnables import RunnableLambda, RunnableParallelrunnable1 = RunnableLambda(lambda x: {"foo": x})runnable2 = RunnableLambda(lambda x: [x] * 2)runnable3 = RunnableLambda(lambda x: str(x))chain = runnable1 | RunnableParallel(second=runnable2, third=runnable3)chain.get_graph().print_ascii()

**API Reference:**[RunnableLambda](https://api.python.langchain.com/en/latest/runnables/langchain_core.runnables.base.RunnableLambda.html) | [RunnableParallel](https://api.python.langchain.com/en/latest/runnables/langchain_core.runnables.base.RunnableParallel.html)

                                 +-------------+                                                           | LambdaInput |                                                           +-------------+                                                                  *                                                                         *                                                                         *                                                         +------------------------------+                                          | Lambda(lambda x: {'foo': x}) |                                          +------------------------------+                                                          *                                                                         *                                                                         *                                                          +-----------------------------+                                           | Parallel<second,third>Input |                                           +-----------------------------+                                              ****                  ***                                             ****                         ****                                       **                                 **                   +---------------------------+               +--------------------------+  | Lambda(lambda x: [x] * 2) |               | Lambda(lambda x: str(x)) |  +---------------------------+               +--------------------------+                          ****                  ***                                                     ****          ****                                                            **      **                                                    +------------------------------+                                          | Parallel<second,third>Output |                                          +------------------------------+

### Get all prompts in a chain[​](#get-all-prompts-in-a-chain "Direct link to Get all prompts in a chain")

#### [Runnable.get\_prompts](https://api.python.langchain.com/en/latest/runnables/langchain_core.runnables.base.Runnable.html#langchain_core.runnables.base.Runnable.get_prompts)[​](#runnableget_prompts "Direct link to runnableget_prompts")

    from langchain_core.prompts import ChatPromptTemplatefrom langchain_core.runnables import RunnableLambdaprompt1 = ChatPromptTemplate.from_messages(    [("system", "good ai"), ("human", "{input}")])prompt2 = ChatPromptTemplate.from_messages(    [        ("system", "really good ai"),        ("human", "{input}"),        ("ai", "{ai_output}"),        ("human", "{input2}"),    ])fake_llm = RunnableLambda(lambda prompt: "i am good ai")chain = prompt1.assign(ai_output=fake_llm) | prompt2 | fake_llmfor i, prompt in enumerate(chain.get_prompts()):    print(f"**prompt {i=}**\n")    print(prompt.pretty_repr())    print("\n" * 3)

**API Reference:**[ChatPromptTemplate](https://api.python.langchain.com/en/latest/prompts/langchain_core.prompts.chat.ChatPromptTemplate.html) | [RunnableLambda](https://api.python.langchain.com/en/latest/runnables/langchain_core.runnables.base.RunnableLambda.html)

    **prompt i=0**================================ System Message ================================good ai================================ Human Message ================================={input}**prompt i=1**================================ System Message ================================really good ai================================ Human Message ================================={input}================================== AI Message =================================={ai_output}================================ Human Message ================================={input2}

### Add lifecycle listeners[​](#add-lifecycle-listeners "Direct link to Add lifecycle listeners")

#### [Runnable.with\_listeners](https://api.python.langchain.com/en/latest/runnables/langchain_core.runnables.base.Runnable.html#langchain_core.runnables.base.Runnable.with_listeners)[​](#runnablewith_listeners "Direct link to runnablewith_listeners")

    import timefrom langchain_core.runnables import RunnableLambdafrom langchain_core.tracers.schemas import Rundef on_start(run_obj: Run):    print("start_time:", run_obj.start_time)def on_end(run_obj: Run):    print("end_time:", run_obj.end_time)runnable1 = RunnableLambda(lambda x: time.sleep(x))chain = runnable1.with_listeners(on_start=on_start, on_end=on_end)chain.invoke(2)

**API Reference:**[RunnableLambda](https://api.python.langchain.com/en/latest/runnables/langchain_core.runnables.base.RunnableLambda.html) | [Run](https://api.python.langchain.com/en/latest/tracers/langchain_core.tracers.schemas.Run.html)

    start_time: 2024-05-17 23:04:00.951065+00:00end_time: 2024-05-17 23:04:02.958765+00:00

[Edit this page](https://github.com/langchain-ai/langchain/edit/master/docs/docs/how_to/lcel_cheatsheet.ipynb)

* * *

#### Was this page helpful?

  

#### You can also leave detailed feedback [on GitHub](https://github.com/langchain-ai/langchain/issues/new?assignees=&labels=03+-+Documentation&projects=&template=documentation.yml&title=DOC%3A+%3CPlease+write+a+comprehensive+title+after+the+%27DOC%3A+%27+prefix%3E).

[

Previous

How to inspect runnables

](/v0.2/docs/how_to/inspect/)[

Next

How to cache LLM responses

](/v0.2/docs/how_to/llm_caching/)

*   [Invoke a runnable](#invoke-a-runnable)
*   [Batch a runnable](#batch-a-runnable)
*   [Stream a runnable](#stream-a-runnable)
*   [Compose runnables](#compose-runnables)
*   [Invoke runnables in parallel](#invoke-runnables-in-parallel)
*   [Turn any function into a runnable](#turn-any-function-into-a-runnable)
*   [Merge input and output dicts](#merge-input-and-output-dicts)
*   [Include input dict in output dict](#include-input-dict-in-output-dict)
*   [Add default invocation args](#add-default-invocation-args)
*   [Add fallbacks](#add-fallbacks)
*   [Add retries](#add-retries)
*   [Configure runnable execution](#configure-runnable-execution)
*   [Add default config to runnable](#add-default-config-to-runnable)
*   [Make runnable attributes configurable](#make-runnable-attributes-configurable)
*   [Make chain components configurable](#make-chain-components-configurable)
*   [Build a chain dynamically based on input](#build-a-chain-dynamically-based-on-input)
*   [Generate a stream of events](#generate-a-stream-of-events)
*   [Yield batched outputs as they complete](#yield-batched-outputs-as-they-complete)
*   [Return subset of output dict](#return-subset-of-output-dict)
*   [Declaratively make a batched version of a runnable](#declaratively-make-a-batched-version-of-a-runnable)
*   [Get a graph representation of a runnable](#get-a-graph-representation-of-a-runnable)
*   [Get all prompts in a chain](#get-all-prompts-in-a-chain)
*   [Add lifecycle listeners](#add-lifecycle-listeners)