Initial Setup (Day 1)

1. Environment Setup

# Create project directory
mkdir saas-builder && cd saas-builder

# Create Python virtual environment (recommended)
python3 -m venv .venv
source .venv/bin/activate  # Linux/Mac
# .venv\Scripts\activate.bat  # Windows

# Verify Python version (3.10+ required)
python --version

2. Install AutoGen Stack

# Install core AgentChat package
pip install -U "autogen-agentchat"

# Install OpenAI extension
pip install "autogen-ext[openai]"

# Optional: Install additional executors
pip install "autogen-ext[docker]"  # For Docker code execution

3. OpenAI API Configuration

# Create .env file
touch .env

# Add to .env file:
# OPENAI_API_KEY=sk-proj-your-key-here
# OPENAI_MODEL=gpt-4o

# Install python-dotenv for environment variable management
pip install python-dotenv

# Verify API key works
python -c "import openai; print('OpenAI configured')"

4. Project Structure Setup

# Create directory structure
mkdir -p agents workflows output logs requirements

# Create core files
touch requirements.txt
touch repo_builder.py
touch config.yaml
touch .gitignore

# Initialize git (for generated repositories)
git init output/generated_repo

5. Dependencies File

cat > requirements.txt << EOF
autogen-agentchat>=0.4.0
autogen-ext[openai]>=0.4.0
python-dotenv>=1.0.0
pyyaml>=6.0
gitpython>=3.1.0
rich>=13.0.0
EOF

pip install -r requirements.txt

Core Agent Patterns

Basic Agent Creation

from autogen_agentchat.agents import AssistantAgent
from autogen_ext.models.openai import OpenAIChatCompletionClient
import os
from dotenv import load_dotenv

load_dotenv()

# Configure model client
model_client = OpenAIChatCompletionClient(
    model="gpt-4o",
    api_key=os.getenv("OPENAI_API_KEY")
)

# Create specialized agent
requirements_analyst = AssistantAgent(
    name="requirements_analyst",
    model_client=model_client,
    system_message="""You are a Requirements Analyst. Your role:
    - Parse technical requirements documents
    - Extract functional and non-functional requirements
    - Identify missing specifications
    - Structure requirements for development teams""",
    description="Analyzes and structures technical requirements"
)

Multi-Agent Team Setup

from autogen_agentchat.teams import RoundRobinGroupChat
from autogen_agentchat.conditions import TextMentionTermination

# Create agent team
agents = [
    requirements_analyst,
    system_architect,
    backend_engineer,
    frontend_engineer,
    qa_engineer,
    devops_engineer
]

# Define termination condition
termination = TextMentionTermination("TASK_COMPLETE")

# Create team with round-robin coordination
team = RoundRobinGroupChat(
    agents,
    termination_condition=termination
)

# Execute team workflow
result = await team.run(task="Build SaaS app from requirements.md")

CLI Commands for Daily Workflow

Week 1: Initial Build

# Day 1: Parse requirements and create architecture
python repo_builder.py init --spec requirements/spec_v1.md --output output/generated_repo

# Day 2: Generate backend scaffolding
python repo_builder.py generate backend --spec requirements/spec_v1.md

# Day 3: Generate frontend scaffolding
python repo_builder.py generate frontend --spec requirements/spec_v1.md

# Day 4: Generate database schema and migrations
python repo_builder.py generate database --spec requirements/spec_v1.md

# Day 5: Generate tests and documentation
python repo_builder.py generate tests --spec requirements/spec_v1.md
python repo_builder.py generate docs --spec requirements/spec_v1.md

Week 2-4: Iterative Development

# Update requirements document
vim requirements/spec_v2.md

# Run targeted update (only affected agents execute)
python repo_builder.py update \
  --spec requirements/spec_v2.md \
  --target backend \
  --files "src/api/users.py,src/models/user.py"

# Run full system update (all agents review and update)
python repo_builder.py update --spec requirements/spec_v2.md --full

# Add new feature with specific agents
python repo_builder.py feature add \
  --name "payment-integration" \
  --agents backend,frontend,qa

# Run tests through QA agent
python repo_builder.py test --target output/generated_repo

# Generate summary of all agent actions
python repo_builder.py summary --output logs/agent_summary_$(date +%Y%m%d).md

Specialized Commands

# Architecture review (architect + PM agents only)
python repo_builder.py review architecture --spec requirements/spec_v3.md

# Security audit (security specialist agent)
python repo_builder.py audit security --target output/generated_repo

