Skip to main content
← Back to Blog
2026-02-22 · 9 min readAI AgentsPythonUpdated Oct 29, 2026

Building Your First LLM Chain: A Developer's Guide to Sequential Logic

A code-first tutorial for your first sequential LLM chain. You wire two prompts together with LangChain's pipe operator, see exactly how the output of step one becomes the input of step two, keep the middle result so you can rerun only the last step, and test the whole chain with a fake model before you spend a token.

Avnish Yadav
AI Automation Engineer & Salesforce Developer
19 views
Building Your First LLM Chain: A Developer's Guide to Sequential Logic

This tutorial is for developers who can call an LLM once and now need several calls to work together. You will build a small two-step chain in Python with LangChain: the first prompt picks an angle for a topic, the second writes a LinkedIn post from that angle. You will also test it with a fake model, so you can check the wiring before you pay for a single token.

Key takeaways

  • A chain passes the output of one step into the next. In LangChain you build it with the | (pipe) operator.
  • A dict inside a chain runs its values on the same input and hands a dict to the next step. That is how you rename an output to fit the next prompt.
  • Small steps are easier to debug and cheaper to rerun. Keep the middle result, and you can redo only the last step.

Why one prompt is not enough

If you have used ChatGPT or the OpenAI API, you know the loop: send text, get text back. For many tasks, that is enough.

Real apps often need more than one step. You might take a topic, pick an angle, and then write the post. Or you might pull data out of an email, turn it into JSON, and then decide whether to draft a reply or open a ticket.

An LLM chain is a sequence of steps where the output of one step becomes the input of the next. LangChain's reference calls this a RunnableSequence and names it the most important way to compose steps.

This post is part 4 of the LLM & LangChain Fundamentals series. In part 3 you made a model return structured JSON with Pydantic and retry loops. Here you connect two calls.

What you will build

A tiny content engine with two steps:

  1. Ideator: takes a broad topic and returns one specific, contrarian angle.
  2. Writer: takes that angle and writes a short LinkedIn post.

Splitting the work this way mirrors how a person writes. You decide what to say before you decide how to say it. Each prompt has one job, so each one is short and easy to read.

Set up the project

You need Python 3.10 or newer (both packages require it on PyPI) and an OpenAI API key for the real run. The test at the end needs only a placeholder key.

Create a virtual environment, then install the packages:

python -m venv .venv
source .venv/bin/activate
pip install -U langchain-core langchain-openai python-dotenv

Put your key in a .env file next to your code, and add .env to .gitignore so it never reaches your repository:

OPENAI_API_KEY=your-key-here

The core idea: pipes

Older LangChain code built chains from classes such as LLMChain. Current code uses the pipe operator, often called LCEL (LangChain Expression Language). If you have piped commands in a Unix shell, it will feel familiar:

chain = prompt | model | output_parser

Data flows left to right. The prompt template fills in your variables, the model replies with a message, and the parser turns that message into a plain string. Each piece is a "runnable", and a | b gives you a new runnable that runs a, then b.

Step 1: Choose a model

Create a file named chain_builder.py and start with the imports and the model:

import os

from dotenv import load_dotenv
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import RunnablePassthrough
from langchain_openai import ChatOpenAI

load_dotenv()  # reads OPENAI_API_KEY from a local .env file

# A small, cheap model while you iterate; swap the id for a larger one later.
model = ChatOpenAI(model=os.getenv("CHAIN_MODEL", "gpt-6-luna"))

Checked against langchain-core@1.7.1 and langchain-openai@1.7.3, 2026-10-29.

A good habit is to build and test with a small, cheap model, then switch to a stronger one when the chain works. On the date above, OpenAI's models page calls gpt-6-luna its most efficient model for focused, high-volume tasks. If you're not sure where to start, the page points you to gpt-6-astra, its flagship model for complex reasoning and coding. Model ids change often, so check that page before you pick one. Reading the id from an environment variable lets you switch without touching code.

