Classifies a document as an ACORD Form, then extracts applicant details, coverage selections, and policy terms from commercial insurance quotes.
An ACORD commercial insurance application is a standardized form submitted by businesses seeking commercial coverage, containing applicant and agency details, selected coverage types, policy terms, effective dates, and billing arrangements for underwriting evaluation. This template takes in ACORD Forms and outputs markdown (.md) with the parsed application text and layout structure, and JSON (.json) with structured fields including applicant information, agency details, coverage selections, policy dates, and billing preferences per the extraction schema. It also classifies weather the document is an ACORD Form by using Extend's Parse, Extract primitives.
Converts the document into clean, layout-aware markdown plus structured blocks with spatial metadata.
blockOptions.text.agentic.enabledtruechangedchunkingStrategy.type"document"engine"parse_performance"You can learn more about Parse configuration in Extend's Parse documentation.
Pulls a defined set of fields from the document and returns them as structured JSON matching a schema.
schemacustom schema — 55 fieldschangedadvancedOptions.advancedMultimodalEnabledtruechangedadvancedOptions.reviewAgent.enabledtruechangedbaseProcessor"extraction_performance"You can learn more about Extract configuration in Extend's Extract documentation.
{
"name": "Commercial Insurance Application Processing Pipeline",
"steps": [
{
"name": "startTrigger1",
"type": "TRIGGER",
"next": [
{
"step": "parse1"
}
]
},
{
"name": "parse1",
"type": "PARSE",
"config": {
"parseConfig": {
"blockOptions": {
"text": {
"agentic": {
"enabled": true
}
}
},
"chunkingStrategy": {
"type": "document"
}
}
},
"next": [
{
"step": "classify2"
}
]
},
{
"name": "classify2",
"type": "CLASSIFY",
"config": {
"classifierConfig": {
"classifications": [
{
"id": "classification1",
"type": "other",
"description": "Use the `other` document type when the provided document can not clearly be classified into one of the described classifications."
},
{
"id": "classification_GEy",
"type": "acord_form",
"description": "An ACORD form is a standardized document used throughout the insurance industry. Created by the Association for Cooperative Operations Research and Development (ACORD)"
}
],
"baseProcessor": "classification_performance",
"advancedOptions": {
"advancedMultimodalEnabled": true
}
}
},
"next": [
{
"step": "extraction3",
"classificationId": "classification1"
},
{
"step": "extraction3",
"classificationId": "classification_GEy"
}
]
},
{
"name": "extraction3",
"type": "EXTRACT",
"config": {
"extractorConfig": {
"schema": {
"type": "object",
"required": [
"county",
"owners",
"website",
"dba_name",
"naic_code",
"agent_name",
"fax_number",
"agency_code",
"agency_name",
"billing_plan",
"contact_name",
"loss_history",
"payment_plan",
"business_type",
"contact_title",
"email_address",
"landlord_name",
"policy_number",
"primary_phone",
"federal_tax_id",
"landlord_phone",
"premises_owned",
"signature_date",
"audit_frequency",
"mailing_address",
"premises_leased",
"secondary_phone",
"application_date",
"number_of_owners",
"physical_address",
"agency_customer_id",
"applicant_signature",
"agent_license_number",
"applicant_legal_name",
"business_description",
"total_annual_payroll",
"year_business_started",
"el_each_accident_limit",
"package_policy_premium",
"el_disease_policy_limit",
"proposed_effective_date",
"estimated_annual_revenue",
"general_liability_limits",
"proposed_expiration_date",
"workers_compensation_code",
"square_footage_of_premises",
"workers_compensation_state",
"business_classification_code",
"number_of_seasonal_employees",
"number_of_full_time_employees",
"number_of_part_time_employees",
"el_disease_each_employee_limit",
"business_classification_description",
"workers_compensation_annual_payroll",
"general_liability_coverages_requested"
],
"properties": {
"county": {
"type": [
"string",
"null"
],
"description": "The county in which the applicant's business is located. May be labeled as 'County' or included as part of the address."
},
"owners": {
"type": "array",
"items": {
"type": "object",
"required": [
"ssn",
"title",
"owner_name",
"date_of_birth",
"ownership_percent"
],
"properties": {
"ssn": {
"type": [
"string",
"null"
],
"description": "The Social Security Number of the owner, if provided."
},
"title": {
"type": [
"string",
"null"
],
"description": "The title or position held by this individual within the business."
},
"owner_name": {
"type": [
"string",
"null"
],
"description": "The full name of the owner, partner, or officer."
},
"date_of_birth": {
"type": [
"string",
"null"
],
"description": "The date of birth of the owner, partner, or officer.",
"extend:type": "date"
},
"ownership_percent": {
"type": [
"number",
"null"
],
"description": "The percentage of ownership held by this individual."
}
},
"additionalProperties": false
},
"description": "A list of owners, partners, or officers for the applicant's business. Each entry includes identifying and ownership information."
},
"website": {
"type": [
"string",
"null"
],
"description": "The website address (URL) for the applicant's business, if provided."
},
"dba_name": {
"type": [
"string",
"null"
],
"description": "The 'doing business as' name, if different from the legal name. This is an alternate business name under which the applicant operates."
},
"naic_code": {
"type": [
"string",
"null"
],
"description": "The NAIC (National Association of Insurance Commissioners) code associated with the insurer or policy. This is a numeric or alphanumeric code used for regulatory identification."
},
"agent_name": {
"type": [
"string",
"null"
],
"description": "The full name of the agent or broker responsible for the application. May be labeled as 'Agent Name', 'Producer', or similar."
},
"fax_number": {
"type": [
"string",
"null"
],
"description": "The fax number for the applicant or business, if provided."
},
"agency_code": {
"type": [
"string",
"null"
],
"description": "A unique code or identifier for the agency, if provided. May be labeled as 'Agency Code', 'Producer Code', or similar."
},
"agency_name": {
"type": [
"string",
"null"
],
"description": "The name of the insurance agency or brokerage handling the application. This is the organization representing the applicant to the insurer."
},
"billing_plan": {
"type": [
"string",
"null"
],
"description": "The selected billing plan for the policy, such as 'Direct Bill', 'Agency Bill', etc. May be indicated by checkboxes or text."
},
"contact_name": {
"type": [
"string",
"null"
],
"description": "The name of the primary contact person for the application or business. May be labeled as 'Contact Name', 'Inspection Contact', or similar."
},
"loss_history": {
"type": "array",
"items": {
"type": "object",
"required": [
"status",
"amount_paid",
"description",
"date_of_loss",
"type_of_loss",
"amount_reserved"
],
"properties": {
"status": {
"type": [
"string",
"null"
],
"description": "The current status of the claim or loss, such as 'Open', 'Closed', 'Pending', etc."
},
"amount_paid": {
"type": [
"number",
"null"
],
"description": "The amount paid to settle the claim or loss, if any."
},
"description": {
"type": [
"string",
"null"
],
"description": "A narrative description of the loss, claim, or incident."
},
"date_of_loss": {
"type": [
"string",
"null"
],
"description": "The date the loss, claim, or incident occurred.",
"extend:type": "date"
},
"type_of_loss": {
"type": [
"string",
"null"
],
"description": "A brief description of the type of loss, such as 'Property Damage', 'Liability', etc."
},
"amount_reserved": {
"type": [
"number",
"null"
],
"description": "The amount reserved for the claim or loss, if any."
}
},
"additionalProperties": false
},
"description": "A list of claims, lawsuits, or incidents reported in the past 5 years. Each entry represents a separate loss event."
},
"payment_plan": {
"type": [
"string",
"null"
],
"description": "The selected payment plan for the policy, such as 'Annual', 'Semi-Annual', etc. May be indicated by checkboxes or text."
},
"business_type": {
"type": [
"string",
"null"
],
"description": "The legal structure of the applicant's business, such as 'Sole Proprietorship', 'LLC', 'Corporation', 'Partnership', etc. May be indicated by checkboxes or text."
},
"contact_title": {
"type": [
"string",
"null"
],
"description": "The job title or role of the primary contact person, such as 'Owner', 'Manager', etc."
},
"email_address": {
"type": [
"string",
"null"
],
"description": "The primary email address for the applicant or business. Used for electronic correspondence."
},
"landlord_name": {
"type": [
"string",
"null"
],
"description": "The name of the landlord or property owner, if the premises are leased."
},
"policy_number": {
"type": [
"string",
"null"
],
"description": "The unique identifier assigned to the insurance policy, if available at the time of application. May include letters, numbers, or special characters. Commonly labeled as 'Policy Number' or 'Policy #'."
},
"primary_phone": {
"type": [
"string",
"null"
],
"description": "The main telephone number for the applicant or business. May include area code and extension."
},
"federal_tax_id": {
"type": [
"string",
"null"
],
"description": "The Federal Employer Identification Number (FEIN) or Social Security Number (SSN) for the applicant. Used for tax and regulatory purposes."
},
"landlord_phone": {
"type": [
"string",
"null"
],
"description": "The phone number of the landlord or property owner, if the premises are leased."
},
"premises_owned": {
"type": [
"boolean",
"null"
],
"description": "Indicates whether the applicant owns the business premises. True if owned, false if not."
},
"signature_date": {
"type": [
"string",
"null"
],
"description": "The date the applicant signed the application, certifying its accuracy.",
"extend:type": "date"
},
"audit_frequency": {
"type": [
"string",
"null"
],
"description": "The frequency of premium audit for the policy, such as 'Annually', 'Semi-Annually', etc."
},
"mailing_address": {
"type": [
"string",
"null"
],
"description": "The complete mailing address for the applicant, including street, city, state, and ZIP code. This is the primary address for correspondence."
},
"premises_leased": {
"type": [
"boolean",
"null"
],
"description": "Indicates whether the applicant leases the business premises. True if leased, false if not."
},
"secondary_phone": {
"type": [
"string",
"null"
],
"description": "An alternate or secondary telephone number for the applicant or business, if provided."
},
"application_date": {
"type": [
"string",
"null"
],
"description": "The date the commercial insurance application was completed or submitted. This is the official date of the application and may be labeled as 'Date', 'Application Date', or similar.",
"extend:type": "date"
},
"number_of_owners": {
"type": [
"integer",
"null"
],
"description": "The total number of owners, partners, or officers associated with the applicant's business."
},
"physical_address": {
"type": [
"string",
"null"
],
"description": "The physical address of the applicant's business, if different from the mailing address. Includes street, city, state, and ZIP code."
},
"agency_customer_id": {
"type": [
"string",
"null"
],
"description": "A unique identifier assigned by the agency to the applicant or account. May be labeled as 'Agency Customer ID', 'Client ID', or similar."
},
"applicant_signature": {
"type": [
"string",
"null"
],
"description": "The name or representation of the applicant's signature, indicating certification of the information provided."
},
"agent_license_number": {
"type": [
"string",
"null"
],
"description": "The license number of the agent or broker, if provided. This is a regulatory identifier for the individual handling the application."
},
"applicant_legal_name": {
"type": [
"string",
"null"
],
"description": "The legal name of the business or individual applying for insurance. This is the primary insured entity and may include DBA (doing business as) names."
},
"business_description": {
"type": [
"string",
"null"
],
"description": "A description of the applicant's primary business operations, activities, or services provided. May be labeled as 'Nature of Business', 'Description of Operations', or similar."
},
"total_annual_payroll": {
"type": [
"number",
"null"
],
"description": "The total annual payroll for all employees of the applicant's business, typically in the local currency."
},
"year_business_started": {
"type": [
"string",
"null"
],
"description": "The year the applicant's business was established or began operations. May be labeled as 'Year Business Started', 'Date Business Started', or similar."
},
"el_each_accident_limit": {
"type": [
"number",
"null"
],
"description": "The employer's liability limit for each accident under workers compensation coverage."
},
"package_policy_premium": {
"type": "object",
"required": [
"amount",
"iso_4217_currency_code"
],
"properties": {
"amount": {
"type": [
"number",
"null"
]
},
"iso_4217_currency_code": {
"type": [
"string",
"null"
]
}
},
"description": "The total premium amount for the package policy, if provided. This is the cost of the insurance coverage for the policy term.",
"extend:type": "currency",
"additionalProperties": false
},
"el_disease_policy_limit": {
"type": [
"number",
"null"
],
"description": "The employer's liability policy limit for disease under workers compensation coverage."
},
"proposed_effective_date": {
"type": [
"string",
"null"
],
"description": "The proposed effective date for the insurance policy. This is the date coverage is requested to begin.",
"extend:type": "date"
},
"estimated_annual_revenue": {
"type": [
"number",
"null"
],
"description": "The estimated or actual annual revenue for the applicant's business, typically in the local currency."
},
"general_liability_limits": {
"type": "object",
"required": [
"each_occurrence",
"medical_expense",
"general_aggregate",
"damage_to_rented_premises",
"personal_advertising_injury",
"products_completed_operations_aggregate"
],
"properties": {
"each_occurrence": {
"type": [
"number",
"null"
],
"description": "The limit for each occurrence under general liability coverage."
},
"medical_expense": {
"type": [
"number",
"null"
],
"description": "The limit for medical expense coverage."
},
"general_aggregate": {
"type": [
"number",
"null"
],
"description": "The general aggregate limit for general liability coverage."
},
"damage_to_rented_premises": {
"type": [
"number",
"null"
],
"description": "The limit for damage to rented premises coverage."
},
"personal_advertising_injury": {
"type": [
"number",
"null"
],
"description": "The limit for personal and advertising injury coverage."
},
"products_completed_operations_aggregate": {
"type": [
"number",
"null"
],
"description": "The aggregate limit for products and completed operations coverage."
}
},
"description": "The requested or quoted limits for general liability coverage. Each property represents a specific coverage limit.",
"additionalProperties": false
},
"proposed_expiration_date": {
"type": [
"string",
"null"
],
"description": "The proposed expiration date for the insurance policy. This is the date coverage is requested to end.",
"extend:type": "date"
},
"workers_compensation_code": {
"type": [
"string",
"null"
],
"description": "The workers compensation classification code applicable to the applicant's business."
},
"square_footage_of_premises": {
"type": [
"integer",
"null"
],
"description": "The total square footage of the business premises occupied by the applicant."
},
"workers_compensation_state": {
"type": [
"string",
"null"
],
"description": "The state in which workers compensation coverage is requested or provided."
},
"business_classification_code": {
"type": [
"string",
"null"
],
"description": "The business classification code (such as NAICS or SIC) that categorizes the applicant's industry or operations."
},
"number_of_seasonal_employees": {
"type": [
"integer",
"null"
],
"description": "The number of seasonal or temporary employees working for the applicant's business."
},
"number_of_full_time_employees": {
"type": [
"integer",
"null"
],
"description": "The number of full-time employees working for the applicant's business."
},
"number_of_part_time_employees": {
"type": [
"integer",
"null"
],
"description": "The number of part-time employees working for the applicant's business."
},
"el_disease_each_employee_limit": {
"type": [
"number",
"null"
],
"description": "The employer's liability limit for disease for each employee under workers compensation coverage."
},
"business_classification_description": {
"type": [
"string",
"null"
],
"description": "A textual description of the business classification or industry for the applicant."
},
"workers_compensation_annual_payroll": {
"type": [
"number",
"null"
],
"description": "The estimated annual payroll for workers compensation purposes."
},
"general_liability_coverages_requested": {
"type": [
"string",
"null"
],
"description": "A list or description of general liability coverages requested, such as 'Premises Operations', 'Products Completed Operations', 'Contractual Liability', etc. May be indicated by checkboxes or text."
}
},
"additionalProperties": false
},
"baseProcessor": "extraction_performance",
"advancedOptions": {
"reviewAgent": {
"enabled": true
},
"advancedMultimodalEnabled": true
}
}
}
}
]
}# Commercial Insurance Application Processing — Extend AI Skill
## What this pipeline does
This pipeline processes ACORD commercial insurance application forms end-to-end: parsing the document to markdown, classifying it as a valid ACORD form or other document type, and extracting 50+ structured fields covering applicant identity, ownership, coverage selections, loss history, and policy terms. The extracted data flows directly into underwriting workflows and CRM systems.
## When to use this
- **New business intake**: Automated ingestion of ACORD applications from brokers with immediate field capture for underwriting review
- **Compliance & audit trails**: Complete extraction of ownership, loss history, and policy terms for regulatory documentation
- **Multi-carrier workflow**: Route classified ACORD forms vs. non-standard applications to different underwriting teams
- **Premium audit preparation**: Capture employee counts, payroll, and coverage selections for actuarial pricing models
- **Fraud detection integration**: Extract loss history and ownership data for cross-referencing against claims databases
## Processor pipeline
### Step 1: Parse (`parse_performance` + `agentic_ocr`)
**Purpose**: Convert the ACORD form to markdown with high-fidelity text capture, handling checkboxes, form fields, and handwritten entries.
**Key config**:
- `engine: "parse_performance"` — optimized for form documents with structured layouts
- `blockOptions.text.agentic.enabled: true` — uses vision-based OCR to read checkboxes and form fills accurately
- `chunkingStrategy.type: "document"` — returns entire form as one logical unit (no page splits)
**Why this config**: ACORD forms are highly structured with precise field positions and checkbox states. Agentic OCR captures both printed and handwritten text; document-level chunking keeps ownership tables and coverage selections intact.
### Step 2: Classify (`classification_performance` + multimodal)
**Purpose**: Verify the document is a valid ACORD form (vs. a generic business insurance letter or renewal notice) before extraction.
**Key config**:
- `baseProcessor: "classification_performance"` — robust multimodal classification
- `advancedOptions.advancedMultimodalEnabled: true` — uses vision to detect ACORD form headers and layout markers
- Two classifications: `acord_form` (the target) and `other` (catch-all for misclassified or non-ACORD documents)
**Why this config**: ACORD forms have standardized visual layouts (header text, section numbering, checkbox grids). Multimodal detection catches scanned, rotated, or low-quality images. The `other` classification gates invalid documents before expensive extraction.
### Step 3: Extract (`extraction_performance` + review agent)
**Purpose**: Pull all applicant, coverage, and loss history fields into a structured JSON object ready for database insertion or underwriting rules engines.
**Key config**:
- `baseProcessor: "extraction_performance"` — highest accuracy for complex, multi-section forms
- `advancedOptions.reviewAgent.enabled: true` — AI review layer corrects inconsistencies (e.g., ownership percentages sum to 100%) before returning results
- Full 50+ field schema with nullable primitives and array structures for owners and loss history
- `extend:type: "date"`, `extend:type: "currency"` annotations for semantic parsing
**Why this config**: Commercial insurance applications have dense, interconnected fields (ownership must sum to 100%; loss history items have multi-field dependencies). Review agent catches data quality issues before they reach underwriting. Currency and date annotations ensure consistent formatting (ISO dates, no currency symbols in amounts).
---
## TypeScript implementation
<SDK_CODE>
import fs from "fs";
import { ExtendClient, extendDate, extendCurrency } from "extend-ai";
import { z } from "zod";
const client = new ExtendClient({ token: process.env.EXTEND_API_KEY });
// Define the full extraction schema using Zod with extend helpers
const insuranceApplicationSchema = z.object({
county: z.string().nullable().describe("The county in which the applicant's business is located."),
owners: z.array(z.object({
ssn: z.string().nullable().describe("The Social Security Number of the owner."),
title: z.string().nullable().describe("The title or position held by this individual."),
owner_name: z.string().nullable().describe("The full name of the owner, partner, or officer."),
date_of_birth: extendDate().describe("The date of birth of the owner (ISO yyyy-mm-dd)."),
ownership_percent: z.number().nullable().describe("The percentage of ownership held."),
})).describe("A list of owners, partners, or officers for the applicant's business."),
website: z.string().nullable().describe("The website address (URL) for the applicant's business."),
dba_name: z.string().nullable().describe("The 'doing business as' name, if different from legal name."),
naic_code: z.string().nullable().describe("The NAIC code associated with the insurer or policy."),
agent_name: z.string().nullable().describe("The full name of the agent or broker."),
fax_number: z.string().nullable().describe("The fax number for the applicant or business."),
agency_code: z.string().nullable().describe("A unique code or identifier for the agency."),
agency_name: z.string().nullable().describe("The name of the insurance agency or brokerage."),
billing_plan: z.string().nullable().describe("The selected billing plan (e.g., 'Direct Bill', 'Agency Bill')."),
contact_name: z.string().nullable().describe("The name of the primary contact person."),
loss_history: z.array(z.object({
status: z.string().nullable().describe("The current status of the claim (e.g., 'Open', 'Closed')."),
amount_paid: z.number().nullable().describe("The amount paid to settle the claim."),
description: z.string().nullable().describe("A narrative description of the loss."),
date_of_loss: extendDate().describe("The date the loss occurred (ISO yyyy-mm-dd)."),
type_of_loss: z.string().nullable().describe("The type of loss (e.g., 'Property Damage', 'Liability')."),
amount_reserved: z.number().nullable().describe("The amount reserved for the claim."),
})).describe("A list of claims, lawsuits, or incidents reported in the past 5 years."),
payment_plan: z.string().nullable().describe("The selected payment plan (e.g., 'Annual', 'Semi-Annual')."),
business_type: z.string().nullable().describe("The legal structure (e.g., 'LLC', 'Corporation', 'Partnership')."),
contact_title: z.string().nullable().describe("The job title or role of the primary contact."),
email_address: z.string().nullable().describe("The primary email address for the applicant."),
landlord_name: z.string().nullable().describe("The name of the landlord or property owner, if leased."),
policy_number: z.string().nullable().describe("The unique identifier assigned to the insurance policy."),
primary_phone: z.string().nullable().describe("The main telephone number for the applicant."),
federal_tax_id: z.string().nullable().describe("The Federal Employer Identification Number (FEIN) or SSN."),
landlord_phone: z.string().nullable().describe("The phone number of the landlord or property owner."),
premises_owned: z.boolean().nullable().describe("Whether the applicant owns the business premises."),
signature_date: extendDate().describe("The date the applicant signed the application (ISO yyyy-mm-dd)."),
audit_frequency: z.string().nullable().describe("The frequency of premium audit (e.g., 'Annually')."),
mailing_address: z.string().nullable().describe("The complete mailing address including street, city, state, ZIP."),
premises_leased: z.boolean().nullable().describe("Whether the applicant leases the business premises."),
secondary_phone: z.string().nullable().describe("An alternate or secondary telephone number."),
application_date: extendDate().describe("The date the application was completed (ISO yyyy-mm-dd)."),
number_of_owners: z.number().nullable().describe("The total number of owners, partners, or officers."),
physical_address: z.string().nullable().describe("The physical address of the business if different from mailing."),
agency_customer_id: z.string().nullable().describe("A unique identifier assigned by the agency to the applicant."),
applicant_signature: z.string().nullable().describe("The name or representation of the applicant's signature."),
agent_license_number: z.string().nullable().describe("The license number of the agent or broker."),
applicant_legal_name: z.string().nullable().describe("The legal name of the business or individual applying."),
business_description: z.string().nullable().describe("A description of the applicant's primary business operations."),
total_annual_payroll: z.number().nullable().describe("The total annual payroll for all employees."),
year_business_started: z.string().nullable().describe("The year the business was established or began operations."),
el_each_accident_limit: z.number().nullable().describe("The employer's liability limit for each accident."),
package_policy_premium: extendCurrency().describe("The total premium amount for the package policy."),
el_disease_policy_limit: z.number().nullable().describe("The employer's liability policy limit for disease."),
proposed_effective_date: extendDate().describe("The proposed effective date for coverage (ISO yyyy-mm-dd)."),
estimated_annual_revenue: z.number().nullable().describe("The estimated or actual annual revenue."),
general_liability_limits: z.object({
each_occurrence: z.number().nullable().describe("The limit for each occurrence."),
medical_expense: z.number().nullable().describe("The limit for medical expense coverage."),
general_aggregate: z.number().nullable().describe("The general aggregate limit."),
damage_to_rented_premises: z.number().nullable().describe("The limit for damage to rented premises."),
personal_advertising_injury: z.number().nullable().describe("The limit for personal and advertising injury."),
products_completed_operations_aggregate: z.number().nullable().describe("The aggregate limit for products/completed operations."),
}).describe("The requested or quoted limits for general liability coverage."),
proposed_expiration_date: extendDate().describe("The proposed expiration date for coverage (ISO yyyy-mm-dd)."),
workers_compensation_code: z.string().nullable().describe("The workers compensation classification code."),
square_footage_of_premises: z.number().nullable().describe("The total square footage of the business premises."),
workers_compensation_state: z.string().nullable().describe("The state for workers compensation coverage."),
business_classification_code: z.string().nullable().describe("The business classification code (NAICS or SIC)."),
number_of_seasonal_employees: z.number().nullable().describe("The number of seasonal or temporary employees."),
number_of_full_time_employees: z.number().nullable().describe("The number of full-time employees."),
number_of_part_time_employees: z.number().nullable().describe("The number of part-time employees."),
el_disease_each_employee_limit: z.number().nullable().describe("The employer's liability limit for disease per employee."),
business_classification_description: z.string().nullable().describe("A textual description of the business classification."),
workers_compensation_annual_payroll: z.number().nullable().describe("The estimated annual payroll for workers compensation."),
general_liability_coverages_requested: z.string().nullable().describe("A list of general liability coverages requested."),
});
async function processCommercialInsuranceApplication(filePath: string) {
console.log(`Processing insurance application from: ${filePath}`);
// Convert local file to data URL for SDK compatibility
const fileBuffer = fs.readFileSync(filePath);
const dataUrl = `data:application/octet-stream;base64,${fileBuffer.toString("base64")}`;
// STEP 1: Parse the document to markdown
console.log("\n[STEP 1] Parsing document to markdown...");
const parseRun = await client.parseRuns.createAndPoll({
file: { url: dataUrl },
config: {
mode: "agentic_ocr", // High-fidelity OCR for forms
outputType: "markdown",
},
});
let parseResult = null;
if (parseRun.status === "PROCESSED" && parseRun.output) {
const markdownContent = parseRun.output.chunks.map((c) => c.content).join("\n\n");
console.log(`Parsed ${parseRun.output.chunks.length} chunks. Content preview (first 500 chars):`);
console.log(markdownContent.substring(0, 500));
parseResult = { status: "success", chunks: parseRun.output.chunks };
} else {
console.log(`Parse failed with status: ${parseRun.status}`);
parseResult = { status: "failed", error: parseRun.status };
}
// STEP 2: Classify the document
console.log("\n[STEP 2] Classifying document...");
const classifyRun = await client.classifyRuns.createAndPoll({
file: { url: dataUrl },
config: {
baseProcessor: "classification_performance",
advancedOptions: { advancedMultimodalEnabled: true },
classifications: [
{
id: "acord_form",
type: "acord_form",
description: "An ACORD form is a standardized document used throughout the insurance industry.",
},
{
id: "other",
type: "other",
description: "Any document that does not fit the above classification.",
},
],
},
});
let classifyResult = null;
if (classifyRun.status === "PROCESSED" && classifyRun.output) {
console.log(`Classification result: ${classifyRun.output.type} (confidence: ${classifyRun.output.confidence})`);
classifyResult = { status: "success", type: classifyRun.output.type, confidence: classifyRun.output.confidence };
} else {
console.log(`Classification failed with status: ${classifyRun.status}`);
classifyResult = { status: "failed", error: classifyRun.status };
}
// STEP 3: Extract structured fields
console.log("\n[STEP 3] Extracting structured fields...");
const extractRun = await client.extractRuns.createAndPoll({
file: { url: dataUrl },
config: {
schema: insuranceApplicationSchema,
baseProcessor: "extraction_performance",
advancedOptions: {
reviewAgent: { enabled: true },
advancedMultimodalEnabled: true,
},
},
});
let extractResult = null;
if (extractRun.status === "PROCESSED" && extractRun.output) {
const extracted = extractRun.output.value;
console.log("\nExtraction successful. Key fields extracted:");
console.log(` Applicant Legal Name: ${extracted.applicant_legal_name || "(not found)"}`);
console.log(` Agency Name: ${extracted.agency_name || "(not found)"}`);
console.log(` Application Date: ${extracted.application_date || "(not found)"}`);
console.log(` Number of Owners: ${extracted.number_of_owners || "(not found)"}`);
console.log(` Business Type: ${extracted.business_type || "(not found)"}`);
console.log(` Primary Phone: ${extracted.primary_phone || "(not found)"}`);
console.log(` Federal Tax ID: ${extracted.federal_tax_id || "(not found)"}`);
console.log(` Total Annual Payroll: ${extracted.total_annual_payroll || "(not found)"}`);
console.log(` Owners: ${extracted.owners?.length || 0} owner(s)`);
console.log(` Loss History: ${extracted.loss_history?.length || 0} claim(s)`);
console.log(` General Liability Limits: ${extracted.general_liability_limits ? "present" : "not found"}`);
extractResult = { status: "success", data: extracted };
} else {
consoleimport { ExtendClient, extendDate } from "extend-ai";
import fs from "fs";
import { z } from "zod";
const client = new ExtendClient({ token: process.env.EXTEND_API_KEY });
/**
* Process a commercial insurance application PDF.
* Parses to markdown, then extracts structured fields.
*
* @param filePath - Local file path to the application PDF
* @returns Parsed markdown and extracted JSON object
*/
export async function processCommercialInsuranceApplication(filePath: string) {
// Read file and convert to base64 data URL
const fileBuffer = fs.readFileSync(filePath);
const base64 = fileBuffer.toString("base64");
const mimeType = "application/pdf";
const fileUrl = `data:${mimeType};base64,${base64}`;
console.log(`[1/2] Parsing ${filePath}...`);
const parseRun = await client.parseRuns.createAndPoll({
file: { url: fileUrl },
config: {
mode: "agentic_ocr",
outputType: "markdown",
},
});
if (parseRun.status !== "PROCESSED") {
throw new Error(
`Parse failed with status ${parseRun.status}: ${parseRun.error?.message}`
);
}
const markdown = parseRun.output.chunks
.map((chunk) => chunk.content)
.join("\n\n");
console.log(`✓ Parsed to ${markdown.length} chars of markdown`);
// Define the extraction schema using Zod
// Matches the provided commercial insurance application schema exactly
const extractionSchema = z.object({
application_date: z
.string()
.nullable()
.describe("Date of commercial insurance application in MM/DD/YYYY format"),
agency_information: z
.object({
agency_name: z.string().nullable(),
contact_name: z.string().nullable(),
phone: z.string().nullable(),
email: z.string().nullable(),
})
.nullable()
.describe("Agency details including name, address, and contact person"),
applicant_address: z
.string()
.nullable()
.describe("Physical address of the applicant/business"),
agency_customer_id: z
.string()
.nullable()
.describe("Unique customer identifier assigned by the agency"),
carrier_information: z
.object({
carrier_name: z.string().nullable(),
naic_code: z.string().nullable(),
underwriter_name: z.string().nullable(),
})
.nullable()
.describe("Insurance carrier details"),
policy_number: z
.string()
.nullable()
.describe("Insurance policy number"),
coverage_types: z
.array(z.string())
.describe(
"List of coverage sections included in the application (e.g., General Liability, Property, Workers Comp)"
),
proposed_effective_date: z
.string()
.nullable()
.describe("Proposed policy effective date in MM/DD/YYYY format"),
proposed_expiration_date: z
.string()
.nullable()
.describe("Proposed policy expiration date in MM/DD/YYYY format"),
billing_plan: z
.string()
.nullable()
.describe("Billing arrangement method (Direct Bill or Agency Bill)"),
payment_plan: z
.string()
.nullable()
.describe("Payment frequency (Annual or Semi-Annual)"),
audit_frequency: z
.string()
.nullable()
.describe("Frequency of policy audit"),
});
console.log("[2/2] Extracting structured fields...");
const extractRun = await client.extractRuns.createAndPoll({
file: { url: fileUrl },
config: {
schema: extractionSchema,
baseProcessor: "extraction_performance",
},
});
if (extractRun.status !== "PROCESSED") {
throw new Error(
`Extract failed with status ${extractRun.status}: ${extractRun.error?.message}`
);
}
const extracted = extractRun.output.value;
console.log("✓ Extraction complete");
return {
markdown,
extracted,
};
}
// Auto-invoke if run directly
const filePath = process.argv[2] || "__FILE_PATH__";
processCommercialInsuranceApplication(filePath)
.then((result) => {
console.log("\n=== EXTRACTED DATA ===");
console.log(JSON.stringify(result.extracted, null, 2));
})
.catch((err) => {
console.error("Error:", err.message);
process.exit(1);
});import os
import base64
from extend_ai import Extend
def process_commercial_insurance_application(file_path: str):
"""
Process a commercial insurance application PDF.
Parses to markdown, then extracts structured fields.
Args:
file_path: Local file path to the application PDF
Returns:
Dictionary with parsed markdown and extracted JSON object
"""
client = Extend(token=os.environ["EXTEND_API_KEY"])
# Read file and convert to base64 data URL
with open(file_path, "rb") as f:
file_buffer = f.read()
base64_str = base64.b64encode(file_buffer).decode("utf-8")
mime_type = "application/pdf"
file_url = f"data:{mime_type};base64,{base64_str}"
print(f"[1/2] Parsing {file_path}...")
parse_run = client.parse_runs.create_and_poll(
file={"url": file_url},
config={
"mode": "agentic_ocr",
"output_type": "markdown",
},
)
if parse_run.status != "PROCESSED":
raise Exception(
f"Parse failed with status {parse_run.status}: {parse_run.error.message if parse_run.error else 'Unknown error'}"
)
markdown = "\n\n".join(chunk.content for chunk in parse_run.output.chunks)
print(f"✓ Parsed to {len(markdown)} chars of markdown")
# Define the extraction schema as a plain dict matching the JSON schema
extraction_schema = {
"type": "object",
"properties": {
"application_date": {
"type": ["string", "null"],
"description": "Date of commercial insurance application in MM/DD/YYYY format",
},
"agency_information": {
"type": ["object", "null"],
"description": "Agency details including name, address, and contact person",
"properties": {
"agency_name": {"type": ["string", "null"]},
"contact_name": {"type": ["string", "null"]},
"phone": {"type": ["string", "null"]},
"email": {"type": ["string", "null"]},
},
},
"applicant_address": {
"type": ["string", "null"],
"description": "Physical address of the applicant/business",
},
"agency_customer_id": {
"type": ["string", "null"],
"description": "Unique customer identifier assigned by the agency",
},
"carrier_information": {
"type": ["object", "null"],
"description": "Insurance carrier details",
"properties": {
"carrier_name": {"type": ["string", "null"]},
"naic_code": {"type": ["string", "null"]},
"underwriter_name": {"type": ["string", "null"]},
},
},
"policy_number": {
"type": ["string", "null"],
"description": "Insurance policy number",
},
"coverage_types": {
"type": "array",
"description": "List of coverage sections included in the application (e.g., General Liability, Property, Workers Comp)",
"items": {"type": "string"},
},
"proposed_effective_date": {
"type": ["string", "null"],
"description": "Proposed policy effective date in MM/DD/YYYY format",
},
"proposed_expiration_date": {
"type": ["string", "null"],
"description": "Proposed policy expiration date in MM/DD/YYYY format",
},
"billing_plan": {
"type": ["string", "null"],
"description": "Billing arrangement method (Direct Bill or Agency Bill)",
},
"payment_plan": {
"type": ["string", "null"],
"description": "Payment frequency (Annual or Semi-Annual)",
},
"audit_frequency": {
"type": ["string", "null"],
"description": "Frequency of policy audit",
},
},
}
print("[2/2] Extracting structured fields...")
extract_run = client.extract_runs.create_and_poll(
file={"url": file_url},
config={
"schema": extraction_schema,
"base_processor": "extraction_performance",
},
)
if extract_run.status != "PROCESSED":
raise Exception(
f"Extract failed with status {extract_run.status}: {extract_run.error.message if extract_run.error else 'Unknown error'}"
)
extracted = extract_run.output.value
print("✓ Extraction complete")
return {
"markdown": markdown,
"extracted": extracted,
}
if __name__ == "__main__":
import sys
file_path = sys.argv[1] if len(sys.argv) > 1 else "__FILE_PATH__"
try:
result = process_commercial_insurance_application(file_path)
print("\n=== EXTRACTED DATA ===")
import json
print(json.dumps(result["extracted"], indent=2))
except Exception as err:
print(f"Error: {err}")
sys.exit(1)// This code uses the Extend REST API directly because Extend has no official Java SDK yet.
// It calls https://api.extend.ai endpoints with java.net.http.HttpClient (no external dependencies).
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;
import java.util.Map;
public class CommercialInsuranceProcessor {
private static final String API_BASE = "https://api.extend.ai";
private static final String API_KEY = System.getenv("EXTEND_API_KEY");
private static final HttpClient httpClient = HttpClient.newHttpClient();
/**
* Process a commercial insurance application PDF.
* Parses to markdown, then extracts structured fields.
*
* @param filePath Local file path to the application PDF
* @return Map containing "markdown" and "extracted" keys
*/
public static Map<String, Object> processCommercialInsuranceApplication(
String filePath) throws IOException, InterruptedException {
// Read file and convert to base64 data URL
byte[] fileBuffer = Files.readAllBytes(Paths.get(filePath));
String base64 = Base64.getEncoder().encodeToString(fileBuffer);
String mimeType = "application/pdf";
String fileUrl = "data:" + mimeType + ";base64," + base64;
System.out.println("[1/2] Parsing " + filePath + "...");
// Parse run
String parseRequestBody =
"{\"file\":{\"url\":\""
+ escapeJson(fileUrl)
+ "\"},\"config\":{\"mode\":\"agentic_ocr\",\"outputType\":\"markdown\"}}";
HttpRequest parseRequest =
HttpRequest.newBuilder()
.uri(URI.create(API_BASE + "/v1/parseRuns/createAndPoll"))
.header("Authorization", "Bearer " + API_KEY)
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(parseRequestBody))
.build();
HttpResponse<String> parseResponse =
httpClient.send(parseRequest, HttpResponse.BodyHandlers.ofString());
Map<String, Object> parseResult = parseJsonToMap(parseResponse.body());
String parseStatus = (String) parseResult.get("status");
if (!"PROCESSED".equals(parseStatus)) {
Map<String, Object> error = (Map<String, Object>) parseResult.get("error");
String errorMsg = error != null ? (String) error.get("message") : "Unknown error";
throw new RuntimeException("Parse failed with status " + parseStatus + ": " + errorMsg);
}
Map<String, Object> output = (Map<String, Object>) parseResult.get("output");
java.util.List<Map<String, Object>> chunks =
(java.util.List<Map<String, Object>>) output.get("chunks");
StringBuilder markdown = new StringBuilder();
for (Map<String, Object> chunk : chunks) {
if (markdown.length() > 0) {
markdown.append("\n\n");
}
markdown.append((String) chunk.get("content"));
}
System.out.println("✓ Parsed to " + markdown.length() + " chars of markdown");
// Extraction schema as JSON
String schemaJson =
"{"
+ "\"type\":\"object\","
+ "\"properties\":{"
+ "\"application_date\":{\"type\":[\"string\",\"null\"],\"description\":\"Date of commercial insurance application in MM/DD/YYYY format\"},"
+ "\"agency_information\":{\"type\":[\"object\",\"null\"],\"description\":\"Agency details including name, address, and contact person\",\"properties\":{\"agency_name\":{\"type\":[\"string\",\"null\"]},\"contact_name\":{\"type\":[\"string\",\"null\"]},\"phone\":{\"type\":[\"string\",\"null\"]},\"email\":{\"type\":[\"string\",\"null\"]}}},"
+ "\"applicant_address\":{\"type\":[\"string\",\"null\"],\"description\":\"Physical address of the applicant/business\"},"
+ "\"agency_customer_id\":{\"type\":[\"string\",\"null\"],\"description\":\"Unique customer identifier assigned by the agency\"},"
+ "\"carrier_information\":{\"type\":[\"object\",\"null\"],\"description\":\"Insurance carrier details\",\"properties\":{\"carrier_name\":{\"type\":[\"string\",\"null\"]},\"naic_code\":{\"type\":[\"string\",\"null\"]},\"underwriter_name\":{\"type\":[\"string\",\"null\"]}}},"
+ "\"policy_number\":{\"type\":[\"string\",\"null\"],\"description\":\"Insurance policy number\"},"
+ "\"coverage_types\":{\"type\":\"array\",\"description\":\"List of coverage sections included in the application\",\"items\":{\"type\":\"string\"}},"
+ "\"proposed_effective_date\":{\"type\":[\"string\",\"null\"],\"description\":\"Proposed policy effective date in MM/DD/YYYY format\"},"
+ "\"proposed_expiration_date\":{\"type\":[\"string\",\"null\"],\"description\":\"Proposed policy expiration date in MM/DD/YYYY format\"},"
+ "\"billing_plan\":{\"type\":[\"string\",\"null\"],\"description\":\"Billing arrangement method (Direct Bill or Agency Bill)\"},"
+ "\"payment_plan\":{\"type\":[\"string\",\"null\"],\"description\":\"Payment frequency (Annual or Semi-Annual)\"},"
+ "\"audit_frequency\":{\"type\":[\"string\",\"null\"],\"description\":\"Frequency of policy audit\"}"
+ "}"
+ "}";
System.out.println("[2/2] Extracting structured fields...");
String extractRequestBody =
"{\"file\":{\"url\":\""
+ escapeJson(fileUrl)
+ "\"},\"config\":{\"schema\":"
+ schemaJson
+ ",\"baseProcessor\":\"extraction_performance\"}}";
HttpRequest extractRequest =
HttpRequest.newBuilder()
.uri(URI.create(API_BASE + "/v1/extractRuns/createAndPoll"))
.header("Authorization", "Bearer " + API_KEY)
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(extractRequestBody))
.build();
HttpResponse<String> extractResponse =
httpClient.send(extractRequest, HttpResponse.BodyHandlers.ofString());
Map<String, Object> extractResult = parseJsonToMap(extractResponse.body());
String extractStatus = (String) extractResult.get("status");
if (!"PROCESSED".equals(extractStatus)) {
Map<String, Object> error = (Map<String, Object>) extractResult.get("error");
String errorMsg = error != null ? (String) error.get("message") : "Unknown error";
throw new RuntimeException("Extract failed with status " + extractStatus + ": " + errorMsg);
}
Map<String, Object> extractOutput = (Map<String, Object>) extractResult.get("output");
Map<String, Object> extracted = (Map<String, Object>) extractOutput.get("value");
System.out.println("✓ Extraction complete");
return Map.of("markdown", markdown.toString(), "extracted", extracted);
}
private static String escapeJson(String s) {
return s.replace("\\", "\\\\")
.replace("\"", "\\\"")
.replace("\n", "\\n")
.replace("\r", "\\r")
.replace("\t", "\\t");
}
private static Map<String, Object> parseJsonToMap(String json) {
// Simple JSON parser for the response structure
return parseJsonObject(json.trim());
}
private static Map<String, Object> parseJsonObject(String json) {
Map<String, Object> map = new java.util.LinkedHashMap<>();
json = json.substring(1, json.length() - 1).trim();
int depth = 0;
int start = 0;
boolean inString = false;
boolean escaped = false;
for (int i = 0; i < json.length(); i++) {
char c = json.charAt(i);
if (escaped) {
escaped = false;
continue;
}
if (c == '\\') {
escaped = true;
continue;
}
if (c == '"') {
inString = !inString;
continue;
}
if (inString) {
continue;
}
if (c == '{' || c == '[') {
depth++;
} else if (c == '}' || c == ']') {
depth--;
} else if (c == ',' && depth == 0) {
String pair = json.substring(start, i).trim();
parsePair(pair, map);
start = i + 1;
}
}
if (start < json.length()) {
String pair = json.substring(start).trim();
parsePair(pair, map);
}
return map;
}
private static void parsePair(String pair, Map<String, Object> map) {
int colonIdx = pair.indexOf(':');
if (colonIdx < 0) return;
String key = pair.substring(0, colonIdx).trim();
if (key.startsWith("\"") && key.endsWith("\"")) {
key = key.substring(1, key.length() - 1);
}
String valueStr = pair.substring(colonIdx + 1).trim();
Object value = parseValue(valueStr);
map.put(key, value);
}
private static Object parseValue(String valueStr) {
if (valueStr.equals("null")) {
return null;
}
if (valueStr.equals("true")) {
return true;
}
if (valueStr.equals("false")) {
return false;
}
if (valueStr.startsWith("\"") && valueStr.endsWith("\"")) {
return valueStr.substring(1, valueStr.length() - 1);
}
if (valueStr.startsWith("{")) {
return parseJsonObject(valueStr);
}
if (valueStr.startsWith("[")) {
return parseJsonArray(valueStr);
}
try {
if (valueStr.contains(".")) {
return Double.parseDouble(valueStr);
} else {
return Long.parseLong(valueStr);
}
} catch (NumberFormatException e) {
return valueStr;
}
}
private static java.util.List<Object> parseJsonArray(String json) {
java.util.List<Object> list = new java.util.ArrayList<>();
json = json.substring(1, json.length() - 1).trim();
if (json.isEmpty()) {
return list;
}
int depth = 0;
int start = 0;
boolean inString = false;
boolean escaped = false;
for (int i = 0; i < json.length(); i++) {
char c = json.charAt(i);
if (escaped) {
escaped = false;
continue;
}
if (c == '\\') {
escaped = true;
continue;
}
if (c == '"') {
inString = !inString;
continue;
}
if (inString) {
continue;
}
if (c == '{' || c == '[') {
depth++;
} else if (c == '}' || c == ']') {
depth--;
} else if (c == ',' && depth == 0) {
String item = json.substring(start, i).trim();
list.add(parseValue(item));
start = i + 1;
}
}
if (start < json.length()) {
String item = json.substring(start).trim();
list.add(parseValue(item));
}
return list;
}
public static void main(String[] args) throws IOException, InterruptedException {
String filePath = args.length > 0 ? args[0] : "__FILE_PATH__";
try {
Map<String, Object> result = processCommercialInsuranceApplication(filePath);
System.out.println("\n=== EXTRACTED DATA ===");
System.out.println(formatJson(result.get("extracted")));
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
System.exit(1);
}
}
private static String formatJson(Object obj) {
return formatJsonInternal(obj, 0);
}
private static String formatJsonInternal(Object obj, int indent) {
String indentStr = " ".repeat(indent);
String nextIndentStr = " ".repeat(indent + 1);
if (obj == null) {
return "null";
}
if (obj instanceof String) {
return "\"" + obj + "\"";
}
if (obj instanceof Boolean || obj instanceof Number) {
return obj.toString();
}
if (obj instanceof Map) {
Map<String, Object> map = (Map<String, Object>) obj;
if (map.isEmpty()) {
return "{}";
}
StringBuilder sb = new StringBuilder("{\n");
java.util.Iterator<java.util.Map.Entry<String, Object>> it = map.entrySet().iterator();
while (it.hasNext()) {
java.util.Map.Entry<String, Object> entry = it.next();
sb.append(nextIndentStr)
.append("\"")
.append(entry.getKey())
.append("\": ")
.append(formatJsonInternal(entry.getValue(), indent + 1));
if (it.hasNext()) {
sb.append(",");
}
sb.append("\n");
}
sb.append(indentStr).append("}");
return sb.toString();
}
if (obj instanceof java.util.List) {
java.util.List<Object> list = (java.util.List<Object>) obj;
if (list.isEmpty()) {
return "[]";
}
StringBuilder sb = new StringBuilder("[\n");
for (int i = 0; i < list.size(); i++) {
sb.append(nextIndentStr).append(formatJsonInternal(list.get(i), indent + 1));
if (i < list.size() - 1) {
sb.append(",");
}
sb.append("\n");
}
sb.append(indentStr).append("]");
return sb.toString();
}
return obj.toString();
}
}// This code uses the Extend REST API directly because Extend has no official Go SDK yet.
// It calls https://api.extend.ai endpoints with standard net/http and encoding/json.
package main
import (
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"strings"
"time"
)
const extendAPIBase = "https://api.extend.ai"
type FileInput struct {
URL string `json:"url"`
}
type ParseConfig struct {
Mode string `json:"mode"`
OutputType string `json:"output_type"`
}
type ParseRunRequest struct {
File FileInput `json:"file"`
Config ParseConfig `json:"config"`
}
type Chunk struct {
Content string `json:"content"`
}
type ParseRunResponse struct {
ID string `json:"id"`
Status string `json:"status"`
Output struct {
Chunks []Chunk `json:"chunks"`
} `json:"output"`
Error *struct {
Message string `json:"message"`
} `json:"error"`
}
type ExtractionSchema map[string]interface{}
type ExtractConfig struct {
Schema ExtractionSchema `json:"schema"`
BaseProcessor string `json:"base_processor"`
}
type ExtractRunRequest struct {
File FileInput `json:"file"`
Config ExtractConfig `json:"config"`
}
type ExtractRunResponse struct {
ID string `json:"id"`
Status string `json:"status"`
Output struct {
Value map[string]interface{} `json:"value"`
} `json:"output"`
Error *struct {
Message string `json:"message"`
} `json:"error"`
}
func createAndPollParseRun(client *http.Client, apiKey string, req ParseRunRequest) (*ParseRunResponse, error) {
body, err := json.Marshal(req)
if err != nil {
return nil, err
}
httpReq, err := http.NewRequest("POST", extendAPIBase+"/parse_runs", bytes.NewReader(body))
if err != nil {
return nil, err
}
httpReq.Header.Set("Authorization", "Bearer "+apiKey)
httpReq.Header.Set("Content-Type", "application/json")
resp, err := client.Do(httpReq)
if err != nil {
return nil, err
}
defer resp.Body.Close()
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
var parseResp ParseRunResponse
if err := json.Unmarshal(respBody, &parseResp); err != nil {
return nil, err
}
// Poll until status is PROCESSED or error
for parseResp.Status != "PROCESSED" && parseResp.Status != "FAILED" {
time.Sleep(2 * time.Second)
pollReq, err := http.NewRequest("GET", extendAPIBase+"/parse_runs/"+parseResp.ID, nil)
if err != nil {
return nil, err
}
pollReq.Header.Set("Authorization", "Bearer "+apiKey)
pollResp, err := client.Do(pollReq)
if err != nil {
return nil, err
}
defer pollResp.Body.Close()
pollBody, err := io.ReadAll(pollResp.Body)
if err != nil {
return nil, err
}
if err := json.Unmarshal(pollBody, &parseResp); err != nil {
return nil, err
}
}
return &parseResp, nil
}
func createAndPollExtractRun(client *http.Client, apiKey string, req ExtractRunRequest) (*ExtractRunResponse, error) {
body, err := json.Marshal(req)
if err != nil {
return nil, err
}
httpReq, err := http.NewRequest("POST", extendAPIBase+"/extract_runs", bytes.NewReader(body))
if err != nil {
return nil, err
}
httpReq.Header.Set("Authorization", "Bearer "+apiKey)
httpReq.Header.Set("Content-Type", "application/json")
resp, err := client.Do(httpReq)
if err != nil {
return nil, err
}
defer resp.Body.Close()
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
var extractResp ExtractRunResponse
if err := json.Unmarshal(respBody, &extractResp); err != nil {
return nil, err
}
// Poll until status is PROCESSED or error
for extractResp.Status != "PROCESSED" && extractResp.Status != "FAILED" {
time.Sleep(2 * time.Second)
pollReq, err := http.NewRequest("GET", extendAPIBase+"/extract_runs/"+extractResp.ID, nil)
if err != nil {
return nil, err
}
pollReq.Header.Set("Authorization", "Bearer "+apiKey)
pollResp, err := client.Do(pollReq)
if err != nil {
return nil, err
}
defer pollResp.Body.Close()
pollBody, err := io.ReadAll(pollResp.Body)
if err != nil {
return nil, err
}
if err := json.Unmarshal(pollBody, &extractResp); err != nil {
return nil, err
}
}
return &extractResp, nil
}
func processCommercialInsuranceApplication(filePath string) (map[string]interface{}, error) {
apiKey := os.Getenv("EXTEND_API_KEY")
if apiKey == "" {
return nil, fmt.Errorf("EXTEND_API_KEY environment variable not set")
}
// Read file and convert to base64 data URL
fileBuffer, err := os.ReadFile(filePath)
if err != nil {
return nil, err
}
base64Str := base64.StdEncoding.EncodeToString(fileBuffer)
mimeType := "application/pdf"
fileURL := fmt.Sprintf("data:%s;base64,%s", mimeType, base64Str)
client := &http.Client{Timeout: 30 * time.Second}
fmt.Printf("[1/2] Parsing %s...\n", filePath)
parseReq := ParseRunRequest{
File: FileInput{URL: fileURL},
Config: ParseConfig{
Mode: "agentic_ocr",
OutputType: "markdown",
},
}
parseRun, err := createAndPollParseRun(client, apiKey, parseReq)
if err != nil {
return nil, err
}
if parseRun.Status != "PROCESSED" {
errMsg := "unknown error"
if parseRun.Error != nil {
errMsg = parseRun.Error.Message
}
return nil, fmt.Errorf("parse failed with status %s: %s", parseRun.Status, errMsg)
}
var markdownParts []string
for _, chunk := range parseRun.Output.Chunks {
markdownParts = append(markdownParts, chunk.Content)
}
markdown := strings.Join(markdownParts, "\n\n")
fmt.Printf("✓ Parsed to %d chars of markdown\n", len(markdown))
// Define extraction schema matching the commercial insurance application
extractionSchema := ExtractionSchema{
"type": "object",
"properties": map[string]interface{}{
"application_date": map[string]interface{}{
"type": []string{"string", "null"},
"description": "Date of commercial insurance application in MM/DD/YYYY format",
},
"agency_information": map[string]interface{}{
"type": []string{"object", "null"},
"description": "Agency details including name, address, and contact person",
"properties": map[string]interface{}{
"agency_name": map[string]interface{}{
"type": []string{"string", "null"},
},
"contact_name": map[string]interface{}{
"type": []string{"string", "null"},
},
"phone": map[string]interface{}{
"type": []string{"string", "null"},
},
"email": map[string]interface{}{
"type": []string{"string", "null"},
},
},
},
"applicant_address": map[string]interface{}{
"type": []string{"string", "null"},
"description": "Physical address of the applicant/business",
},
"agency_customer_id": map[string]interface{}{
"type": []string{"string", "null"},
"description": "Unique customer identifier assigned by the agency",
},
"carrier_information": map[string]interface{}{
"type": []string{"object", "null"},
"description": "Insurance carrier details",
"properties": map[string]interface{}{
"carrier_name": map[string]interface{}{
"type": []string{"string", "null"},
},
"naic_code": map[string]interface{}{
"type": []string{"string", "null"},
},
"underwriter_name": map[string]interface{}{
"type": []string{"string", "null"},
},
},
},
"policy_number": map[string]interface{}{
"type": []string{"string", "null"},
"description": "Insurance policy number",
},
"coverage_types": map[string]interface{}{
"type": "array",
"description": "List of coverage sections included in the application",
"items": map[string]interface{}{
"type": "string",
},
},
"proposed_effective_date": map[string]interface{}{
"type": []string{"string", "null"},
"description": "Proposed policy effective date in MM/DD/YYYY format",
},
"proposed_expiration_date": map[string]interface{}{
"type": []string{"string", "null"},
"description": "Proposed policy expiration date in MM/DD/YYYY format",
},
"billing_plan": map[string]interface{}{
"type": []string{"string", "null"},
"description": "Billing arrangement method (Direct Bill or Agency Bill)",
},
"payment_plan": map[string]interface{}{
"type": []string{"string", "null"},
"description": "Payment frequency (Annual or Semi-Annual)",
},
"audit_frequency": map[string]interface{}{
"type": []string{"string", "null"},
"description": "Frequency of policy audit",
},
},
}
fmt.Println("[2/2] Extracting structured fields...")
extractReq := ExtractRunRequest{
File: FileInput{URL: fileURL},
Config: ExtractConfig{
Schema: extractionSchema,
BaseProcessor: "extraction_performance",
},
}
extractRun, err := createAndPollExtractRun(client, apiKey, extractReq)
if err != nil {
return nil, err
}
if extractRun.Status != "PROCESSED" {
errMsg := "unknown error"
if extractRun.Error != nil {
errMsg = extractRun.Error.Message
}
return nil, fmt.Errorf("extract failed with status %s: %s", extractRun.Status, errMsg)
}
fmt.Println("✓ Extraction complete")
result := map[string]interface{}{
"markdown": markdown,
"extracted": extractRun.Output.Value,
}
return result, nil
}
func main() {
filePath := "__FILE_PATH__"
if len(os.Args) > 1 {
filePath = os.Args[1]
}
result, err := processCommercialInsuranceApplication(filePath)
if err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
fmt.Println("\n=== EXTRACTED DATA ===")
extracted := result["extracted"].(map[string]interface{})
jsonBytes, _ := json.MarshalIndent(extracted, "", " ")
fmt.Println(string(jsonBytes))
}// Deploy the "Commercial Insurance Application" pipeline to YOUR Extend account.
//
// The workflow below is fully self-contained — every EXTRACT/CLASSIFY/SPLIT
// step carries its extractor/classifier/splitter config INLINE, so this is a
// single API call. No processors to create or wire up beforehand.
// Idempotent: the created workflow id is cached in .extend/acord-form-classifier.json,
// so re-running updates the existing workflow instead of duplicating it.
//
// Usage:
// export EXTEND_API_KEY=sk_... (from https://dashboard.extend.ai → API Keys)
// npx tsx provision.ts
//
// Generated by doc1 (template: acord-form-classifier).
import fs from "node:fs";
import path from "node:path";
const API = "https://api.extend.ai";
const VERSION = "2026-02-09";
const API_KEY = process.env.EXTEND_API_KEY;
if (!API_KEY) { console.error("Set EXTEND_API_KEY first."); process.exit(1); }
const STATE_DIR = path.join(process.cwd(), ".extend");
const STATE_FILE = path.join(STATE_DIR, "acord-form-classifier.json");
type State = { workflowId?: string };
const state: State = fs.existsSync(STATE_FILE)
? JSON.parse(fs.readFileSync(STATE_FILE, "utf8"))
: {};
function saveState() {
fs.mkdirSync(STATE_DIR, { recursive: true });
fs.writeFileSync(STATE_FILE, JSON.stringify(state, null, 2));
}
async function api(method: string, pathName: string, body?: unknown) {
const res = await fetch(API + pathName, {
method,
headers: {
Authorization: `Bearer ${API_KEY}`,
"x-extend-api-version": VERSION,
...(body ? { "Content-Type": "application/json" } : {}),
},
body: body ? JSON.stringify(body) : undefined,
});
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(`${method} ${pathName} failed (${res.status}): ${JSON.stringify(data).slice(0, 300)}`);
return data;
}
// ── Workflow definition — extractor/classifier/splitter configs inline ──────
const WORKFLOW = {
"name": "Commercial Insurance Application Processing Pipeline",
"steps": [
{
"name": "startTrigger1",
"type": "TRIGGER",
"next": [
{
"step": "parse1"
}
]
},
{
"name": "parse1",
"type": "PARSE",
"config": {
"parseConfig": {
"blockOptions": {
"text": {
"agentic": {
"enabled": true
}
}
},
"chunkingStrategy": {
"type": "document"
}
}
},
"next": [
{
"step": "classify2"
}
]
},
{
"name": "classify2",
"type": "CLASSIFY",
"config": {
"classifierConfig": {
"classifications": [
{
"id": "classification1",
"type": "other",
"description": "Use the `other` document type when the provided document can not clearly be classified into one of the described classifications."
},
{
"id": "classification_GEy",
"type": "acord_form",
"description": "An ACORD form is a standardized document used throughout the insurance industry. Created by the Association for Cooperative Operations Research and Development (ACORD)"
}
],
"baseProcessor": "classification_performance",
"advancedOptions": {
"advancedMultimodalEnabled": true
}
}
},
"next": [
{
"step": "extraction3",
"classificationId": "classification1"
},
{
"step": "extraction3",
"classificationId": "classification_GEy"
}
]
},
{
"name": "extraction3",
"type": "EXTRACT",
"config": {
"extractorConfig": {
"schema": {
"type": "object",
"required": [
"county",
"owners",
"website",
"dba_name",
"naic_code",
"agent_name",
"fax_number",
"agency_code",
"agency_name",
"billing_plan",
"contact_name",
"loss_history",
"payment_plan",
"business_type",
"contact_title",
"email_address",
"landlord_name",
"policy_number",
"primary_phone",
"federal_tax_id",
"landlord_phone",
"premises_owned",
"signature_date",
"audit_frequency",
"mailing_address",
"premises_leased",
"secondary_phone",
"application_date",
"number_of_owners",
"physical_address",
"agency_customer_id",
"applicant_signature",
"agent_license_number",
"applicant_legal_name",
"business_description",
"total_annual_payroll",
"year_business_started",
"el_each_accident_limit",
"package_policy_premium",
"el_disease_policy_limit",
"proposed_effective_date",
"estimated_annual_revenue",
"general_liability_limits",
"proposed_expiration_date",
"workers_compensation_code",
"square_footage_of_premises",
"workers_compensation_state",
"business_classification_code",
"number_of_seasonal_employees",
"number_of_full_time_employees",
"number_of_part_time_employees",
"el_disease_each_employee_limit",
"business_classification_description",
"workers_compensation_annual_payroll",
"general_liability_coverages_requested"
],
"properties": {
"county": {
"type": [
"string",
"null"
],
"description": "The county in which the applicant's business is located. May be labeled as 'County' or included as part of the address."
},
"owners": {
"type": "array",
"items": {
"type": "object",
"required": [
"ssn",
"title",
"owner_name",
"date_of_birth",
"ownership_percent"
],
"properties": {
"ssn": {
"type": [
"string",
"null"
],
"description": "The Social Security Number of the owner, if provided."
},
"title": {
"type": [
"string",
"null"
],
"description": "The title or position held by this individual within the business."
},
"owner_name": {
"type": [
"string",
"null"
],
"description": "The full name of the owner, partner, or officer."
},
"date_of_birth": {
"type": [
"string",
"null"
],
"description": "The date of birth of the owner, partner, or officer.",
"extend:type": "date"
},
"ownership_percent": {
"type": [
"number",
"null"
],
"description": "The percentage of ownership held by this individual."
}
},
"additionalProperties": false
},
"description": "A list of owners, partners, or officers for the applicant's business. Each entry includes identifying and ownership information."
},
"website": {
"type": [
"string",
"null"
],
"description": "The website address (URL) for the applicant's business, if provided."
},
"dba_name": {
"type": [
"string",
"null"
],
"description": "The 'doing business as' name, if different from the legal name. This is an alternate business name under which the applicant operates."
},
"naic_code": {
"type": [
"string",
"null"
],
"description": "The NAIC (National Association of Insurance Commissioners) code associated with the insurer or policy. This is a numeric or alphanumeric code used for regulatory identification."
},
"agent_name": {
"type": [
"string",
"null"
],
"description": "The full name of the agent or broker responsible for the application. May be labeled as 'Agent Name', 'Producer', or similar."
},
"fax_number": {
"type": [
"string",
"null"
],
"description": "The fax number for the applicant or business, if provided."
},
"agency_code": {
"type": [
"string",
"null"
],
"description": "A unique code or identifier for the agency, if provided. May be labeled as 'Agency Code', 'Producer Code', or similar."
},
"agency_name": {
"type": [
"string",
"null"
],
"description": "The name of the insurance agency or brokerage handling the application. This is the organization representing the applicant to the insurer."
},
"billing_plan": {
"type": [
"string",
"null"
],
"description": "The selected billing plan for the policy, such as 'Direct Bill', 'Agency Bill', etc. May be indicated by checkboxes or text."
},
"contact_name": {
"type": [
"string",
"null"
],
"description": "The name of the primary contact person for the application or business. May be labeled as 'Contact Name', 'Inspection Contact', or similar."
},
"loss_history": {
"type": "array",
"items": {
"type": "object",
"required": [
"status",
"amount_paid",
"description",
"date_of_loss",
"type_of_loss",
"amount_reserved"
],
"properties": {
"status": {
"type": [
"string",
"null"
],
"description": "The current status of the claim or loss, such as 'Open', 'Closed', 'Pending', etc."
},
"amount_paid": {
"type": [
"number",
"null"
],
"description": "The amount paid to settle the claim or loss, if any."
},
"description": {
"type": [
"string",
"null"
],
"description": "A narrative description of the loss, claim, or incident."
},
"date_of_loss": {
"type": [
"string",
"null"
],
"description": "The date the loss, claim, or incident occurred.",
"extend:type": "date"
},
"type_of_loss": {
"type": [
"string",
"null"
],
"description": "A brief description of the type of loss, such as 'Property Damage', 'Liability', etc."
},
"amount_reserved": {
"type": [
"number",
"null"
],
"description": "The amount reserved for the claim or loss, if any."
}
},
"additionalProperties": false
},
"description": "A list of claims, lawsuits, or incidents reported in the past 5 years. Each entry represents a separate loss event."
},
"payment_plan": {
"type": [
"string",
"null"
],
"description": "The selected payment plan for the policy, such as 'Annual', 'Semi-Annual', etc. May be indicated by checkboxes or text."
},
"business_type": {
"type": [
"string",
"null"
],
"description": "The legal structure of the applicant's business, such as 'Sole Proprietorship', 'LLC', 'Corporation', 'Partnership', etc. May be indicated by checkboxes or text."
},
"contact_title": {
"type": [
"string",
"null"
],
"description": "The job title or role of the primary contact person, such as 'Owner', 'Manager', etc."
},
"email_address": {
"type": [
"string",
"null"
],
"description": "The primary email address for the applicant or business. Used for electronic correspondence."
},
"landlord_name": {
"type": [
"string",
"null"
],
"description": "The name of the landlord or property owner, if the premises are leased."
},
"policy_number": {
"type": [
"string",
"null"
],
"description": "The unique identifier assigned to the insurance policy, if available at the time of application. May include letters, numbers, or special characters. Commonly labeled as 'Policy Number' or 'Policy #'."
},
"primary_phone": {
"type": [
"string",
"null"
],
"description": "The main telephone number for the applicant or business. May include area code and extension."
},
"federal_tax_id": {
"type": [
"string",
"null"
],
"description": "The Federal Employer Identification Number (FEIN) or Social Security Number (SSN) for the applicant. Used for tax and regulatory purposes."
},
"landlord_phone": {
"type": [
"string",
"null"
],
"description": "The phone number of the landlord or property owner, if the premises are leased."
},
"premises_owned": {
"type": [
"boolean",
"null"
],
"description": "Indicates whether the applicant owns the business premises. True if owned, false if not."
},
"signature_date": {
"type": [
"string",
"null"
],
"description": "The date the applicant signed the application, certifying its accuracy.",
"extend:type": "date"
},
"audit_frequency": {
"type": [
"string",
"null"
],
"description": "The frequency of premium audit for the policy, such as 'Annually', 'Semi-Annually', etc."
},
"mailing_address": {
"type": [
"string",
"null"
],
"description": "The complete mailing address for the applicant, including street, city, state, and ZIP code. This is the primary address for correspondence."
},
"premises_leased": {
"type": [
"boolean",
"null"
],
"description": "Indicates whether the applicant leases the business premises. True if leased, false if not."
},
"secondary_phone": {
"type": [
"string",
"null"
],
"description": "An alternate or secondary telephone number for the applicant or business, if provided."
},
"application_date": {
"type": [
"string",
"null"
],
"description": "The date the commercial insurance application was completed or submitted. This is the official date of the application and may be labeled as 'Date', 'Application Date', or similar.",
"extend:type": "date"
},
"number_of_owners": {
"type": [
"integer",
"null"
],
"description": "The total number of owners, partners, or officers associated with the applicant's business."
},
"physical_address": {
"type": [
"string",
"null"
],
"description": "The physical address of the applicant's business, if different from the mailing address. Includes street, city, state, and ZIP code."
},
"agency_customer_id": {
"type": [
"string",
"null"
],
"description": "A unique identifier assigned by the agency to the applicant or account. May be labeled as 'Agency Customer ID', 'Client ID', or similar."
},
"applicant_signature": {
"type": [
"string",
"null"
],
"description": "The name or representation of the applicant's signature, indicating certification of the information provided."
},
"agent_license_number": {
"type": [
"string",
"null"
],
"description": "The license number of the agent or broker, if provided. This is a regulatory identifier for the individual handling the application."
},
"applicant_legal_name": {
"type": [
"string",
"null"
],
"description": "The legal name of the business or individual applying for insurance. This is the primary insured entity and may include DBA (doing business as) names."
},
"business_description": {
"type": [
"string",
"null"
],
"description": "A description of the applicant's primary business operations, activities, or services provided. May be labeled as 'Nature of Business', 'Description of Operations', or similar."
},
"total_annual_payroll": {
"type": [
"number",
"null"
],
"description": "The total annual payroll for all employees of the applicant's business, typically in the local currency."
},
"year_business_started": {
"type": [
"string",
"null"
],
"description": "The year the applicant's business was established or began operations. May be labeled as 'Year Business Started', 'Date Business Started', or similar."
},
"el_each_accident_limit": {
"type": [
"number",
"null"
],
"description": "The employer's liability limit for each accident under workers compensation coverage."
},
"package_policy_premium": {
"type": "object",
"required": [
"amount",
"iso_4217_currency_code"
],
"properties": {
"amount": {
"type": [
"number",
"null"
]
},
"iso_4217_currency_code": {
"type": [
"string",
"null"
]
}
},
"description": "The total premium amount for the package policy, if provided. This is the cost of the insurance coverage for the policy term.",
"extend:type": "currency",
"additionalProperties": false
},
"el_disease_policy_limit": {
"type": [
"number",
"null"
],
"description": "The employer's liability policy limit for disease under workers compensation coverage."
},
"proposed_effective_date": {
"type": [
"string",
"null"
],
"description": "The proposed effective date for the insurance policy. This is the date coverage is requested to begin.",
"extend:type": "date"
},
"estimated_annual_revenue": {
"type": [
"number",
"null"
],
"description": "The estimated or actual annual revenue for the applicant's business, typically in the local currency."
},
"general_liability_limits": {
"type": "object",
"required": [
"each_occurrence",
"medical_expense",
"general_aggregate",
"damage_to_rented_premises",
"personal_advertising_injury",
"products_completed_operations_aggregate"
],
"properties": {
"each_occurrence": {
"type": [
"number",
"null"
],
"description": "The limit for each occurrence under general liability coverage."
},
"medical_expense": {
"type": [
"number",
"null"
],
"description": "The limit for medical expense coverage."
},
"general_aggregate": {
"type": [
"number",
"null"
],
"description": "The general aggregate limit for general liability coverage."
},
"damage_to_rented_premises": {
"type": [
"number",
"null"
],
"description": "The limit for damage to rented premises coverage."
},
"personal_advertising_injury": {
"type": [
"number",
"null"
],
"description": "The limit for personal and advertising injury coverage."
},
"products_completed_operations_aggregate": {
"type": [
"number",
"null"
],
"description": "The aggregate limit for products and completed operations coverage."
}
},
"description": "The requested or quoted limits for general liability coverage. Each property represents a specific coverage limit.",
"additionalProperties": false
},
"proposed_expiration_date": {
"type": [
"string",
"null"
],
"description": "The proposed expiration date for the insurance policy. This is the date coverage is requested to end.",
"extend:type": "date"
},
"workers_compensation_code": {
"type": [
"string",
"null"
],
"description": "The workers compensation classification code applicable to the applicant's business."
},
"square_footage_of_premises": {
"type": [
"integer",
"null"
],
"description": "The total square footage of the business premises occupied by the applicant."
},
"workers_compensation_state": {
"type": [
"string",
"null"
],
"description": "The state in which workers compensation coverage is requested or provided."
},
"business_classification_code": {
"type": [
"string",
"null"
],
"description": "The business classification code (such as NAICS or SIC) that categorizes the applicant's industry or operations."
},
"number_of_seasonal_employees": {
"type": [
"integer",
"null"
],
"description": "The number of seasonal or temporary employees working for the applicant's business."
},
"number_of_full_time_employees": {
"type": [
"integer",
"null"
],
"description": "The number of full-time employees working for the applicant's business."
},
"number_of_part_time_employees": {
"type": [
"integer",
"null"
],
"description": "The number of part-time employees working for the applicant's business."
},
"el_disease_each_employee_limit": {
"type": [
"number",
"null"
],
"description": "The employer's liability limit for disease for each employee under workers compensation coverage."
},
"business_classification_description": {
"type": [
"string",
"null"
],
"description": "A textual description of the business classification or industry for the applicant."
},
"workers_compensation_annual_payroll": {
"type": [
"number",
"null"
],
"description": "The estimated annual payroll for workers compensation purposes."
},
"general_liability_coverages_requested": {
"type": [
"string",
"null"
],
"description": "A list or description of general liability coverages requested, such as 'Premises Operations', 'Products Completed Operations', 'Contractual Liability', etc. May be indicated by checkboxes or text."
}
},
"additionalProperties": false
},
"baseProcessor": "extraction_performance",
"advancedOptions": {
"reviewAgent": {
"enabled": true
},
"advancedMultimodalEnabled": true
}
}
}
}
]
};
async function main() {
console.log(`Deploying "${WORKFLOW.name}"…`);
if (state.workflowId) {
console.log(`✓ workflow already provisioned (${state.workflowId}) — updating steps`);
await api("POST", `/workflows/${state.workflowId}`, { steps: WORKFLOW.steps });
} else {
// Reuse an existing workflow with the same name if one exists (e.g. a
// previous run's state file was lost) instead of creating a duplicate.
try {
const list = await api("GET", `/workflows?name=${encodeURIComponent(WORKFLOW.name)}`);
const items = (list.data ?? list.items ?? []) as Array<{ name?: string; id?: string }>;
const existing = items.find((x) => x.name === WORKFLOW.name);
if (existing?.id) {
state.workflowId = existing.id; saveState();
console.log(`✓ workflow "${WORKFLOW.name}" found in your account (${existing.id}) — updating steps`);
await api("POST", `/workflows/${existing.id}`, { steps: WORKFLOW.steps });
}
} catch { /* lookup is best-effort; fall through to create */ }
if (!state.workflowId) {
const created = await api("POST", "/workflows", WORKFLOW);
const wfId = created.id ?? created.workflow?.id;
if (!wfId) throw new Error("Could not read created workflow id from response");
state.workflowId = wfId; saveState();
console.log(`+ created workflow (${wfId})`);
}
}
// Deploy the current draft as a new version so the workflow is runnable —
// best-effort: some accounts/plans may not require this explicit step.
await api("POST", `/workflows/${state.workflowId}/versions`, {}).catch(() => {});
console.log("\nDone. Run documents through it with:");
console.log(` POST ${API}/workflow_runs { workflow: { id: "${state.workflowId}" }, file: { url: "https://…" } }`);
console.log("Or open the workflow in the Extend dashboard to review and deploy it.");
}
main().catch((e) => { console.error(e.message ?? e); process.exit(1); });
import os
import json
import sys
from pathlib import Path
import requests
API = "https://api.extend.ai"
VERSION = "2026-02-09"
API_KEY = os.environ.get("EXTEND_API_KEY")
if not API_KEY:
print("Set EXTEND_API_KEY first.", file=sys.stderr)
sys.exit(1)
STATE_DIR = Path.cwd() / ".extend"
STATE_FILE = STATE_DIR / "acord-form-classifier.json"
state: dict = {}
if STATE_FILE.exists():
with open(STATE_FILE, "r") as f:
state = json.load(f)
def save_state() -> None:
STATE_DIR.mkdir(parents=True, exist_ok=True)
with open(STATE_FILE, "w") as f:
json.dump(state, f, indent=2)
def api(method: str, path_name: str, body: dict | None = None) -> dict:
headers = {
"Authorization": f"Bearer {API_KEY}",
"x-extend-api-version": VERSION,
}
if body:
headers["Content-Type"] = "application/json"
res = requests.request(
method,
API + path_name,
headers=headers,
json=body,
)
try:
data = res.json()
except Exception:
data = {}
if not res.ok:
error_msg = json.dumps(data)[:300]
raise Exception(f"{method} {path_name} failed ({res.status_code}): {error_msg}")
return data
WORKFLOW = {
"name": "Commercial Insurance Application Processing Pipeline",
"steps": [
{
"name": "startTrigger1",
"type": "TRIGGER",
"next": [{"step": "parse1"}],
},
{
"name": "parse1",
"type": "PARSE",
"config": {
"parseConfig": {
"blockOptions": {"text": {"agentic": {"enabled": True}}},
"chunkingStrategy": {"type": "document"},
}
},
"next": [{"step": "classify2"}],
},
{
"name": "classify2",
"type": "CLASSIFY",
"config": {
"classifierConfig": {
"classifications": [
{
"id": "classification1",
"type": "other",
"description": "Use the `other` document type when the provided document can not clearly be classified into one of the described classifications.",
},
{
"id": "classification_GEy",
"type": "acord_form",
"description": "An ACORD form is a standardized document used throughout the insurance industry. Created by the Association for Cooperative Operations Research and Development (ACORD)",
},
],
"baseProcessor": "classification_performance",
"advancedOptions": {"advancedMultimodalEnabled": True},
}
},
"next": [
{"step": "extraction3", "classificationId": "classification1"},
{"step": "extraction3", "classificationId": "classification_GEy"},
],
},
{
"name": "extraction3",
"type": "EXTRACT",
"config": {
"extractorConfig": {
"schema": {
"type": "object",
"properties": {
"county": {
"type": ["string", "null"],
"description": "The county in which the applicant's business is located. May be labeled as 'County' or included as part of the address.",
},
"owners": {
"type": "array",
"items": {
"type": "object",
"properties": {
"ssn": {
"type": ["string", "null"],
"description": "The Social Security Number of the owner, if provided.",
},
"title": {
"type": ["string", "null"],
"description": "The title or position held by this individual within the business.",
},
"owner_name": {
"type": ["string", "null"],
"description": "The full name of the owner, partner, or officer.",
},
"date_of_birth": {
"type": ["string", "null"],
"extend:type": "date",
"description": "The date of birth of the owner, partner, or officer.",
},
"ownership_percent": {
"type": ["number", "null"],
"description": "The percentage of ownership held by this individual.",
},
},
"additionalProperties": False,
"required": [
"ssn",
"title",
"owner_name",
"date_of_birth",
"ownership_percent",
],
},
"description": "A list of owners, partners, or officers for the applicant's business. Each entry includes identifying and ownership information.",
},
"website": {
"type": ["string", "null"],
"description": "The website address (URL) for the applicant's business, if provided.",
},
"dba_name": {
"type": ["string", "null"],
"description": "The 'doing business as' name, if different from the legal name. This is an alternate business name under which the applicant operates.",
},
"naic_code": {
"type": ["string", "null"],
"description": "The NAIC (National Association of Insurance Commissioners) code associated with the insurer or policy. This is a numeric or alphanumeric code used for regulatory identification.",
},
"agent_name": {
"type": ["string", "null"],
"description": "The full name of the agent or broker responsible for the application. May be labeled as 'Agent Name', 'Producer', or similar.",
},
"fax_number": {
"type": ["string", "null"],
"description": "The fax number for the applicant or business, if provided.",
},
"agency_code": {
"type": ["string", "null"],
"description": "A unique code or identifier for the agency, if provided. May be labeled as 'Agency Code', 'Producer Code', or similar.",
},
"agency_name": {
"type": ["string", "null"],
"description": "The name of the insurance agency or brokerage handling the application. This is the organization representing the applicant to the insurer.",
},
"billing_plan": {
"type": ["string", "null"],
"description": "The selected billing plan for the policy, such as 'Direct Bill', 'Agency Bill', etc. May be indicated by checkboxes or text.",
},
"contact_name": {
"type": ["string", "null"],
"description": "The name of the primary contact person for the application or business. May be labeled as 'Contact Name', 'Inspection Contact', or similar.",
},
"loss_history": {
"type": "array",
"items": {
"type": "object",
"properties": {
"status": {
"type": ["string", "null"],
"description": "The current status of the claim or loss, such as 'Open', 'Closed', 'Pending', etc.",
},
"amount_paid": {
"type": ["number", "null"],
"description": "The amount paid to settle the claim or loss, if any.",
},
"description": {
"type": ["string", "null"],
"description": "A narrative description of the loss, claim, or incident.",
},
"date_of_loss": {
"type": ["string", "null"],
"extend:type": "date",
"description": "The date the loss, claim, or incident occurred.",
},
"type_of_loss": {
"type": ["string", "null"],
"description": "A brief description of the type of loss, such as 'Property Damage', 'Liability', etc.",
},
"amount_reserved": {
"type": ["number", "null"],
"description": "The amount reserved for the claim or loss, if any.",
},
},
"additionalProperties": False,
"required": [
"status",
"amount_paid",
"description",
"date_of_loss",
"type_of_loss",
"amount_reserved",
],
},
"description": "A list of claims, lawsuits, or incidents reported in the past 5 years. Each entry represents a separate loss event.",
},
"payment_plan": {
"type": ["string", "null"],
"description": "The selected payment plan for the policy, such as 'Annual', 'Semi-Annual', etc. May be indicated by checkboxes or text.",
},
"business_type": {
"type": ["string", "null"],
"description": "The legal structure of the applicant's business, such as 'Sole Proprietorship', 'LLC', 'Corporation', 'Partnership', etc. May be indicated by checkboxes or text.",
},
"contact_title": {
"type": ["string", "null"],
"description": "The job title or role of the primary contact person, such as 'Owner', 'Manager', etc.",
},
"email_address": {
"type": ["string", "null"],
"description": "The primary email address for the applicant or business. Used for electronic correspondence.",
},
"landlord_name": {
"type": ["string", "null"],
"description": "The name of the landlord or property owner, if the premises are leased.",
},
"policy_number": {
"type": ["string", "null"],
"description": "The unique identifier assigned to the insurance policy, if available at the time of application. May include letters, numbers, or special characters. Commonly labeled as 'Policy Number' or 'Policy #'.",
},
"primary_phone": {
"type": ["string", "null"],
"description": "The main telephone number for the applicant or business. May include area code and extension.",
},
"federal_tax_id": {
"type": ["string", "null"],
"description": "The Federal Employer Identification Number (FEIN) or Social Security Number (SSN) for the applicant. Used for tax and regulatory purposes.",
},
"landlord_phone": {
"type": ["string", "null"],
"description": "The phone number of the landlord or property owner, if the premises are leased.",
},
"premises_owned": {
"type": ["boolean", "null"],
"description": "Indicates whether the applicant owns the business premises. True if owned, false if not.",
},
"signature_date": {
"type": ["string", "null"],
"extend:type": "date",
"description": "The date the applicant signed the application, certifying its accuracy.",
},
"audit_frequency": {
"type": ["string", "null"],
"description": "The frequency of premium audit for the policy, such as 'Annually', 'Semi-Annually', etc.",
},
"mailing_address": {
"type": ["string", "null"],
"description": "The complete mailing address for the applicant, including street, city, state, and ZIP code. This is the primary address for correspondence.",
},
"premises_leased": {
"type": ["boolean", "null"],
"description": "Indicates whether the applicant leases the business premises. True if leased, false if not.",
},
"secondary_phone": {
"type": ["string", "null"],
"description": "An alternate or secondary telephone number for the applicant or business, if provided.",
},
"application_date": {
"type": ["string", "null"],
"extend:type": "date",
"description": "The date the commercial insurance application was completed or submitted. This is the official date of the application and may be labeled as 'Date', 'Application Date', or similar.",
},
"number_of_owners": {
"type": ["integer", "null"],
"description": "The total number of owners, partners, or officers associated with the applicant's business.",
},
"physical_address": {
"type": ["string", "null"],
"description": "The physical address of the applicant's business, if different from the mailing address. Includes street, city, state, and ZIP code.",
},
"agency_customer_id": {
"type": ["string", "null"],
"description": "A unique identifier assigned by the agency to the applicant or account. May be labeled as 'Agency Customer ID', 'Client ID', or similar.",
},
"applicant_signature": {
"type": ["string", "null"],
"description": "The name or representation of the applicant's signature, indicating certification of the information provided.",
},
"agent_license_number": {
"type": ["string", "null"],
"description": "The license number of the agent or broker, if provided. This is a regulatory identifier for the individual handling the application.",
},
"applicant_legal_name": {
"type": ["string", "null"],
"description": "The legal name of the business or individual applying for insurance. This is the primary insured entity and may include DBA (doing business as) names.",
},
"business_description": {
"type": ["string", "null"],
"description": "A description of the applicant's primary business operations, activities, or services provided. May be labeled as 'Nature of Business', 'Description of Operations', or similar.",
},
"total_annual_payroll": {
"type": ["number", "null"],
"description": "The total annual payroll for all employees of the applicant's business, typically in the local currency.",
},
"year_business_started": {
"type": ["string", "null"],
"description": "The year the applicant's business was established or began operations. May be labeled as 'Year Business Started', 'Date Business Started', or similar.",
},
"el_each_accident_limit": {
"type": ["number", "null"],
"description": "The employer's liability limit for each accident under workers compensation coverage.",
},
"package_policy_premium": {
"type": "object",
"properties": {
"amount": {"type": ["number", "null"]},
"iso_4217_currency_code": {"type": ["string", "null"]},
},
"additionalProperties": False,
"required": ["amount", "iso_4217_currency_code"],
"extend:type": "currency",
"description": "The total premium amount for the package policy, if provided. This is the cost of the insurance coverage for the policy term.",
},
"el_disease_policy_limit": {
"type": ["number", "null"],
"description": "The employer's liability policy limit for disease under workers compensation coverage.",
},
"proposed_effective_date": {
"type": ["string", "null"],
"extend:type": "date",
"description": "The proposed effective date for the insurance policy. This is the date coverage is requested to begin.",
},
"estimated_annual_revenue": {
"type": ["number", "null"],
"description": "The estimated or actual annual revenue for the applicant's business, typically in the local currency.",
},
"general_liability_limits": {
"type": "object",
"properties": {
"each_occurrence": {
"type": ["number", "null"],
"description": "The limit for each occurrence under general liability coverage.",
},
"medical_expense": {
"type": ["number", "null"],
"description": "The limit for medical expense coverage.",
},
"general_aggregate": {
"type": ["number", "null"],
"description": "The general aggregate limit for general liability coverage.",
},
"damage_to_rented_premises": {
"type": ["number", "null"],
"description": "The limit for damage to rented premises coverage.",
},
"personal_advertising_injury": {
"type": ["number", "null"],
"description": "The limit for personal and advertising injury coverage.",
},
"products_completed_operations_aggregate": {
"type": ["number", "null"],
"description": "The aggregate limit for products and completed operations coverage.",
},
},
"additionalProperties": False,
"required": [
"each_occurrence",
"medical_expense",
"general_aggregate",
"damage_to_rented_premises",
"personal_advertising_injury",
"products_completed_operations_aggregate",
],
"description": "The requested or quoted limits for general liability coverage. Each property represents a specific coverage limit.",
},
"proposed_expiration_date": {
"type": ["string", "null"],
"extend:type": "date",
"description": "The proposed expiration date for the insurance policy. This is the date coverage is requested to end.",
},
"workers_compensation_code": {
"type": ["string", "null"],
"description": "The workers compensation classification code applicable to the applicant's business.",
},
"square_footage_of_premises": {
"type": ["integer", "null"],
"description": "The total square footage of the business premises occupied by the applicant.",
},
"workers_compensation_state": {
"type": ["string", "null"],
"description": "The state in which workers compensation coverage is requested or provided.",
},
"business_classification_code": {
"type": ["string", "null"],
"description": "The business classification code (such as NAICS or SIC) that categorizes the applicant's industry or operations.",
},
"number_of_seasonal_employees": {
"type": ["integer", "null"],
"description": "The number of seasonal or temporary employees working for the applicant's business.",
},
"number_of_full_time_employees": {
"type": ["integer", "null"],
"description": "The number of full-time employees working for the applicant's business.",
},
"number_of_part_time_employees": {
"type": ["integer", "null"],
"description": "The number of part-time employees working for the applicant's business.",
},
"el_disease_each_employee_limit": {
"type": ["number", "null"],
"description": "The employer's liability limit for disease for each employee under workers compensation coverage.",
},
"business_classification_description": {
"type": ["string", "null"],
"description": "A textual description of the business classification or industry for the applicant.",
},
"workers_compensation_annual_payroll": {
"type": ["number", "null"],
"description": "The estimated annual payroll for workers compensation purposes.",
},
"general_liability_coverages_requested": {
"type": ["string", "null"],
"description": "A list or description of general liability coverages requested, such as 'Premises Operations', 'Products Completed Operations', 'Contractual Liability', etc. May be indicated by checkboxes or text.",
},
},
"required": [
"county",
"owners",
"website",
"dba_name",
"naic_code",
"agent_name",
"fax_number",
"agency_code",
"agency_name",
"billing_plan",
"contact_name",
"loss_history",
"payment_plan",
"business_type",
"contact_title",
"email_address",
"landlord_name",
"policy_number",
"primary_phone",
"federal_tax_id",
"landlord_phone",
"premises_owned",
"signature_date",
"audit_frequency",
"mailing_address",
"premises_leased",
"secondary_phone",
"application_date",
"number_of_owners",
"physical_address",
"agency_customer_id",
"applicant_signature",
"agent_license_number",
"applicant_legal_name",
"business_description",
"total_annual_payroll",
"year_business_started",
"el_each_accident_limit",
"package_policy_premium",
"el_disease_policy_limit",
"proposed_effective_date",
"estimated_annual_revenue",
"general_liability_limits",
"proposed_expiration_date",
"workers_compensation_code",
"square_footage_of_premises",
"workers_compensation_state",
"business_classification_code",
"number_of_seasonal_employees",
"number_of_full_time_employees",
"number_of_part_time_employees",
"el_disease_each_employee_limit",
"business_classification_description",
"workers_compensation_annual_payroll",
"general_liability_coverages_requested",
],
"additionalProperties": False,
},
"baseProcessor": "extraction_performance",
"advancedOptions": {
"reviewAgent": {"enabled": True},
"advancedMultimodalEnabled": True,
},
}
},
},
],
}
def main() -> None:
print(f'Deploying "{WORKFLOW["name"]}…"')
if state.get("workflowId"):
print(
f'✓ workflow already provisioned ({state["workflowId"]}) — updating steps'
)
api("POST", f'/workflows/{state["workflowId"]}', {"steps": WORKFLOW["steps"]})
else:
try:
list_response = api(
"GET",
f'/workflows?name={WORKFLOW["name"].replace(" ", "%20")}',
)
items = list_response.get("data") or list_response.get("items") or []
existing = next(
(x for x in items if x.get("name") == WORKFLOW["name"]), None
)
if existing and existing.get("id"):
state["workflowId"] = existing["id"]
save_state()
print(
f'✓ workflow "{WORKFLOW["name"]}" found in your account ({existing["id"]}) — updating steps'
)
api(
"POST",
f'/workflows/{existing["id"]}',
{"steps": WORKFLOW["steps"]},
)
except Exception:
pass
if not state.get("workflowId"):
created = api("POST", "/workflows", WORKFLOW)
wf_id = created.get("id") or (
created.get("workflow", {}).get("id") if created.get("workflow") else None
)
if not wf_id:
raise Exception("Could not read created workflow id from response")
state["workflowId"] = wf_id
save_state()
print(f"+ created workflow ({wf_id})")
try:
api("POST", f'/workflows/{state["workflowId"]}/versions', {})
except Exception:
pass
print("\nDone. Run documents through it with:")
print(
f' POST {API}/workflow_runs {{ workflow: {{ id: "{state["workflowId"]}" }}, file: {{ url: "https://…" }} }}'
)
print("Or open the workflow in the Extend dashboard to review and deploy it.")
if __name__ == "__main__":
try:
main()
except Exception as e:
print(str(e), file=sys.stderr)
sys.exit(1)// This code uses Extend's REST API directly because Extend has no official Java SDK yet.
// It deploys the "Commercial Insurance Application" pipeline to your Extend account.
//
// Usage:
// export EXTEND_API_KEY=sk_... (from https://dashboard.extend.ai → API Keys)
// javac Provision.java && java Provision
//
// Generated by doc1 (template: acord-form-classifier).
import java.io.*;
import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
public class Provision {
private static final String API = "https://api.extend.ai";
private static final String VERSION = "2026-02-09";
private static final String API_KEY = System.getenv("EXTEND_API_KEY");
private static final Path STATE_DIR = Paths.get(System.getProperty("user.dir"), ".extend");
private static final Path STATE_FILE = STATE_DIR.resolve("acord-form-classifier.json");
static {
if (API_KEY == null || API_KEY.isEmpty()) {
System.err.println("Set EXTEND_API_KEY first.");
System.exit(1);
}
}
private static final HttpClient HTTP_CLIENT = HttpClient.newHttpClient();
static class State {
String workflowId;
}
private static State state = new State();
static {
if (Files.exists(STATE_FILE)) {
try {
String json = Files.readString(STATE_FILE);
Map<String, Object> map = parseJson(json);
state.workflowId = (String) map.get("workflowId");
} catch (IOException e) {
// Ignore; start with empty state
}
}
}
private static void saveState() throws IOException {
Files.createDirectories(STATE_DIR);
Map<String, Object> map = new LinkedHashMap<>();
if (state.workflowId != null) {
map.put("workflowId", state.workflowId);
}
Files.writeString(STATE_FILE, toJson(map));
}
private static Map<String, Object> api(String method, String pathName, Object body) throws Exception {
String url = API + pathName;
HttpRequest.Builder builder = HttpRequest.newBuilder(URI.create(url))
.method(method, body == null ? HttpRequest.BodyPublishers.noBody() : HttpRequest.BodyPublishers.ofString(toJson(body)))
.header("Authorization", "Bearer " + API_KEY)
.header("x-extend-api-version", VERSION);
if (body != null) {
builder.header("Content-Type", "application/json");
}
HttpRequest request = builder.build();
HttpResponse<String> response = HTTP_CLIENT.send(request, HttpResponse.BodyHandlers.ofString());
Map<String, Object> data = new LinkedHashMap<>();
if (!response.body().isEmpty()) {
data = parseJson(response.body());
}
if (response.statusCode() < 200 || response.statusCode() >= 300) {
String errorMsg = toJson(data);
if (errorMsg.length() > 300) {
errorMsg = errorMsg.substring(0, 300);
}
throw new Exception(method + " " + pathName + " failed (" + response.statusCode() + "): " + errorMsg);
}
return data;
}
private static String toJson(Object obj) {
if (obj == null) return "null";
if (obj instanceof String) return "\"" + escapeJson((String) obj) + "\"";
if (obj instanceof Number) return obj.toString();
if (obj instanceof Boolean) return obj.toString();
if (obj instanceof Map) {
Map<?, ?> map = (Map<?, ?>) obj;
StringBuilder sb = new StringBuilder("{");
boolean first = true;
for (Map.Entry<?, ?> e : map.entrySet()) {
if (!first) sb.append(",");
sb.append("\"").append(escapeJson(e.getKey().toString())).append("\":");
sb.append(toJson(e.getValue()));
first = false;
}
sb.append("}");
return sb.toString();
}
if (obj instanceof List) {
List<?> list = (List<?>) obj;
StringBuilder sb = new StringBuilder("[");
boolean first = true;
for (Object item : list) {
if (!first) sb.append(",");
sb.append(toJson(item));
first = false;
}
sb.append("]");
return sb.toString();
}
return "\"" + escapeJson(obj.toString()) + "\"";
}
private static String escapeJson(String s) {
return s.replace("\\", "\\\\").replace("\"", "\\\"").replace("\n", "\\n").replace("\r", "\\r").replace("\t", "\\t");
}
private static Map<String, Object> parseJson(String json) {
json = json.trim();
if (!json.startsWith("{")) return new LinkedHashMap<>();
json = json.substring(1, json.length() - 1);
Map<String, Object> map = new LinkedHashMap<>();
if (json.isEmpty()) return map;
int depth = 0;
StringBuilder key = new StringBuilder();
StringBuilder value = new StringBuilder();
boolean inString = false;
boolean readingKey = true;
for (int i = 0; i < json.length(); i++) {
char c = json.charAt(i);
if (c == '"' && (i == 0 || json.charAt(i - 1) != '\\')) {
inString = !inString;
}
if (!inString) {
if (c == '{' || c == '[') depth++;
else if (c == '}' || c == ']') depth--;
else if (c == ':' && depth == 0 && readingKey) {
readingKey = false;
continue;
} else if (c == ',' && depth == 0) {
String k = key.toString().trim().replaceAll("^\"|\"$", "");
String v = value.toString().trim();
map.put(k, parseJsonValue(v));
key = new StringBuilder();
value = new StringBuilder();
readingKey = true;
continue;
}
}
if (readingKey) key.append(c);
else value.append(c);
}
if (key.length() > 0) {
String k = key.toString().trim().replaceAll("^\"|\"$", "");
String v = value.toString().trim();
map.put(k, parseJsonValue(v));
}
return map;
}
private static Object parseJsonValue(String v) {
v = v.trim();
if (v.equals("null")) return null;
if (v.equals("true")) return true;
if (v.equals("false")) return false;
if (v.startsWith("\"") && v.endsWith("\"")) {
return v.substring(1, v.length() - 1).replace("\\\"", "\"").replace("\\\\", "\\");
}
if (v.startsWith("{") || v.startsWith("[")) {
return v;
}
try {
if (v.contains(".")) return Double.parseDouble(v);
return Long.parseLong(v);
} catch (NumberFormatException e) {
return v;
}
}
private static Map<String, Object> buildWorkflow() {
Map<String, Object> workflow = new LinkedHashMap<>();
workflow.put("name", "Commercial Insurance Application Processing Pipeline");
List<Map<String, Object>> steps = new ArrayList<>();
// startTrigger1
Map<String, Object> startTrigger = new LinkedHashMap<>();
startTrigger.put("name", "startTrigger1");
startTrigger.put("type", "TRIGGER");
List<Map<String, Object>> nextTrigger = new ArrayList<>();
Map<String, Object> nextStep1 = new LinkedHashMap<>();
nextStep1.put("step", "parse1");
nextTrigger.add(nextStep1);
startTrigger.put("next", nextTrigger);
steps.add(startTrigger);
// parse1
Map<String, Object> parse = new LinkedHashMap<>();
parse.put("name", "parse1");
parse.put("type", "PARSE");
Map<String, Object> parseConfig = new LinkedHashMap<>();
Map<String, Object> parseConfigInner = new LinkedHashMap<>();
Map<String, Object> blockOptions = new LinkedHashMap<>();
Map<String, Object> textOptions = new LinkedHashMap<>();
Map<String, Object> agenticOptions = new LinkedHashMap<>();
agenticOptions.put("enabled", true);
textOptions.put("agentic", agenticOptions);
blockOptions.put("text", textOptions);
parseConfigInner.put("blockOptions", blockOptions);
Map<String, Object> chunkingStrategy = new LinkedHashMap<>();
chunkingStrategy.put("type", "document");
parseConfigInner.put("chunkingStrategy", chunkingStrategy);
parseConfig.put("parseConfig", parseConfigInner);
parse.put("config", parseConfig);
List<Map<String, Object>> nextParse = new ArrayList<>();
Map<String, Object> nextStep2 = new LinkedHashMap<>();
nextStep2.put("step", "classify2");
nextParse.add(nextStep2);
parse.put("next", nextParse);
steps.add(parse);
// classify2
Map<String, Object> classify = new LinkedHashMap<>();
classify.put("name", "classify2");
classify.put("type", "CLASSIFY");
Map<String, Object> classifyConfig = new LinkedHashMap<>();
Map<String, Object> classifierConfig = new LinkedHashMap<>();
List<Map<String, Object>> classifications = new ArrayList<>();
Map<String, Object> classOther = new LinkedHashMap<>();
classOther.put("id", "classification1");
classOther.put("type", "other");
classOther.put("description", "Use the `other` document type when the provided document can not clearly be classified into one of the described classifications.");
classifications.add(classOther);
Map<String, Object> classAcord = new LinkedHashMap<>();
classAcord.put("id", "classification_GEy");
classAcord.put("type", "acord_form");
classAcord.put("description", "An ACORD form is a standardized document used throughout the insurance industry. Created by the Association for Cooperative Operations Research and Development (ACORD)");
classifications.add(classAcord);
classifierConfig.put("classifications", classifications);
classifierConfig.put("baseProcessor", "classification_performance");
Map<String, Object> advancedOptions = new LinkedHashMap<>();
advancedOptions.put("advancedMultimodalEnabled", true);
classifierConfig.put("advancedOptions", advancedOptions);
classifyConfig.put("classifierConfig", classifierConfig);
classify.put("config", classifyConfig);
List<Map<String, Object>> nextClassify = new ArrayList<>();
Map<String, Object> nextStep3a = new LinkedHashMap<>();
nextStep3a.put("step", "extraction3");
nextStep3a.put("classificationId", "classification1");
nextClassify.add(nextStep3a);
Map<String, Object> nextStep3b = new LinkedHashMap<>();
nextStep3b.put("step", "extraction3");
nextStep3b.put("classificationId", "classification_GEy");
nextClassify.add(nextStep3b);
classify.put("next", nextClassify);
steps.add(classify);
// extraction3
Map<String, Object> extraction = new LinkedHashMap<>();
extraction.put("name", "extraction3");
extraction.put("type", "EXTRACT");
Map<String, Object> extractionConfig = new LinkedHashMap<>();
Map<String, Object> extractorConfig = new LinkedHashMap<>();
extractorConfig.put("schema", buildSchema());
extractorConfig.put("baseProcessor", "extraction_performance");
Map<String, Object> extractAdvancedOptions = new LinkedHashMap<>();
Map<String, Object> reviewAgent = new LinkedHashMap<>();
reviewAgent.put("enabled", true);
extractAdvancedOptions.put("reviewAgent", reviewAgent);
extractAdvancedOptions.put("advancedMultimodalEnabled", true);
extractorConfig.put("advancedOptions", extractAdvancedOptions);
extractionConfig.put("extractorConfig", extractorConfig);
extraction.put("config", extractionConfig);
steps.add(extraction);
workflow.put("steps", steps);
return workflow;
}
private static Map<String, Object> buildSchema() {
Map<String, Object> schema = new LinkedHashMap<>();
schema.put("type", "object");
Map<String, Object> properties = new LinkedHashMap<>();
// county
properties.put("county", buildStringProperty("The county in which the applicant's business is located. May be labeled as 'County' or included as part of the address."));
// owners (array of objects)
Map<String, Object> owners = new LinkedHashMap<>();
owners.put("type", "array");
Map<String, Object> ownerItem = new LinkedHashMap<>();
ownerItem.put("type", "object");
Map<String, Object> ownerProps = new LinkedHashMap<>();
ownerProps.put("ssn", buildStringProperty("The Social Security Number of the owner, if provided."));
ownerProps.put("title", buildStringProperty("The title or position held by this individual within the business."));
ownerProps.put("owner_name", buildStringProperty("The full name of the owner, partner, or officer."));
Map<String, Object> dob = buildStringProperty("The date of birth of the owner, partner, or officer.");
dob.put("extend:type", "date");
ownerProps.put("date_of_birth", dob);
ownerProps.put("ownership_percent", buildNumberProperty("The percentage of ownership held by this individual."));
ownerItem.put("properties", ownerProps);
ownerItem.put("additionalProperties", false);
List<String> ownerRequired = Arrays.asList("ssn", "title", "owner_name", "date_of_birth", "ownership_percent");
ownerItem.put("required", ownerRequired);
owners.put("items", ownerItem);
owners.put("description", "A list of owners, partners, or officers for the applicant's business. Each entry includes identifying and ownership information.");
properties.put("owners", owners);
// website
properties.put("website", buildStringProperty("The website address (URL) for the applicant's business, if provided."));
// dba_name
properties.put("dba_name", buildStringProperty("The 'doing business as' name, if different from the legal name. This is an alternate business name under which the applicant operates."));
// naic_code
properties.put("naic_code", buildStringProperty("The NAIC (National Association of Insurance Commissioners) code associated with the insurer or policy. This is a numeric or alphanumeric code used for regulatory identification."));
// agent_name
properties.put("agent_name", buildStringProperty("The full name of the agent or broker responsible for the application. May be labeled as 'Agent Name', 'Producer', or similar."));
// fax_number
properties.put("fax_number", buildStringProperty("The fax number for the applicant or business, if provided."));
// agency_code
properties.put("agency_code", buildStringProperty("A unique code or identifier for the agency, if provided. May be labeled as 'Agency Code', 'Producer Code', or similar."));
// agency_name
properties.put("agency_name", buildStringProperty("The name of the insurance agency or brokerage handling the application. This is the organization representing the applicant to the insurer."));
// billing_plan
properties.put("billing_plan", buildStringProperty("The selected billing plan for the policy, such as 'Direct Bill', 'Agency Bill', etc. May be indicated by checkboxes or text."));
// contact_name
properties.put("contact_name", buildStringProperty("The name of the primary contact person for the application or business. May be labeled as 'Contact Name', 'Inspection Contact', or similar."));
// loss_history (array of objects)
Map<String, Object> lossHistory = new LinkedHashMap<>();
lossHistory.put("type", "array");
Map<String, Object> lossItem = new LinkedHashMap<>();
lossItem.put("type", "object");
Map<String, Object> lossProps = new LinkedHashMap<>();
lossProps.put("status", buildStringProperty("The current status of the claim or loss, such as 'Open', 'Closed', 'Pending', etc."));
lossProps.put("amount_paid", buildNumberProperty("The amount paid to settle the claim or loss, if any."));
lossProps.put("description", buildStringProperty("A narrative description of the loss, claim, or incident."));
Map<String, Object> dol = buildStringProperty("The date the loss, claim, or incident occurred.");
dol.put("extend:type", "date");
lossProps.put("date_of_loss", dol);
lossProps.put("type_of_loss", buildStringProperty("A brief description of the type of loss, such as 'Property Damage', 'Liability', etc."));
lossProps.put("amount_reserved", buildNumberProperty("The amount reserved for the claim or loss, if any."));
lossItem.put("properties", lossProps);
lossItem.put("additionalProperties", false);
List<String> lossRequired = Arrays.asList("status", "amount_paid", "description", "date_of_loss", "type_of_loss", "amount_reserved");
lossItem.put("required", lossRequired);
lossHistory.put("items", lossItem);
lossHistory.put("description", "A list of claims, lawsuits, or incidents reported in the past 5 years. Each entry represents a separate loss event.");
properties.put("loss_history", lossHistory);
// payment_plan
properties.put("payment_plan", buildStringProperty("The selected payment plan for the policy, such as 'Annual', 'Semi-Annual', etc. May be indicated by checkboxes or text."));
// business_type
properties.put("business_type", buildStringProperty("The legal structure of the applicant's business, such as 'Sole Proprietorship', 'LLC', 'Corporation', 'Partnership', etc. May be indicated by checkboxes or text."));
// contact_title
properties.put("contact_title", buildStringProperty("The job title or role of the primary contact person, such as 'Owner', 'Manager', etc."));
// email_address
properties.put("email_address", buildStringProperty("The primary email address for the applicant or business. Used for electronic correspondence."));
// landlord_name
properties.put("landlord_name", buildStringProperty("The name of the landlord or property owner, if the premises are leased."));
// policy_number
properties.put("policy_number", buildStringProperty("The unique identifier assigned to the insurance policy, if available at the time of application. May include letters, numbers, or special characters. Commonly labeled as 'Policy Number' or 'Policy #'."));
// primary_phone
properties.put("primary_phone", buildStringProperty("The main telephone number for the applicant or business. May include area code and extension."));
// federal_tax_id
properties.put("federal_tax_id", buildStringProperty("The Federal Employer Identification Number (FEIN) or Social Security Number (SSN) for the applicant. Used for tax and regulatory purposes."));
// landlord_phone
properties.put("landlord_phone", buildStringProperty("The phone number of the landlord or property owner, if the premises are leased."));
// premises_owned
properties.put("premises_owned", buildBooleanProperty("Indicates whether the applicant owns the business premises. True if owned, false if not."));
// signature_date
Map<String, Object> sigDate = buildStringProperty("The date the applicant signed the application, certifying its accuracy.");
sigDate.put("extend:type", "date");
properties.put("signature_date", sigDate);
// audit_frequency
properties.put("audit_frequency", buildStringProperty("The frequency of premium audit for the policy, such as 'Annually', 'Semi-Annually', etc."));
// mailing_address
properties.put("mailing_address", buildStringProperty("The complete mailing address for the applicant, including street, city, state, and ZIP code. This is the primary address for correspondence."));
// premises_leased
properties.put("premises_leased", buildBooleanProperty("Indicates whether the applicant leases the business premises. True if leased, false if not."));
// secondary_phone
properties.put("secondary_phone", buildStringProperty("An alternate or secondary telephone number for the applicant or business, if provided."));
// application_date
Map<String, Object> appDate = buildStringProperty("The date the commercial insurance application was completed or submitted. This is the official date of the application and may be labeled as 'Date', 'Application Date', or similar.");
appDate.put("extend:type", "date");
properties.put("application_date", appDate);
// number_of_owners
properties.put("number_of_owners", buildIntegerProperty("The total number of owners, partners, or officers associated with the applicant's business."));
// physical_address
properties.put("physical_address", buildStringProperty("The physical address of the applicant's business, if different from the mailing address. Includes street, city, state, and ZIP code."));
// agency_customer_id
properties.put("agency_customer_id", buildStringProperty("A unique identifier assigned by the agency to the applicant or account. May be labeled as 'Agency Customer ID', 'Client ID', or similar."));
// applicant_signature
properties.put("applicant_signature", buildStringProperty("The name or representation of the applicant's signature, indicating certification of the information provided."));
// agent_license_number
properties.put("agent_license_number", buildStringProperty("The license number of the agent or broker, if provided. This is a regulatory identifier for the individual handling the application."));
// applicant_legal_name
properties.put("applicant_legal_name", buildStringProperty("The legal name of the business or individual applying for insurance. This is the primary insured entity and may include DBA (doing business as) names."));
// business_description
properties.put("business_description", buildStringProperty("A description of the applicant's primary business operations, activities, or services provided. May be labeled as 'Nature of Business', 'Description of Operations', or similar."));
// total_annual_payroll
properties.put("total_annual_payroll", buildNumberProperty("The total annual payroll for all employees of the applicant's business, typically in the local currency."));
// year_business_started
properties.put("year_business_started", buildStringProperty("The year the applicant's business was established or began operations. May be labeled as 'Year Business Started', 'Date Business Started', or similar."));
// el_each_accident_limit
properties.put("el_each_accident_limit", buildNumberProperty("The employer's liability limit for each accident under workers compensation coverage."));
// package_policy_premium
Map<String, Object> ppp = new LinkedHashMap<>();
ppp.put("type", "object");
Map<String, Object> pppProps = new LinkedHashMap<>();
pppProps.put("amount", buildNumberProperty(null));
pppProps.put("iso_4217_currency_code", buildStringProperty(null));
ppp.put("properties", pppProps);
ppp.put("additionalProperties", false);
ppp.put("required", Arrays.asList("amount", "iso_4217_currency_code"));
ppp.put("extend:type", "currency");
ppp.put("description", "The total premium amount for the package policy, if provided. This is the cost of the insurance coverage for the policy term.");
properties.put("package_policy_premium", ppp);
// el_disease_policy_limit
properties.put("el_disease_policy_limit", buildNumberProperty("The employer's liability policy limit for disease under workers compensation coverage."));
// proposed_effective_date
Map<String, Object> ped = buildStringProperty("The proposed effective date for the insurance policy. This is the date coverage is requested to begin.");
ped.put("extend:type", "date");
properties.put("proposed_effective_date", ped);
// estimated_annual_revenue
properties.put("estimated_annual_revenue", buildNumberProperty("The estimated or actual annual revenue for the applicant's business, typically in the local currency."));
// general_liability_limits
Map<String, Object> gll = new LinkedHashMap<>();
gll.put("type", "object");
Map<String, Object> gllProps = new LinkedHashMap<>();
gllProps.put("each_occurrence", buildNumberProperty("The limit for each occurrence under general liability coverage."));
gllProps.put("medical_expense", buildNumberProperty("The limit for medical expense coverage."));
gllProps.put("general_aggregate", buildNumberProperty("The general aggregate limit for general liability coverage."));
gllProps.put("damage_to_rented_premises", buildNumberProperty("The limit for damage to rented premises coverage."));
gllProps.put("personal_advertising_injury", buildNumberProperty("The limit for personal and advertising injury coverage."));
gllProps.put("products_completed_operations_aggregate", buildNumberProperty("The aggregate limit for products and completed operations coverage."));
gll.put("properties", gllProps);
gll.put("additionalProperties", false);
gll.put("required", Arrays.asList("each_occurrence", "medical_expense", "general_aggregate", "damage_to_rented_premises", "personal_advertising_injury", "products_completed_operations_aggregate"));
gll.put("description", "The requested or quoted limits for general liability coverage. Each property represents a specific coverage limit.");
properties.put("general_liability_limits", gll);
// proposed_expiration_date
Map<String, Object> ped2 = buildStringProperty("The proposed expiration date for the insurance policy. This is the date coverage is requested to end.");
ped2.put("extend:type", "date");
properties.put("proposed_expiration_date", ped2);
// workers_compensation_code
properties.put("workers_compensation_code", buildStringProperty("The workers compensation classification code applicable to the applicant's business."));
// square_footage_of_premises
properties.put("square_footage_of_premises", buildIntegerProperty("The total square footage of the business premises occupied by the applicant."));
// workers_compensation_state
properties.put("workers_compensation_state", buildStringProperty("The state in which workers compensation coverage is requested or provided."));
// business_classification_code
properties.put("business_classification_code", buildStringProperty("The business classification code (such as NAICS or SIC) that categorizes the applicant's industry or operations."));
// number_of_seasonal_employees
properties.put("number_of_seasonal_employees", buildIntegerProperty("The number of seasonal or temporary employees working for the applicant's business."));
// number_of_full_time_employees
properties.put("number_of_full_time_employees", buildIntegerProperty("The number of full-time employees working for the applicant's business."));
// number_of_part_time_employees
properties.put("number_of_part_time_employees", buildIntegerProperty("The number of part-time employees working for the applicant's business."));
// el_disease_each_employee_limit
properties.put("el_disease_each_employee_limit", buildNumberProperty("The employer's liability limit for disease for each employee under workers compensation coverage."));
// business_classification_description
properties.put("business_classification_description", buildStringProperty("A textual description of the business classification or industry for the applicant."));
// workers_compensation_annual_payroll
properties.put("workers_compensation_annual_payroll", buildNumberProperty("The estimated annual payroll for workers compensation purposes."));
// general_liability_coverages_requested
properties.put("general_liability_coverages_requested", buildStringProperty("A list or description of general liability coverages requested, such as 'Premises Operations', 'Products Completed Operations', 'Contractual Liability', etc. May be indicated by checkboxes or text."));
schema.put("properties", properties);
List<String> required = Arrays.asList(
"county", "owners", "website", "dba_name", "naic_code", "agent_name", "fax_number", "agency_code",
"agency_name", "billing_plan", "contact_name", "loss_history", "payment_plan", "business_type",
"contact_title", "email_address", "landlord_name", "policy_number", "primary_phone", "federal_tax_id",
"landlord_phone", "premises_owned", "signature_date", "audit_frequency", "mailing_address",
"premises_leased", "secondary_phone", "application_date", "number_of_owners", "physical_address",
"agency_customer_id", "applicant_signature", "agent_license_number", "applicant_legal_name",
"business_description", "total_annual_payroll", "year_business_started", "el_each_accident_limit",
"package_policy_premium", "el_disease_policy_limit", "proposed_effective_date", "estimated_annual_revenue",
"general_liability_limits", "proposed_expiration_date", "workers_compensation_code",
"square_footage_of_premises", "workers_compensation_state", "business_classification_code",
"number_of_seasonal_employees", "number_of_full_time_employees", "number_of_part_time_employees",
"el_disease_each_employee_limit", "business_classification_description", "workers_compensation_annual_payroll",
"general_liability_coverages_requested"
);
schema.put("required", required);
schema.put("additionalProperties", false);
return schema;
}
private static Map<String, Object> buildStringProperty(String description) {
Map<String, Object> prop = new LinkedHashMap<>();
prop.put("type", Arrays.asList("string", "null"));
if (description != null) {
prop.put("description", description);
}
return prop;
}
private static Map<String, Object> buildNumberProperty(String description) {
Map<String, Object> prop = new LinkedHashMap<>();
prop.put("type", Arrays.asList("number", "null"));
if (description != null) {
prop.put("description", description);
}
return prop;
}
private static Map<String, Object> buildIntegerProperty(String description) {
Map<String, Object> prop = new LinkedHashMap<>();
prop.put("type", Arrays.asList("integer", "null"));
if (description != null) {
prop.put("description", description);
}
return prop;
}
private static Map<String, Object> buildBooleanProperty(String description) {
Map<String, Object> prop = new LinkedHashMap<>();
prop.put("type", Arrays.asList("boolean", "null"));
if (description != null) {
prop.put("description", description);
}
return prop;
}
public static void main(String[] args) {
try {
Map<String, Object> workflow = buildWorkflow();
System.out.println("Deploying \"" + workflow.get("name") + "\"…");
if (state.workflowId != null && !state.workflowId.isEmpty()) {
System.out.println("✓ workflow already provisioned (" + state.workflowId + ") — updating steps");
Map<String, Object> updateBody = new LinkedHashMap<>();
updateBody.put("steps", workflow.get("steps"));
api("POST", "/workflows/" + state.workflowId, updateBody);
} else {
String workflowName = (String) workflow.get("name");
try {
String encodedName = URLEncoder.encode(workflowName, StandardCharsets.UTF_8);
Map<String, Object> listResponse = api("GET", "/workflows?name=" + encodedName, null);
List<?> items = (List<?>) (listResponse.get("data") != null ? listResponse.get("data") : listResponse.get("items"));
if (items != null) {
for (Object item : items) {
if (item instanceof Map) {
Map<?, ?> itemMap = (Map<?, ?>) item;
if (workflowName.equals(itemMap.get("name"))) {
Object id = itemMap.get("id");
if (id != null) {
state.workflowId = id.toString();
saveState();
System.out.println("✓ workflow \"" + workflowName + "\" found in your account (" + state.workflowId + ") — updating steps");
Map<String, Object> updateBody = new LinkedHashMap<>();
updateBody.put("steps", workflow.get("steps"));
api("POST", "/workflows/" + state.workflowId, updateBody);
printDone(state.workflowId);
return;
}
}
}
}
}
} catch (Exception e) {
// Lookup is best-effort; fall through to create
}
if (state.workflowId == null || state.workflowId.isEmpty()) {
Map<String, Object> created = api("POST", "/workflows", workflow);
String wfId = (String) (created.get("id") != null ? created.get("id") :
(created.get("workflow") instanceof Map ? ((Map<?, ?>) created.get("workflow")).get("id") : null));
if (wfId == null) {
throw new Exception("Could not read created workflow id from response");
}
state.workflowId = wfId;
saveState();
System.out.println("+ created workflow (" + wfId + ")");
}
}
// Deploy the current draft as a new version
try {
api("POST", "/workflows/" + state.workflowId + "/versions", new LinkedHashMap<>());
} catch (Exception e) {
// Best-effort; some accounts may not require this
}
printDone(state.workflowId);
} catch (Exception e) {
System.err.println(e.getMessage() != null ? e.getMessage() : e.toString());
System.exit(1);
}
}
private static void printDone(String workflowId) {
System.out.println("\nDone. Run documents through it with:");
System.out.println(" POST " + API + "/workflow_runs { workflow: { id: \"" + workflowId + "\" }, file: { url: \"https://…\" } }");
System.out.println("Or open the workflow in the Extend dashboard to review and deploy it.");
}
}// This code uses the Extend REST API directly because Extend has no official Go SDK yet.
// It deploys the "Commercial Insurance Application" pipeline to your Extend account.
//
// Usage:
// export EXTEND_API_KEY=sk_... (from https://dashboard.extend.ai → API Keys)
// go run provision.go
//
// Generated by doc1 (template: acord-form-classifier).
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"os"
"path/filepath"
)
const (
API = "https://api.extend.ai"
VERSION = "2026-02-09"
)
var (
apiKey string
stateDir string
stateFile string
)
type State struct {
WorkflowID string `json:"workflowId,omitempty"`
}
var state State
func init() {
apiKey = os.Getenv("EXTEND_API_KEY")
if apiKey == "" {
fmt.Fprintf(os.Stderr, "Set EXTEND_API_KEY first.\n")
os.Exit(1)
}
cwd, _ := os.Getwd()
stateDir = filepath.Join(cwd, ".extend")
stateFile = filepath.Join(stateDir, "acord-form-classifier.json")
if data, err := os.ReadFile(stateFile); err == nil {
json.Unmarshal(data, &state)
}
}
func saveState() error {
os.MkdirAll(stateDir, 0755)
data, _ := json.MarshalIndent(state, "", " ")
return os.WriteFile(stateFile, data, 0644)
}
func apiCall(method, pathName string, body interface{}) (map[string]interface{}, error) {
var reqBody io.Reader
if body != nil {
data, _ := json.Marshal(body)
reqBody = bytes.NewReader(data)
}
req, _ := http.NewRequest(method, API+pathName, reqBody)
req.Header.Set("Authorization", "Bearer "+apiKey)
req.Header.Set("x-extend-api-version", VERSION)
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
respData := make(map[string]interface{})
json.NewDecoder(resp.Body).Decode(&respData)
if resp.StatusCode >= 400 {
respBytes, _ := json.Marshal(respData)
if len(respBytes) > 300 {
respBytes = respBytes[:300]
}
return nil, fmt.Errorf("%s %s failed (%d): %s", method, pathName, resp.StatusCode, string(respBytes))
}
return respData, nil
}
var workflow = map[string]interface{}{
"name": "Commercial Insurance Application Processing Pipeline",
"steps": []map[string]interface{}{
{
"name": "startTrigger1",
"type": "TRIGGER",
"next": []map[string]interface{}{
{"step": "parse1"},
},
},
{
"name": "parse1",
"type": "PARSE",
"config": map[string]interface{}{
"parseConfig": map[string]interface{}{
"blockOptions": map[string]interface{}{
"text": map[string]interface{}{
"agentic": map[string]interface{}{
"enabled": true,
},
},
},
"chunkingStrategy": map[string]interface{}{
"type": "document",
},
},
},
"next": []map[string]interface{}{
{"step": "classify2"},
},
},
{
"name": "classify2",
"type": "CLASSIFY",
"config": map[string]interface{}{
"classifierConfig": map[string]interface{}{
"classifications": []map[string]interface{}{
{
"id": "classification1",
"type": "other",
"description": "Use the `other` document type when the provided document can not clearly be classified into one of the described classifications.",
},
{
"id": "classification_GEy",
"type": "acord_form",
"description": "An ACORD form is a standardized document used throughout the insurance industry. Created by the Association for Cooperative Operations Research and Development (ACORD)",
},
},
"baseProcessor": "classification_performance",
"advancedOptions": map[string]interface{}{
"advancedMultimodalEnabled": true,
},
},
},
"next": []map[string]interface{}{
{"step": "extraction3", "classificationId": "classification1"},
{"step": "extraction3", "classificationId": "classification_GEy"},
},
},
{
"name": "extraction3",
"type": "EXTRACT",
"config": map[string]interface{}{
"extractorConfig": map[string]interface{}{
"schema": map[string]interface{}{
"type": "object",
"properties": map[string]interface{}{
"county": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The county in which the applicant's business is located. May be labeled as 'County' or included as part of the address.",
},
"owners": map[string]interface{}{
"type": "array",
"items": map[string]interface{}{
"type": "object",
"properties": map[string]interface{}{
"ssn": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The Social Security Number of the owner, if provided.",
},
"title": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The title or position held by this individual within the business.",
},
"owner_name": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The full name of the owner, partner, or officer.",
},
"date_of_birth": map[string]interface{}{
"type": []string{"string", "null"},
"extend:type": "date",
"description": "The date of birth of the owner, partner, or officer.",
},
"ownership_percent": map[string]interface{}{
"type": []string{"number", "null"},
"description": "The percentage of ownership held by this individual.",
},
},
"additionalProperties": false,
"required": []string{"ssn", "title", "owner_name", "date_of_birth", "ownership_percent"},
},
"description": "A list of owners, partners, or officers for the applicant's business. Each entry includes identifying and ownership information.",
},
"website": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The website address (URL) for the applicant's business, if provided.",
},
"dba_name": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The 'doing business as' name, if different from the legal name. This is an alternate business name under which the applicant operates.",
},
"naic_code": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The NAIC (National Association of Insurance Commissioners) code associated with the insurer or policy. This is a numeric or alphanumeric code used for regulatory identification.",
},
"agent_name": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The full name of the agent or broker responsible for the application. May be labeled as 'Agent Name', 'Producer', or similar.",
},
"fax_number": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The fax number for the applicant or business, if provided.",
},
"agency_code": map[string]interface{}{
"type": []string{"string", "null"},
"description": "A unique code or identifier for the agency, if provided. May be labeled as 'Agency Code', 'Producer Code', or similar.",
},
"agency_name": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The name of the insurance agency or brokerage handling the application. This is the organization representing the applicant to the insurer.",
},
"billing_plan": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The selected billing plan for the policy, such as 'Direct Bill', 'Agency Bill', etc. May be indicated by checkboxes or text.",
},
"contact_name": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The name of the primary contact person for the application or business. May be labeled as 'Contact Name', 'Inspection Contact', or similar.",
},
"loss_history": map[string]interface{}{
"type": "array",
"items": map[string]interface{}{
"type": "object",
"properties": map[string]interface{}{
"status": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The current status of the claim or loss, such as 'Open', 'Closed', 'Pending', etc.",
},
"amount_paid": map[string]interface{}{
"type": []string{"number", "null"},
"description": "The amount paid to settle the claim or loss, if any.",
},
"description": map[string]interface{}{
"type": []string{"string", "null"},
"description": "A narrative description of the loss, claim, or incident.",
},
"date_of_loss": map[string]interface{}{
"type": []string{"string", "null"},
"extend:type": "date",
"description": "The date the loss, claim, or incident occurred.",
},
"type_of_loss": map[string]interface{}{
"type": []string{"string", "null"},
"description": "A brief description of the type of loss, such as 'Property Damage', 'Liability', etc.",
},
"amount_reserved": map[string]interface{}{
"type": []string{"number", "null"},
"description": "The amount reserved for the claim or loss, if any.",
},
},
"additionalProperties": false,
"required": []string{"status", "amount_paid", "description", "date_of_loss", "type_of_loss", "amount_reserved"},
},
"description": "A list of claims, lawsuits, or incidents reported in the past 5 years. Each entry represents a separate loss event.",
},
"payment_plan": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The selected payment plan for the policy, such as 'Annual', 'Semi-Annual', etc. May be indicated by checkboxes or text.",
},
"business_type": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The legal structure of the applicant's business, such as 'Sole Proprietorship', 'LLC', 'Corporation', 'Partnership', etc. May be indicated by checkboxes or text.",
},
"contact_title": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The job title or role of the primary contact person, such as 'Owner', 'Manager', etc.",
},
"email_address": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The primary email address for the applicant or business. Used for electronic correspondence.",
},
"landlord_name": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The name of the landlord or property owner, if the premises are leased.",
},
"policy_number": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The unique identifier assigned to the insurance policy, if available at the time of application. May include letters, numbers, or special characters. Commonly labeled as 'Policy Number' or 'Policy #'.",
},
"primary_phone": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The main telephone number for the applicant or business. May include area code and extension.",
},
"federal_tax_id": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The Federal Employer Identification Number (FEIN) or Social Security Number (SSN) for the applicant. Used for tax and regulatory purposes.",
},
"landlord_phone": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The phone number of the landlord or property owner, if the premises are leased.",
},
"premises_owned": map[string]interface{}{
"type": []string{"boolean", "null"},
"description": "Indicates whether the applicant owns the business premises. True if owned, false if not.",
},
"signature_date": map[string]interface{}{
"type": []string{"string", "null"},
"extend:type": "date",
"description": "The date the applicant signed the application, certifying its accuracy.",
},
"audit_frequency": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The frequency of premium audit for the policy, such as 'Annually', 'Semi-Annually', etc.",
},
"mailing_address": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The complete mailing address for the applicant, including street, city, state, and ZIP code. This is the primary address for correspondence.",
},
"premises_leased": map[string]interface{}{
"type": []string{"boolean", "null"},
"description": "Indicates whether the applicant leases the business premises. True if leased, false if not.",
},
"secondary_phone": map[string]interface{}{
"type": []string{"string", "null"},
"description": "An alternate or secondary telephone number for the applicant or business, if provided.",
},
"application_date": map[string]interface{}{
"type": []string{"string", "null"},
"extend:type": "date",
"description": "The date the commercial insurance application was completed or submitted. This is the official date of the application and may be labeled as 'Date', 'Application Date', or similar.",
},
"number_of_owners": map[string]interface{}{
"type": []string{"integer", "null"},
"description": "The total number of owners, partners, or officers associated with the applicant's business.",
},
"physical_address": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The physical address of the applicant's business, if different from the mailing address. Includes street, city, state, and ZIP code.",
},
"agency_customer_id": map[string]interface{}{
"type": []string{"string", "null"},
"description": "A unique identifier assigned by the agency to the applicant or account. May be labeled as 'Agency Customer ID', 'Client ID', or similar.",
},
"applicant_signature": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The name or representation of the applicant's signature, indicating certification of the information provided.",
},
"agent_license_number": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The license number of the agent or broker, if provided. This is a regulatory identifier for the individual handling the application.",
},
"applicant_legal_name": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The legal name of the business or individual applying for insurance. This is the primary insured entity and may include DBA (doing business as) names.",
},
"business_description": map[string]interface{}{
"type": []string{"string", "null"},
"description": "A description of the applicant's primary business operations, activities, or services provided. May be labeled as 'Nature of Business', 'Description of Operations', or similar.",
},
"total_annual_payroll": map[string]interface{}{
"type": []string{"number", "null"},
"description": "The total annual payroll for all employees of the applicant's business, typically in the local currency.",
},
"year_business_started": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The year the applicant's business was established or began operations. May be labeled as 'Year Business Started', 'Date Business Started', or similar.",
},
"el_each_accident_limit": map[string]interface{}{
"type": []string{"number", "null"},
"description": "The employer's liability limit for each accident under workers compensation coverage.",
},
"package_policy_premium": map[string]interface{}{
"type": "object",
"properties": map[string]interface{}{
"amount": map[string]interface{}{
"type": []string{"number", "null"},
},
"iso_4217_currency_code": map[string]interface{}{
"type": []string{"string", "null"},
},
},
"additionalProperties": false,
"required": []string{"amount", "iso_4217_currency_code"},
"extend:type": "currency",
"description": "The total premium amount for the package policy, if provided. This is the cost of the insurance coverage for the policy term.",
},
"el_disease_policy_limit": map[string]interface{}{
"type": []string{"number", "null"},
"description": "The employer's liability policy limit for disease under workers compensation coverage.",
},
"proposed_effective_date": map[string]interface{}{
"type": []string{"string", "null"},
"extend:type": "date",
"description": "The proposed effective date for the insurance policy. This is the date coverage is requested to begin.",
},
"estimated_annual_revenue": map[string]interface{}{
"type": []string{"number", "null"},
"description": "The estimated or actual annual revenue for the applicant's business, typically in the local currency.",
},
"general_liability_limits": map[string]interface{}{
"type": "object",
"properties": map[string]interface{}{
"each_occurrence": map[string]interface{}{
"type": []string{"number", "null"},
"description": "The limit for each occurrence under general liability coverage.",
},
"medical_expense": map[string]interface{}{
"type": []string{"number", "null"},
"description": "The limit for medical expense coverage.",
},
"general_aggregate": map[string]interface{}{
"type": []string{"number", "null"},
"description": "The general aggregate limit for general liability coverage.",
},
"damage_to_rented_premises": map[string]interface{}{
"type": []string{"number", "null"},
"description": "The limit for damage to rented premises coverage.",
},
"personal_advertising_injury": map[string]interface{}{
"type": []string{"number", "null"},
"description": "The limit for personal and advertising injury coverage.",
},
"products_completed_operations_aggregate": map[string]interface{}{
"type": []string{"number", "null"},
"description": "The aggregate limit for products and completed operations coverage.",
},
},
"additionalProperties": false,
"required": []string{"each_occurrence", "medical_expense", "general_aggregate", "damage_to_rented_premises", "personal_advertising_injury", "products_completed_operations_aggregate"},
"description": "The requested or quoted limits for general liability coverage. Each property represents a specific coverage limit.",
},
"proposed_expiration_date": map[string]interface{}{
"type": []string{"string", "null"},
"extend:type": "date",
"description": "The proposed expiration date for the insurance policy. This is the date coverage is requested to end.",
},
"workers_compensation_code": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The workers compensation classification code applicable to the applicant's business.",
},
"square_footage_of_premises": map[string]interface{}{
"type": []string{"integer", "null"},
"description": "The total square footage of the business premises occupied by the applicant.",
},
"workers_compensation_state": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The state in which workers compensation coverage is requested or provided.",
},
"business_classification_code": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The business classification code (such as NAICS or SIC) that categorizes the applicant's industry or operations.",
},
"number_of_seasonal_employees": map[string]interface{}{
"type": []string{"integer", "null"},
"description": "The number of seasonal or temporary employees working for the applicant's business.",
},
"number_of_full_time_employees": map[string]interface{}{
"type": []string{"integer", "null"},
"description": "The number of full-time employees working for the applicant's business.",
},
"number_of_part_time_employees": map[string]interface{}{
"type": []string{"integer", "null"},
"description": "The number of part-time employees working for the applicant's business.",
},
"el_disease_each_employee_limit": map[string]interface{}{
"type": []string{"number", "null"},
"description": "The employer's liability limit for disease for each employee under workers compensation coverage.",
},
"business_classification_description": map[string]interface{}{
"type": []string{"string", "null"},
"description": "A textual description of the business classification or industry for the applicant.",
},
"workers_compensation_annual_payroll": map[string]interface{}{
"type": []string{"number", "null"},
"description": "The estimated annual payroll for workers compensation purposes.",
},
"general_liability_coverages_requested": map[string]interface{}{
"type": []string{"string", "null"},
"description": "A list or description of general liability coverages requested, such as 'Premises Operations', 'Products Completed Operations', 'Contractual Liability', etc. May be indicated by checkboxes or text.",
},
},
"required": []string{
"county", "owners", "website", "dba_name", "naic_code", "agent_name", "fax_number",
"agency_code", "agency_name", "billing_plan", "contact_name", "loss_history", "payment_plan",
"business_type", "contact_title", "email_address", "landlord_name", "policy_number",
"primary_phone", "federal_tax_id", "landlord_phone", "premises_owned", "signature_date",
"audit_frequency", "mailing_address", "premises_leased", "secondary_phone", "application_date",
"number_of_owners", "physical_address", "agency_customer_id", "applicant_signature",
"agent_license_number", "applicant_legal_name", "business_description", "total_annual_payroll",
"year_business_started", "el_each_accident_limit", "package_policy_premium",
"el_disease_policy_limit", "proposed_effective_date", "estimated_annual_revenue",
"general_liability_limits", "proposed_expiration_date", "workers_compensation_code",
"square_footage_of_premises", "workers_compensation_state", "business_classification_code",
"number_of_seasonal_employees", "number_of_full_time_employees", "number_of_part_time_employees",
"el_disease_each_employee_limit", "business_classification_description",
"workers_compensation_annual_payroll", "general_liability_coverages_requested",
},
"additionalProperties": false,
},
"baseProcessor": "extraction_performance",
"advancedOptions": map[string]interface{}{
"reviewAgent": map[string]interface{}{
"enabled": true,
},
"advancedMultimodalEnabled": true,
},
},
},
},
},
}
func main() {
workflowName := workflow["name"].(string)
fmt.Printf("Deploying \"%s\"…\n", workflowName)
if state.WorkflowID != "" {
fmt.Printf("✓ workflow already provisioned (%s) — updating steps\n", state.WorkflowID)
_, err := apiCall("POST", fmt.Sprintf("/workflows/%s", state.WorkflowID), map[string]interface{}{
"steps": workflow["steps"],
})
if err != nil {
fmt.Fprintf(os.Stderr, "%v\n", err)
os.Exit(1)
}
} else {
// Try to find existing workflow with same name
query := url.QueryEscape(workflowName)
list, err := apiCall("GET", fmt.Sprintf("/workflows?name=%s", query), nil)
if err == nil {
var items []map[string]interface{}
if data, ok := list["data"].([]interface{}); ok {
for _, item := range data {
items = append(items, item.(map[string]interface{}))
}
} else if data, ok := list["items"].([]interface{}); ok {
for _, item := range data {
items = append(items, item.(map[string]interface{}))
}
}
for _, item := range items {
if name, ok := item["name"].(string); ok && name == workflowName {
if id, ok := item["id"].(string); ok {
state.WorkflowID = id
saveState()
fmt.Printf("✓ workflow \"%s\" found in your account (%s) — updating steps\n", workflowName, id)
_, err := apiCall("POST", fmt.Sprintf("/workflows/%s", id), map[string]interface{}{
"steps": workflow["steps"],
})
if err != nil {
fmt.Fprintf(os.Stderr, "%v\n", err)
os.Exit(1)
}
deployVersion()
printDone(state.WorkflowID)
return
}
}
}
}
// Create new workflow
created, err := apiCall("POST", "/workflows", workflow)
if err != nil {
fmt.Fprintf(os.Stderr, "%v\n", err)
os.Exit(1)
}
var wfID string
if id, ok := created["id"].(string); ok {
wfID = id
} else if wf, ok := created["workflow"].(map[string]interface{}); ok {
if id, ok := wf["id"].(string); ok {
wfID = id
}
}
if wfID == "" {
fmt.Fprintf(os.Stderr, "Could not read created workflow id from response\n")
os.Exit(1)
}
state.WorkflowID = wfID
saveState()
fmt.Printf("+ created workflow (%s)\n", wfID)
}
deployVersion()
printDone(state.WorkflowID)
}
func deployVersion() {
_, _ = apiCall("POST", fmt.Sprintf("/workflows/%s/versions", state.WorkflowID), map[string]interface{}{})
}
func printDone(wfID string) {
fmt.Println("\nDone. Run documents through it with:")
fmt.Printf(" POST %s/workflow_runs { workflow: { id: \"%s\" }, file: { url: \"https://…\" } }\n", API, wfID)
fmt.Println("Or open the workflow in the Extend dashboard to review and deploy it.")
}This template processes ACORD commercial insurance application forms, capturing applicant and agency information, selected coverage types, policy effective dates, and billing arrangements. It handles multi-section checkbox selections and structured policy metadata for underwriting workflows. First, it classifies a document as an ACORD form vs not an ACORD form. Then, it routes it to a personalized extractor.