# Performance optimization (backend + devops agents)
python repo_builder.py optimize performance

# Dependency updates (devops agent)
python repo_builder.py deps update

# Generate deployment configs (devops agent)
python repo_builder.py deploy config --env production

# Code quality check (all agents)
python repo_builder.py quality check --output logs/quality_report.md

# Rollback to previous iteration
python repo_builder.py rollback --iteration 12

# Compare iterations
python repo_builder.py diff --from 12 --to 15

repo_builder.py (Main CLI Entry Point)

Complete Implementation

#!/usr/bin/env python3
"""
Main CLI for multi-agent SaaS repository builder
Usage: python repo_builder.py <command> [options]
"""

import asyncio
import argparse
from pathlib import Path
from autogen_agentchat.agents import AssistantAgent
from autogen_agentchat.teams import RoundRobinGroupChat
from autogen_agentchat.conditions import TextMentionTermination
from autogen_ext.models.openai import OpenAIChatCompletionClient
import os
from dotenv import load_dotenv

load_dotenv()

class RepoBuilder:
    def __init__(self, spec_file: str, output_dir: str):
        self.spec_file = Path(spec_file)
        self.output_dir = Path(output_dir)
        self.model_client = OpenAIChatCompletionClient(
            model="gpt-4o",
            api_key=os.getenv("OPENAI_API_KEY")
        )
        self.agents = self._create_agents()
    
    def _create_agents(self):
        """Create specialized agent team"""
        return {
            "pm": AssistantAgent(
                name="product_manager",
                model_client=self.model_client,
                system_message="You are a Product Manager..."
            ),
            "architect": AssistantAgent(
                name="architect",
                model_client=self.model_client,
                system_message="You are a System Architect..."
            ),
            "backend": AssistantAgent(
                name="backend_engineer",
                model_client=self.model_client,
                system_message="You are a Backend Engineer..."
            ),
            "frontend": AssistantAgent(
                name="frontend_engineer",
                model_client=self.model_client,
                system_message="You are a Frontend Engineer..."
            ),
            "qa": AssistantAgent(
                name="qa_engineer",
                model_client=self.model_client,
                system_message="You are a QA Engineer..."
            ),
            "devops": AssistantAgent(
                name="devops_engineer",
                model_client=self.model_client,
                system_message="You are a DevOps Engineer..."
            )
        }
    
    async def init_project(self):
        """Initialize new project from requirements"""
        spec_content = self.spec_file.read_text()
        
        team = RoundRobinGroupChat(
            list(self.agents.values()),
            termination_condition=TextMentionTermination("INITIALIZATION_COMPLETE")
        )
        
        task = f"""Create a new SaaS application based on these requirements:

{spec_content}

Output structure:
1. Project architecture document
2. Backend scaffolding (API routes, models, services)
3. Frontend scaffolding (components, pages, state management)
4. Database schema and migrations
5. Test suites
6. Documentation (README, API docs)
7. Deployment configuration

INITIALIZATION_COMPLETE when all files are generated."""

        result = await team.run(task=task)
        self._save_results(result)
        return result
    
    async def update_feature(self, target_agents: list, description: str):
        """Update specific feature with targeted agents"""
        spec_content = self.spec_file.read_text()
        
        # Select only required agents
        selected_agents = [self.agents[name] for name in target_agents]
        
        team = RoundRobinGroupChat(
            selected_agents,
            termination_condition=TextMentionTermination("UPDATE_COMPLETE")
        )
        
        task = f"""Update the following feature:

{description}

Current requirements: {spec_content}

Only modify files related to this feature. Preserve all other code.
UPDATE_COMPLETE when changes are implemented and tested."""

        result = await team.run(task=task)
        self._save_results(result)
        return result
    
    def _save_results(self, result):
        """Save agent outputs and summaries"""
        # Implementation: parse result.messages and write to files
        pass

