How to Use: Copy this document's content into Google AI Studio Build and run it. If you encounter an error, click "auto-fix".

1. Introduction

This document outlines a high-level system design for "Loop Forge," applying Axiomatic Design principles based on the project's Module Design Document (MDD). The goal of Axiomatic Design is to create robust and efficient systems by systematically mapping Customer Needs (CNs) to Functional Requirements (FRs), and then to Design Parameters (DPs), while adhering to the Independence and Information axioms.

This design follows these core principles:

  • Axiomatic Design: A clear mapping from CNs -> FRs -> DPs, aiming for independence and minimal information content.
  • Functional Programming Concepts: Breaking down features into stateless units (DPs) with clear inputs and outputs, focusing on data flow and transformations.
  • Simplicity (Occam's Razor): Avoiding unnecessary complexity. DPs should be concise and serve their functional requirements directly.
  • Language-Agnostic: Design parameters and process flows are described abstractly, independent of any specific programming language or framework.

This document serves as the blueprint for engineering and development, guiding the construction of system components and their interactions.

2. Customer Needs (CNs)

The primary customer needs, distilled from project goals and user stories, are:

  • CN1: Users can iteratively generate, review, and refine documents or code with AI help.
  • CN2: Users have flexible control over the key settings and flow of the iteration process.
  • CN3: Users can easily track and look back at the entire iteration history, including all AI outputs and feedback.
  • CN4: The system must be able to use background materials provided by the user and produce structured, predictable AI outputs.
  • CN5: The system must be stable and reliable, providing clear status updates and error messages when problems occur.

Example User Journey:

  • A user uploads a document to serve as context.
  • The user prompts the Writer AI to draft a document using the provided context.
  • The user gives the Reviewer AI a set of standards for evaluating the document.
  • The user configures the Writer AI to produce 2 drafts per iteration.
  • The user sets the process to run for a minimum of 2 rounds and a maximum of 5, with a target score of 90 to stop.
  • The user starts the iterative process.
  • The system runs automatically, iterating until a satisfactory draft is produced, the max iteration count is reached, or the score threshold is met, requiring no further user input.
  • The user downloads the resulting document.
  • Once the process finishes, the user can download the final draft but also has the option to intervene, modify the last round of feedback, and run more iterations.

3. Functional Requirements (FRs)

We break down customer needs into specific, actionable functional requirements:

  • FR1: AI-Powered Content Generation & Revision (Covers CN1, CN4)

    • FR1.1: The system must accept and parse various file formats for background context.
    • FR1.2: The system must accept the user's initial prompt for the writer.
    • FR1.3: The AI Writer must generate N separate drafts based on the initial prompt and provided context, where N is specified by the user.
    • FR1.4: Based on the previous round's selected draft and consolidated feedback, the AI Writer must revise it and generate N new, distinct drafts.
    • FR1.5: The AI Writer's output must be a structured JSON object adhering to a predefined schema, containing a response to feedback and N drafts (each with content and a revision summary).
  • FR2: AI-Powered Content Review & Feedback (Coovers CN1, CN4)

    • FR2.1: The system must accept the user's criteria for the reviewer.
    • FR2.2: The AI Reviewer must be able to assess all N drafts from the AI Writer.
    • FR2.3: For each draft, the AI Reviewer must provide detailed feedback and a score from 0 to 100.
    • FR2.4: The AI Reviewer must select the single best draft out of the N options, identifying it by its index.
    • FR2.5: The AI Reviewer must provide a consolidated feedback summary, explaining its choice and giving actionable suggestions for improving the selected draft.
    • FR2.6: The AI Reviewer's output must be a structured JSON object adhering to a predefined schema, containing an array of reviews, the index of the selected draft, and the consolidated feedback.
  • FR3: Configurable and Controllable Iteration (Covers CN2)

    • FR3.1: Users must be able to set the minimum number of iterations.
    • FR3.2: Users must be able to set the maximum number of iterations.
    • FR3.3: Users must be able to set a target score that will stop the process.
    • FR3.4: Users must be able to configure how many drafts (e.g., 1-3) the AI Writer should generate per round.
    • FR3.5: Users must be able to start or reset the process. The system must automatically pause based on configured stopping conditions.
    • FR3.6: When the process is paused, users must be able to edit the AI Reviewer's consolidated feedback and manually trigger a specific number of additional iterations.
  • FR4: History & Results Management (Covers CN3)

    • FR4.1: The system must display a clear, sequential history of every iteration round.
    • FR4.2: Each round's history must show the writer's prompt, the writer's full output (response to feedback, N drafts with summaries and content), and the reviewer's full output (individual reviews and scores, selected draft index, and consolidated feedback).
    • FR4.3: The UI must clearly highlight the current active step and the reviewer's chosen draft.
    • FR4.4: Users must be able to download the content of the final selected draft.
    • FR4.5: The system must track and display the total input and output token count from Gemini API calls.
  • FR5: System Stability & Feedback (Covers CN5)

    • FR5.1: The system must gracefully handle external API errors (e.g., invalid key, network failure, rate limits).
    • FR5.2: The system must gracefully handle AI response parsing errors (e.g., malformed JSON, missing fields from the expected schema).
    • FR5.3: The UI must show users clear, easy-to-understand messages about the current system status and any errors.

4. Design Parameters (DPs)

We assign a specific Design Parameter (DP) to each Functional Requirement (FR). A DP represents a logical or physical component that fulfills an FR. Each DP is defined by its inputs, outputs, and core responsibilities in a language-agnostic way.

  • DP1: User Input & Config Handler

    • Inputs: User-uploaded files, text prompts, configuration values, UI events (e.g., button clicks).
    • Outputs: Structured context data, initial writer prompt, review criteria, iteration config object, manual continuation command.
    • Responsibility: To parse, validate, and structure all user-provided inputs and manage system configuration.
    • Primary FRs: FR1.1, FR1.2, FR2.1, FR3.1-3.4, FR3.6.
  • DP2: AI Writer Prompt Generator

    • Inputs: Structured context (from DP1), initial writer prompt (from DP1), previous review result (from DP6), current iteration number, config settings (from DP1).
    • Output: A complete prompt for the AI Writer model.
    • Responsibility: To construct the specific prompt sent to the AI Writer, combining user input with the state of the iteration.
    • Primary FRs: FR1.3, FR1.4.
  • DP3: AI Reviewer Prompt Generator

    • Inputs: Review criteria (from DP1), all draft contents from the current round (from DP5).
    • Output: A complete prompt for the AI Reviewer model.
    • Responsibility: To construct the specific prompt sent to the AI Reviewer, combining the review criteria with the drafts to be assessed.
    • Primary FRs: FR2.2.
  • DP4: External AI Model Gateway

    • Inputs: An AI model prompt (from DP2 or DP3), model settings.
    • Outputs: The raw response from the AI model, or a standardized error object for API/communication failures.
    • Responsibility: To manage all communication with the external AI service. It handles requests, responses, low-level errors (auth, network, quotas), and tracks token usage.
    • Primary FRs: FR1.3, FR1.4, FR2.2, FR4.5, FR5.1.
  • DP5: AI Writer Response Parser

    • Inputs: Raw AI model response (from DP4), the writer's JSON schema.
    • Outputs: A structured writer result object, or a standardized error object for parsing/validation failures.
    • Responsibility: To validate and parse the raw AI response into the expected structured object. Handles JSON errors and schema violations.
    • Primary FRs: FR1.5, FR5.2.
  • DP6: AI Reviewer Response Parser

    • Inputs: Raw AI model response (from DP4), the reviewer's JSON schema.
    • Outputs: A structured reviewer result object, or a standardized error object for parsing/validation failures.
    • Responsibility: To validate and parse the raw AI response into the expected structured object. Handles JSON errors and schema violations.
    • Primary FRs: FR2.6, FR5.2.
  • DP7: Iteration Flow Manager

    • Inputs: Iteration config (from DP1), manual continue command (from DP1), previous review result (from DP6), current state and history (from DP9), error objects (from DP4, DP5, DP6).
    • Outputs: Calls to other DPs, system status updates (e.g., Running, Paused, Error).
    • Responsibility: To orchestrate the execution of other DPs. It controls the iteration loop's flow—starting, running, pausing, and stopping—based on user configuration and the system's current state. It also centralizes the reaction to errors from other components.
    • Core Flow: (Simplified)
      1. Initialize -> (DP7)
      2. Load Config & Inputs (DP1) -> (DP7)
      3. Loop (until stop condition is met):
        a. (DP7) -> Generate Writer Prompt (DP2)
        b. (DP7) -> Call AI (DP4) with Writer Prompt -> [Receive Response or Error]
        c. (DP7) -> Parse Writer Response (DP5) -> [Receive Result or Error]
        d. (DP7) -> Generate Reviewer Prompt (DP3)
        e. (DP7) -> Call AI (DP4) with Reviewer Prompt -> [Receive Response or Error]
        f. (DP7) -> Parse Reviewer Response (DP6) -> [Receive Result or Error]
        g. (DP7) -> Store round results in History (DP9)
        h. (DP7) -> Check stop conditions; if met, pause and wait for user input (from DP1).
        i. Error Handling: If any step (b, c, e, f) returns an error, DP7 catches it, sets the system state to Error, and forwards the error to DP10.
      4. (DP7) -> Set final state (Completed or Error) -> (DP10/DP8)
  • DP8: UI Renderer & Interaction Handler

    • Inputs: All structured data (from DP1, DP9, DP5, DP6), system status and errors (from DP7, DP10).
    • Outputs: UI events forwarded to DP1 or DP7.
    • Responsibility: To render the system's internal state and data for the user. It captures user actions (clicks, edits) and translates them into system commands. Provides download functionality.
    • Primary FRs: FR3.1-3.6 (UI elements), FR4.1-4.5, FR5.3 (displaying status/errors).
  • DP9: Iteration History Store

    • Inputs: The structured writer (DP5) and reviewer (DP6) results from each round.
    • Outputs: The complete, queryable history of the entire iteration process.
    • Responsibility: To store and manage all data generated during the iterative process. Provides an API to access historical data.
    • Primary FRs: FR4.1-4.3, FR4.4 (by providing access to final content).
  • DP10: Error & Status Reporter

    • Inputs: Error objects (from DP4, DP5, DP6, DP7), status updates (from DP7).
    • Outputs: User-friendly error messages, current system status identifier.
    • Responsibility: To translate internal error signals into user-facing messages. Manages and reports the system's high-level operational status.
    • Primary FRs: FR5.1-5.3.

5. FR-DP Mapping Matrix (Design Matrix)

This matrix analyzes the relationships between Functional Requirements (FRs) and Design Parameters (DPs). An ideal design is decoupled (a diagonal matrix) or weakly coupled (a lower-triangular matrix).

DP1 Input/Config DP2 Writer Prompt DP3 Reviewer Prompt DP4 AI Interface DP5 Writer Parser DP6 Reviewer Parser DP7 Flow Manager DP8 UI Presenter DP9 History Mgmt DP10 Error/Status
FR1.1 X x
FR1.2 X x x
FR1.3 x X X x x x x
FR1.4 x X X x x x x x
FR1.5 X x x x x
FR2.1 X x x
FR2.2 x X X x x x x x
FR2.3 X x x x x
FR2.4 X x x x x
FR2.5 X x x x x
FR2.6 X x x x x
FR3.1-4 X x x
FR3.5 x X x x
FR3.6 X x x X x x
FR4.1-3 x x x X X x
FR4.4 x x x X x
FR4.5 X x x x
FR5.1 x x x x x X
FR5.2 x x x x X
FR5.3 x X X
  • X: The primary DP responsible for this FR.
  • x: A secondary dependency; this DP is involved in or affects the FR.

A Deeper Look at the Design Matrix: The matrix reveals several types of coupling between DPs, which is expected in an interactive, iterative system. The design goal is to manage this coupling effectively.

  • Sequential Coupling: The flow is naturally sequential: DP2 depends on DP1, DP5 depends on DP4, etc. This is managed by DP7 (Flow Manager), which orchestrates the call sequence. By designing each DP to be a pure, testable function, this coupling becomes predictable and robust.
  • Broadcast Coupling: Some information, like status updates from DP7 or errors from multiple sources, needs to be broadcast. This is managed through event-driven patterns (like an observer or message bus), where publishers (e.g., DP7) don't need to know about all subscribers (e.g., DP8, DP10).
  • Data Coupling: DPs communicate by passing data structures. The risk here is managed by defining strict, stable data contracts (via JSON Schemas). This ensures that changes to one DP's internal logic don't break another, as long as the data contract is respected.
  • Control Coupling: DP7 (Flow Manager) explicitly controls other DPs. This is by design. Centralizing control logic in one place is simpler than managing distributed control flow.

By defining clear interfaces (inputs/outputs) for each DP and centralizing orchestration (DP7), this design makes the necessary coupling explicit and manageable, adhering to the two axioms of Axiomatic Design:

  1. The Independence Axiom: We maintain independence by defining clear module boundaries and contracts. For example, the internal implementation of DP4 (AI Gateway) can be swapped out (e.g., to use a different AI provider) without impacting any other part of the system, as long as the new implementation honors the same interface contract.
  2. The Information Axiom: We minimize information content by giving each DP a single, focused responsibility. Prompt generation logic lives in DP2/DP3, API logic in DP4, parsing in DP5/DP6, and orchestration in DP7. This maximizes the cohesion of each module.

Error handling (DP10) is treated as a cross-cutting concern. An executing DP (like DP4 or DP5) reports a standardized error to the Flow Manager (DP7), which decides the next step (e.g., halt the process) and informs the Reporter (DP10), which then formats the message for the UI (DP8). This creates a consistent error-handling pathway.

6. Conclusion

This document translates customer needs into functional requirements and maps them to language-agnostic design parameters, following the principles of Axiomatic Design. Our analysis of the FR-DP matrix acknowledges the system's inherent coupling and proposes to manage it through clear interfaces, stable data contracts (Schemas), and a centralized flow controller (DP7). This approach ensures that we can meet the system's complex interactive requirements while maximizing modular independence and cohesion. The design also establishes a robust, centralized pattern for error handling.

The resulting set of DPs, with their defined inputs, outputs, and responsibilities, provides a clear and robust blueprint for implementation. This blueprint is aligned with principles of Axiomatic Design, functional programming, and simplicity. Future development should adhere to these definitions to ensure a faithful implementation of the design.

7. Default Parameters

  • Background context is optional; the app works without it.
  • Default AI Writer task: "Write a Python function for the Fibonacci sequence. Provide at least 4 distinct algorithms."
  • Default AI Reviewer task: "Perform a code review. The code should be elegant, and there must be at least 4 substantively different algorithms for the Fibonacci sequence."
  • Default min iterations: 2
  • Default max iterations: 5
  • Default score threshold: 90
  • Default UI language: Chinese.

8. Reference

Using structured output is recommended, as shown below:

// To run this code you need to install the following dependencies:
// npm install @google/genai mime
// npm install -D @types/node

import {
  GoogleGenAI,
  Type,
} from '@google/genai';

async function main() {
  const ai = new GoogleGenAI({
    apiKey: process.env.GEMINI_API_KEY,
  });
  const config = {
    thinkingConfig: {
      thinkingBudget: -1,
    },
    responseMimeType: 'application/json',
    responseSchema: {
      type: Type.OBJECT,
      properties: {
        propertyA: {
          type: Type.STRING,
        },
        propertyB: {
          type: Type.NUMBER,
        },
      },
    },
  };
  const model = 'gemini-2.5-pro-preview-06-05';
  const contents = [
    {
      role: 'user',
      parts: [
        {
          text: `INSERT_INPUT_HERE`,
        },
      ],
    },
  ];

  const response = await ai.models.generateContentStream({
    model,
    config,
    contents,
  });
  let fileIndex = 0;
  for await (const chunk of response) {
    console.log(chunk.text);
  }
}

main();