0
0
LangChainframework~5 mins

What is a chain in LangChain

Choose your learning style9 modes available
Introduction

A chain in LangChain helps you connect different steps to process language tasks smoothly. It makes complex tasks easier by linking simple parts together.

When you want to combine multiple language model calls in a sequence.
When you need to process input through several steps, like summarizing then translating.
When building chatbots that follow a flow of questions and answers.
When automating tasks that require several language-based actions in order.
When you want to reuse small pieces of logic and connect them for bigger tasks.
Syntax
LangChain
from langchain.chains import LLMChain

chain = LLMChain(llm=llm, prompt=prompt)
result = chain.run("input_text")
A chain connects prompts and language models to run tasks step-by-step.
You create a chain by specifying the language model and the prompt or logic it uses.
Examples
This example creates a chain that translates English text to French using a prompt template.
LangChain
from langchain.chains import LLMChain
from langchain.llms import OpenAI
from langchain.prompts import PromptTemplate

llm = OpenAI()
prompt = PromptTemplate(template="Translate this to French: {text}", input_variables=["text"])
chain = LLMChain(llm=llm, prompt=prompt)
result = chain.run("Hello, how are you?")
This shows how to link two chains in order, passing output from one to the next.
LangChain
from langchain.chains import SequentialChain

chain1 = LLMChain(...)
chain2 = LLMChain(...)

seq_chain = SequentialChain(chains=[chain1, chain2], input_variables=["input"], output_variables=["output"])
result = seq_chain.run({"input": "Some text"})
Sample Program

This program uses a chain to ask the language model for a company name based on a product description.

LangChain
from langchain.llms import OpenAI
from langchain.prompts import PromptTemplate
from langchain.chains import LLMChain

# Create a language model instance
llm = OpenAI(temperature=0)

# Define a prompt template
prompt = PromptTemplate(
    template="What is a good name for a company that makes {product}?",
    input_variables=["product"]
)

# Create a chain with the model and prompt
chain = LLMChain(llm=llm, prompt=prompt)

# Run the chain with input
result = chain.run("colorful socks")
print(result)
OutputSuccess
Important Notes

Chains help organize language model calls into clear steps.

You can build complex workflows by combining simple chains.

Always test your chain with sample inputs to see how it behaves.

Summary

A chain links language model calls and prompts to perform tasks step-by-step.

Use chains to build flows like translation, summarization, or chatbots.

LangChain provides different chain types to fit your needs.