> ## Documentation Index
> Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Chains

> Explains LangChain chains as modular, composable pipelines connecting prompts, models, retrieval, parsing, memory, and functions to build sequential, parallel, conditional, and stateful workflows.

The name LangChain highlights that the framework is centered on chains — composable pipelines that connect modular components to perform multi-stage tasks. Chains let you assemble prompts, models, functions, retrievers, output parsers, memory, and even other chains into a single workflow that produces a final result for your application.

Chains can be composed in different topologies:

* Sequential: components run in a defined order, with each step receiving the previous step's output (for example: prompt → LLM → output parser).
* Parallel / concurrent: multiple components run at the same time (for example: multiple retrievers or API calls), and their outputs are aggregated and passed downstream.
* Conditional / routing: logic chooses which sub-chain to run based on input or intermediate results.
* Stateful / memory-enabled: chains incorporate memory components to maintain context across invocations (useful for chat or multi-turn workflows).

<Frame>
  <img src="https://mintcdn.com/kodekloud-c4ac6d9a/Xqjckn2TzkOV2Gz2/images/LangChain/Key-Components-of-LangChain/Chains/stylized-chain-prompts-models-functions.jpg?fit=max&auto=format&n=Xqjckn2TzkOV2Gz2&q=85&s=73e23d00d43c9d2396c13d0c956ee1b6" alt="The image shows a stylized chain divided into three colored sections labeled &#x22;Prompts,&#x22; &#x22;Models,&#x22; and &#x22;Functions.&#x22; The sections are connected, visually representing a process or workflow." width="1920" height="1080" data-path="images/LangChain/Key-Components-of-LangChain/Chains/stylized-chain-prompts-models-functions.jpg" />
</Frame>

Practical patterns and when to use them:

* One-off responses: Use a minimal sequential chain (prompt → LLM) when you only need a single formatted response.
* Retrieval-augmented generation (RAG): Add a retriever step before the LLM to fetch relevant documents from a knowledge base, then synthesize the retrieved context with the model output.
* Enforced output format: Insert an output parser after the model to validate, normalize, or transform responses into structured formats (JSON, CSV, etc.).
* Stateful conversations: Add memory to persist prior conversation turns or results and feed them back into the prompt/context.
* Parallel enrichment: Run multiple retrievers, APIs, or models in parallel and then aggregate outputs (rank, dedupe, or fuse) before the final step.
* Composability: Build sub-chains and reuse them as single components inside larger pipelines.

Table: Common chain types, use cases, and conceptual examples

| Chain Type            | Use Case                                          | Conceptual Example                                       |             |
| --------------------- | ------------------------------------------------- | -------------------------------------------------------- | ----------- |
| Sequential            | Single linear flow (prompt → model → parser)      | `prompt -> LLM -> OutputParser`                          |             |
| Retrieval + LLM (RAG) | Augment model with external documents             | `retriever -> combine -> LLM -> parser`                  |             |
| Parallel / Concurrent | Enrich results or call multiple APIs concurrently | `parallel([retrieverA, retrieverB]) -> aggregate -> LLM` |             |
| Router / Conditional  | Route input to different sub-chains               | \`router(input) -> subchainA                             | subchainB\` |
| Stateful (Memory)     | Maintain context across turns                     | `memory + prompt -> LLM -> memory.update()`              |             |

Example snippets (conceptual pseudo-code)

* Simple sequential chain (prompt → LLM → parser)

```python theme={null}
# Pseudo-code (conceptual)
prompt = PromptTemplate("Summarize the text: {text}")
llm_output = LLM.call(prompt.format(text=article))
structured = OutputParser.parse(llm_output)
return structured
```

* Retrieval-augmented generation (RAG) with a retriever and combiner

```python theme={null}
# Pseudo-code (conceptual)
query = "What does the user ask about X?"
docs = Retriever.search(query, top_k=5)        # fetch relevant documents
context = Combiner.combine(docs)               # combine/truncate for context window
response = LLM.call(prompt_with_context(query, context))
return OutputParser.parse(response)
```

* Parallel retrieval and aggregation

```python theme={null}
# Pseudo-code (conceptual)
results = parallel_run([RetrieverA.search(q), RetrieverB.search(q)])
merged = deduplicate_and_rank(results)
answer = LLM.call(prompt_with_context(q, merged[:10]))
```

Best practices

* Keep chains modular: encapsulate repeatable logic in sub-chains and reuse them as building blocks.
* Validate outputs: use output parsers or schema validators early when the downstream system expects structured data.
* Control context size: when combining many documents or tool outputs, apply truncation or scoring to fit the model's context window.
* Monitor latency and cost: parallel steps can increase responsiveness but may also raise cost; balance concurrency with budget and SLAs.
* Version and test sub-chains: since chains are composable, maintaining tests for each sub-chain prevents regression when reusing them.

<Callout icon="lightbulb" color="#1CB2FE">
  Chains provide a modular way to build complex pipelines by combining prompts, models, retrieval, parsing, and functions into reusable units.
</Callout>

Chains are a foundational capability in LangChain. For implementation details and API-specific examples, see the official LangChain documentation: [LangChain — Chains](https://langchain.readthedocs.io/) and related guides for retrieval, memory, and output parsers.

<CardGroup>
  <Card title="Watch Video" icon="video" cta="Learn more" href="https://learn.kodekloud.com/user/courses/langchain/module/5bedac05-3eaa-4d0d-9892-e05b80c528fb/lesson/79d145d4-21fc-49e3-af36-4616e469466f" />
</CardGroup>
