agentleFS
deepread-techdeepread-tech/skills/.cursor/rules/deepread-form-fill.mdc

skills / rules

Cursor rule4 starsChanged 2 months agoMITView on GitHub

DeepRead Form Fill API. AI-powered PDF form filling — upload any PDF form + JSON data, get back a completed PDF. Endpoints, auth, request/response formats, and code examples.

  • Reads credentials
  • Sends data out

The file

We split this deepread-form-fill.mdc into the rules it gives an agent

3 rules. About 0 are common, 0 are distinctive, and 3 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈0

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 3

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    If you provide webhook_url, DeepRead POSTs results when the job finishes:

    line 142
  2. Very specific:

    Verify the signature before trusting a payload.

    line 189
  3. Very specific:

    If your JSON has keys that don't match any form field, they appear in unmapped_user_keys.

    line 221

≈ “Common” is an estimate: at least 1 in 5 of the 3,030 Cursor rule files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
deepread-form-fill.mdc
---
description: "DeepRead Form Fill API. AI-powered PDF form filling — upload any PDF form + JSON data, get back a completed PDF. Endpoints, auth, request/response formats, and code examples."
alwaysApply: false
---

# DeepRead Form Fill API Reference

You are helping a developer integrate DeepRead Form Fill into their application. You know the full API and can write working integration code in any language.

**Base URL:** `https://api.deepread.tech`
**Auth:** `X-API-Key` header with key from `https://www.deepread.tech/dashboard` or via the device authorization flow (see deepread-setup rule)

---

## What It Does

Upload any PDF form + your data as JSON. AI detects fields visually, maps your data semantically, fills the form with quality checks, and returns a completed PDF.

**Works with any PDF** — scanned paper forms, government PDFs, custom templates. No AcroForm fields required. This is visual coordinate-based filling, not AcroForm-based.

---

## POST /v1/form-fill — Submit a Form for Filling

**Auth:** `X-API-Key: YOUR_KEY`
**Content-Type:** `multipart/form-data`

| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
| `file` | File | Yes | — | PDF form to fill |
| `form_fields` | JSON string | Yes | — | `{"field_name": "value"}` — your data to fill |
| `webhook_url` | string | No | — | HTTPS URL to notify on completion |
| `idempotency_key` | string | No | — | Prevent duplicate submissions |
| `url_expires_in` | integer | No | `604800` | Signed URL expiry in seconds (min: 3600, max: 604800 = 7 days) |

**Response (200 OK):**
```json
{
  "id": "<job_id>",
  "status": "queued"
}
```

Processing is **asynchronous** — poll the GET endpoint or use a webhook.

**Errors:**
| Status | Meaning |
|--------|---------|
| 400 | Invalid JSON in form_fields, unsupported file type (PDF only) |
| 401 | Invalid or missing API key |
| 402 | Form fill is not on your plan (Enterprise), or the credits do not cover the job — the body names what is needed |
| 413 | Over the hard maximum: 2,000 pages or 500 MB |
| 429 | Requests per minute or pages in flight exceeded — `Retry-After` says when to retry (a form-fill job counts as one page in flight) |

---

## GET /v1/form-fill/{job_id} — Get Job Status & Results

**Auth:** `X-API-Key: YOUR_KEY`
**Rate limit:** 20 requests per 60 seconds

Poll every 5-10 seconds until `status` is `completed` or `failed`.

**Status values:** `queued` -> `processing` -> `completed` | `failed`

**Response (completed):**
```json
{
  "id": "<job_id>",
  "status": "completed",
  "file_name": "tax_form.pdf",
  "created_at": "2025-06-15T10:00:00Z",
  "completed_at": "2025-06-15T10:00:18Z",
  "filled_form_url": "https://storage.deepread.tech/form_fill/.../filled.pdf",
  "fields_detected": 25,
  "fields_filled": 23,
  "fields_verified": 21,
  "fields_hil_flagged": 2,
  "duration_seconds": 18.3,
  "report": {
    "summary": {
      "fields_detected": 25,
      "fields_filled": 23,
      "fields_verified": 21,
      "fields_hil_flagged": 2,
      "mappings_created": 23,
      "unmapped_keys": 0,
      "adjustments_made": 3
    },
    "fields": [
      {
        "field_index": 0,
        "label": "Taxpayer Name",
        "field_type": "text",
        "page": 1,
        "value": "Jane Doe",
        "hil_flag": false,
        "verified": true
      },
      {
        "field_index": 8,
        "label": "Total Income",
        "field_type": "text",
        "page": 2,
        "value": "85000",
        "hil_flag": true,
        "verified": false,
        "reason": "Text overlaps adjacent field"
      }
    ],
    "mappings": [
      {
        "user_key": "taxpayer_name",
        "field_index": 0,
        "value_to_fill": "Jane Doe",
        "confidence": 0.95
      }
    ],
    "unmapped_user_keys": [],
    "adjustments_made": ["Field 8: reduced font size from 12pt to 8pt"],
    "qa_feedback": ["Total Income: text overlaps adjacent field"],
    "errors": []
  },
  "errors": null,
  "error_message": null
}
```