def main():
    parser = argparse.ArgumentParser(description="Multi-agent SaaS repository builder")
    subparsers = parser.add_subparsers(dest="command", help="Commands")
    
    # init command
    init_parser = subparsers.add_parser("init", help="Initialize new project")
    init_parser.add_argument("--spec", required=True, help="Requirements document")
    init_parser.add_argument("--output", required=True, help="Output directory")
    
    # update command
    update_parser = subparsers.add_parser("update", help="Update existing project")
    update_parser.add_argument("--spec", required=True, help="Updated requirements")
    update_parser.add_argument("--target", help="Target agents (comma-separated)")
    update_parser.add_argument("--full", action="store_true", help="Full system update")
    
    # feature command
    feature_parser = subparsers.add_parser("feature", help="Add new feature")
    feature_parser.add_argument("action", choices=["add", "remove", "modify"])
    feature_parser.add_argument("--name", required=True, help="Feature name")
    feature_parser.add_argument("--agents", help="Required agents (comma-separated)")
    
    args = parser.parse_args()
    
    builder = RepoBuilder(args.spec, args.output)
    
    if args.command == "init":
        asyncio.run(builder.init_project())
    elif args.command == "update":
        target_agents = args.target.split(",") if args.target else list(builder.agents.keys())
        asyncio.run(builder.update_feature(target_agents, "Update from spec"))
    
    print("✓ Operation completed successfully")

if __name__ == "__main__":
    main()
# Make executable
chmod +x repo_builder.py

Iteration Workflow Patterns

Pattern 1: Full Multi-Agent Run (10x/month)

# Update requirements document
vim requirements/spec_v3.md

# Run all agents for comprehensive rebuild
python repo_builder.py update --spec requirements/spec_v3.md --full

# Review generated summary
cat logs/agent_summary_latest.md

# Test generated code
cd output/generated_repo && npm test && pytest

# Commit iteration
git add . && git commit -m "Iteration 15: Added payment gateway"

Pattern 2: Targeted Update (20x/month)

# Small feature addition - only backend + QA
python repo_builder.py feature add \
  --name "user-profile-avatar" \
  --agents backend,qa \
  --spec requirements/spec_v3.md

# Bug fix - only relevant agent
python repo_builder.py fix \
  --issue "API rate limiting not working" \
  --agent backend

# UI change - only frontend
python repo_builder.py update \
  --target frontend \
  --files "src/components/Dashboard.tsx"

Pattern 3: Trickle-Down Delegation

# PM reviews spec change → Architect approves → Engineers implement
python repo_builder.py workflow \
  --type hierarchical \
  --spec requirements/spec_v4.md \
  --approval-chain pm,architect,backend,frontend,qa

# Only execute if PM and architect approve
# Automatically delegates to relevant engineers

Monitoring & Logging

Track Token Usage

# Add to your code
from autogen_agentchat.ui import Console

async def run_with_logging(team, task):
    result = await Console(team.run_stream(task=task))
    
    # Log token usage
    total_tokens = sum(msg.usage.total_tokens for msg in result.messages if hasattr(msg, 'usage'))
    cost = (total_tokens / 1_000_000) * 2.50  # GPT-4o input pricing
    
    print(f"Tokens used: {total_tokens:,}")
    print(f"Estimated cost: ${cost:.4f}")
    
    return result

Generate Agent Summaries

# Export all agent actions from current iteration
python repo_builder.py summary \
  --format markdown \
  --output logs/iteration_15_summary.md

# Example output structure:
# - Requirements Analyst: Parsed 15 new requirements
# - Architect: Updated API design for payment gateway
# - Backend Engineer: Implemented Stripe integration (3 files)
# - Frontend Engineer: Created checkout UI (5 components)
# - QA Engineer: Added 12 integration tests
# - DevOps: Updated deployment config for PCI compliance

Daily/Weekly Reports

# Generate weekly activity report
python repo_builder.py report weekly \
  --from 2026-02-01 \
  --to 2026-02-07 \
  --output reports/week_6.md

# Token usage report
python repo_builder.py report tokens \
  --month february \
  --output reports/cost_february.csv

Debugging & Troubleshooting

Common Commands

# Verbose output mode (see all agent messages)
python repo_builder.py --verbose update --spec requirements/spec.md

# Dry-run mode (preview without executing)
python repo_builder.py --dry-run feature add --name "export-data"

# Debug specific agent
python repo_builder.py debug agent backend \
  --task "Explain current API structure"

# Validate requirements document
python repo_builder.py validate spec requirements/spec_v5.md

# Check agent health
python repo_builder.py health check

# Reset agent context (clear memory)
python repo_builder.py reset context --agent all

Environment Management

# Check installed versions
pip list | grep autogen

# Update AutoGen to latest
pip install -U autogen-agentchat autogen-ext[openai]

# Verify OpenAI API connectivity
python -c "from autogen_ext.models.openai import OpenAIChatCompletionClient; import os; client = OpenAIChatCompletionClient(model='gpt-4o', api_key=os.getenv('OPENAI_API_KEY')); print('✓ API connected')"

