LangChain / Beginner

Simple LangChain LLMChain

Modern LangChain pipeline: prompt → model → parser. Build a reusable summarisation chain in 20 lines of Python.

📅 May 2026 ⏱️ 5 min read 👤 Trenzy Vibes
Python LangChain OpenAI LLM Beginner

The Modern Pipeline

Modern LangChain encourages building pipelines using the pipe operator: prompt → model → parser. This is cleaner, more composable, and easier to debug than the old LLMChain class approach.

📝 Prompt
|
🤖 Model
|
✨ Parser

Each step transforms the output and passes it to the next — like Unix pipes

💡 Why This Pattern?

The pipe operator (|) makes chains readable and composable. You can swap any component without rewriting the whole chain. Want to change the model? Just replace that box. New parser? Same thing.

Complete Code

A reusable summarisation chain with system instructions and human input:

python
from langchain.chat_models import init_chat_model
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
from dotenv import load_dotenv

load_dotenv()

def create_summarisation_chain():

    # initialise model
    model = init_chat_model(
        model="gpt-3.5-turbo",
        temperature=0.2,
        max_tokens=200,
    )

    # Create your prompt
    prompt = ChatPromptTemplate.from_messages([
        ("system", "You are a helpful assistant that explains concepts in simple terms."),
        ("human", "{text}")
    ])

    # initialise parser
    parser = StrOutputParser()

    chain = prompt | model | parser

    return chain

if __name__ == "__main__":
    chain = create_summarisation_chain()

    # Run the chain with an example input
    summary = chain.invoke({"text": 
    """The top 1% differentiate themselves by mastering execution over mere consumption. They use deliberate, first principles learning and tight feedback loops. While the rest passively consume theory, the top 1% synthesize information into actionable systems, optimizing for speed, leverage, and practical iteration."""
    })

    print(summary)

How It Works

1. Initialise the Model

init_chat_model() is the modern way to create a chat model in LangChain. It auto-detects the provider from the model name and handles API key loading from environment variables.

python
model = init_chat_model(
    model="gpt-3.5-turbo",
    temperature=0.2,       # lower = more focused, higher = more creative
    max_tokens=200,           # cap output length
)

2. Build the Prompt

ChatPromptTemplate.from_messages() creates a chat-style prompt with two roles:

3. Add the Parser

StrOutputParser() ensures the final output is a plain Python string — not a complex message object. This makes the output immediately usable in your app.

4. Pipe It Together

The magic line:

python
chain = prompt | model | parser

This creates a pipeline where:

  1. Prompt formats the input variables into a message list
  2. Model sends the messages to GPT-3.5-turbo and gets the response
  3. Parser extracts the text content from the response object

✅ Key Insight

The pipe operator isn't just syntax sugar — each component implements Runnable, so LangChain can automatically handle batching, streaming, retries, and error handling across the entire chain.

Running the Chain

Invoke with a dictionary of variables:

python
summary = chain.invoke({"text": "Your long text here..."})

With the example input about "top 1% execution vs consumption", the output would be a concise summary like:

The top 1% succeed through first-principles thinking, fast iteration, and systems over to-do lists. They treat learning as active experimentation and build automated processes for execution. Unlike others who wait for perfection, they launch minimal versions, gather data, and refine rapidly. Their mindset mirrors elite athletes: strict routines that make high performance automatic, not motivation-dependent.

Dependencies

bash
pip install langchain langchain-openai python-dotenv

⚠️ Requirements

• Create a .env file with your OPENAI_API_KEY
init_chat_model requires langchain-openai for GPT models
• The pipe syntax | requires Python 3.9+

Next Steps

Extend this pattern:

  1. Add memory for multi-turn conversations using RunnableWithMessageHistory
  2. Swap GPT-3.5 for GPT-4o-mini for better quality at lower cost
  3. Chain multiple prompts together for multi-step reasoning
  4. Add output validation with Pydantic models instead of StrOutputParser
  5. See the Save & Load Config tutorial to serialize this chain for production

🚀 Building Something Bigger?

I help teams productionize LangChain apps with proper pipelines, config management, and monitoring.

Let's Talk