**Response (failed):**
```json
{
  "id": "<job_id>",
  "status": "failed",
  "error_message": "Vision model timeout"
}
```

---

## Webhook Notification

If you provide `webhook_url`, DeepRead POSTs results when the job finishes:

**Completed:**
```json
{
  "job_id": "<job_id>",
  "status": "completed",
  "created_at": "<ISO 8601>",
  "completed_at": "<ISO 8601>",
  "result": {
    "filled_form_url": "<signed URL>",
    "fields_detected": 25,
    "fields_filled": 23,
    "fields_verified": 21,
    "fields_hil_flagged": 2,
    "report": { ... }
  }
}
```

**Failed:**
```json
{
  "job_id": "<job_id>",
  "status": "failed",
  "created_at": "<ISO 8601>",
  "completed_at": "<ISO 8601>",
  "error": "Form fill timed out after 600s",
  "errors": ["Form fill timed out after 600s"]
}
```

**Signature — verify every delivery.** Each POST carries `X-DeepRead-Signature: t=<unix seconds>,v1=<hex>`: HMAC-SHA256 over `"<t>.<raw request body>"` keyed by your account's signing secret (`GET /dashboard/v1/webhooks/secret`, created on first read; rotate with `POST /dashboard/v1/webhooks/secret/rotate`). Verify over the exact bytes you received, compare in constant time, and reject a `t` older than five minutes:

```python
import hmac, hashlib, time

def verify(secret: str, header: str, body: bytes, tolerance: int = 300) -> bool:
    parts = dict(p.split("=", 1) for p in header.split(","))
    t = int(parts["t"])
    if abs(time.time() - t) > tolerance:
        return False
    expected = hmac.new(secret.encode(), f"{t}.".encode() + body, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, parts["v1"])
```

**Important:**
- Verify the signature before trusting a payload; `GET /v1/form-fill/{job_id}` stays the canonical result if you ever need to re-fetch
- Must be HTTPS
- Return 2xx to confirm delivery
- Design your endpoint for idempotency (may receive duplicates)

---

## Understanding the Report

### fields_detected vs fields_filled vs fields_verified vs fields_hil_flagged

