# ADR-004: Context Optimizer + Context Assembler as their own services ## Status Accepted ## Context Turning a set of retrieved chunks plus their expanded graph elements into a final LLM prompt involves several distinct decisions: deduplicating elements reached via multiple paths, picking a token budget, deciding which images are worth attaching, choosing a table format, and ordering the content. Left inline in `gateway.py`, this logic tends to grow into a single large function branching on question type. ## Decision Split this into two services: - `context_optimizer.py` — strategy-agnostic: deduplication and noise reduction only, run once regardless of question type. - `context_assembler.py` — a small `AssemblyStrategy` base class with one subclass per generation mode (`McqStrategy`, `EssayStrategy`, `BlueprintStrategy`, `ChatStrategy`, `DiagramQuestionStrategy`), each owning only its token budget and image-selection threshold. ## Alternatives considered - **One function with `if question_type == ...` branches** (the natural default): rejected — this is exactly the shape that turns into an unmaintainable file after a few more question types are added. - **Folding deduplication into each strategy**: rejected — deduplication has nothing to do with question type; every strategy needing to reimplement it is pure duplication. ## Reasoning `gateway.py` should only need to resolve the right strategy and call it — adding a new question type or supporting a new model tier's context needs should mean adding one new strategy class, not modifying a shared branching function.