Files
magnus919_agent-skills/langchain/references/lcel-reference.md
T
Magnus Hedemark 7f2842b358 feat: langchain v1.1.0 — research-validated deepening
Major deepening of the langchain expert skill based on source audit against
official LangChain docs (docs.langchain.com, reference.langchain.com).

Changes:
- Added references/validation-audit.md documenting all research findings
- Deepened references/agent-patterns.md from 74 to 200+ lines:
  create_react_agent full parameter table, @tool decorator with
  args_schema/parse_docstring, streaming events, multi-agent supervisor
- Deepened references/lcel-reference.md from 79 to 180+ lines:
  RunnablePassthrough.assign(), RunnableParallel dict shorthand,
  RunnableLambda, RunnableConfig, .with_fallbacks(), .configurable_fields()
- Deepened references/rag-strategies.md with advanced retrieval patterns
- Deepened references/production-deployment.md with LangSmith Datasets/
  Evaluation Runs/Prompt Hub
- Added new references/callbacks.md (BaseCallbackHandler, event table,
  agent auditing patterns, async callbacks)
- Deepened references/faq-and-troubleshooting.md with Pydantic v1/v2,
  streaming+tools, checkpoint serialization guidance

All API surface claims verified against official documentation.
v1.0.3 -> v1.1.0
2026-07-09 14:33:42 -04:00

3.6 KiB

LCEL (LangChain Expression Language) Reference

LCEL uses the pipe operator (|) to connect Runnable components. Every component — prompt, model, parser, retriever — implements the Runnable interface.

Basic Chain

from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI
from langchain_core.output_parsers import StrOutputParser

chain = ChatPromptTemplate.from_template("Answer: {q}") | ChatOpenAI() | StrOutputParser()
result = chain.invoke({"q": "What is LCEL?"})

The Runnable Interface

All components implement Runnable, providing these methods:

Method Description
invoke(input) Sync execution
ainvoke(input) Async execution
stream(input) Token-by-token streaming
astream(input) Async streaming
batch(inputs) Batch processing
abatch(inputs) Async batch
astream_events(input, version) Event stream with metadata

Runnable Primitives

RunnablePassthrough

from langchain_core.runnables import RunnablePassthrough, RunnableParallel

# Pass input unchanged
RunnablePassthrough()

# Incrementally add keys to a dict — critical for RAG chains
RunnablePassthrough.assign(
    upper=lambda x: x["text"].upper()
)

# Combine both patterns
RunnableParallel(
    origin=RunnablePassthrough(),
    modified=lambda x: x["num"] + 1
)

RunnableParallel — Concurrent Execution

chain = RunnableParallel(
    answer=prompt_a | model | parser,
    summary=prompt_b | model | parser,
)

Dictionaries are automatically coerced to RunnableParallel:

chain = {"answer": chain_a, "summary": chain_b}  # shorthand

RunnableLambda — Wrap Any Function

from langchain_core.runnables import RunnableLambda

def format_docs(docs):
    return "\n\n".join(d.page_content for d in docs)

chain = retriever | RunnableLambda(format_docs) | prompt | model | parser

RunnableConfig

Field Description
max_concurrency Limit parallel calls
recursion_limit Max steps before error
tags Labels for tracing
callbacks Custom callback handlers
metadata Arbitrary key-value data
from langchain_core.runnables import RunnableConfig

chain.invoke(input, config=RunnableConfig(max_concurrency=5, tags=["prod"]))

Error Handling

# Fallback chain if primary fails
safe_chain = chain.with_fallbacks([fallback_chain])

Runtime Configuration

# Make parameters configurable at invocation time
configurable_chain = (
    ChatPromptTemplate.from_template("Answer: {q}")
    | ChatOpenAI().configurable_fields(
        model=ConfigurableField(id="model", name="Model")
    )
    | StrOutputParser()
)

chain.with_config(configurable={"model": "gpt-4"})

Branching

from langchain_core.runnables import RunnableBranch

branch = RunnableBranch(
    (lambda x: len(x["q"]) > 100, long_chain),
    (lambda x: "code" in x["q"], code_chain),
    default_chain,
)

Common Patterns Reference

Pattern Syntax Use Case
Sequential `A B
Parallel RunnableParallel(a=A, b=B) Independent operations
Passthrough RunnablePassthrough() Pass input unchanged
.assign .assign(key=fn) Incremental dict building
Lambda wrap RunnableLambda(fn) Wrap arbitrary Python fn
Branching RunnableBranch(...) Conditional routing
Fallback .with_fallbacks([...]) Error recovery
Config .configurable_fields(...) Runtime model/param config