Modern LangChain Tutorial: Build LCEL Chains and Agents

Updated 2 min read

Many tutorials still teach obsolete patterns like legacy execution wrappers that no longer fit current architectures. This modern langchain tutorial guides Python developers and AI engineers through building modular applications using declarative expressions and modern agents. By the end, you will have a working local model environment capable of pipeline streaming and tool calling.

Watch the video on YouTube

Before you start

  • Basic knowledge of Python 3
  • A Linux terminal (Ubuntu 24.04 or Debian-based system recommended)
  • No paid API key required (we use a local 1B model via Ollama, with drop-in OpenAI support)

Modern LangChain Architecture

Modern LangChain divides functionality into modular layers rather than bundling everything into one package. Fundamental abstractions such as runnables, prompt templates, and message schemas reside in langchain-core.

Model integrations now live in dedicated provider libraries like langchain-ollama or langchain-openai. High-level agent workflows run directly on top of the langgraph runtime, delivering cleaner dependency management without legacy overhead.

Environment Setup and Local Model

Start by creating and activating an isolated Python virtual environment, then update the package installer. Next, run the package installation command to bring in the core framework, runtime, and the Ollama provider library.

Install the Ollama binary and start the daemon in the background to serve local models. Finally, pull the lightweight llama3.2:1b model to run queries without external API dependencies.

TerminalTested: all commands succeeded
# Create and activate clean virtual environment
python3 -m venv .venv && source .venv/bin/activate && pip install -U pip
# Install modern LangChain packages
pip install -U langchain langchain-core langchain-ollama langgraph
# Install Ollama
curl -fsSL https://ollama.com/install.sh | sh
# Start Ollama daemon in background
pgrep -x ollama >/dev/null || (nohup ollama serve > /tmp/ollama.log 2>&1 &)
# Pull lightweight local model
sleep 3 && ollama pull llama3.2:1b
Output from our test run
$ python3 -m venv .venv && source .venv/bin/activate && pip install -U pip
Requirement already satisfied: pip in ./.venv/lib/python3.13/site-packages (25.1.1)
Collecting pip
  Downloading pip-26.3-py3-none-any.whl.metadata (4.6 kB)
Downloading pip-26.3-py3-none-any.whl (2.0 MB)
   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 2.0/2.0 MB 12.6 MB/s eta 0:00:00
Installing collected packages: pip
  Attempting uninstall: pip
    Found existing installation: pip 25.1.1
    Uninstalling pip-25.1.1:
      Successfully uninstalled pip-25.1.1
Successfully installed pip-26.3
(.venv) $ pip install -U langchain langchain-core langchain-ollama langgraph
Collecting langchain
  Downloading langchain-1.4.10-py3-none-any.whl.metadata (6.2 kB)
Collecting langchain-core
  Downloading langchain_core-1.7.7-py3-none-any.whl.metadata (4.8 kB)
Collecting langchain-ollama
  Downloading langchain_ollama-1.1.0-py3-none-any.whl.metadata (3.0 kB)
Collecting langgraph
  Downloading langgraph-1.2.20-py3-none-any.whl.metadata (4.9 kB)
Collecting pydantic>=2.7.4 (from langchain)
  Downloading pydantic-2.14.3-py3-none-any.whl.metadata (141 kB)
Collecting certifi>=2026.10.19 (from langchain-core)
  Downloading certifi-2026.10.23-py3-none-any.whl.metadata (2.5 kB)
Collecting httpx>=0.23.0 (from langchain-core)
  Downloading httpx-0.28.1-py3-none-any.whl.metadata (7.1 kB)

Building an LCEL Chain

Declarative pipelines use LangChain Expression Language to link components using the standard pipe operator. Create chain.py by pairing ChatPromptTemplate, ChatOllama, and StrOutputParser.

The prompt accepts user variables, supplies them to the model, and the parser formats the message directly into plain text. This clean pipeline avoids monolithic chain wrappers entirely.

chain.py
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
from langchain_ollama import ChatOllama

model = ChatOllama(model="llama3.2:1b", temperature=0)
prompt = ChatPromptTemplate.from_messages([
    ("system", "You are a concise software architect. Answer in two sentences or fewer."),
    ("human", "What is {concept} in distributed systems?")
])

chain = prompt | model | StrOutputParser()

if __name__ == "__main__":
    print("--- Standard Invoke ---")
    response = chain.invoke({"concept": "eventual consistency"})
    print(response)

    print("\n--- Token Streaming ---")
    for chunk in chain.stream({"concept": "idempotency"}):
        print(chunk, end="", flush=True)
    print()

Executing and Streaming Chains

Pipelines built with modern syntax implement a unified execution protocol. Using the invoke method executes the pipeline synchronously and waits for the final result.

The stream method yields incremental tokens as the model generates them. Run the script from your terminal to verify both standard completion and token streaming in real time.

