# AgentForms Examples — Human-in-the-Loop Patterns

Demonstrations of integrating [AgentForms](https://agentforms.io) with popular AI agent frameworks. Each example shows a complete flow: **create form → send link to human → receive response → continue workflow**.

---

## Quick Start

```bash
export AGENTFORMS_API_KEY="your-api-key"
pip install agentforms requests
```

---

## Example 1: CrewAI Human-in-the-Loop

**File:** `crewai_human_in_loop.py`

A CrewAI agent generates content (e.g. a blog post), then pauses to request human approval before publishing.

**Pattern:**
1. Agent generates a draft.
2. Agent creates an AgentForms approval form with the SDK.
3. Shareable link is sent to the human reviewer.
4. Agent polls the API for a submission.
5. Based on the response (approve / revise / stop), the agent continues, revises, or halts.

**Key classes:**
- `ApprovalGate` — creates the form, shares the link, polls until the human responds.
- `build_crew_ai_agent()` — full CrewAI workflow with approval gating.

**Run:**
```bash
pip install crewai agentforms
python crewai_human_in_loop.py
```

**When to use:** Content generation pipelines, code review gates, deployment approvals — any workflow where an agent's output needs human sign-off before proceeding.

---

## Example 2: LangChain Form Generator Agent

**File:** `langchain_form_agent.py`

A LangChain agent that dynamically generates AgentForms from natural-language prompts.

**Pattern:**
1. Human describes a form in plain English.
2. LangChain agent calls either:
   - `generate_agentform(prompt)` — AgentForms' built-in AI generates fields.
   - `create_agentform(name, fields)` — Agent builds the fields programmatically.
3. The agent returns a shareable form URL.
4. Optionally, the agent polls for and summarises collected submissions.

**Key tools:**
- `generate_agentform` — AI-powered form generation (Starter+ tier).
- `create_agentform` — Programmatic form creation with explicit field definitions.
- `poll_submissions` — Wait for and summarise form responses.

**Run:**
```bash
# Direct SDK demo (no LangChain needed):
pip install agentforms
python langchain_form_agent.py

# Full LangChain agent:
pip install langchain langchain-openai agentforms
python langchain_form_agent.py langchain
```

**When to use:** Dynamic data collection, user-facing agents that need to gather structured input, survey generation, onboarding flows.

---

## Example 3: Webhook Receiver (FastAPI / Flask)

**File:** `webhook_receiver.py`

A webhook server that receives AgentForms submissions and unblocks a waiting agent — eliminating the need for polling.

**Architecture:**
```
┌──────────┐   share URL    ┌───────────┐   webhook POST   ┌──────────────┐
│  Agent   │ ─────────────► │  Human    │ ───────────────► │  Webhook     │
│  (AI)    │ ◄───────────── │  (Browser)│                  │  Receiver    │
└──────────┘   resume       └───────────┘   (async signal) └──────────────┘
```

**Pattern:**
1. Agent creates a form with a webhook URL pointing to this server.
2. Agent shares the form link with a human and waits on a shared channel.
3. Human fills out the form; AgentForms POSTs to the webhook URL.
4. Webhook handler parses the payload and signals the waiting agent.
5. Agent resumes with the human's decision.

**Key components:**
- `PendingRequests` — in-memory store matching webhook payloads to pending agent sessions.
- `WebhookApprovalGate` — agent-facing class that creates forms and waits for webhook delivery.
- `build_fastapi_app()` — FastAPI webhook endpoint with health and status checks.
- `build_flask_app()` — Flask alternative.

**Run:**
```bash
# Start FastAPI server:
pip install fastapi uvicorn agentforms
python webhook_receiver.py server

# Start Flask server:
pip install flask agentforms
python webhook_receiver.py flask

# Run the full demo (creates form, starts server, simulates webhook):
python webhook_receiver.py demo
```

**Webhook payload format:**
```json
{
  "event": "submission",
  "site_id": 42,
  "site_name": "Approval Request",
  "submission_id": 156,
  "submitted_at": "2026-06-12T14:30:00Z",
  "fields": {
    "approved": "Yes",
    "revision_notes": "Looks good, proceed."
  },
  "field_metadata": {}
}
```

**When to use:** Production deployments where polling is undesirable, real-time workflows, systems with strict latency requirements, or when you need audit logging of webhook deliveries.

---

## Comparison

| Aspect | `crewai_human_in_loop` | `langchain_form_agent` | `webhook_receiver` |
|---|---|---|---|
| **Pattern** | Agent polls after creating form | Agent generates forms on demand | Webhook pushes response to agent |
| **Transport** | Polling (simple) | Polling (simple) | Webhook (real-time) |
| **Best for** | Approval gates, review loops | Dynamic form creation | Production, low-latency flows |
| **Framework** | CrewAI | LangChain | FastAPI / Flask |
| **Complexity** | Low | Medium | Medium-High |

---

## SDK Reference

All examples use the [AgentForms Python SDK](../sdk-python/):

```python
from agentforms import AgentForms

af = AgentForms(api_key="afk_live_...")

# Create a form
form = af.forms.create(
    name="My Form",
    fields=[
        {"name": "field_name", "label": "Label", "type": "text", "required": True},
        {"name": "choice", "label": "Choose", "type": "select",
         "options": ["A", "B", "C"], "required": True},
    ],
)
print(form.share_url)  # Share this with the human

# Or generate with AI
form = af.forms.generate(prompt="A food preference form for catering")

# List submissions
subs = af.submissions.list(form_token=form.token)
```

Full API docs: https://agentforms.io/api/v2
