pythonintermediate

LangChain Sequential Multi-Step Chain

Build a multi-step reasoning pipeline where each step's output feeds into the next chain.

python
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser

llm    = ChatOpenAI(model='gpt-4o-mini')
parser = StrOutputParser()

outline_chain = (
    ChatPromptTemplate.from_template('Create a 3-point outline for an article about: {topic}')
    | llm | parser
)

write_chain = (
    ChatPromptTemplate.from_template('Write a short introduction paragraph based on this outline:\n{outline}')
    | llm | parser
)

seo_chain = (
    ChatPromptTemplate.from_template('Generate 5 SEO keywords for this intro:\n{intro}')
    | llm | parser
)

full_pipeline = ({'outline': outline_chain} | {'intro': write_chain, 'outline': lambda x: x['outline']} | {'keywords': seo_chain, 'intro': lambda x: x['intro']})

result = full_pipeline.invoke({'topic': 'Python data engineering'})
print(result)

Use Cases

  • multi-step AI pipelines
  • content generation
  • sequential processing

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.