| Metric | What it means |
|--------|---------------|
| `fields_detected` | Total form fields AI found on the PDF |
| `fields_filled` | Fields where your data was placed |
| `fields_verified` | Fields that passed visual QA (text readable, positioned correctly) |
| `fields_hil_flagged` | Fields needing human review (AI couldn't fully verify) |

**Typical result:** 90-95% of fields verified, 2-5% flagged for review.

### HIL Flags (Human-in-the-Loop)

A field gets `hil_flag: true` when:
- Text overlaps an adjacent field
- Font had to be shrunk significantly
- Value doesn't visually match field expectations
- Repair attempts didn't fully resolve the issue

Each flagged field includes a `reason` explaining why review is needed.

### Unmapped Keys

If your JSON has keys that don't match any form field, they appear in `unmapped_user_keys`. This means the form doesn't have a matching field, or the field label is ambiguous.

---

## Idempotency

Prevent duplicate submissions with `idempotency_key`:

```bash
# First request
curl -X POST https://api.deepread.tech/v1/form-fill \
  -H "X-API-Key: YOUR_KEY" \
  -F "file=@form.pdf" \
  -F 'form_fields={"name": "Jane"}' \
  -F "idempotency_key=submission-abc-123"
# -> {"id": "<job_id>", "status": "queued"}

# Retry (same key) — returns the same job, no duplicate
curl -X POST https://api.deepread.tech/v1/form-fill \
  -H "X-API-Key: YOUR_KEY" \
  -F "file=@form.pdf" \
  -F 'form_fields={"name": "Jane"}' \
  -F "idempotency_key=submission-abc-123"
# -> {"id": "<same job_id>", "status": "queued"}  <- SAME JOB
```

---

## Code Examples

### Python

```python
import requests
import time
import json

API_KEY = "sk_live_YOUR_KEY"
BASE = "https://api.deepread.tech"

# Submit form + data
form_fields = {
    "full_name": "Jane Doe",
    "date_of_birth": "03/15/1990",
    "ssn": "123-45-6789",
    "address": "123 Main St, Portland OR 97201"
}

with open("application.pdf", "rb") as f:
    resp = requests.post(
        f"{BASE}/v1/form-fill",
        headers={"X-API-Key": API_KEY},
        files={"file": f},
        data={"form_fields": json.dumps(form_fields)}
    )
job_id = resp.json()["id"]

# Poll with backoff
delay = 5
while True:
    time.sleep(delay)
    result = requests.get(
        f"{BASE}/v1/form-fill/{job_id}",
        headers={"X-API-Key": API_KEY}
    ).json()

    if result["status"] in ("completed", "failed"):
        break
    delay = min(delay * 1.5, 30)

# Use results
if result["status"] == "completed":
    print(f"Download: {result['filled_form_url']}")
    print(f"Fields: {result['fields_filled']}/{result['fields_detected']} filled, "
          f"{result['fields_hil_flagged']} need review")

    # Check flagged fields
    for field in result["report"]["fields"]:
        if field["hil_flag"]:
            print(f"  REVIEW: {field['label']} = {field['value']} ({field.get('reason')})")
```

### JavaScript / Node.js

```javascript
import fs from "fs";

const API_KEY = "sk_live_YOUR_KEY";
const BASE = "https://api.deepread.tech";

// Submit form + data
const form = new FormData();
form.append("file", fs.createReadStream("application.pdf"));
form.append("form_fields", JSON.stringify({
  full_name: "Jane Doe",
  date_of_birth: "03/15/1990",
  ssn: "123-45-6789",
  address: "123 Main St, Portland OR 97201"
}));

const { id: jobId } = await fetch(`${BASE}/v1/form-fill`, {
  method: "POST",
  headers: { "X-API-Key": API_KEY },
  body: form
}).then(r => r.json());

// Poll with backoff
let delay = 5000;
let result;
do {
  await new Promise(r => setTimeout(r, delay));
  result = await fetch(`${BASE}/v1/form-fill/${jobId}`, {
    headers: { "X-API-Key": API_KEY }
  }).then(r => r.json());
  delay = Math.min(delay * 1.5, 30000);
} while (!["completed", "failed"].includes(result.status));

if (result.status === "completed") {
  console.log("Download:", result.filled_form_url);
  console.log(`Fields: ${result.fields_filled}/${result.fields_detected} filled`);
}
```

### cURL

```bash
# Submit form + data
curl -X POST https://api.deepread.tech/v1/form-fill \
  -H "X-API-Key: YOUR_KEY" \
  -F "file=@application.pdf" \
  -F 'form_fields={"full_name": "Jane Doe", "date_of_birth": "03/15/1990", "address": "123 Main St"}'

# Get results
curl https://api.deepread.tech/v1/form-fill/JOB_ID \
  -H "X-API-Key: YOUR_KEY"

# With webhook + idempotency
curl -X POST https://api.deepread.tech/v1/form-fill \
  -H "X-API-Key: YOUR_KEY" \
  -F "file=@form.pdf" \
  -F 'form_fields={"name": "Jane Doe"}' \
  -F "webhook_url=https://your-app.com/webhooks/form-fill" \
  -F "idempotency_key=batch-001"
```

---

## Rate Limits & Pricing

Form fill is an **Enterprise** feature; other plans receive `402` with the plan named.

| Plan | Pages | Price |
|------|-------|-------|
| Free | 2,000 a month (resets on your signup day); no form fill | $0 (no credit card) |
| Standard | No page limits; no form fill | Prepaid credits from $10 per 1,000 pages (Parse $10, Extract $20, Deep Extract $40) |
| Enterprise | Custom — includes form fill, PII redaction, searchable PDF, retention, incognito, BYOK | Custom |

Submits per minute: 10 Free, 100 Standard, 500 Enterprise (`429` + `Retry-After` past the limit). Pages in flight (queued + processing jobs; a form-fill job counts as one page): 16 / 200 / 500. Hard maximum for everyone: 2,000 pages or 500 MB (`413`).

Response headers: `X-RateLimit-Limit`, `X-RateLimit-Remaining`, `X-RateLimit-Used`, `X-RateLimit-Reset`

---

## Troubleshooting

- **400 "Only PDF files are supported"** — Upload a `.pdf` file. Other formats are not yet supported.
- **400 "Invalid JSON in form_fields"** — Must be a valid JSON object: `{"name": "Jane"}`, not an array or string.
- **402 "Form fill is not on the ... plan"** — Form fill is an Enterprise feature; upgrade the plan.
- **429 with `Retry-After`** — Too many submits this minute, or too many pages in flight. Wait the seconds given and retry with the same `idempotency_key`.
- **Status "failed" with "Vision model timeout"** — Form is very complex or has many pages. Try splitting into sections.
- **Fields not mapped correctly** — Use descriptive key names: `"applicant_full_name"` not `"field1"`.
- **Some fields flagged for review** — Expected for 2-5% of fields. Check `report.fields` for the `reason`.
- **Unmapped keys in report** — Your JSON keys didn't match form fields. Check `unmapped_user_keys`.

---

## Help the Developer

- **No API key yet** -> use the device authorization flow (see deepread-setup rule) or sign up at https://www.deepread.tech/dashboard
- **Fill a form** -> POST /v1/form-fill with `file` + `form_fields`, show code in their language
- **Check results** -> GET /v1/form-fill/{job_id}, look at `filled_form_url` and `report`
- **Prevent duplicates** -> use `idempotency_key` parameter
- **Real-time updates** -> set up `webhook_url`, build receiver endpoint
- **Hitting errors** -> check API key, plan limits, file format, JSON validity
- **Review workflow** -> filter fields by `hil_flag: true`, check `reason` for each
- **Batch processing** -> loop with `idempotency_key` per submission, poll all jobs

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.