# Check Python version
python --version  # Should be 3.10+

# Reinstall if issues
pip uninstall autogen-agentchat autogen-ext -y
pip install autogen-agentchat autogen-ext[openai]

Git Workflow Integration

Track Iterations with Git

# After each iteration, commit generated code
cd output/generated_repo

git add .
git commit -m "Iteration $(date +%Y%m%d): Feature XYZ - Agents: backend,frontend,qa"

# Tag major iterations
git tag -a v0.1.0 -m "Initial MVP - Iteration 10"

# Branch for experimental features
git checkout -b feature/payment-gateway
python ../../repo_builder.py feature add --name "stripe-integration"

# Merge when approved
git checkout main && git merge feature/payment-gateway

Diff Between Iterations

# Compare generated code across iterations
git diff iteration-12..iteration-15 > diffs/12_to_15.patch

# Show what changed in specific file
git log --follow src/api/payments.py

# Blame: which agent/iteration created this line
git blame src/models/user.py

Monthly Workflow Summary

Week 1: Foundation

# Day 1-2: Initial requirements & architecture
python repo_builder.py init --spec requirements/mvp_spec.md --output output/saas_app

# Day 3-5: Core feature implementation
for feature in auth dashboard api-core; do
  python repo_builder.py feature add --name $feature --spec requirements/mvp_spec.md
done

Week 2-3: Feature Iteration (20-25 updates)

# Typical daily pattern:
# 1. Update spec for new feature/change
vim requirements/spec_v{2..10}.md

# 2. Run targeted update
python repo_builder.py update --target backend,frontend --spec requirements/spec_v*.md

# 3. Review and test
cd output/saas_app && npm run test:all

# 4. Commit iteration
git add . && git commit -m "Iteration X: ..."

Week 4: Polish & Deploy (5-8 updates)

# Performance optimization
python repo_builder.py optimize performance

# Security audit
python repo_builder.py audit security

# Generate production configs
python repo_builder.py deploy config --env production

# Final documentation update
python repo_builder.py generate docs --comprehensive

# Monthly summary
python repo_builder.py report monthly --month february --output reports/february_2026.md

Cost Tracking

Monitor Monthly Spend

# Track token usage in real-time
# Add to your Python scripts:

import json
from datetime import datetime

def log_usage(tokens_used, cost):
    log_entry = {
        "timestamp": datetime.now().isoformat(),
        "tokens": tokens_used,
        "cost_usd": cost
    }
    
    with open("logs/usage.jsonl", "a") as f:
        f.write(json.dumps(log_entry) + "\n")

# Generate monthly report
python -c "
import json
total_cost = sum(json.loads(line)['cost_usd'] for line in open('logs/usage.jsonl'))
print(f'Monthly cost: \${total_cost:.2f}')
"

Cost Optimization

# Use cheaper models for simpler agents
qa_agent = AssistantAgent(
    name="qa_engineer",
    model_client=OpenAIChatCompletionClient(model="gpt-3.5-turbo"),  # Cheaper
    system_message="..."
)

docs_agent = AssistantAgent(
    name="docs_writer",
    model_client=OpenAIChatCompletionClient(model="gpt-3.5-turbo"),  # Cheaper
    system_message="..."
)

# Use GPT-4o only for critical reasoning (architect, complex backend)
architect = AssistantAgent(
    name="architect",
    model_client=OpenAIChatCompletionClient(model="gpt-4o"),  # Premium
    system_message="..."
)

Quick Reference: Most Used Commands

Setup (once)

python3 -m venv .venv && source .venv/bin/activate
pip install autogen-agentchat autogen-ext[openai] python-dotenv
echo "OPENAI_API_KEY=sk-..." > .env

Daily Workflow

python repo_builder.py update --spec requirements/spec.md --target backend,frontend
python repo_builder.py test
python repo_builder.py summary --output logs/today.md
git add . && git commit -m "Iteration X"

Debugging

python repo_builder.py --verbose update --spec requirements/spec.md
python repo_builder.py validate spec requirements/spec.md
python repo_builder.py health check

Reports

python repo_builder.py report weekly --output reports/week_N.md
python repo_builder.py report tokens --month february

Additional Resources

Key Information

Cost Estimate: ~$5 USD/month for 30 iterations (GPT-4o)

Time to Prototype: 2-4 hours (setup + initial build)

Recommended Python: 3.10 or 3.11 (3.12 works but some deps may lag)