Back to roadmaps langchain Course

Mastering LangChain Expression Language

LangChain Expression Language (LCEL) is a declarative way to compose chains of LLM components. It utilizes a pipe-like operator syntax to link outputs of one component directly to the inputs of the next.


1. The Pipe Line Composition

Using the pipeline operator, you can build a chain using this standard layout:

// Define the logical flow
const chain = prompt | model | parser;

When invoking chain.invoke(), data flows through these steps:

  1. Input variables are injected into the prompt template.
  2. The formatted prompt string is passed to the model object.
  3. The raw output is parsed into final text or JSON by the parser.

2. Coding a Basic LCEL Chain in Node.js

Create a simple chain that translates programming concepts:

// src/services/translationChain.ts
import { ChatOpenAI } from "@langchain/openai";
import { ChatPromptTemplate } from "@langchain/core/prompts";
import { StringOutputParser } from "@langchain/core/output_parsers";

// 1. Instantiate the Model
const model = new ChatOpenAI({
  modelName: "gpt-4o-mini",
  temperature: 0,
});

// 2. Instantiate Prompt template
const prompt = ChatPromptTemplate.fromMessages([
  ["system", "You are a senior coding translator. Translate all code terms to Spanish."],
  ["user", "Explain what {concept} is in 2 sentences."]
]);

// 3. Instantiate output parser
const parser = new StringOutputParser();

// 4. Compose the chain using pipe methods
const translationChain = prompt.pipe(model).pipe(parser);

export async function runTranslation(conceptName: string) {
  // Pass variables directly to invoke
  const output = await translationChain.invoke({
    concept: conceptName,
  });

  console.log("Translation Output:", output);
  return output;
}

3. Advantages of LCEL Chains

  • Streaming Support: Call .stream() on a composed chain. The SDK automatically propagates streaming output from the model through to the parser.
  • Async/Await Hooks: Provides native async handlers for large concurrent workloads.
  • Debugging: Easier to trace inputs and outputs of intermediate nodes using monitoring frameworks like LangSmith.
Published on Last updated: