# SOLID Principles in Python, Explained by Building a LangGraph Agent

> SOLID principles in Python, explained by building one LangGraph support agent: single responsibility, open/closed, Liskov, interface segregation, DIP.

Author: Saksham Malhotra
Published: 2026-10-31
Canonical: https://sakshambuilds.dev/writing/solid-principles

## TL;DR

- **S, Single Responsibility:** one class, one reason to change.
- **O, Open/Closed:** add behaviour by adding a class, not by editing one that works.
- **L, Liskov Substitution:** every subclass must keep the parent's promise. No type checks at the call site.
- **I, Interface Segregation:** small interfaces. No class implements things it can't support.
- **D, Dependency Inversion:** depend on interfaces and pass the real thing in. Don't create concrete classes inside.

## What are we building?

A customer support agent with [LangGraph](https://langchain-ai.github.io/langgraph/). A ticket comes in, and the graph:

1. classifies it (bug, how-to or feature request),
2. searches the help docs,
3. drafts a reply, calling tools like an issue lookup when it needs facts,
4. posts the draft to Slack for a human to approve.

Every node reads and updates one shared state:

```python
class TicketState(TypedDict, total=False):
    ticket: str
    category: str
    docs: list[str]
    reply: str
```

Each principle has a **Before** and **After** class diagram. Click to switch.

- `<<abstract>>` marks an interface.
- A hollow arrow means "inherits from".
- A plain arrow means "uses", and a dashed one means "creates".
- Red is the problem. Green is new code.

## What is the Single Responsibility Principle?

A class should have one reason to change.

```mermaid
---
title: Before
---
classDiagram
    direction LR
    class SupportAgent {
        +handle(state) dict
    }
    note for SupportAgent "classifies, searches docs, drafts and posts to Slack"
    SupportAgent ..> ChatOpenAI : creates
    SupportAgent ..> Chroma : creates
    SupportAgent ..> WebClient : creates
    class SupportAgent:::broken
    classDef broken stroke:#f87171,stroke-width:2px,fill:#4a1414,color:#fecaca
```

```mermaid
---
title: After
---
classDiagram
    direction LR
    class TicketClassifier {
        +classify(state) dict
    }
    class DocRetriever {
        +retrieve(state) dict
    }
    class ReplyDrafter {
        +draft(state) dict
    }
    class SlackPublisher {
        +publish(state) dict
    }
    StateGraph --> TicketClassifier : node
    StateGraph --> DocRetriever : node
    StateGraph --> ReplyDrafter : node
    StateGraph --> SlackPublisher : node
```

**Before:** one class does the whole job.

```python
class SupportAgent:
    def __init__(self):
        self.llm = ChatOpenAI()
        self.vector_store = Chroma(collection_name=DOCS_COLLECTION, embedding_function=OpenAIEmbeddings())
        self.slack = WebClient(token=os.environ["SLACK_TOKEN"])

    def handle(self, state: TicketState) -> dict:
        category = self.llm.invoke(CLASSIFY_PROMPT.format(ticket=state["ticket"])).content
        docs = [doc.page_content for doc in self.vector_store.similarity_search(state["ticket"], k=TOP_K)]
        reply = self.llm.invoke(DRAFT_PROMPT.format(docs="\n".join(docs), ticket=state["ticket"])).content
        self.slack.chat_postMessage(channel=SUPPORT_CHANNEL, text=reply)
        return {"category": category, "docs": docs, "reply": reply}
```

It's hard to extend. Tweaking the classifier prompt, changing how many docs come back, and moving from Slack to email all mean editing `handle` and retesting all four steps. A slip in one step breaks the other three.

**After:** one class per job. Each one becomes its own node in the graph.

```python
class TicketClassifier:
    def __init__(self):
        self.llm = ChatOpenAI()

    def classify(self, state: TicketState) -> dict:
        prompt = CLASSIFY_PROMPT.format(ticket=state["ticket"])
        return {"category": self.llm.invoke(prompt).content}


class SlackPublisher:
    def __init__(self):
        self.slack = WebClient(token=os.environ["SLACK_TOKEN"])

    def publish(self, state: TicketState) -> dict:
        self.slack.chat_postMessage(channel=SUPPORT_CHANNEL, text=state["reply"])
        return {}

# DocRetriever.retrieve and ReplyDrafter.draft follow the same shape.

graph = StateGraph(TicketState)
graph.add_node("classify", TicketClassifier().classify)
graph.add_node("retrieve", DocRetriever().retrieve)
graph.add_node("draft", ReplyDrafter().draft)
graph.add_node("publish", SlackPublisher().publish)
graph.add_edge(START, "classify")
graph.add_edge("classify", "retrieve")
graph.add_edge("retrieve", "draft")
graph.add_edge("draft", "publish")
graph.add_edge("publish", END)
app = graph.compile()
```

A prompt change touches `TicketClassifier` alone. The other nodes and their tests stay untouched. LangGraph nudges you this way already, since every node is a separate step.

Each class still creates its own `ChatOpenAI` and `WebClient`. Dependency Inversion fixes that, and it's covered last.

Think of a restaurant kitchen. The chef cooks and the waiter serves. Ask the chef to wait tables too, and the food burns the moment it gets busy.

## What is the Open/Closed Principle?

Open to extension, closed to modification. A new feature should be a new class, not an edit to code that already works.

The drafter calls tools when it needs facts, like whether a bug is already known or whether there's an outage.

```mermaid
---
title: Before
---
classDiagram
    direction LR
    class ToolRunner {
        +run(tool_name, query) str
    }
    note for ToolRunner "if/elif on tool_name. A new tool means editing run()"
    ReplyDrafter --> ToolRunner
    class ToolRunner:::broken
    classDef broken stroke:#f87171,stroke-width:2px,fill:#4a1414,color:#fecaca
```

```mermaid
---
title: After
---
classDiagram
    direction TB
    class Tool {
        <<abstract>>
        +name str
        +run(query) str
    }
    class ToolRunner {
        +run(tool_name, query) str
    }
    ReplyDrafter --> ToolRunner
    ToolRunner --> Tool : tools_by_name
    Tool <|-- IssueLookupTool
    Tool <|-- StatusPageTool
    Tool <|-- ReleaseNotesTool
    note for Tool "each subclass documents itself in its own docstring"
    class ReleaseNotesTool:::added
    classDef added stroke:#4ade80,stroke-width:2px,stroke-dasharray:4 3,fill:#0f2a17,color:#bbf7d0
```

**Before:** one function knows every tool.

```python
class ToolRunner:
    def run(self, tool_name: str, query: str) -> str:
        if tool_name == "issue_lookup":
            return self.issues.get(query).summary()
        elif tool_name == "status_page":
            return requests.get(STATUS_PAGE_URL).json()["status"]
        raise ValueError(f"Unknown tool: {tool_name}")
```

It's hard to extend. Every new tool means editing `run`, which already serves the working ones. You retest all of them, and one wrong branch breaks a tool customers rely on.

**After:** one abstract class, one subclass per tool. Each tool describes itself in its own docstring.

```python
class Tool(ABC):
    """Base class for agent tools. The model never sees this docstring."""

    name: str

    @abstractmethod
    def run(self, query: str) -> str: ...


class IssueLookupTool(Tool):
    """Looks up a known bug by its issue id, like ENG-142, and returns its status."""

    name = "issue_lookup"

    def run(self, query: str) -> str:
        return self.issues.get(query).summary()


class StatusPageTool(Tool):
    """Checks the public status page for ongoing outages."""

    name = "status_page"

    def run(self, query: str) -> str:
        return requests.get(STATUS_PAGE_URL).json()["status"]


class ToolRunner:
    def __init__(self, tools: list[Tool]):
        self.tools_by_name = {tool.name: tool for tool in tools}

    def run(self, tool_name: str, query: str) -> str:
        return self.tools_by_name[tool_name].run(query)
```

A release notes tool is a new `ReleaseNotesTool(Tool)` with its own docstring and tests, added to the list passed to `ToolRunner`. `ToolRunner`, the drafter and the existing tools aren't touched, so they can't break.

How those docstrings actually reach the model is LangChain specific, so I've kept it for the end.

It's the same idea as a camera with swappable lenses. A new lens clicks onto the mount you already have, and nobody opens up the camera body to fit it.

## What is the Liskov Substitution Principle?

A subclass must work anywhere its parent works. The caller shouldn't need to know which subclass it got.

```mermaid
---
title: Before
---
classDiagram
    direction TB
    class Tool {
        <<abstract>>
        +run(query) str
    }
    class IssueLookupTool {
        +run(query) raises IssueNotFoundError
    }
    ToolRunner --> Tool
    Tool <|-- IssueLookupTool
    Tool <|-- StatusPageTool
    note for IssueLookupTool "a typo in the issue id crashes the whole graph run"
    class IssueLookupTool:::broken
    classDef broken stroke:#f87171,stroke-width:2px,fill:#4a1414,color:#fecaca
```

```mermaid
---
title: After
---
classDiagram
    direction TB
    class Tool {
        <<abstract>>
        +run(query) str
    }
    class IssueLookupTool {
        +run(query) str
    }
    ToolRunner --> Tool
    Tool <|-- IssueLookupTool
    Tool <|-- StatusPageTool
    note for Tool "always returns text the model can read. A miss is text too, never an exception"
```

**Before:** the issue lookup raises when the id doesn't exist.

```python
class IssueLookupTool(Tool):
    """Looks up a known bug by its issue id, like ENG-142, and returns its status."""

    def run(self, query: str) -> str:
        issue = self.issues.get(query)
        if issue is None:
            raise IssueNotFoundError(query)
        return issue.summary()
```

A customer pastes an issue id with a typo, the exception escapes the node, and the ticket never gets a reply. The usual patch is `if isinstance(tool, IssueLookupTool): try ... except` inside `ToolRunner`. Now `ToolRunner` has to know every special case, and each new tool means editing it again, retesting it, and hoping the others still work.

**After:** write the promise on the parent's `run`, and keep it in every subclass.

```python
class Tool(ABC):
    @abstractmethod
    def run(self, query: str) -> str:
        """Returns text the model can read. A miss is text too, never an exception."""


class IssueLookupTool(Tool):
    """Looks up a known bug by its issue id, like ENG-142, and returns its status."""

    def run(self, query: str) -> str:
        issue = self.issues.get(query)
        if issue is None:
            return f"No issue found with id {query}. Ask the customer for the link to it."
        return issue.summary()
```

The two docstrings have different readers. The one on `run` is the contract for developers writing tools. The class docstring is what the model reads. More on that at the end.

The model reads the "No issue found" text and asks the customer for the right link, which is better behaviour anyway. `ToolRunner` works with every tool without checking which one it has. A new tool only has to keep the promise. If a subclass truly can't keep it, that behaviour doesn't belong on the parent. Interface Segregation, next, deals with exactly that.

Think of booking a sedan on a rental app. You don't care which one shows up, as long as it drives like a sedan. If it needs a special licence, the booking lied to you.

## What is the Interface Segregation Principle?

No class should be forced to implement things it doesn't use. Several small interfaces beat one that tries to describe everyone.

```mermaid
---
title: Before
---
classDiagram
    direction TB
    class KnowledgeBase {
        <<abstract>>
        +search(query, limit) list
        +add_documents(documents)
        +delete_documents(document_ids)
    }
    class HelpCenterSearch {
        +search(query, limit) list
        +add_documents() raises NotImplementedError
        +delete_documents() raises NotImplementedError
    }
    KnowledgeBase <|-- ChromaKnowledgeBase
    KnowledgeBase <|-- HelpCenterSearch
    class HelpCenterSearch:::broken
    classDef broken stroke:#f87171,stroke-width:2px,fill:#4a1414,color:#fecaca
```

```mermaid
---
title: After
---
classDiagram
    direction TB
    class Searchable {
        <<abstract>>
        +search(query, limit) list
    }
    class Indexable {
        <<abstract>>
        +add_documents(documents)
        +delete_documents(document_ids)
    }
    Searchable <|-- ChromaKnowledgeBase
    Indexable <|-- ChromaKnowledgeBase
    Searchable <|-- HelpCenterSearch
    DocRetriever --> Searchable
    DocIngestor --> Indexable
```

**Before:** the docs interface was written for our own Chroma store, which we search and also re-index every night.

```python
class KnowledgeBase(ABC):
    @abstractmethod
    def search(self, query: str, limit: int) -> list[str]: ...

    @abstractmethod
    def add_documents(self, documents: list[str]) -> None: ...

    @abstractmethod
    def delete_documents(self, document_ids: list[str]) -> None: ...
```

Then we add the public help center's search API as a second source. It's read only, so `add_documents` and `delete_documents` just raise `NotImplementedError`. Adding metadata to `add_documents` later changes an interface every source implements. Every source gets edited and retested, even the read only one. (Those `NotImplementedError` methods break Liskov Substitution too. The two often show up together.)

**After:** split by what each user of the interface actually needs.

```python
class Searchable(ABC):
    @abstractmethod
    def search(self, query: str, limit: int) -> list[str]: ...


class Indexable(ABC):
    @abstractmethod
    def add_documents(self, documents: list[str]) -> None: ...

    @abstractmethod
    def delete_documents(self, document_ids: list[str]) -> None: ...


class ChromaKnowledgeBase(Searchable, Indexable): ...
class HelpCenterSearch(Searchable): ...
```

The retrieve node only needs `Searchable`. The nightly `DocIngestor` job only needs `Indexable`. A change to indexing touches `Indexable` and Chroma, and the help center source doesn't change. Hand a `HelpCenterSearch` to `DocIngestor` and mypy or pyright flags it before it runs.

Job posts work the same way. Nobody hiring a waiter asks them to cook as well, just in case.

## What is the Dependency Inversion Principle?

High level classes, like the graph's nodes, shouldn't depend on low level details like OpenAI, Chroma or Slack. Both should depend on an interface, and the concrete class is passed in.

```mermaid
---
title: Before
---
classDiagram
    direction LR
    TicketClassifier ..> ChatOpenAI : creates
    ReplyDrafter ..> ChatOpenAI : creates
    DocRetriever ..> Chroma : creates
    SlackPublisher ..> WebClient : creates
    class TicketClassifier:::broken
    class ReplyDrafter:::broken
    class DocRetriever:::broken
    class SlackPublisher:::broken
    classDef broken stroke:#f87171,stroke-width:2px,fill:#4a1414,color:#fecaca
```

```mermaid
---
title: After
---
classDiagram
    direction TB
    class BaseChatModel {
        <<abstract>>
    }
    class Searchable {
        <<abstract>>
    }
    class ReplyChannel {
        <<abstract>>
        +send(text)
    }
    TicketClassifier --> BaseChatModel
    ReplyDrafter --> BaseChatModel
    DocRetriever --> Searchable
    ReplyPublisher --> ReplyChannel
    BaseChatModel <|-- ChatOpenAI
    BaseChatModel <|-- ChatOllama
    BaseChatModel <|-- FakeListChatModel
    ReplyChannel <|-- SlackChannel
    ReplyChannel <|-- EmailChannel
    class ChatOllama:::added
    class FakeListChatModel:::added
    class EmailChannel:::added
    classDef added stroke:#4ade80,stroke-width:2px,stroke-dasharray:4 3,fill:#0f2a17,color:#bbf7d0
```

**Before:** every node from the Single Responsibility section creates its own `ChatOpenAI`, `Chroma` or `WebClient`. Running a local model in development, or posting drafts to email, means editing the nodes themselves and retesting the whole graph. And the tests can't run without calling OpenAI and posting into a real Slack channel.

**After:** nodes ask for interfaces in `__init__`. One function wires in the real classes.

```python
class ReplyChannel(ABC):
    @abstractmethod
    def send(self, text: str) -> None: ...


class ReplyPublisher:
    def __init__(self, channel: ReplyChannel):
        self.channel = channel

    def publish(self, state: TicketState) -> dict:
        self.channel.send(state["reply"])
        return {}


class TicketClassifier:
    def __init__(self, llm: BaseChatModel):
        self.llm = llm


def build_support_graph(llm: BaseChatModel, knowledge_base: Searchable, channel: ReplyChannel, tools: list[Tool]):
    graph = StateGraph(TicketState)
    graph.add_node("classify", TicketClassifier(llm).classify)
    graph.add_node("retrieve", DocRetriever(knowledge_base).retrieve)
    graph.add_node("draft", ReplyDrafter(llm, ToolRunner(tools)).draft)
    graph.add_node("publish", ReplyPublisher(channel).publish)
    # same edges as before
    return graph.compile()
```

You don't have to write the LLM interface yourself. LangChain's `BaseChatModel` already is one, and `ChatOpenAI`, `ChatOllama` and the rest all inherit from it.

```python
# production
app = build_support_graph(ChatOpenAI(), ChromaKnowledgeBase(), SlackChannel(), [IssueLookupTool(), StatusPageTool()])

# test: no API calls, no Slack
class FakeToolCallingModel(FakeListChatModel):
    def bind_tools(self, tools, **kwargs):
        return self  # FakeListChatModel can't bind tools, see the LangChain and LangGraph section below


llm = FakeToolCallingModel(responses=["how-to", "Go to Settings, then Export, and pick CSV."])
channel = FakeChannel()
app = build_support_graph(llm, InMemorySearch(HELP_DOCS), channel, [StatusPageTool()])
app.invoke({"ticket": "How do I export my data?"})
assert channel.sent == ["Go to Settings, then Export, and pick CSV."]
```

Moving drafts to email means passing in an `EmailChannel`, and a local model means passing in `ChatOllama`. The nodes and their tests don't change.

Not everything needs an interface. `ToolRunner` stays a concrete class because there's only one. Add the interface when a second implementation shows up.

Your phone charger already works like this. It plugs into the wall socket and couldn't care less whether the power comes from coal or solar.

## LangChain and LangGraph specifics: how tools reach the model

Back to the tools from the Open/Closed section. The model never sees your Python. It only sees each tool's name and description, and picks a tool from those. LangChain's `@tool` decorator reads a function's docstring as its description and refuses a function without one. Class based tools need the same guarantee, so `Tool` grows three LangChain parts:

```python
QUERY_PARAMETERS = {"type": "object", "properties": {"query": {"type": "string"}}, "required": ["query"]}


class Tool(ABC):
    """Base class for agent tools. The model never sees this docstring."""

    name: str

    def __init_subclass__(cls, **kwargs):
        super().__init_subclass__(**kwargs)
        if not cls.__dict__.get("__doc__"):
            raise TypeError(f"{cls.__name__} needs a docstring. The model reads it to decide when to call the tool.")

    @property
    def description(self) -> str:
        return inspect.cleandoc(type(self).__doc__)

    def to_schema(self) -> dict:
        return {"name": self.name, "description": self.description, "parameters": QUERY_PARAMETERS}

    @abstractmethod
    def run(self, query: str) -> str: ...


class ToolRunner:
    def __init__(self, tools: list[Tool]):
        self.tools_by_name = {tool.name: tool for tool in tools}

    def schemas(self) -> list[dict]:
        return [tool.to_schema() for tool in self.tools_by_name.values()]

    def run(self, tool_name: str, query: str) -> str:
        return self.tools_by_name[tool_name].run(query)
```

**Why `type(self).__doc__` and not `inspect.getdoc`?** Python has two ways to read a class's docstring, and they disagree when a subclass forgot one. Without the `__init_subclass__` check:

```python
class StatusPageTool(Tool):  # forgot its docstring
    name = "status_page"


StatusPageTool.__doc__          # None, every class gets its own __doc__, even an empty one
inspect.getdoc(StatusPageTool)  # "Base class for agent tools...", borrowed from the parent
```

- **`inspect.getdoc` hides the mistake.** It falls back to the parent's docstring. Every tool that forgot one would tell the model it's a "Base class for agent tools". The model can't tell those tools apart, and nothing raises an error.
- **`type(self)` is the concrete tool.** `description` is written once, in `Tool`. But at runtime `self` is the actual tool object, so `type(self)` is `StatusPageTool` and `type(self).__doc__` is that class's own docstring.
- **`None` is what makes the check possible.** A missing docstring reads as `None`, not as a borrowed one. So `__init_subclass__` catches it with a `TypeError` the moment the class is defined, not in production when the model picks the wrong tool.
**How does a tool call actually run?** The customer never calls a tool, and neither does the graph. The model asks for one, and the draft node runs it:

```mermaid
sequenceDiagram
    participant Graph as StateGraph
    participant Drafter as ReplyDrafter
    participant Model as ChatModel + bind_tools
    participant Runner as ToolRunner
    participant Tool as IssueLookupTool
    Graph->>Drafter: draft(state)
    Drafter->>Model: invoke(messages)
    Model-->>Drafter: AIMessage with tool_calls
    Drafter->>Runner: run("issue_lookup", "ENG-142")
    Runner->>Tool: run("ENG-142")
    Tool-->>Runner: "ENG-142: fixed in release 4.2"
    Runner-->>Drafter: result text
    Drafter->>Model: invoke(messages + ToolMessage)
    Model-->>Drafter: AIMessage with the reply
    Drafter-->>Graph: {"reply": ...}
```

```python
MAX_TOOL_ROUNDS = 3
TOOL_LIMIT_REPLY = "This one needs a human. The agent hit its tool call limit."


class ReplyDrafter:
    def __init__(self, llm: BaseChatModel, tool_runner: ToolRunner):
        self.llm = llm.bind_tools(tool_runner.schemas())
        self.tool_runner = tool_runner

    def draft(self, state: TicketState) -> dict:
        prompt = DRAFT_PROMPT.format(docs="\n".join(state["docs"]), ticket=state["ticket"])
        messages = [HumanMessage(prompt)]
        for _ in range(MAX_TOOL_ROUNDS):
            response = self.llm.invoke(messages)
            messages.append(response)
            if not response.tool_calls:
                return {"reply": response.content}
            for tool_call in response.tool_calls:
                result = self.tool_runner.run(tool_call["name"], tool_call["args"]["query"])
                messages.append(ToolMessage(result, tool_call_id=tool_call["id"]))
        return {"reply": TOOL_LIMIT_REPLY}
```

1. **`bind_tools` runs once, in `__init__`.** It returns a copy of the model that sends every schema from `ToolRunner.schemas()` (name, description and `QUERY_PARAMETERS`) along with each `invoke`.
2. **The model answers in one of two ways.** Either plain text, which is the reply, or an `AIMessage` whose `tool_calls` lists what it wants run, like `{"name": "issue_lookup", "args": {"query": "ENG-142"}, "id": "call_1"}`. The `args` follow `QUERY_PARAMETERS`, which is why `run` takes a single `query`.
3. **The node runs each call through `ToolRunner`.** It looks the tool up by `name`, and the result goes back as a `ToolMessage` with the same `tool_call_id`, so the model knows which call it answers.
4. **The loop repeats** until the model replies with text. `MAX_TOOL_ROUNDS` stops a model that keeps calling tools, and hands the ticket to a human.

LangGraph can also give tools their own node, with `ToolNode` and `tools_condition` from `langgraph.prebuilt`, which expect LangChain tool objects. The loop above keeps our own `Tool` classes and does the same job inside one node.

## SOLID principles cheat sheet

| Principle | You'll notice it when | What we changed in the agent |
|---|---|---|
| Single Responsibility | Unrelated changes keep landing in the same class | Split it into one class per node: classify, retrieve, draft, publish |
| Open/Closed | Every new feature adds another `elif` | Gave each tool its own `Tool` subclass and docstring |
| Liskov Substitution | Callers start checking `isinstance` before trusting a subclass | Made every tool return text, even when it finds nothing |
| Interface Segregation | A class implements methods just to raise `NotImplementedError` | Split `KnowledgeBase` into `Searchable` and `Indexable` |
| Dependency Inversion | Business classes build their own OpenAI, Chroma or Slack clients | Passed `BaseChatModel`, `Searchable` and `ReplyChannel` in through `__init__` |

None of these are rules for day one. They're what you reach for when a change starts to hurt.