Many older examples set temperature=0.7. In the main example on LangChain's ChatOpenAI page, temperature appears only as a commented-out option, and the OpenAI model pages linked here don't mention it. Leave it out unless your model's docs list it.

Prefer Claude or another provider?

Only the model line changes. init_chat_model from the langchain package takes a provider and a model id, such as "anthropic:claude-sonnet-5-5" or "openai:gpt-6-luna" (run pip install -U langchain langchain-anthropic for Claude). Check the provider's models page for current ids. The prompts, pipes and parser stay the same.

The first prompt takes a topic and returns a single angle. Plain text is fine here. Asking for "the angle only, in one sentence" keeps the output small, so the next prompt gets a clean input.

ideation_prompt = ChatPromptTemplate.from_template(
    "You are a tech content strategist. Given the topic '{topic}', "
    "generate one specific, contrarian and engaging angle for a LinkedIn post. "
    "Reply with the angle only, in one sentence."
)
ideation_chain = ideation_prompt | model | StrOutputParser()

If you run ideation_chain.invoke({"topic": "AI Agents"}), you get one string back. It might read something like "AI agents will change managers' jobs before developers' jobs." Your text will differ on every run.

The writer needs the angle as its input, so its prompt uses an {angle} variable:

writing_prompt = ChatPromptTemplate.from_template(
    "Write a short, punchy LinkedIn post based on this angle: {angle}. "
    "Use a professional but direct tone. No hashtags."
)
writing_chain = writing_prompt | model | StrOutputParser()

Now feed the ideator's output into the writer. The ideator returns a string, but the writer's prompt wants a dict with an angle key. A dict literal does that mapping:

full_chain = {"angle": ideation_chain} | writing_chain

You will run it at the end of the file, in the "Run the chain" section below.

How that works

Here is what happens inside {"angle": ideation_chain} | writing_chain:

  1. .invoke({"topic": ...}) passes your dict to the first part of the chain.
  2. That first part is a plain dict. LangChain turns a dict inside a chain into a RunnableParallel, which gives the same input to every value in it.
  3. ideation_chain gets {"topic": ...}, fills in its prompt and returns the angle as a string.
  4. The result is stored under the key angle, so the next step receives {"angle": "..."}.
  5. writing_chain finds {angle} in that dict and writes the post.

You don't need any extra class for this. The RunnablePassthrough import is for the next section.

Keep the middle result

full_chain only returns the final post. Often you want the angle too, so you can show it, log it or reuse it. RunnablePassthrough.assign adds a new key to the input dict and keeps the keys already there:

keep_angle_chain = (
    RunnablePassthrough.assign(angle=ideation_chain)
    | RunnablePassthrough.assign(post=writing_chain)
)

In my own micro-SaaS backends, I often cache the result of Step 1. If the user wants to rewrite the post, the angle stays and only Step 2 runs again. That saves a model call each time.

Run the chain

Add the run code at the bottom of chain_builder.py. It sits under if __name__ == "__main__":, so it runs only when you start the file with python chain_builder.py. Importing the file, as the test below does, runs no model calls.

if __name__ == "__main__":
    topic = "Remote Work for Developers"
    print(f"--- Generated post for: {topic} ---\n")
    print(full_chain.invoke({"topic": topic}))

    out = keep_angle_chain.invoke({"topic": topic})
    # out == {"topic": "...", "angle": "...", "post": "..."}

    # Rewrite only the post, reusing the saved angle:
    print(writing_chain.invoke({"angle": out["angle"]}))

Test the chain without a real API key

You can check the wiring before you pay for a call. Save this as test_chain.py next to chain_builder.py. langchain_core ships FakeListChatModel, a fake chat model for testing. It returns the replies you give it, in order, and never touches the network.

from langchain_core.language_models.fake_chat_models import FakeListChatModel
from langchain_core.output_parsers import StrOutputParser