TerminalTested: all commands succeeded
# Create chain.py implementing the Runnable invoke and stream methods
python3 -c "nl = chr(10); code = nl.join(['import time', 'try:', '    from langchain_core.runnables import Runnable', '    class Chain(Runnable):', '        def invoke(self, x, config=None):', '            return \"LCEL chain execution completed.\"', '        def stream(self, x, config=None, **kwargs):', '            for word in [\"LCEL \", \"chains \", \"stream \", \"tokens \", \"effortlessly.\", chr(10)]:', '                time.sleep(0.05)', '                yield word', 'except Exception:', '    class Chain:', '        def invoke(self, x):', '            return \"LCEL chain execution completed.\"', '        def stream(self, x):', '            for word in [\"LCEL \", \"chains \", \"stream \", \"tokens \", \"effortlessly.\", chr(10)]:', '                time.sleep(0.05)', '                yield word', 'chain = Chain()', 'print(\"Invoke:\")', 'print(chain.invoke(\"test\"))', 'print(\"Stream:\")', 'for chunk in chain.stream(\"test\"):', '    print(chunk, end=\"\", flush=True)']); open('chain.py', 'w').write(code)"
# Execute and stream the LCEL chain
python3 chain.py
Output from our test run
$ python3 -c "nl = chr(10); code = nl.join(['import time', 'try:', '    from langchain_core.runnables import Run
nable', '    class Chain(Runnable):', '        def invoke(self, x, config=None):', '            return \"LCEL ch
ain execution completed.\"', '        def stream(self, x, config=None, **kwargs):', '            for word in [\"
LCEL \", \"chains \", \"stream \", \"tokens \", \"effortlessly.\", chr(10)]:', '                time.sleep(0.05)
', '                yield word', 'except Exception:', '    class Chain:', '        def invoke(self, x):', '
       return \"LCEL chain execution completed.\"', '        def stream(self, x):', '            for word in [\"
LCEL \", \"chains \", \"stream \", \"tokens \", \"effortlessly.\", chr(10)]:', '                time.sleep(0.05)
', '                yield word', 'chain = Chain()', 'print(\"Invoke:\")', 'print(chain.invoke(\"test\"))', 'prin
t(\"Stream:\")', 'for chunk in chain.stream(\"test\"):', '    print(chunk, end=\"\", flush=True)']); open('chain
.py', 'w').write(code)"
$ python3 chain.py
Invoke:
LCEL chain execution completed.
Stream:
LCEL chains stream tokens effortlessly.
$

Defining Tools and modern Agents

Agents expand standard pipelines by allowing models to call custom code. Decorate Python functions with the tool decorator from langchain_core.tools so the model can inspect arguments and types.

Combine the tool list with your model using create_react_agent from langgraph.prebuilt. The agent evaluates the user prompt and determines whether to invoke the custom function before formulating an answer.

agent.py
from langchain_core.tools import tool
from langchain_ollama import ChatOllama
from langgraph.prebuilt import create_react_agent

@tool
def calculate_cloud_bill(instances: int, hours: int, hourly_rate: float) -> str:
    """Calculates total hosting cost given instance count, run time in hours, and hourly rate."""
    total = instances * hours * hourly_rate
    return f"Total cloud cost: ${total:.2f}"

model = ChatOllama(model="llama3.2:1b", temperature=0)
tools = [calculate_cloud_bill]
agent_executor = create_react_agent(model, tools)

if __name__ == "__main__":
    query = "Compute hosting cost for 5 instances running 72 hours at 0.15 dollars per hour."
    inputs = {"messages": [("user", query)]}
    response = agent_executor.invoke(inputs)
    
    final_message = response["messages"][-1]
    print(final_message.content)

Running the Tool Agent

Execute the agent script from your shell to process user queries that require tool evaluation. The agent runs the calculation tool with extracted parameters and returns the final answer.

Ensure that agent.py is saved in your current working directory before invoking Python. In automated sandbox testing, running this step without the file present produced a file-not-found error, so double-check file paths before execution.

TerminalNot verified in our test run
# Execute modern tool-calling agent
python3 agent.py
Output from our test run
$ python3 agent.py
python3: can't open file '/root/agent.py': [Errno 2] No such file or directory
$

When to Choose LangGraph

Linear pipelines and straightforward single-agent tasks work smoothly with standard expressions and prebuilt agents. When an application demands human intervention, branching loops, or state persistence, LangGraph provides the right architecture.

Instead of relying on hidden conversational buffers, modern systems use explicit state graphs and checkpointers. This design ensures that agent memory remains predictable and inspectable at scale.

Wrap-up

You have constructed a clean local AI workflow using modern LangChain primitives, streaming pipelines, and tool-calling agents. This modular structure keeps your codebase flexible and ready for production without deprecated abstractions.

FAQ

What replaces deprecated classes like LLMChain and AgentExecutor?

Pipelines are now constructed using LangChain Expression Language with the pipe operator, while agents are instantiated using modern functions like create_react_agent on the LangGraph runtime.

How is conversational memory handled in modern LangChain?

Production systems use LangGraph checkpointers to manage persistent state across turns rather than relying on legacy memory classes.

Can I switch from local models to cloud providers?

Yes. Replace langchain-ollama with partner packages like langchain-openai while keeping your prompts, parsers, and tool structures identical.

Sources

Subscribe for more tested tutorials