0
0
LangChainframework~5 mins

LangChain Expression Language (LCEL) basics

Choose your learning style9 modes available
Introduction

LCEL helps you write simple expressions to control how LangChain works. It makes building chains easier and clearer.

You want to combine different steps in a LangChain workflow.
You need to create conditions or logic inside your chain.
You want to reuse small expressions for cleaner code.
You want to quickly test or change parts of your chain without rewriting code.
Syntax
LangChain
expression := value | variable | function_call | expression operator expression

value := number | string | boolean

operator := + | - | * | / | == | != | && | || | > | < | >= | <=

function_call := functionName(arg1, arg2, ...)
LCEL expressions look like simple math or logic statements.
You can use variables and call built-in functions inside expressions.
Examples
Adds two numbers and returns 8.
LangChain
5 + 3
Checks if the variable userInput equals the string "hello".
LangChain
userInput == "hello"
Calls a function to change userName to uppercase letters.
LangChain
toUpperCase(userName)
Returns true if score is greater than 10 and isActive is true.
LangChain
score > 10 && isActive
Sample Program

This example defines a simple chain with two steps. The first step checks if the user said "hello". The second step chooses a response based on that check. When userInput is "hello", it prints a friendly greeting.

LangChain
chain = {
  "steps": [
    {"name": "checkGreeting", "expression": "userInput == 'hello'"},
    {"name": "response", "expression": "'Hi there!' if checkGreeting else 'Please say hello.'"}
  ]
}

userInput = 'hello'
checkGreeting = eval(chain['steps'][0]['expression'])
result = eval(chain['steps'][1]['expression'])
print(result)
OutputSuccess
Important Notes

LCEL is designed to be easy to read and write, like simple math or logic.

Remember to use quotes around strings and proper operators for logic.

LCEL expressions run inside LangChain to control flow and data.

Summary

LCEL lets you write small expressions to control LangChain chains.

You can use variables, operators, and functions in LCEL.

It helps make your chains clearer and easier to manage.