Module 4 Lesson 3: Sequential Chains
·LangChain

Module 4 Lesson 3: Sequential Chains

Multi-Step reasoning. How to pipe the output of one LLM call directly into the input of a second LLM call.

Sequential Chains: The Logic Chain

Rarely does an AI solve a complex problem in one step. An agent usually needs to Think (Step 1) and then Execute (Step 2). A Sequential Chain is when you take the output string of Chain A and use it as a variable in the prompt for Chain B.

1. The "Writer-Translator" Pattern

Imagine you want an AI to write a joke and then translate it to French.

# Chain 1: Write a joke
chain_one = ChatPromptTemplate.from_template(\"Joke about {topic}\") | model | StrOutputParser()

# Chain 2: Translate the result
chain_two = ChatPromptTemplate.from_template(\"Translate to French: {joke}\") | model | StrOutputParser()

# COMBINE THEM
# We use a lambda or a dictionary to map the output of chain_one to the input of chain_two
full_chain = (
    {\"joke\": chain_one} 
    | chain_two
)

result = full_chain.invoke({\"topic\": \"Cats\"})

2. Passing Multiple Inputs

Sometimes you need to keep the original input while adding the new output. We use RunnablePassthrough for this.

from langchain_core.runnables import RunnablePassthrough

# This ensures 'topic' and 'joke' are both available to the next step
full_chain = (
    {\"topic\": RunnablePassthrough(), \"joke\": chain_one} 
    | chain_two
)

3. Visualizing the Sequence

graph TD
    In[Topic: 'Business'] --> C1[Chain 1: Generate Slogan]
    C1 -->|Slogan: 'Fast Code'| C2[Chain 2: Review Slogan]
    C2 -->|Review: 'Too generic'| C3[Chain 3: Improve Slogan]
    C3 --> Final['Vortex Engineering']

4. Why this is safer than "One Big Prompt"

If you ask one model to "Write a slogan, review it, and then improve it" in one single prompt, the model often gets lazy and skips the review. By using Sequential Chains, you force the model to finish the "Slogan" before it even sees the "Review" instructions. This leads to much higher quality.


5. Engineering Tip: Debugging Steps

With sequential chains, if the French translation is bad, you can look at the intermediate "Joke" step to see if the problem was the translation or the joke itself.


Key Takeaways

  • Sequential Chains break big problems into small, accurate steps.
  • RunnablePassthrough helps maintain context between steps.
  • Multi-step chains are more reliable than single, massive prompts.
  • Granular Debugging is the primary advantage of sequential architecture.

Subscribe to our newsletter

Get the latest posts delivered right to your inbox.

Subscribe on LinkedIn