# Agent + Form Integration Example

**Multi-agent collaborative workflows with forms as validation checkpoints**

This example demonstrates how AI agents work WITH TypeDialog forms in a human-in-the-loop workflow. Forms collect structured data; agents analyze and synthesize; users validate at key decision points.

## Overview

Traditional workflows: Form → Database
This example: Form → Agent → Form → Agent → Output

**Key insight:** Agents are best used for analysis and recommendations, while forms are best for structured data collection and validation. Together they create powerful decision support systems.

## The Workflow

```
┌─────────────────────────────────────────────────────────────┐
│ STEP 1: Project Questionnaire (Form)                        │
│ User fills: project type, requirements, constraints        │
│ Output: project-input.json                                 │
└────────────────────────┬────────────────────────────────────┘
                         ↓
┌─────────────────────────────────────────────────────────────┐
│ STEP 2: Initial Analysis (Agent - Claude Sonnet)            │
│ Analyzes project structure & requirements                   │
│ Suggests database choice, API patterns, deployment         │
│ Output: analysis.md                                         │
└────────────────────────┬────────────────────────────────────┘
                         ↓
┌─────────────────────────────────────────────────────────────┐
│ STEP 3: Validate Suggestions (Form)                         │
│ User reviews agent suggestions & provides feedback         │
│ Output: validation.json                                     │
└────────────────────────┬────────────────────────────────────┘
                         ↓
┌─────────────────────────────────────────────────────────────┐
│ STEP 4: Constraint Validation (Agent - GPT-4o)              │
│ Checks suggestions against architectural patterns          │
│ Validates database choice, scaling assumptions             │
│ Output: constraints-check.md                               │
└────────────────────────┬────────────────────────────────────┘
                         ↓
┌─────────────────────────────────────────────────────────────┐
│ STEP 5: User Confirmation (Form)                            │
│ Final review & approval of architecture                    │
│ Output: approval.json                                       │
└────────────────────────┬────────────────────────────────────┘
                         ↓
┌─────────────────────────────────────────────────────────────┐
│ STEP 6: Final Synthesis (Agent - Claude Opus)               │
│ Generates ADRs (Architecture Decision Records)             │
│ Creates deployment guide & tech stack summary              │
│ Output: final-architecture.md + adr/ directory             │
└─────────────────────────────────────────────────────────────┘
```

## Running the Example

### Quick Start (Complete Workflow)

```bash
# Execute all 6 steps
./workflow.sh

# Follow prompts at each step
# Final output: final-architecture.md with ADRs and diagrams
```

### Step-by-Step Execution

```bash
# Step 1: Collect requirements
cargo run -p typedialog -- form architecture-form.toml \
  --format json > data/project-input.json

# Step 2: Initial analysis
cargo run -p typedialog-ag -- project-architect-1.agent.mdx \
  --input data/project-input.json > data/analysis.md

# Step 3: Validate suggestions
cargo run -p typedialog -- form recommendations-form.toml \
  --format json > data/validation.json

# Step 4: Check constraints
cargo run -p typedialog-ag -- project-architect-2.agent.mdx \
  --input data/project-input.json \
  --context data/validation.json > data/constraints-check.md

# Step 5: Final approval
cargo run -p typedialog -- form confirmation-form.toml \
  --format json > data/approval.json

# Step 6: Generate ADRs
cargo run -p typedialog-ag -- project-architect-3.agent.mdx \
  --input data/project-input.json \
  --recommendations data/analysis.md \
  --approval data/approval.json > final-architecture.md
```

## Forms Demonstrated

### 1. `architecture-form.toml` - Initial Questionnaire

Collects project details:
- **Project Type** - Microservices, monolith, serverless, event-driven
- **Scale Requirements** - Concurrent users, data volume, traffic patterns
- **Technology Constraints** - Team expertise, deployment platform, budget
- **Performance Goals** - Latency, throughput, availability requirements
- **Features Needed** - Real-time, offline-first, multi-tenancy, etc.

