Skip to main content
AI & Machine Learning

LangChain & LangGraph Orchestration

Advanced

LCEL expression language, prompt templates, output parsers, memory state, and LangGraph multi-agent cyclical graphs.

Instant Copy & SearchProduction Flagged SyntaxCurrent Flag Reference

LangChain & LangGraph Orchestration Interactive Command Directory

Browse, search, and copy battle-tested commands & syntax recipes (16 Total Commands).

16+ Verified Recipes
LCEL Chainprompt | model | parser
from langchain_core.prompts import ChatPromptTemplate from langchain_core.output_parsers import StrOutputParser chain = prompt | model | StrOutputParser() result = await chain.ainvoke({"topic": "vector databases"})

Compose declarative streaming pipeline using pipe operator (|).

Structured Outputwith_structured_output()
from pydantic import BaseModel class Extraction(BaseModel): entities: list[str] structured_llm = model.with_structured_output(Extraction)

Enforce deterministic JSON schema validation using tool calling.

LangGraph StateGraphStateGraph, compile()
from langgraph.graph import StateGraph, END workflow = StateGraph(AgentState) workflow.add_node("agent", call_model) workflow.add_node("tools", call_tool) workflow.add_edge("tools", "agent") app = workflow.compile()

Define stateful cyclical agent workflow graph with routing edges.

RAG Retrieveras_retriever(k=5)
retriever = vectorstore.as_retriever(search_type="similarity", search_kwargs={"k": 5}) docs = retriever.invoke("How does caching work?")

Query dense vector database embeddings to augment prompt context.

Model InstantiationChatOpenAI
from langchain_openai import ChatOpenAI model = ChatOpenAI(model='gpt-4o', temperature=0)

Initialize type-safe chat model interface with deterministic temperature settings.

LCEL Streaming PipelinesLCEL, StrOutputParser
chain = prompt | model | StrOutputParser()

Compose LangChain Expression Language pipeline chaining prompt template, LLM, and string parser.

Parallel Runnable GraphsRunnableParallel
from langchain_core.runnables import RunnableParallel, RunnablePassthrough chain = RunnableParallel({'context': retriever, 'question': RunnablePassthrough()}) | prompt | model

Execute parallel graph branches simultaneously merging document retrieval and query passthrough.

Document ParsingPyPDFLoader
from langchain_community.document_loaders import PyPDFLoader docs = PyPDFLoader('paper.pdf').load_and_split()

Parse and chunk PDF documents into structured LangChain Document objects.

Text ChunkingRecursiveCharacterTextSplitter
from langchain_text_splitters import RecursiveCharacterTextSplitter splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)

Recursively split text by paragraph, sentence, and word boundaries preserving semantic context.

Vector Store IngestionChroma.from_documents
from langchain_community.vectorstores import Chroma from langchain_openai import OpenAIEmbeddings vectorstore = Chroma.from_documents(docs, OpenAIEmbeddings())

Embed document chunks into local Chroma vector database using OpenAI embeddings.

Tool-Calling Agentscreate_tool_calling_agent
from langchain.agents import create_tool_calling_agent, AgentExecutor agent = create_tool_calling_agent(model, tools, prompt) executor = AgentExecutor(agent=agent, tools=tools, verbose=True)

Construct agent runtime leveraging native LLM function calling with automated tool execution loop.

Custom Tool Decorator@tool
from langchain_core.tools import tool @tool def get_weather(location: str) -> str: '''Return current weather for location.''' return f'Sunny in {location}'

Define custom agent tools using Python decorator with automatic JSON schema generation from docstrings.

Session MemoryRunnableWithMessageHistory
from langchain_core.runnables.history import RunnableWithMessageHistory with_history = RunnableWithMessageHistory(chain, get_session_history)

Wrap LCEL chains with conversational session memory managing multi-turn dialogue history.

Real-Time Streaming CallbacksBaseCallbackHandler
class StreamHandler(BaseCallbackHandler): def on_llm_new_token(self, token: str, **kwargs): print(token, end='', flush=True)

Callback handler streaming generated tokens directly to console or WebSocket output.

Async Stream Generatorchain.astream
async for chunk in chain.astream({'input': 'Explain vectors'}): print(chunk, end='')

Consume asynchronous generator streaming token chunks directly from LLM pipelines.

