LangChain

Key Components of LangChain

Chains

Chains are the fundamental building blocks of LangChain. They let you assemble prompts, language models (LLMs), retrieval components, parsers, functions, and even other chains into unified pipelines. With chains, you can design complex, end-to-end workflows that enhance the capabilities of your language model applications.

The image shows three colored chain link icons stacked vertically, with an API gear icon above them, labeled "Chains."

Why Use Chains?

By composing modular stages—such as retrievers, prompts, LLMs, and output parsers—you can:

  • Inject relevant context before calling an LLM
  • Validate or transform model outputs
  • Orchestrate multi-step processes, from data fetching to API calls

This approach scales from simple one-step interactions to sophisticated pipelines that power production systems.

Core Chain Components

ComponentPurposeLangChain Class Example
RetrieverFetches contextual data (e.g., from a vector store)VectorDBRetriever
PromptDefines the template for LLM inputPromptTemplate
LLMExecutes the prompt and generates the raw completionOpenAI, AzureOpenAI
Output ParserParses or validates LLM outputs (e.g., JSON, regex)PydanticOutputParser
Function CallInvokes external APIs or Python functions as part of flowStructuredToolChain

Note

You can easily insert an output parser to enforce structure on your LLM’s response (for example, ensure valid JSON).

Basic Sequential Chain Example

The following example shows how to build a simple translation chain:

from langchain import PromptTemplate, OpenAI, LLMChain

# 1. Define a prompt template
template = "Translate the following text to French:\n\n{text}"
prompt = PromptTemplate(template=template, input_variables=["text"])

# 2. Initialize the LLM
llm = OpenAI(temperature=0.0)

# 3. Assemble the chain
translation_chain = LLMChain(
    llm=llm,
    prompt=prompt
)

# 4. Run the chain
result = translation_chain.run({"text": "Hello, world!"})
print(result)  # "Bonjour le monde !"

Chain Execution Modes

Chains in LangChain support two primary execution modes:

Chain TypeDescriptionUse Case
SequentialChainExecutes each component step-by-step in a defined orderPrompt → LLM → Parser
Router/ParallelDispatches inputs to multiple branches in parallel, then merges outputCalling different APIs or data sources

Warning

Parallel execution can increase throughput but may also raise costs on API calls. Monitor usage carefully.

Next Steps

Chains are highly extensible. In upcoming sections, we’ll cover:

  • Customizing chains with callbacks and middleware
  • Building nested or recursive chains
  • Integrating chains with external data stores and tools

For more details, see the LangChain Chains documentation.

Watch Video

Watch video content

Previous
Retrieval
Next
Tools