Skip to main content

Chains in LangChain

The Role of Chains in LangChain

Chains in LangChain serve as the fundamental orchestration mechanism for guiding language model behavior through structured, multi-step tasks. Unlike agents, which determine the control flow at runtime, chains are deterministic pipelines where each step is predefined and executed in sequence.

Chains are ideal for scenarios that require controlled reasoning, sequential formatting, and repeated application of logic—such as summarizing data, formatting outputs, transforming inputs, or chaining multiple LLM calls.

LangChain supports several chain variants:

  • LLMChain: A basic chain that pairs a single prompt with a language model.
  • SimpleSequentialChain: A linear chain of multiple LLMs where the output of one is passed to the next.
  • SequentialChain: A more advanced version that allows named inputs/outputs and intermediate variable passing.
Creating an LLMChain for Question Answering

The simplest chain in LangChain is the LLMChain, which takes a prompt and an LLM and returns a response. This is appropriate for atomic tasks such as Q&A, summarization, or classification.

🔗 Open in Colab
llm = ChatOpenAI(model="gpt-4", temperature=0)

prompt = PromptTemplate( input_variables=["topic"], template="What are the latest trends in {topic}?" )

chain = LLMChain(llm=llm, prompt=prompt) response = chain.run({"topic": "machine learning"}) print(response)

In this example, the prompt is dynamically populated based on user input. The LLMChain encapsulates the full round-trip of generation.

Composing Multi-Step Logic with SimpleSequentialChain

SimpleSequentialChain allows the developer to stack multiple LLMChain objects in a pipeline. The output of one chain is fed directly into the next as input. This is useful for cases where reasoning and formatting are performed in stages.

Example: Summarize → Rephrase

🔗 Open in Colab
from langchain.chains import SimpleSequentialChain

First Chain: Summarize input text
summarize_prompt = PromptTemplate( input_variables=["input_text"], template="Summarize this content: {input_text}" ) summarize_chain = LLMChain(llm=llm, prompt=summarize_prompt)

Second Chain: Rephrase the summary
rephrase_prompt = PromptTemplate( input_variables=["text"], template="Rephrase this summary professionally: {text}" ) rephrase_chain = LLMChain(llm=llm, prompt=rephrase_prompt)

Compose the chain
pipeline = SimpleSequentialChain(chains=[summarize_chain, rephrase_chain], verbose=True)

output = pipeline.run("The global AI market is projected to grow significantly over the next decade.") print(output)

This model shows how output from one reasoning stage can be transformed and refined in subsequent steps.

Advanced Composition with SequentialChain

SequentialChain introduces greater control by allowing the developer to name inputs and outputs. This enables complex multi-step processes where intermediate outputs are preserved and passed selectively.

Use Case: Extract Entities → Summarize → Format Response

🔗 Open in Colab
from langchain.chains import SequentialChain

Prompt 1: Extract named entities
entity_prompt = PromptTemplate( input_variables=["input_text"], template="Extract all people, organizations, and locations from the following: {input_text}" ) entity_chain = LLMChain(llm=llm, prompt=entity_prompt, output_key="entities")

Prompt 2: Summarize entities
summary_prompt = PromptTemplate( input_variables=["entities"], template="Summarize the following extracted entities: {entities}" ) summary_chain = LLMChain(llm=llm, prompt=summary_prompt, output_key="summary")

Prompt 3: Format response
format_prompt = PromptTemplate( input_variables=["summary"], template="Format this into a user-friendly paragraph: {summary}" ) format_chain = LLMChain(llm=llm, prompt=format_prompt, output_key="final_output")

Compose the multi-step chain
sequential_chain = SequentialChain( chains=[entity_chain, summary_chain, format_chain], input_variables=["input_text"], output_variables=["final_output"], verbose=True )

result = sequential_chain({"input_text": "OpenAI and Google DeepMind are competing in developing AGI."}) print(result["final_output"])

This modular design enables debugging, logging, and reusability.

Popular posts from this blog

Intelligent Agents and Their Application to Businesses

Intelligent agents have moved from a research topic to something most businesses now interact with directly. An agent is software that perceives its environment (a database, a webpage, a codebase, a set of sensors), decides what to do next, and takes action toward a goal, largely on its own, adjusting as conditions change. What used to be a narrow academic definition now describes tools millions of people use daily: coding assistants that read a codebase and ship a fix, browsing agents that complete a multi-step task on a website, and customer-facing bots that resolve a support ticket end to end instead of just answering one question. What Makes Something an "Agent," Not Just a Model A language model on its own answers a question. An agent does something with the answer: it calls a tool, queries a database, sends an email, or hands a result to another agent, then observes what happened and decides on the next step. That loop, perceive, reason, act, observe, repeat, is wha...

Exploring Sentiment Analysis Using Support Vector Machines

Sentiment analysis, a powerful application of Natural Language Processing (NLP), involves extracting opinions, attitudes, and emotions from textual data. It enables businesses to make data-driven decisions by analyzing customer feedback, social media posts, and other text-based interactions. Modern sentiment analysis has evolved from simple rule-based methods to advanced machine learning and deep learning approaches that detect subtle nuances in language. As text communication continues to dominate digital interactions, sentiment analysis is an essential tool for understanding public opinion and driving actionable insights. The GoEmotions Dataset The GoEmotions dataset, developed by Google Research, is a benchmark in emotion recognition. It consists of over 67,000 text entries labeled across 27 emotion categories, such as joy, anger, admiration, and sadness. For practical applications, these emotions can be grouped into broader categories like positive and negati...

Role of Fourier Transform in Speech Recognition

Speech recognition has become an integral part of modern technology, from voice assistants to transcription services. A key mathematical tool enabling these advancements is the Fourier Transform (FT), particularly its variant, the Short-Time Fourier Transform (STFT). The Fourier Transform provides a way to convert speech signals from the time domain to the frequency domain, allowing us to extract meaningful features for analysis and recognition. Why Use Fourier Transform in Speech Recognition? Speech signals are inherently time-domain signals, with varying amplitude over time. However, speech carries crucial information in its frequency content, such as phonemes, tones, and pitch. The Fourier Transform enables us to analyze these characteristics by breaking the signal into its constituent frequencies. The Fourier Transform is widely used in speech recognition for: Spectrogram Generation: Converting speech signals into visual representations of frequency over time. Fea...