KatInterview

Decompose a Monolithic Chatbot into SOLID Components

System DesignModel answer
MediumModel answerSystem Designobject-oriented-designrefactoringSOLID

Last 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/elif string 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_messages budget — but never removes system messages.

3. Tool Abstraction and Registry

  • An abstract Tool base with a name, a description, and an execute(**kwargs) -> str method.
  • A ToolRegistry that 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:

  1. Add the user message to memory.
  2. Call the LLM with the current context and available tool schemas.
  3. If the model returns a tool call, execute it, add the result to memory, and call the model again.
  4. 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 tool result 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.