4  LCEL - Basic

LangChain Expression Language: https://python.langchain.com/v0.2/docs/how_to/lcel_cheatsheet/

4.1 Function to runnable

from langchain_core.runnables import RunnableLambda

def func(x):
    return x + 5

runnable = RunnableLambda(func)
runnable.invoke(2)
7

4.1.1 Invoke

runnable = RunnableLambda(lambda x: str(x + 1))
runnable.invoke(5)
'6'

4.1.2 Batch

runnable = RunnableLambda(lambda x: str(x + 1))
runnable.batch([7, 8, 9])
# Async variant:
# await runnable.abatch([7, 8, 9])
['8', '9', '10']

4.1.3 Stream

def func(x):
    for y in x:
        yield str(y)


runnable = RunnableLambda(func)
for chunk in runnable.stream(range(5)):
    print(chunk)
0
1
2
3
4

4.2 Compose with |

from langchain_core.runnables import RunnableLambda

runnable1 = RunnableLambda(lambda x: x + 1)
runnable2 = RunnableLambda(lambda x: x * 2)

chain = runnable1 | runnable2

chain.invoke(2)
6

4.3 Parallel Runable

from langchain_core.runnables import RunnableLambda, RunnableParallel

runnable1 = RunnableLambda(lambda x: x + 1)
runnable2 = RunnableLambda(lambda x: x * 2)

chain = RunnableParallel(first=runnable1, second=runnable2)
chain
{
  first: RunnableLambda(lambda x: x + 1),
  second: RunnableLambda(lambda x: x * 2)
}
type(chain)
langchain_core.runnables.base.RunnableParallel
chain.invoke(2)
6