Contextual CompressionContextualCompressionRetriever
from langchain.retrievers import ContextualCompressionRetriever from langchain.retrievers.document_compressors import LLMChainExtractor compressor = LLMChainExtractor.from_llm(model) comp_retriever = ContextualCompressionRetriever(base_compressor=compressor, base_retriever=retriever)

Extract and compress only query-relevant sentences from retrieved documents before LLM synthesis.

Zero Setup100% In-Browser Execution

Companion Developer Tools & Playgrounds

Accelerate command execution and syntax debugging with HelloAIHub suite of interactive tools.

Explore all developer tools

LangChain & LangGraph Orchestration: Command Groups & Quick Index

16 indexed entries across 16 sections
LCEL Chain1 items
Structured Output1 items
LangGraph StateGraph1 items
RAG Retriever1 items
Model Instantiation1 items
LCEL Streaming Pipelines1 items
Parallel Runnable Graphs1 items
Document Parsing1 items
Text Chunking1 items
Vector Store Ingestion1 items
Tool-Calling Agents1 items
Custom Tool Decorator1 items
Session Memory1 items
Real-Time Streaming Callbacks1 items
Async Stream Generator1 items
Contextual Compression1 items

Highlighted Flags & Syntax Examples in LangChain & LangGraph Orchestration

from langchain_core.prompts import ChatPromptTemplate from langchain_core.output_parsers import StrOutputParser chain = prompt | model | StrOutputParser() result = await chain.ainvoke({"topic": "vector databases"})

Compose declarative streaming pipeline using pipe operator (|).

Flags: prompt | model | parser
from pydantic import BaseModel class Extraction(BaseModel): entities: list[str] structured_llm = model.with_structured_output(Extraction)

Enforce deterministic JSON schema validation using tool calling.

Flags: with_structured_output()
from langgraph.graph import StateGraph, END workflow = StateGraph(AgentState) workflow.add_node("agent", call_model) workflow.add_node("tools", call_tool) workflow.add_edge("tools", "agent") app = workflow.compile()

Define stateful cyclical agent workflow graph with routing edges.

Flags: StateGraph, compile()
retriever = vectorstore.as_retriever(search_type="similarity", search_kwargs={"k": 5}) docs = retriever.invoke("How does caching work?")

Query dense vector database embeddings to augment prompt context.

Flags: as_retriever(k=5)

Frequently Asked Questions

Expert recommendations, common traps, and production best practices for LangChain & LangGraph Orchestration.

What is LCEL (LangChain Expression Language)?

LCEL is a declarative syntax for composing chains using the pipe operator (|). It provides unified support for sync, async, streaming, batching, parallel execution, and built-in tracing.

Why use LangGraph instead of classic linear chains?

Classic chains are Directed Acyclic Graphs (DAGs) that cannot loop or backtrack. LangGraph adds cycles and state persistence, which are essential for autonomous reasoning agents that must iteratively self-correct and execute tools.

What is RAG (Retrieval-Augmented Generation) and how does LangChain orchestrate it?

RAG grounds LLM responses on proprietary data. LangChain orchestrates RAG via a 4-step pipeline: 1. Loading documents via DocumentLoaders. 2. Chunking text with TextSplitters. 3. Embedding chunks into a VectorStore. 4. Querying the VectorStore via a Retriever and passing relevant chunks into the LLM prompt context.

What is the difference between LangChain and LangGraph?

Classic LangChain chains (LCEL) are directed acyclic graphs (DAGs) best suited for linear, one-pass pipelines. LangGraph adds stateful multi-agent workflows with loops, conditional branching, and persistence, making it ideal for complex autonomous agents that must retry, backtrack, or collaborate.

Why is chunk overlap critical when splitting documents with RecursiveCharacterTextSplitter?

Chunk overlap (e.g. 200 characters on a 1,000-character chunk) ensures that sentences or context split across chunk boundaries are not lost. Without overlap, a key relational fact split midway across two chunks might fail semantic vector similarity searches in both chunks.

How does LangChain handle structured outputs using with_structured_output() and Pydantic?

'model.with_structured_output(PydanticSchema)' configures the underlying LLM's native tool calling or JSON mode to guarantee that model responses conform strictly to the defined Pydantic schema, automatically validating types and parsing responses into Python objects.

Cross-Hub Skill Acceleration

Combine command lookups with active coding interviews and complete career paths.

Need More Cheat Sheets?

Explore developer cheat sheets and syntax guides on HelloAIHub.

Browse All Cheat Sheets