Output: Structured JSON with all decisions for agent analysis

### 2. `recommendations-form.toml` - Agent Suggestions Review

User validates or modifies agent recommendations:
- **Database Choice** - SQL vs NoSQL vs Graph (with rationale from agent)
- **API Pattern** - REST vs GraphQL vs gRPC (with trade-offs)
- **Deployment** - Kubernetes, Lambda, Docker Swarm (with costs)
- **Caching** - Redis, Memcached, CDN (with hit rates)
- **Authentication** - JWT vs OAuth vs mTLS (with security implications)

User can accept, modify, or reject each suggestion

### 3. `confirmation-form.toml` - Final Approval

Binary decisions at the end:
- Approve database architecture
- Approve deployment strategy
- Approve security approach
- Approve team training needs

## Agents Demonstrated

### 1. `project-architect-1.agent.mdx` - Project Analyzer (Claude Sonnet)

**Input:** Project questionnaire (JSON)

**Processing:**
- Analyzes project requirements vs available architecture patterns
- Matches against internal knowledge base (architecture-patterns.json)
- Suggests database, API, deployment choices with rationale
- Identifies potential risks or constraints

**Output:** Markdown with structured recommendations and trade-offs

**Why Sonnet:** Balanced cost/performance for initial analysis

### 2. `project-architect-2.agent.mdx` - Constraints Validator (GPT-4o)

**Input:**
- Original requirements (JSON)
- User validation feedback (JSON)

**Processing:**
- Validates suggestions against architectural constraints
- Checks for conflicting requirements
- Verifies scaling assumptions are realistic
- Audits security implications

**Output:** Markdown with validation results and remediation suggestions

**Why GPT-4o:** Precise constraint checking and validation

### 3. `project-architect-3.agent.mdx` - Synthesizer (Claude Opus)

**Input:**
- Project requirements (JSON)
- Agent recommendations (Markdown)
- User approvals (JSON)

**Processing:**
- Creates Architecture Decision Records (ADRs) for each major decision
- Generates deployment guide with step-by-step instructions
- Produces tech stack summary and team training recommendations
- Creates architecture diagram (ASCII art or Mermaid)

**Output:** Markdown with comprehensive architecture blueprint

**Why Opus:** Highest quality for final synthesis and ADRs

## Key Patterns

### Pattern 1: Forms as Data Collection

**When to use:** Structured input with validation rules

```toml
[[elements]]
name = "concurrent_users"
type = "text"
prompt = "Expected concurrent users"
required = true
validation = "min: 1, max: 1000000"
```

### Pattern 2: Agents as Analysis

**When to use:** Complex evaluation, pattern matching, synthesis

```yaml
# Agent input
{
  "project_type": "microservices",
  "concurrent_users": 10000,
  "budget": "high",
  "team_size": 15,
  "deployment": "kubernetes"
}

# Agent output
## Database Recommendation: PostgreSQL + Read Replicas
Rationale: Your microservices architecture with 10K concurrent users
requires strong consistency and complex queries. PostgreSQL provides...
```

### Pattern 3: Human-in-the-Loop

**When to use:** Critical decisions need user validation

```bash
# After each agent step, present form for user validation
# User can accept, modify, or request re-analysis
# This prevents garbage-in/garbage-out scenarios
```

### Pattern 4: JSON for Interchange

**Forms output to JSON:** Structured data for agents

```bash
cargo run -p typedialog -- form architecture-form.toml --format json
# Output: {"project_type": "microservices", "concurrent_users": 10000, ...}
```

**Agents read/write JSON:** Easy parsing and validation

```bash
cat project-input.json | typedialog-ag project-architect-1.agent.mdx
```

## Architecture Patterns Library

The `architecture-patterns.json` file contains:

