Decompose a Monolithic Chatbot into SOLID Components
System DesignModel answerLast updated
Refactor a single-class chatbot prototype into modular, testable, dependency-injected components following SOLID design principles.
Break Up a Tangled Chatbot
You've inherited a chatbot prototype that started as a quick script and was never cleaned up. Everything lives inside one class: conversation history, context pruning, prompt assembly, a hardcoded tool dispatcher, and a fake model call. It works, barely, but adding a new feature requires touching everything at once and testing any part of it in isolation is nearly impossible.
Your job is to redesign this into a set of focused, interchangeable components that each have a single clear responsibility.
What's Wrong With the Current Design
- The model provider is hardcoded — swapping to a real API means editing core logic.
- Tools are matched with a chain of
if/elifstring comparisons, not a registry. - Context window trimming is tangled up inside the code that builds the API request.
- There is no injection point for adding content moderation or alternate storage.
What to Build
Implement the following components:
1. Structured Messages
Represent a conversation turn as a typed object with a role ("system", "user", "assistant", or "tool"), a content string, and optional tool-call metadata.
2. Conversation Memory
A stateful store that:
- Keeps system-level instructions separate from dialogue.
- Accepts new messages via
add_message. - Exposes the full context window via
get_context(system messages first, then the most recent dialogue). - Prunes the oldest dialogue turns when the history exceeds a
max_messagesbudget — but never removes system messages.
3. Tool Abstraction and Registry
- An abstract
Toolbase with aname, adescription, and anexecute(**kwargs) -> strmethod. - A
ToolRegistrythat lets you register tools at runtime, exposes their schemas to the model, and dispatches calls by name.
4. LLM Client Interface
An abstract LLMClient with a single method:
def generate(self, messages: list[Message], tools: list[dict]) -> LLMResponse
Provide a MockLLMClient implementation that replays a scripted sequence of responses and records every call, so tests can make assertions on what the model received.
5. Orchestrator (ChatEngine)
Wires everything together. Given a user input string, it must:
- Add the user message to memory.
- Call the LLM with the current context and available tool schemas.
- If the model returns a tool call, execute it, add the result to memory, and call the model again.
- Return the model's final text response.
Skeleton to Flesh Out
from abc import ABC, abstractmethod
from typing import Any, Dict, List, Optional
class Message:
def __init__(self, role: str, content: str,
tool_call: Optional[Dict[str, Any]] = None,
tool_call_id: Optional[str] = None):
...
class Tool(ABC):
name: str
description: str
@abstractmethod
def execute(self, **kwargs) -> str: ...
class ConversationMemory:
def __init__(self, max_messages: int = 10): ...
def add_message(self, message: Message) -> None: ...
def get_context(self) -> List[Message]: ...
class LLMClient(ABC):
@abstractmethod
def generate(self, messages: List[Message],
tools: List[Dict[str, Any]]) -> "LLMResponse": ...
class ChatEngine:
def __init__(self, llm_client: LLMClient,
memory: ConversationMemory,
tools: Optional["ToolRegistry"] = None,
max_tool_iterations: int = 5): ...
def process_user_input(self, text: str) -> str: ...
Edge Cases to Handle
- System messages must survive even the most aggressive pruning.
- After pruning, the dialogue must not begin with an orphaned
toolresult whose parent assistant message was already removed — most real APIs will reject that. - If the model keeps requesting tools beyond
max_tool_iterations, stop the loop and return a safe fallback string rather than looping forever. - Unknown tool names and exceptions thrown inside a tool should both be surfaced to the model as an error string, not as a crash.
- Registering a tool name that already exists should raise an error rather than silently overwrite the previous tool.
Hints
Hint 1
Start by listing the five concerns tangled in the monolith, then assign exactly one class to each. Resist the urge to combine memory and the orchestrator — they change for different reasons.
Hint 2
The hardest memory invariant is the orphaned-tool-message problem: if pruning removes an assistant message that contained a tool_call, the following tool-role message becomes invalid. After trimming by count, scan the front of the dialogue deque and drop any leading tool messages.
Hint 3
For the tool loop in ChatEngine, use a simple counter rather than a while True. Check the counter before each model call, not after, so that hitting the limit never makes one extra request.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core move is to identify every distinct concern in the monolith and give it its own class. The five concerns here are: data shape (messages), history management (memory), plugin dispatch (tool registry), model access (LLM client), and turn orchestration (engine). Once those are separate, each one can be tested, replaced, or extended without touching the others.
The ChatEngine should depend only on the abstractions LLMClient, ConversationMemory, and ToolRegistry, receiving them via its constructor. That means swapping a provider, adding moderation, or using a database-backed memory store requires zero changes to the engine itself.
Memory Invariants — the Part Most Candidates Get Wrong
Two rules must hold regardless of how small max_messages is:
- System messages are never evicted. Store them in a separate list; the pruning logic only touches the dialogue deque.
- The context window must not begin with an orphaned
toolmessage. If the budget is tight and the assistant message that issued a tool call gets popped, the matchingtool-role reply at the front of the deque is now invalid (real APIs reject this). After trimming by count, walk the front of the deque and drop any leadingtoolmessages.
Tool Loop and Failure Handling
The engine's turn loop runs at most max_tool_iterations + 1 model calls. If the limit is hit, return a canned fallback rather than making one more request. Two failure modes — unknown tool name and an exception raised inside a tool — are both converted into an error string and fed back to the model as the tool's result. The model can reason about the error; the engine never crashes.
Complexity
add_message: amortized O(1) — each message is appended and popped at most once.get_context: O(n) where n =max_messages.ToolRegistry.execute: O(1) dict lookup plus the tool's own work.- One full user turn: O(k · n) local work, where k ≤
max_tool_iterations + 1. Network latency dominates in practice. - Space: O(n + T) where T = number of registered tools.
Common Mistakes
- Putting the truncation logic inside
get_contextinstead ofadd_message— this means history quietly shrinks on every read and you can never reliably test what got stored. - Forgetting the orphaned-tool-message check, which causes cryptic API errors that are hard to trace.
- Using
while Truefor the tool loop with a break condition buried inside — a counter with an early-exit check is clearer and easier to unit-test. - Silently overwriting a registered tool name instead of raising, which hides configuration bugs.
Full Implementation
from __future__ import annotations
from abc import ABC, abstractmethod
from collections import deque
from dataclasses import dataclass, field
from typing import Any, Deque, Dict, List, Optional
# ── Data objects ──────────────────────────────────────────────────────────────
@dataclass
class Message:
role: str # "system" | "user" | "assistant" | "tool"
content: str
# Set by the model when it wants to call a tool.
tool_call: Optional[Dict[str, Any]] = None # {"id", "name", "arguments"}
# Set on the reply message that carries the tool's output.
tool_call_id: Optional[str] = None
@dataclass
class LLMResponse:
content: str = ""
tool_call: Optional[Dict[str, Any]] = None # present when model wants a tool
# ── Memory ────────────────────────────────────────────────────────────────────
class ConversationMemory:
def __init__(self, max_messages: int = 10) -> None:
if max_messages < 1:
raise ValueError("max_messages must be >= 1")
self.max_messages = max_messages
self._system: List[Message] = []
self._dialogue: Deque[Message] = deque()
def add_message(self, message: Message) -> None:
if message.role == "system":
self._system.append(message)
return
self._dialogue.append(message)
self._prune()
def _prune(self) -> None:
# 1. Enforce the message budget.
while len(self._dialogue) > self.max_messages:
self._dialogue.popleft()
# 2. Never start with an orphaned tool result.
while self._dialogue and self._dialogue[0].role == "tool":
self._dialogue.popleft()
def get_context(self) -> List[Message]:
return list(self._system) + list(self._dialogue)
def clear(self) -> None:
self._dialogue.clear()
# ── Tool abstraction ──────────────────────────────────────────────────────────
class Tool(ABC):
name: str
description: str
parameters: Dict[str, Any] = {}
@abstractmethod
def execute(self, **kwargs) -> str: ...
def schema(self) -> Dict[str, Any]:
return {
"name": self.name,
"description": self.description,
"parameters": self.parameters,
}
class ToolRegistry:
def __init__(self) -> None:
self._tools: Dict[str, Tool] = {}
def register(self, tool: Tool) -> None:
if tool.name in self._tools:
raise ValueError(f"Tool '{tool.name}' is already registered")
self._tools[tool.name] = tool
def schemas(self) -> List[Dict[str, Any]]:
return [t.schema() for t in self._tools.values()]
def execute(self, name: str, arguments: Optional[Dict[str, Any]]) -> str:
tool = self._tools.get(name)
if tool is None:
return f"Error: unknown tool '{name}'"
try:
return tool.execute(**(arguments or {}))
except Exception as exc:
return f"Error executing '{name}': {exc}"
# ── LLM client interface + mock ───────────────────────────────────────────────
class LLMClient(ABC):
@abstractmethod
def generate(
self,
messages: List[Message],
tools: List[Dict[str, Any]],
) -> LLMResponse: ...
class MockLLMClient(LLMClient):
"""Replays a scripted list of LLMResponse objects; records every call."""
def __init__(
self,
responses: Optional[List[LLMResponse]] = None,
default: str = "OK",
) -> None:
self._responses: Deque[LLMResponse] = deque(responses or [])
self._default = default
self.calls: List[List[Message]] = []
def generate(
self,
messages: List[Message],
tools: List[Dict[str, Any]],
) -> LLMResponse:
self.calls.append(list(messages))
if self._responses:
return self._responses.popleft()
return LLMResponse(content=self._default)
# ── Orchestrator ──────────────────────────────────────────────────────────────
class ChatEngine:
FALLBACK = "I couldn't complete that request (tool iteration limit reached)."
def __init__(
self,
llm_client: LLMClient,
memory: ConversationMemory,
tools: Optional[ToolRegistry] = None,
max_tool_iterations: int = 5,
) -> None:
self._client = llm_client
self._memory = memory
self._tools = tools or ToolRegistry()
self._max_iterations = max_tool_iterations
def process_user_input(self, text: str) -> str:
self._memory.add_message(Message(role="user", content=text))
for _ in range(self._max_iterations + 1):
response = self._client.generate(
messages=self._memory.get_context(),
tools=self._tools.schemas(),
)
if response.tool_call is None:
# Plain text reply — store it and return.
self._memory.add_message(
Message(role="assistant", content=response.content)
)
return response.content
# Model wants to call a tool.
tc = response.tool_call
self._memory.add_message(
Message(role="assistant", content="", tool_call=tc)
)
result = self._tools.execute(tc.get("name", ""), tc.get("arguments"))
self._memory.add_message(
Message(
role="tool",
content=result,
tool_call_id=tc.get("id", ""),
)
)
# Exceeded the iteration cap.
self._memory.add_message(Message(role="assistant", content=self.FALLBACK))
return self.FALLBACK
Quick Smoke Test
# A tool that returns the current weather (stubbed).
class WeatherTool(Tool):
name = "get_weather"
description = "Returns weather for a city."
parameters = {"city": {"type": "string"}}
def execute(self, city: str = "") -> str:
return f"Sunny, 22 °C in {city}"
registry = ToolRegistry()
registry.register(WeatherTool())
responses = [
LLMResponse(tool_call={"id": "1", "name": "get_weather",
"arguments": {"city": "Paris"}}),
LLMResponse(content="It's sunny and 22 °C in Paris."),
]
engine = ChatEngine(
llm_client=MockLLMClient(responses),
memory=ConversationMemory(max_messages=10),
tools=registry,
)
reply = engine.process_user_input("What's the weather in Paris?")
assert reply == "It's sunny and 22 °C in Paris."