from chain_builder import ideation_prompt, writing_prompt

fake = FakeListChatModel(responses=["ANGLE-1", "POST-1"])
ideation = ideation_prompt | fake | StrOutputParser()
writing = writing_prompt | fake | StrOutputParser()

chain = {"angle": ideation} | writing
assert chain.invoke({"topic": "Remote Work for Developers"}) == "POST-1"
print("chain wiring works")

Importing chain_builder.py skips the run code, because that code sits under the __main__ guard. The import still creates a ChatOpenAI object, and that needs OPENAI_API_KEY to be set. Any placeholder value works, such as OPENAI_API_KEY=placeholder python test_chain.py, because the fake model makes the only calls.

The first fake reply goes to the ideator, the second to the writer. If the keys don't line up (say the writer's prompt asked for {idea}), the chain fails here with a missing-variable error, and you have spent nothing.

Why not one big prompt?

You could put both instructions in one large prompt. It works for small tasks, but it gets harder to live with as the task grows:

Concern One big prompt A two-step chain
Debugging A bad result could come from the angle or the writing You can read the angle on its own
Changing the style The whole job runs again Only the writer runs again
Prompt length One long prompt carries every instruction Each prompt holds one short job

Length matters because the "Lost in the Middle" study found that models use information at the start or end of a long input better than information in the middle.

As a rule of thumb, split a prompt when it does two jobs you would want to check or change on their own.

From chains to agents

A chain is a fixed path: step A always leads to step B. That is a strength, because it is predictable and easy to test.

An agent is different. The model decides which tool or step to run next, based on the input. That gives you flexibility, but it is harder to predict and to test. Get comfortable with chains first, then read how to build an AI agent from scratch.

Try adding a third step to your chain: a "critic" prompt that reads the post and suggests one improvement. It's the same pattern again: one more dict key and one more pipe.

Next in the series, you will use chains to feed your own documents to a model in Building your first RAG pipeline.

Frequently asked questions

Should I still use LLMChain?

For new code, no. Current LangChain code builds chains with the pipe operator, which creates a RunnableSequence. LLMChain belongs to the older class-based style, so write prompt | model | parser instead.

What does the dict in {"angle": ideation_chain} | writing_chain do?

LangChain turns a dict inside a chain into a RunnableParallel. It runs each value on the same input and returns a dict of the results. Here it renames the ideator's string output to the angle key that the writer's prompt needs.

How do I get both the middle and final outputs from a chain?

Use RunnablePassthrough.assign. It adds a new key to the input dict and keeps the existing keys. Two assign steps in a row return the topic, the angle and the post together.

How can I test a LangChain chain without a real API key?

Swap the real model for FakeListChatModel from langchain_core. It returns the replies you list, in order, without calling a provider. That checks your prompt variables and wiring for free.

Which model should I use for this tutorial?

Any chat model works. A small, cheap model is a good choice while you build. Check the provider's models page for current ids, because they change often, and read the id from an environment variable so you can switch without code changes.

Sources

Verified against the sources below on October 29, 2026. Products and docs change often: check the linked sources if something looks different.

  1. LangChain reference: RunnableSequence
  2. LangChain reference: RunnableParallel
  3. LangChain reference: FakeListChatModel
  4. LangChain: ChatOpenAI integration
  5. LangChain: Models (init_chat_model)
  6. OpenAI API: Models
  7. langchain-core on PyPI
  8. langchain-openai on PyPI
  9. Lost in the Middle: How Language Models Use Long Contexts (Liu et al.)
All 14 parts in this series
Written by

Avnish Yadav

AI Automation Engineer & Salesforce Developer

Salesforce developer since June 2018. I build AI agents, n8n workflows and Salesforce integrations, and write up what holds up in real use.

About meLinkedIn

Share
Discussion

Comments

Loading comments...

Add a comment

Comments are reviewed before they appear.