```json
{
  "databases": {
    "postgresql": {
      "best_for": ["relational", "complex_queries", "strong_consistency"],
      "scaling": "read_replicas",
      "max_connections": 5000
    },
    "dynamodb": {
      "best_for": ["serverless", "simple_queries", "high_throughput"],
      "scaling": "auto",
      "max_connections": "unlimited"
    }
  },
  "api_patterns": {
    "rest": { "latency": "medium", "complexity": "low" },
    "graphql": { "latency": "low", "complexity": "high" },
    "grpc": { "latency": "very_low", "complexity": "very_high" }
  }
}
```

Agents reference this when making recommendations

## Validation Rules

`validation-rules.toml` defines constraints agents must respect:

```toml
[scaling_rules]
# Rule: More than 1000 concurrent users needs read replicas
min_users_for_replicas = 1000

# Rule: Multi-region requires 99.99% SLA
multi_region_sla = 0.9999

[architecture_patterns]
# Rule: Monolith OK up to 50 person-months of development
max_monolith_team_size = 50

# Rule: Microservices need at least 10 person team
min_microservices_team_size = 10
```

## Data Files Generated

The workflow generates these files in the `data/` directory:

```
data/
├── project-input.json          # User's initial questionnaire
├── analysis.md                 # Agent 1 analysis & recommendations
├── validation.json             # User's feedback on recommendations
├── constraints-check.md        # Agent 2 validation results
├── approval.json              # User's final approval
└── final-architecture.md      # Agent 3 synthesis + ADRs
```

Each step preserves intermediate results for review and debugging

## Learning Outcomes

After working through this example, you'll understand:

1. **Agent Responsibilities vs Form Responsibilities**
   - Forms: Collect structured data, validate required fields
   - Agents: Analyze, recommend, synthesize

2. **Human-in-the-Loop Workflow**
   - Why forms are checkpoints between agent steps
   - How to ensure user stays in control
   - Risk mitigation through validation

3. **Multi-Agent Coordination**
   - Sequential workflows (Agent 1 → Form → Agent 2)
   - Different LLMs for different tasks (Sonnet/GPT-4o/Opus)
   - Passing context between agents

4. **Data Interchange**
   - JSON as universal format
   - Form → JSON → Agent → Markdown → Form
   - Parsing and validation at each step

5. **Architecture Decision Making**
   - How to structure complex technical decisions
   - Creating ADRs (Architecture Decision Records)
   - Documenting trade-offs and rationale

## Real-World Applications

This pattern works for:

- **Architecture Planning** - Design software systems (this example)
- **Infrastructure Provisioning** - Choose cloud resources, networking
- **Database Migration** - Evaluate migration strategies
- **Team Onboarding** - New developer training paths based on tech stack
- **Compliance Assessment** - Security & regulatory decision making
- **Bug Triage** - Categorize and assign bugs based on severity/component

## Troubleshooting

**"Agent failed to parse JSON"**
- Ensure form outputs valid JSON with `--format json` flag
- Check the JSON file is not empty

**"Agent recommendation doesn't match constraints"**
- This is expected! Agent 2 validates recommendations
- User can reject and request re-analysis

**"User skipped validation form"**
- Workflow continues with default values
- Modify `workflow.sh` to require all steps

**"Different LLM provider not available"**
- Ensure API keys are set (ANTHROPIC_API_KEY, OPENAI_API_KEY)
- Modify agent files to use available providers

## Next Steps

1. **Customize for your domain** - Replace architecture patterns with your use case
2. **Add more agents** - Include security review, performance review, cost analysis
3. **Extend validation** - Add business rules specific to your organization
4. **Build a UI** - Wrap this workflow in a web interface for non-developers
5. **Multi-step approval** - Add stakeholder sign-off forms between agent steps

---

**Key Takeaway:** Agents excel at analysis and synthesis, not at data collection. Forms excel at validation and user input, not at analysis. Together, they create powerful systems that are both intelligent and reliable.
