Extracts insured party, insurers, coverage details, and certificate information from liability insurance documents.
A Certificate of Liability Insurance is an ACORD-standard document issued by an insurance producer that verifies an insured party's active coverage, detailing policyholder information, multiple insurers with their NAIC codes, policy numbers, coverage types, limits, effective dates, and special provisions for contractual and risk management purposes. This template takes in Certificate of Liability Insurance and outputs markdown (.md) capturing the certificate's full text and layout structure, and JSON (.json) with structured fields including insured and certificate holder details, producer contact information, complete insurer listings with NAIC codes, and policy-level data encompassing coverage types, limits, dates, and endorsement flags per the extraction schema 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 — 15 fieldschangedadvancedOptions.advancedMultimodalEnabledtruechangedadvancedOptions.reviewAgent.enabledtruechangedbaseProcessor"extraction_performance"You can learn more about Extract configuration in Extend's Extract documentation.
{
"name": "Certificate of Liability Insurance 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": "extraction2"
}
]
},
{
"name": "extraction2",
"type": "EXTRACT",
"config": {
"extractorConfig": {
"schema": {
"type": "object",
"required": [
"insurers",
"policies",
"insured_name",
"producer_name",
"producer_email",
"producer_phone",
"insured_address",
"revision_number",
"certificate_date",
"certificate_number",
"producer_contact_name",
"certificate_holder_name",
"authorized_representative",
"description_of_operations",
"certificate_holder_address"
],
"properties": {
"insurers": {
"type": "array",
"items": {
"type": "object",
"required": [
"naic_number",
"insurer_name",
"insurer_letter"
],
"properties": {
"naic_number": {
"type": [
"string",
"null"
],
"description": "The NAIC (National Association of Insurance Commissioners) number for the insurer, if provided."
},
"insurer_name": {
"type": [
"string",
"null"
],
"description": "The full name of the insurance company providing coverage."
},
"insurer_letter": {
"type": [
"string",
"null"
],
"description": "The letter designation (e.g., 'A', 'B', 'C') used to reference this insurer in the policy table."
}
},
"additionalProperties": false
},
"description": "A list of insurance companies (insurers) providing coverage under the policies referenced in this certificate. Each entry includes the insurer's name, letter designation, and NAIC number if available."
},
"policies": {
"type": "array",
"items": {
"type": "object",
"required": [
"policy_number",
"insurer_letter",
"coverage_limits",
"type_of_insurance",
"additional_insured",
"subrogation_waived",
"policy_effective_date",
"policy_expiration_date"
],
"properties": {
"policy_number": {
"type": [
"string",
"null"
],
"description": "The unique identifier or number assigned to this insurance policy."
},
"insurer_letter": {
"type": [
"string",
"null"
],
"description": "The letter designation (e.g., 'A', 'B', 'C') corresponding to the insurer providing this policy, as referenced in the insurers list."
},
"coverage_limits": {
"type": "array",
"items": {
"type": "object",
"required": [
"limit_amount",
"coverage_type"
],
"properties": {
"limit_amount": {
"type": [
"number",
"null"
],
"description": "The monetary amount of the coverage limit for this coverage type, excluding currency symbols and formatting."
},
"coverage_type": {
"type": [
"string",
"null"
],
"description": "The specific type of coverage or limit (e.g., 'Each Occurrence', 'General Aggregate', 'Bodily Injury', 'Property Damage', etc.)."
}
},
"additionalProperties": false
},
"description": "A list of specific coverage limits and their corresponding amounts for this policy. Each entry represents a particular coverage type and its monetary limit."
},
"type_of_insurance": {
"type": [
"string",
"null"
],
"description": "The type or category of insurance provided by this policy (e.g., 'Commercial General Liability', 'Automobile Liability', 'Workers Compensation', 'Umbrella Liability', etc.)."
},
"additional_insured": {
"type": [
"string",
"null"
],
"description": "Indicates whether this policy includes an additional insured provision. May be marked as 'Y', 'Yes', or similar, or left blank if not applicable."
},
"subrogation_waived": {
"type": [
"string",
"null"
],
"description": "Indicates if subrogation rights are waived for this policy. May be marked as 'Y', 'Yes', or similar, or left blank if not applicable."
},
"policy_effective_date": {
"type": [
"string",
"null"
],
"description": "The date on which this insurance policy becomes effective and coverage begins.",
"extend:type": "date"
},
"policy_expiration_date": {
"type": [
"string",
"null"
],
"description": "The date on which this insurance policy expires and coverage ends.",
"extend:type": "date"
}
},
"additionalProperties": false
},
"description": "A list of insurance policies covered by this certificate. Each entry details a specific policy, including type, insurer, policy number, effective and expiration dates, and coverage limits. This array captures the core insurance coverage information."
},
"insured_name": {
"type": [
"string",
"null"
],
"description": "The full legal name of the insured party or business entity covered by the insurance policies listed in this certificate."
},
"producer_name": {
"type": [
"string",
"null"
],
"description": "The name of the insurance agency, broker, or producer responsible for issuing this certificate. This is the entity facilitating the insurance coverage."
},
"producer_email": {
"type": [
"string",
"null"
],
"description": "The email address for the insurance producer or agency, used for correspondence regarding this certificate."
},
"producer_phone": {
"type": [
"string",
"null"
],
"description": "The phone number for the insurance producer or agency, including area code and any extensions if present."
},
"insured_address": {
"type": [
"string",
"null"
],
"description": "The mailing address of the insured party, including street, city, state, and postal code. This is the address associated with the insured entity."
},
"revision_number": {
"type": [
"string",
"null"
],
"description": "The revision or version number of this certificate, indicating if it has been updated or reissued. May be labeled as 'Revision Number' or similar."
},
"certificate_date": {
"type": [
"string",
"null"
],
"description": "The date on which this certificate of liability insurance was issued. This is the official date of the document and is often found near the top, but may appear elsewhere depending on the layout.",
"extend:type": "date"
},
"certificate_number": {
"type": [
"string",
"null"
],
"description": "The unique identifier assigned to this certificate of insurance. This number is used for tracking and reference purposes and may be labeled as 'Certificate Number', 'Cert No.', or similar."
},
"producer_contact_name": {
"type": [
"string",
"null"
],
"description": "The name of the primary contact person at the producer or agency who can be reached for questions about this certificate."
},
"certificate_holder_name": {
"type": [
"string",
"null"
],
"description": "The name of the certificate holder, i.e., the entity or individual to whom this certificate is issued as evidence of insurance."
},
"authorized_representative": {
"type": [
"string",
"null"
],
"description": "The name or signature of the authorized representative or agent who has validated or signed this certificate."
},
"description_of_operations": {
"type": [
"string",
"null"
],
"description": "Any additional remarks, descriptions of operations, locations, vehicles, or special provisions related to the insurance coverage. This may include notes about additional insureds, exclusions, or endorsements."
},
"certificate_holder_address": {
"type": [
"string",
"null"
],
"description": "The address of the certificate holder, including street, suite, city, state, and postal code."
}
},
"additionalProperties": false
},
"baseProcessor": "extraction_performance",
"advancedOptions": {
"reviewAgent": {
"enabled": true
},
"advancedMultimodalEnabled": true
}
}
}
}
]
}# Certificate of Liability Insurance Processing — Extend AI Skill
## What this pipeline does
Ingests a Certificate of Liability Insurance (ACORD-standard form) and extracts structured data about insured parties, producers, insurers, policies, and coverage limits into JSON. First parses the document to markdown with agentic OCR (handles scans, handwriting, complex layouts), then extracts 15+ fields plus nested arrays of insurers and policies with per-policy coverage limits. Output includes policy dates, amounts, additional insured flags, and subrogation waivers—everything needed for risk management and contractual compliance verification.
## When to use this
- **Contract procurement workflows**: Verify that a contractor or vendor has required coverage limits before work begins
- **Certificate repository**: Ingest certificates at scale, extract to searchable JSON, populate insurance tracking databases
- **Risk renewal monitoring**: Extract expiration dates and coverage types to alert when policies need renewal
- **Automated endorsement checks**: Pull additional insured and subrogation waiver flags to confirm policy meets contract terms
- **Multi-insurer policy analysis**: Parse certificates with multiple insurers and policies side-by-side, correlate by letter designation
## Processor pipeline
### Step 1: Parse (`parse_performance` + agentic OCR)
**Purpose**: Convert certificate (PDF, scan, or handwritten annotations) to machine-readable markdown.
**Config**:
- `engine: "parse_performance"` — balances speed and accuracy; sufficient for most certificates
- `blockOptions.text.agentic.enabled: true` — enables visual reasoning for complex table layouts, handwritten notes, and variable form formatting (ACORD 25 forms have many variations)
- `chunkingStrategy.type: "document"` — keeps entire certificate as one logical unit (vs. per-page chunks), which improves extraction accuracy on cross-page policy tables
**Why**: Certificates are structured but variable. Agentic OCR interprets table headers, multi-column layouts, and checkboxes more reliably than light parsing. Document-level chunking preserves policy cross-references (policy letter → insurer letter correspondence).
### Step 2: Extract (`extraction_performance` + review agent)
**Purpose**: Pull 15+ top-level fields and nested structures (insurers array, policies array with coverage_limits sub-array) into validated JSON.
**Config**:
- `baseProcessor: "extraction_performance"` — high-accuracy extractor; certificates are high-value, low-volume documents where speed is less critical than precision
- `advancedOptions.reviewAgent.enabled: true` — post-extraction validation pass checks for logical consistency (e.g., policy insurer_letter matches an entry in insurers array), catches hallucinations
- `advancedOptions.advancedMultimodalEnabled: true` — leverages layout and visual cues for field positioning (certificate fields have fixed positions on ACORD forms)
**Why**: Insurance data is legally binding. Review agent catches extraction errors before they propagate downstream. Multimodal extraction reads form field boxes, checkmarks, and numeric tables more accurately than text alone.
---
## TypeScript implementation
---
## CLI equivalent
```bash
# Step 1: Parse with agentic OCR
extend parse cert.pdf \
--block-options-text-agentic-enabled true \
--chunking-strategy-type document
# Step 2: Extract into JSON using schema file
extend extract cert.pdf \
--schema certificate-schema.json \
--base-processor extraction_performance \
--review-agent-enabled true \
--advanced-multimodal-enabled true > extracted.json
```
**schema file** (`certificate-schema.json`):
```json
{
"type": "object",
"properties": {
"insurers": {
"type": "array",
"items": {
"type": "object",
"properties": {
"naic_number": { "type": ["string", "null"] },
"insurer_name": { "type": ["string", "null"] },
"insurer_letter": { "type": ["string", "null"] }
}
}
},
"policies": {
"type": "array",
"items": {
"type": "object",
"properties": {
"policy_number": { "type": ["string", "null"] },
"insurer_letter": { "type": ["string", "null"] },
"coverage_limits": {
"type": "array",
"items": {
"type": "object",
"properties": {
"limit_amount": { "type": ["number", "null"] },
"coverage_type": { "type": ["string", "null"] }
}
}
},
"type_of_insurance": { "type": ["string", "null"] },
"additional_insured": { "type": ["string", "null"] },
"subrogation_waived": { "type": ["string", "null"] },
"policy_effective_date": { "type": ["string", "null"] },
"policy_expiration_date": { "type": ["string", "null"] }
}
}
},
"insured_name": { "type": ["string", "null"] },
"producer_name": { "type": ["string", "null"] },
"producer_email": { "type": ["string", "null"] },
"producer_phone": { "type": ["string", "null"] },
"insured_address": { "type": ["string", "null"] },
"revision_import { ExtendClient, extendDate, extendCurrency } from "extend-ai";
import { z } from "zod";
import fs from "fs";
const client = new ExtendClient({ token: process.env.EXTEND_API_KEY });
// Define the Zod schema matching the certificate structure
const certificateSchema = z.object({
// Insurer entries: each has a name, NAIC number, and letter designation
insurers: z.array(
z.object({
naic_number: z.string().nullable().describe(
"The NAIC (National Association of Insurance Commissioners) number for the insurer, if provided."
),
insurer_name: z.string().nullable().describe(
"The full name of the insurance company providing coverage."
),
insurer_letter: z.string().nullable().describe(
"The letter designation (e.g., 'A', 'B', 'C') used to reference this insurer in the policy table."
),
})
).describe(
"A list of insurance companies (insurers) providing coverage under the policies referenced in this certificate. Each entry includes the insurer's name, letter designation, and NAIC number if available."
),
// Policy entries: each policy references an insurer by letter and lists coverage limits
policies: z.array(
z.object({
policy_number: z.string().nullable().describe(
"The unique identifier or number assigned to this insurance policy."
),
insurer_letter: z.string().nullable().describe(
"The letter designation (e.g., 'A', 'B', 'C') corresponding to the insurer providing this policy, as referenced in the insurers list."
),
coverage_limits: z.array(
z.object({
limit_amount: z.number().nullable().describe(
"The monetary amount of the coverage limit for this coverage type, excluding currency symbols and formatting."
),
coverage_type: z.string().nullable().describe(
"The specific type of coverage or limit (e.g., 'Each Occurrence', 'General Aggregate', 'Bodily Injury', 'Property Damage', etc.)."
),
})
).describe(
"A list of specific coverage limits and their corresponding amounts for this policy. Each entry represents a particular coverage type and its monetary limit."
),
type_of_insurance: z.string().nullable().describe(
"The type or category of insurance provided by this policy (e.g., 'Commercial General Liability', 'Automobile Liability', 'Workers Compensation', 'Umbrella Liability', etc.)."
),
additional_insured: z.string().nullable().describe(
"Indicates whether this policy includes an additional insured provision. May be marked as 'Y', 'Yes', or similar, or left blank if not applicable."
),
subrogation_waived: z.string().nullable().describe(
"Indicates if subrogation rights are waived for this policy. May be marked as 'Y', 'Yes', or similar, or left blank if not applicable."
),
policy_effective_date: extendDate().describe(
"The date on which this insurance policy becomes effective and coverage begins."
),
policy_expiration_date: extendDate().describe(
"The date on which this insurance policy expires and coverage ends."
),
})
).describe(
"A list of insurance policies covered by this certificate. Each entry details a specific policy, including type, insurer, policy number, effective and expiration dates, and coverage limits. This array captures the core insurance coverage information."
),
// Top-level fields: insured and producer information
insured_name: z.string().nullable().describe(
"The full legal name of the insured party or business entity covered by the insurance policies listed in this certificate."
),
producer_name: z.string().nullable().describe(
"The name of the insurance agency, broker, or producer responsible for issuing this certificate. This is the entity facilitating the insurance coverage."
),
producer_email: z.string().nullable().describe(
"The email address for the insurance producer or agency, used for correspondence regarding this certificate."
),
producer_phone: z.string().nullable().describe(
"The phone number for the insurance producer or agency, including area code and any extensions if present."
),
insured_address: z.string().nullable().describe(
"The mailing address of the insured party, including street, city, state, and postal code. This is the address associated with the insured entity."
),
revision_number: z.string().nullable().describe(
"The revision or version number of this certificate, indicating if it has been updated or reissued. May be labeled as 'Revision Number' or similar."
),
certificate_date: extendDate().describe(
"The date on which this certificate of liability insurance was issued. This is the official date of the document and is often found near the top, but may appear elsewhere depending on the layout."
),
certificate_number: z.string().nullable().describe(
"The unique identifier assigned to this certificate of insurance. This number is used for tracking and reference purposes and may be labeled as 'Certificate Number', 'Cert No.', or similar."
),
producer_contact_name: z.string().nullable().describe(
"The name of the primary contact person at the producer or agency who can be reached for questions about this certificate."
),
certificate_holder_name: z.string().nullable().describe(
"The name of the certificate holder, i.e., the entity or individual to whom this certificate is issued as evidence of insurance."
),
authorized_representative: z.string().nullable().describe(
"The name or signature of the authorized representative or agent who has validated or signed this certificate."
),
description_of_operations: z.string().nullable().describe(
"Any additional remarks, descriptions of operations, locations, vehicles, or special provisions related to the insurance coverage. This may include notes about additional insureds, exclusions, or endorsements."
),
certificate_holder_address: z.string().nullable().describe(
"The address of the certificate holder, including street, suite, city, state, and postal code."
),
});
export async function processCertificateOfLiabilityInsurance(filePath: string) {
// Convert local file to base64 data URL for SDK consumption
const fileBuffer = fs.readFileSync(filePath);
const base64Data = fileBuffer.toString("base64");
const dataUrl = `data:application/octet-stream;base64,${base64Data}`;
console.log(`Processing certificate: ${filePath}`);
try {
// Step 1: Parse the certificate to markdown (agentic OCR enabled)
console.log("Step 1: Parsing certificate with agentic OCR...");
const parseRun = await client.parseRuns.createAndPoll({
file: { url: dataUrl },
config: {
parseConfig: {
blockOptions: {
text: {
agentic: {
enabled: true, // Enable visual reasoning for complex layouts
},
},
},
chunkingStrategy: {
type: "document", // Keep entire certificate as one logical unit
},
},
},
});
if (parseRun.status !== "PROCESSED") {
throw new Error(`Parse failed with status: ${parseRun.status}`);
}
// Collect parsed markdown for reference (optional)
const markdownContent = parseRun.output.chunks
.map((chunk) => chunk.content)
.join("\n\n");
console.log(`✓ Parse complete. Document size: ${markdownContent.length} chars`);
// Step 2: Extract structured fields using Zod schema
console.log("Step 2: Extracting structured certificate fields...");
const extractRun = await client.extractRuns.createAndPoll({
file: { url: dataUrl },
config: {
schema: certificateSchema,
// Use extraction_performance for high accuracy
baseProcessor: "extraction_performance",
advancedOptions: {
reviewAgent: {
enabled: true, // Post-extraction validation
},
advancedMultimodalEnabled: true, // Use visual layout cues
},
},
});
if (extractRun.status !== "PROCESSED") {
throw new Error(`Extraction failed with status: ${extractRun.status}`);
}
const extracted = extractRun.output.value;
console.log("✓ Extraction complete.");
// Display results
console.log("\n=== CERTIFICATE SUMMARY ===");
console.log(`Insured: ${extracted.insured_name}`);
console.log(`Certificate #: ${extracted.certificate_number}`);
console.log(`Issued: ${extracted.certificate_date}`);
console.log(`Producer: ${extracted.producer_name} (${extracted.producer_email})`);
console.log(`\n=== INSURERS (${extracted.insurers.length}) ===`);
for (const insurer of extracted.insurers) {
console.log(
` [${insurer.insurer_letter}] ${insurer.insurer_name} (NAIC: ${insurer.naic_number || "N/A"})`
);
}
console.log(`\n=== POLICIES (${extracted.policies.length}) ===`);
for (const policy of extracted.policies) {
console.log(
` Policy: ${policy.policy_number} [Insurer: ${policy.insurer_letter}]`
);
console.log(
` Type: ${policy.type_of_insurance}`
);
console.log(
` Effective: ${policy.policy_effective_date} → Expires: ${policy.policy_expiration_date}`
);
console.log(
` Additional Insured: ${policy.additional_insured || "N/A"}, Subrogation Waived: ${policy.subrogation_waived || "N/A"}`
);
console.log(` Coverage Limits:`);
for (const limit of policy.coverage_limits) {
console.log(` - ${limit.coverage_type}: $${limit.limit_amount?.toLocaleString() || "N/A"}`);
}
}
console.log(`\n=== CERTIFICATE HOLDER ===`);
console.log(`Name: ${extracted.certificate_holder_name}`);
console.log(`Address: ${extracted.certificate_holder_address}`);
// Return the fully extracted object for downstream use
return extracted;
} catch (error) {
console.error("Error processing certificate:", error);
throw error;
}
}
// Execute if run directly
const filePath = process.argv[2];
if (!filePath) {
console.error("Usage: npx ts-node solution.ts <path-to-certificate.pdf>");
process.exit(1);
}
processCertificateOfLiabilityInsurance(filePath).then(() => {
console.log("\n✓ Processing complete.");
process.exit(0);
});import os
import base64
from extend_ai import Extend
client = Extend(token=os.environ["EXTEND_API_KEY"])
# Define the extraction schema as a dictionary matching the certificate structure
certificate_schema = {
"type": "object",
"properties": {
"insurers": {
"type": "array",
"items": {
"type": "object",
"properties": {
"naic_number": {
"type": ["string", "null"],
"description": "The NAIC (National Association of Insurance Commissioners) number for the insurer, if provided."
},
"insurer_name": {
"type": ["string", "null"],
"description": "The full name of the insurance company providing coverage."
},
"insurer_letter": {
"type": ["string", "null"],
"description": "The letter designation (e.g., 'A', 'B', 'C') used to reference this insurer in the policy table."
}
},
"additionalProperties": False,
"required": ["naic_number", "insurer_name", "insurer_letter"]
},
"description": "A list of insurance companies (insurers) providing coverage under the policies referenced in this certificate. Each entry includes the insurer's name, letter designation, and NAIC number if available."
},
"policies": {
"type": "array",
"items": {
"type": "object",
"properties": {
"policy_number": {
"type": ["string", "null"],
"description": "The unique identifier or number assigned to this insurance policy."
},
"insurer_letter": {
"type": ["string", "null"],
"description": "The letter designation (e.g., 'A', 'B', 'C') corresponding to the insurer providing this policy, as referenced in the insurers list."
},
"coverage_limits": {
"type": "array",
"items": {
"type": "object",
"properties": {
"limit_amount": {
"type": ["number", "null"],
"description": "The monetary amount of the coverage limit for this coverage type, excluding currency symbols and formatting."
},
"coverage_type": {
"type": ["string", "null"],
"description": "The specific type of coverage or limit (e.g., 'Each Occurrence', 'General Aggregate', 'Bodily Injury', 'Property Damage', etc.)."
}
},
"additionalProperties": False,
"required": ["limit_amount", "coverage_type"]
},
"description": "A list of specific coverage limits and their corresponding amounts for this policy. Each entry represents a particular coverage type and its monetary limit."
},
"type_of_insurance": {
"type": ["string", "null"],
"description": "The type or category of insurance provided by this policy (e.g., 'Commercial General Liability', 'Automobile Liability', 'Workers Compensation', 'Umbrella Liability', etc.)."
},
"additional_insured": {
"type": ["string", "null"],
"description": "Indicates whether this policy includes an additional insured provision. May be marked as 'Y', 'Yes', or similar, or left blank if not applicable."
},
"subrogation_waived": {
"type": ["string", "null"],
"description": "Indicates if subrogation rights are waived for this policy. May be marked as 'Y', 'Yes', or similar, or left blank if not applicable."
},
"policy_effective_date": {
"type": ["string", "null"],
"extend:type": "date",
"description": "The date on which this insurance policy becomes effective and coverage begins."
},
"policy_expiration_date": {
"type": ["string", "null"],
"extend:type": "date",
"description": "The date on which this insurance policy expires and coverage ends."
}
},
"additionalProperties": False,
"required": ["policy_number", "insurer_letter", "coverage_limits", "type_of_insurance", "additional_insured", "subrogation_waived", "policy_effective_date", "policy_expiration_date"]
},
"description": "A list of insurance policies covered by this certificate. Each entry details a specific policy, including type, insurer, policy number, effective and expiration dates, and coverage limits. This array captures the core insurance coverage information."
},
"insured_name": {
"type": ["string", "null"],
"description": "The full legal name of the insured party or business entity covered by the insurance policies listed in this certificate."
},
"producer_name": {
"type": ["string", "null"],
"description": "The name of the insurance agency, broker, or producer responsible for issuing this certificate. This is the entity facilitating the insurance coverage."
},
"producer_email": {
"type": ["string", "null"],
"description": "The email address for the insurance producer or agency, used for correspondence regarding this certificate."
},
"producer_phone": {
"type": ["string", "null"],
"description": "The phone number for the insurance producer or agency, including area code and any extensions if present."
},
"insured_address": {
"type": ["string", "null"],
"description": "The mailing address of the insured party, including street, city, state, and postal code. This is the address associated with the insured entity."
},
"revision_number": {
"type": ["string", "null"],
"description": "The revision or version number of this certificate, indicating if it has been updated or reissued. May be labeled as 'Revision Number' or similar."
},
"certificate_date": {
"type": ["string", "null"],
"extend:type": "date",
"description": "The date on which this certificate of liability insurance was issued. This is the official date of the document and is often found near the top, but may appear elsewhere depending on the layout."
},
"certificate_number": {
"type": ["string", "null"],
"description": "The unique identifier assigned to this certificate of insurance. This number is used for tracking and reference purposes and may be labeled as 'Certificate Number', 'Cert No.', or similar."
},
"producer_contact_name": {
"type": ["string", "null"],
"description": "The name of the primary contact person at the producer or agency who can be reached for questions about this certificate."
},
"certificate_holder_name": {
"type": ["string", "null"],
"description": "The name of the certificate holder, i.e., the entity or individual to whom this certificate is issued as evidence of insurance."
},
"authorized_representative": {
"type": ["string", "null"],
"description": "The name or signature of the authorized representative or agent who has validated or signed this certificate."
},
"description_of_operations": {
"type": ["string", "null"],
"description": "Any additional remarks, descriptions of operations, locations, vehicles, or special provisions related to the insurance coverage. This may include notes about additional insureds, exclusions, or endorsements."
},
"certificate_holder_address": {
"type": ["string", "null"],
"description": "The address of the certificate holder, including street, suite, city, state, and postal code."
}
},
"required": ["insurers", "policies", "insured_name", "producer_name", "producer_email", "producer_phone", "insured_address", "revision_number", "certificate_date", "certificate_number", "producer_contact_name", "certificate_holder_name", "authorized_representative", "description_of_operations", "certificate_holder_address"],
"additionalProperties": False
}
async def process_certificate_of_liability_insurance(file_path: str) -> dict:
"""Process a Certificate of Liability Insurance document."""
# Read file and convert to base64 data URL
with open(file_path, "rb") as f:
file_buffer = f.read()
base64_data = base64.b64encode(file_buffer).decode("utf-8")
data_url = f"data:application/octet-stream;base64,{base64_data}"
print(f"Processing certificate: {file_path}")
try:
# Step 1: Parse the certificate to markdown (agentic OCR enabled)
print("Step 1: Parsing certificate with agentic OCR...")
parse_run = await client.parse_runs.create_and_poll(
file={"url": data_url},
config={
"parse_config": {
"block_options": {
"text": {
"agentic": {
"enabled": True, # Enable visual reasoning for complex layouts
},
},
},
"chunking_strategy": {
"type": "document", # Keep entire certificate as one logical unit
},
},
},
)
if parse_run.status != "PROCESSED":
raise Exception(f"Parse failed with status: {parse_run.status}")
# Collect parsed markdown for reference (optional)
markdown_content = "\n\n".join(
chunk.content for chunk in parse_run.output.chunks
)
print(f"✓ Parse complete. Document size: {len(markdown_content)} chars")
# Step 2: Extract structured fields using schema
print("Step 2: Extracting structured certificate fields...")
extract_run = await client.extract_runs.create_and_poll(
file={"url": data_url},
config={
"schema": certificate_schema,
"base_processor": "extraction_performance",
"advanced_options": {
"review_agent": {
"enabled": True, # Post-extraction validation
},
"advanced_multimodal_enabled": True, # Use visual layout cues
},
},
)
if extract_run.status != "PROCESSED":
raise Exception(f"Extraction failed with status: {extract_run.status}")
extracted = extract_run.output.value
print("✓ Extraction complete.")
# Display results
print("\n=== CERTIFICATE SUMMARY ===")
print(f"Insured: {extracted.get('insured_name')}")
print(f"Certificate #: {extracted.get('certificate_number')}")
print(f"Issued: {extracted.get('certificate_date')}")
print(f"Producer: {extracted.get('producer_name')} ({extracted.get('producer_email')})")
insurers = extracted.get("insurers", [])
print(f"\n=== INSURERS ({len(insurers)}) ===")
for insurer in insurers:
print(
f" [{insurer.get('insurer_letter')}] {insurer.get('insurer_name')} (NAIC: {insurer.get('naic_number') or 'N/A'})"
)
policies = extracted.get("policies", [])
print(f"\n=== POLICIES ({len(policies)}) ===")
for policy in policies:
print(
f" Policy: {policy.get('policy_number')} [Insurer: {policy.get('insurer_letter')}]"
)
print(f" Type: {policy.get('type_of_insurance')}")
print(
f" Effective: {policy.get('policy_effective_date')} → Expires: {policy.get('policy_expiration_date')}"
)
print(
f" Additional Insured: {policy.get('additional_insured') or 'N/A'}, Subrogation Waived: {policy.get('subrogation_waived') or 'N/A'}"
)
print(" Coverage Limits:")
for limit in policy.get("coverage_limits", []):
limit_amount = limit.get("limit_amount")
formatted_amount = (
f"${limit_amount:,.2f}" if limit_amount is not None else "N/A"
)
print(f" - {limit.get('coverage_type')}: {formatted_amount}")
print("\n=== CERTIFICATE HOLDER ===")
print(f"Name: {extracted.get('certificate_holder_name')}")
print(f"Address: {extracted.get('certificate_holder_address')}")
# Return the fully extracted object for downstream use
return extracted
except Exception as error:
print(f"Error processing certificate: {error}")
raise
# Execute if run directly
if __name__ == "__main__":
import sys
import asyncio
if len(sys.argv) < 2:
print("Usage: python solution.py <path-to-certificate.pdf>")
sys.exit(1)
file_path = sys.argv[1]
asyncio.run(process_certificate_of_liability_insurance(file_path))
print("\n✓ Processing complete.")// Extend AI REST API client code — Extend does not publish an official Java SDK.
// This code calls the REST API directly using only java.net.http.HttpClient (no external deps).
import java.io.*;
import java.net.URI;
import java.net.http.*;
import java.nio.file.*;
import java.util.*;
import java.util.Base64;
public class CertificateOfLiabilityInsuranceProcessor {
private static final String API_BASE_URL = "https://api.extend.ai";
private static final String API_KEY = System.getenv("EXTEND_API_KEY");
static class Insurer {
public String naic_number;
public String insurer_name;
public String insurer_letter;
}
static class CoverageLimit {
public Double limit_amount;
public String coverage_type;
}
static class Policy {
public String policy_number;
public String insurer_letter;
public List<CoverageLimit> coverage_limits;
public String type_of_insurance;
public String additional_insured;
public String subrogation_waived;
public String policy_effective_date;
public String policy_expiration_date;
}
static class CertificateData {
public List<Insurer> insurers;
public List<Policy> policies;
public String insured_name;
public String producer_name;
public String producer_email;
public String producer_phone;
public String insured_address;
public String revision_number;
public String certificate_date;
public String certificate_number;
public String producer_contact_name;
public String certificate_holder_name;
public String authorized_representative;
public String description_of_operations;
public String certificate_holder_address;
}
public static void main(String[] args) throws Exception {
if (args.length == 0) {
System.err.println("Usage: java CertificateOfLiabilityInsuranceProcessor <path-to-certificate.pdf>");
System.exit(1);
}
String filePath = args[0];
processCertificateOfLiabilityInsurance(filePath);
}
public static CertificateData processCertificateOfLiabilityInsurance(String filePath) throws Exception {
byte[] fileBytes = Files.readAllBytes(Paths.get(filePath));
String base64Data = Base64.getEncoder().encodeToString(fileBytes);
String dataUrl = "data:application/octet-stream;base64," + base64Data;
System.out.println("Processing certificate: " + filePath);
try {
// Step 1: Parse the certificate to markdown (agentic OCR enabled)
System.out.println("Step 1: Parsing certificate with agentic OCR...");
String parseRunId = createParseRun(dataUrl);
Map<String, Object> parseRun = pollParseRun(parseRunId);
if (!"PROCESSED".equals(parseRun.get("status"))) {
throw new RuntimeException("Parse failed with status: " + parseRun.get("status"));
}
System.out.println("✓ Parse complete.");
// Step 2: Extract structured fields using schema
System.out.println("Step 2: Extracting structured certificate fields...");
String extractRunId = createExtractRun(dataUrl);
Map<String, Object> extractRun = pollExtractRun(extractRunId);
if (!"PROCESSED".equals(extractRun.get("status"))) {
throw new RuntimeException("Extraction failed with status: " + extractRun.get("status"));
}
CertificateData extracted = parseExtractedData(extractRun);
System.out.println("✓ Extraction complete.");
// Display results
System.out.println("\n=== CERTIFICATE SUMMARY ===");
System.out.println("Insured: " + extracted.insured_name);
System.out.println("Certificate #: " + extracted.certificate_number);
System.out.println("Issued: " + extracted.certificate_date);
System.out.println("Producer: " + extracted.producer_name + " (" + extracted.producer_email + ")");
System.out.println("\n=== INSURERS (" + extracted.insurers.size() + ") ===");
for (Insurer insurer : extracted.insurers) {
System.out.println(" [" + insurer.insurer_letter + "] " + insurer.insurer_name +
" (NAIC: " + (insurer.naic_number != null ? insurer.naic_number : "N/A") + ")");
}
System.out.println("\n=== POLICIES (" + extracted.policies.size() + ") ===");
for (Policy policy : extracted.policies) {
System.out.println(" Policy: " + policy.policy_number + " [Insurer: " + policy.insurer_letter + "]");
System.out.println(" Type: " + policy.type_of_insurance);
System.out.println(" Effective: " + policy.policy_effective_date + " → Expires: " + policy.policy_expiration_date);
System.out.println(" Additional Insured: " + (policy.additional_insured != null ? policy.additional_insured : "N/A") +
", Subrogation Waived: " + (policy.subrogation_waived != null ? policy.subrogation_waived : "N/A"));
System.out.println(" Coverage Limits:");
for (CoverageLimit limit : policy.coverage_limits) {
String amount = limit.limit_amount != null ? String.format("$%,.2f", limit.limit_amount) : "N/A";
System.out.println(" - " + limit.coverage_type + ": " + amount);
}
}
System.out.println("\n=== CERTIFICATE HOLDER ===");
System.out.println("Name: " + extracted.certificate_holder_name);
System.out.println("Address: " + extracted.certificate_holder_address);
System.out.println("\n✓ Processing complete.");
return extracted;
} catch (Exception error) {
System.err.println("Error processing certificate: " + error.getMessage());
error.printStackTrace();
throw error;
}
}
private static String createParseRun(String dataUrl) throws Exception {
String requestBody = """
{
"file": {"url": "%s"},
"config": {
"parseConfig": {
"blockOptions": {
"text": {
"agentic": {
"enabled": true
}
}
},
"chunkingStrategy": {
"type": "document"
}
}
}
}""".formatted(dataUrl.replace("\"", "\\\""));
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(API_BASE_URL + "/v1/parse-runs"))
.header("Authorization", "Bearer " + API_KEY)
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(requestBody))
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
Map<String, Object> json = parseJson(response.body());
return (String) json.get("id");
}
private static Map<String, Object> pollParseRun(String runId) throws Exception {
HttpClient client = HttpClient.newHttpClient();
int maxAttempts = 300;
int attempt = 0;
long delayMs = 1000;
while (attempt < maxAttempts) {
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(API_BASE_URL + "/v1/parse-runs/" + runId))
.header("Authorization", "Bearer " + API_KEY)
.GET()
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
Map<String, Object> json = parseJson(response.body());
if ("PROCESSED".equals(json.get("status")) || "FAILED".equals(json.get("status"))) {
return json;
}
Thread.sleep(delayMs);
attempt++;
}
throw new RuntimeException("Parse run polling timeout");
}
private static String createExtractRun(String dataUrl) throws Exception {
String schemaJson = """
{
"type": "object",
"properties": {
"insurers": {
"type": "array",
"items": {
"type": "object",
"properties": {
"naic_number": {"type": ["string", "null"]},
"insurer_name": {"type": ["string", "null"]},
"insurer_letter": {"type": ["string", "null"]}
},
"required": ["naic_number", "insurer_name", "insurer_letter"]
}
},
"policies": {
"type": "array",
"items": {
"type": "object",
"properties": {
"policy_number": {"type": ["string", "null"]},
"insurer_letter": {"type": ["string", "null"]},
"coverage_limits": {
"type": "array",
"items": {
"type": "object",
"properties": {
"limit_amount": {"type": ["number", "null"]},
"coverage_type": {"type": ["string", "null"]}
},
"required": ["limit_amount", "coverage_type"]
}
},
"type_of_insurance": {"type": ["string", "null"]},
"additional_insured": {"type": ["string", "null"]},
"subrogation_waived": {"type": ["string", "null"]},
"policy_effective_date": {"type": ["string", "null"], "extend:type": "date"},
"policy_expiration_date": {"type": ["string", "null"], "extend:type": "date"}
},
"required": ["policy_number", "insurer_letter", "coverage_limits", "type_of_insurance",
"additional_insured", "subrogation_waived", "policy_effective_date", "policy_expiration_date"]
}
},
"insured_name": {"type": ["string", "null"]},
"producer_name": {"type": ["string", "null"]},
"producer_email": {"type": ["string", "null"]},
"producer_phone": {"type": ["string", "null"]},
"insured_address": {"type": ["string", "null"]},
"revision_number": {"type": ["string", "null"]},
"certificate_date": {"type": ["string", "null"], "extend:type": "date"},
"certificate_number": {"type": ["string", "null"]},
"producer_contact_name": {"type": ["string", "null"]},
"certificate_holder_name": {"type": ["string", "null"]},
"authorized_representative": {"type": ["string", "null"]},
"description_of_operations": {"type": ["string", "null"]},
"certificate_holder_address": {"type": ["string", "null"]}
},
"required": ["insurers", "policies", "insured_name", "producer_name", "producer_email",
"producer_phone", "insured_address", "revision_number", "certificate_date",
"certificate_number", "producer_contact_name", "certificate_holder_name",
"authorized_representative", "description_of_operations", "certificate_holder_address"]
}""";
String requestBody = """
{
"file": {"url": "%s"},
"config": {
"schema": %s,
"baseProcessor": "extraction_performance",
"advancedOptions": {
"reviewAgent": {
"enabled": true
},
"advancedMultimodalEnabled": true
}
}
}""".formatted(dataUrl.replace("\"", "\\\""), schemaJson);
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(API_BASE_URL + "/v1/extract-runs"))
.header("Authorization", "Bearer " + API_KEY)
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(requestBody))
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
Map<String, Object> json = parseJson(response.body());
return (String) json.get("id");
}
private static Map<String, Object> pollExtractRun(String runId) throws Exception {
HttpClient client = HttpClient.newHttpClient();
int maxAttempts = 300;
int attempt = 0;
long delayMs = 1000;
while (attempt < maxAttempts) {
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(API_BASE_URL + "/v1/extract-runs/" + runId))
.header("Authorization", "Bearer " + API_KEY)
.GET()
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
Map<String, Object> json = parseJson(response.body());
if ("PROCESSED".equals(json.get("status")) || "FAILED".equals(json.get("status"))) {
return json;
}
Thread.sleep(delayMs);
attempt++;
}
throw new RuntimeException("Extract run polling timeout");
}
private static CertificateData parseExtractedData(Map<String, Object> extractRun) {
CertificateData data = new CertificateData();
Map<String, Object> output = (Map<String, Object>) extractRun.get("output");
Map<String, Object> value = (Map<String, Object>) output.get("value");
data.insured_name = (String) value.get("insured_name");
data.producer_name = (String) value.get("producer_name");
data.producer_email = (String) value.get("producer_email");
data.producer_phone = (String) value.get("producer_phone");
data.insured_address = (String) value.get("insured_address");
data.revision_number = (String) value.get("revision_number");
data.certificate_date = (String) value.get("certificate_date");
data.certificate_number = (String) value.get("certificate_number");
data.producer_contact_name = (String) value.get("producer_contact_name");
data.certificate_holder_name = (String) value.get("certificate_holder_name");
data.authorized_representative = (String) value.get("authorized_representative");
data.description_of_operations = (String) value.get("description_of_operations");
data.certificate_holder_address = (String) value.get("certificate_holder_address");
data.insurers = new ArrayList<>();
List<Map<String, Object>> insurersRaw = (List<Map<String, Object>>) value.get("insurers");
if (insurersRaw != null) {
for (Map<String, Object> ins : insurersRaw) {
Insurer i = new Insurer();
i.naic_number = (String) ins.get("naic_number");
i.insurer_name = (String) ins.get("insurer_name");
i.insurer_letter = (String) ins.get("insurer_letter");
data.insurers.add(i);
}
}
data.policies = new ArrayList<>();
List<Map<String, Object>> policiesRaw = (List<Map<String, Object>>) value.get("policies");
if (policiesRaw != null) {
for (Map<String, Object> pol : policiesRaw) {
Policy p = new Policy();
p.policy_number = (String) pol.get("policy_number");
p.insurer_letter = (String) pol.get("insurer_letter");
p.type_of_insurance = (String) pol.get("type_of_insurance");
p.additional_insured = (String) pol.get("additional_insured");
p.subrogation_waived = (String) pol.get("subrogation_waived");
p.policy_effective_date = (String) pol.get("policy_effective_date");
p.policy_expiration_date = (String) pol.get("policy_expiration_date");
p.coverage_limits = new ArrayList<>();
List<Map<String, Object>> limitsRaw = (List<Map<String, Object>>) pol.get("coverage_limits");
if (limitsRaw != null) {
for (Map<String, Object> lim : limitsRaw) {
CoverageLimit cl = new CoverageLimit();
Object amountObj = lim.get("limit_amount");
if (amountObj instanceof Number) {
cl.limit_amount = ((Number) amountObj).doubleValue();
}
cl.coverage_type = (String) lim.get("coverage_type");
p.coverage_limits.add(cl);
}
}
data.policies.add(p);
}
}
return data;
}
@SuppressWarnings("unchecked")
private static Map<String, Object> parseJson(String json) {
json = json.trim();
if (!json.startsWith("{")) {
throw new RuntimeException("Expected JSON object");
}
Map<String, Object> map = new LinkedHashMap<>();
int depth = 0;
StringBuilder key = new StringBuilder();
StringBuilder value = new StringBuilder();
boolean inString = false;
boolean inKey = true;
boolean escaped = false;
for (int i = 1; i < json.length() - 1; i++) {
char c = json.charAt(i);
if (escaped) {
if (inKey) key.append(c);
else value.append(c);
escaped = false;
continue;
}
if (c == '\\') {
escaped = true;
if (inKey) key.append(c);
else value.append(c);
continue;
}
if (c == '"') {
inString = !inString;
if (inKey) key.append(c);
else value.append(c);
continue;
}
if (inString) {
if (inKey) key.append(c);
else value.append(c);
continue;
}
if (c == ':') {
inKey = false;
continue;
}
if (c == ',' && depth == 0) {
String k = key.toString().trim();
if (k.startsWith("\"") && k.endsWith("\"")) {
k = k.substring(1, k.length() - 1);
}
String v = value.toString().trim();
map.put(k, parseValue(v));
key = new StringBuilder();
value = new StringBuilder();
inKey = true;
continue;
}
if (c == '{' || c == '[') {
depth++;
} else if (c == '}' || c == ']') {
depth--;
}
if (inKey) key.append(c);
else value.append(c);
}
if (key.length() > 0) {
String k = key.toString().trim();
if (k.startsWith("\"") && k.endsWith("\"")) {
k = k.substring(1, k.length() - 1);
}
String v = value.toString().trim();
map.put(k, parseValue(v));
}
return map;
}
private static Object parseValue(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("\\\"", "\"");
}
if (v.startsWith("[")) {
List<Object> list = new ArrayList<>();
String inner = v.substring(1, v.length() - 1).trim();
if (!inner.isEmpty()) {
int depth = 0;
StringBuilder item = new StringBuilder();
for (char c : inner.toCharArray()) {
if ((c == ',' || c == ']') && depth == 0) {
list.add(parseValue(item.toString().trim()));
item = new StringBuilder();
continue;
}
if (c == '{' || c == '[') depth++;
else if (c == '}' || c == ']') depth--;
item.append(c);
}
if (item.length() > 0) {
list.add(parseValue(item.toString().trim()));
}
}
return list;
}
if (v.startsWith("{")) {
return parseJson(v);
}
try {
if (v.contains(".")) return Double.parseDouble(v);
return Long.parseLong(v);
} catch (NumberFormatException e) {
return v;
}
}
}// This code calls the Extend REST API directly (https://api.extend.ai) using only Go's standard library.
// Extend does not publish an official Go SDK; this approach uses net/http and encoding/json only.
package main
import (
"bytes"
"encoding/base64"
"encoding/json"
"flag"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"time"
)
const extendAPIBase = "https://api.extend.ai"
// Insurer represents a single insurance company entry
type Insurer struct {
NAICNumber *string `json:"naic_number"`
InsurerName *string `json:"insurer_name"`
InsurerLetter *string `json:"insurer_letter"`
}
// CoverageLimit represents a single coverage limit within a policy
type CoverageLimit struct {
LimitAmount *float64 `json:"limit_amount"`
CoverageType *string `json:"coverage_type"`
}
// Policy represents a single insurance policy
type Policy struct {
PolicyNumber *string `json:"policy_number"`
InsurerLetter *string `json:"insurer_letter"`
CoverageLimits []CoverageLimit `json:"coverage_limits"`
TypeOfInsurance *string `json:"type_of_insurance"`
AdditionalInsured *string `json:"additional_insured"`
SubrogationWaived *string `json:"subrogation_waived"`
PolicyEffectiveDate *string `json:"policy_effective_date"`
PolicyExpirationDate *string `json:"policy_expiration_date"`
}
// Certificate represents the extracted certificate structure
type Certificate struct {
Insurers []Insurer `json:"insurers"`
Policies []Policy `json:"policies"`
InsuredName *string `json:"insured_name"`
ProducerName *string `json:"producer_name"`
ProducerEmail *string `json:"producer_email"`
ProducerPhone *string `json:"producer_phone"`
InsuredAddress *string `json:"insured_address"`
RevisionNumber *string `json:"revision_number"`
CertificateDate *string `json:"certificate_date"`
CertificateNumber *string `json:"certificate_number"`
ProducerContactName *string `json:"producer_contact_name"`
CertificateHolderName *string `json:"certificate_holder_name"`
AuthorizedRepresentative *string `json:"authorized_representative"`
DescriptionOfOperations *string `json:"description_of_operations"`
CertificateHolderAddress *string `json:"certificate_holder_address"`
}
// ParseRunOutput represents the parsed document output
type ParseRunOutput struct {
Chunks []struct {
Content string `json:"content"`
} `json:"chunks"`
}
// ParseRun represents a parse run response
type ParseRun struct {
Status string `json:"status"`
Output ParseRunOutput `json:"output"`
}
// ExtractRunOutput represents the extracted data output
type ExtractRunOutput struct {
Value Certificate `json:"value"`
}
// ExtractRun represents an extract run response
type ExtractRun struct {
Status string `json:"status"`
Output ExtractRunOutput `json:"output"`
}
// ParseConfig holds parsing configuration
type ParseConfig struct {
BlockOptions struct {
Text struct {
Agentic struct {
Enabled bool `json:"enabled"`
} `json:"agentic"`
} `json:"text"`
} `json:"blockOptions"`
ChunkingStrategy struct {
Type string `json:"type"`
} `json:"chunkingStrategy"`
}
// ParseRequest represents a parse run creation request
type ParseRequest struct {
File struct {
URL string `json:"url"`
} `json:"file"`
Config struct {
ParseConfig ParseConfig `json:"parseConfig"`
} `json:"config"`
}
// ExtractRequest represents an extract run creation request
type ExtractRequest struct {
File struct {
URL string `json:"url"`
} `json:"file"`
Config struct {
Schema map[string]interface{} `json:"schema"`
BaseProcessor string `json:"baseProcessor"`
AdvancedOptions struct {
ReviewAgent struct {
Enabled bool `json:"enabled"`
} `json:"reviewAgent"`
AdvancedMultimodalEnabled bool `json:"advancedMultimodalEnabled"`
} `json:"advancedOptions"`
} `json:"config"`
}
// processCertificateOfLiabilityInsurance processes a certificate file
func processCertificateOfLiabilityInsurance(filePath string, apiKey string) (*Certificate, error) {
// Convert local file to base64 data URL
fileData, err := os.ReadFile(filePath)
if err != nil {
return nil, fmt.Errorf("failed to read file: %w", err)
}
base64Data := base64.StdEncoding.EncodeToString(fileData)
dataURL := fmt.Sprintf("data:application/octet-stream;base64,%s", base64Data)
fmt.Printf("Processing certificate: %s\n", filePath)
// Step 1: Parse the certificate to markdown (agentic OCR enabled)
fmt.Println("Step 1: Parsing certificate with agentic OCR...")
parseRun, err := createAndPollParseRun(dataURL, apiKey)
if err != nil {
return nil, fmt.Errorf("parse failed: %w", err)
}
if parseRun.Status != "PROCESSED" {
return nil, fmt.Errorf("parse failed with status: %s", parseRun.Status)
}
// Collect parsed markdown for reference
markdownContent := ""
for _, chunk := range parseRun.Output.Chunks {
markdownContent += chunk.Content + "\n\n"
}
fmt.Printf("✓ Parse complete. Document size: %d chars\n", len(markdownContent))
// Step 2: Extract structured fields using JSON schema
fmt.Println("Step 2: Extracting structured certificate fields...")
extractRun, err := createAndPollExtractRun(dataURL, apiKey)
if err != nil {
return nil, fmt.Errorf("extraction failed: %w", err)
}
if extractRun.Status != "PROCESSED" {
return nil, fmt.Errorf("extraction failed with status: %s", extractRun.Status)
}
extracted := &extractRun.Output.Value
fmt.Println("✓ Extraction complete.")
// Display results
fmt.Println("\n=== CERTIFICATE SUMMARY ===")
fmt.Printf("Insured: %s\n", derefStr(extracted.InsuredName))
fmt.Printf("Certificate #: %s\n", derefStr(extracted.CertificateNumber))
fmt.Printf("Issued: %s\n", derefStr(extracted.CertificateDate))
fmt.Printf("Producer: %s (%s)\n", derefStr(extracted.ProducerName), derefStr(extracted.ProducerEmail))
fmt.Printf("\n=== INSURERS (%d) ===\n", len(extracted.Insurers))
for _, insurer := range extracted.Insurers {
naic := "N/A"
if insurer.NAICNumber != nil {
naic = *insurer.NAICNumber
}
fmt.Printf(" [%s] %s (NAIC: %s)\n", derefStr(insurer.InsurerLetter), derefStr(insurer.InsurerName), naic)
}
fmt.Printf("\n=== POLICIES (%d) ===\n", len(extracted.Policies))
for _, policy := range extracted.Policies {
fmt.Printf(" Policy: %s [Insurer: %s]\n", derefStr(policy.PolicyNumber), derefStr(policy.InsurerLetter))
fmt.Printf(" Type: %s\n", derefStr(policy.TypeOfInsurance))
fmt.Printf(" Effective: %s → Expires: %s\n", derefStr(policy.PolicyEffectiveDate), derefStr(policy.PolicyExpirationDate))
fmt.Printf(" Additional Insured: %s, Subrogation Waived: %s\n", derefStr(policy.AdditionalInsured), derefStr(policy.SubrogationWaived))
fmt.Println(" Coverage Limits:")
for _, limit := range policy.CoverageLimits {
amount := "N/A"
if limit.LimitAmount != nil {
amount = fmt.Sprintf("$%.0f", *limit.LimitAmount)
}
fmt.Printf(" - %s: %s\n", derefStr(limit.CoverageType), amount)
}
}
fmt.Println("\n=== CERTIFICATE HOLDER ===")
fmt.Printf("Name: %s\n", derefStr(extracted.CertificateHolderName))
fmt.Printf("Address: %s\n", derefStr(extracted.CertificateHolderAddress))
return extracted, nil
}
// createAndPollParseRun creates and polls a parse run until completion
func createAndPollParseRun(dataURL string, apiKey string) (*ParseRun, error) {
req := ParseRequest{}
req.File.URL = dataURL
req.Config.ParseConfig.BlockOptions.Text.Agentic.Enabled = true
req.Config.ParseConfig.ChunkingStrategy.Type = "document"
body, _ := json.Marshal(req)
httpReq, _ := http.NewRequest("POST", extendAPIBase+"/api/v1/parse_runs", bytes.NewBuffer(body))
httpReq.Header.Set("Authorization", fmt.Sprintf("Bearer %s", apiKey))
httpReq.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(httpReq)
if err != nil {
return nil, err
}
defer resp.Body.Close()
respBody, _ := io.ReadAll(resp.Body)
var run ParseRun
json.Unmarshal(respBody, &run)
// Poll until processed
runID := extractIDFromResponse(string(respBody))
for run.Status != "PROCESSED" && run.Status != "FAILED" {
time.Sleep(2 * time.Second)
pollReq, _ := http.NewRequest("GET", extendAPIBase+"/api/v1/parse_runs/"+runID, nil)
pollReq.Header.Set("Authorization", fmt.Sprintf("Bearer %s", apiKey))
pollResp, _ := client.Do(pollReq)
pollBody, _ := io.ReadAll(pollResp.Body)
pollResp.Body.Close()
json.Unmarshal(pollBody, &run)
}
return &run, nil
}
// createAndPollExtractRun creates and polls an extract run until completion
func createAndPollExtractRun(dataURL string, apiKey string) (*ExtractRun, error) {
schema := getCertificateSchema()
req := ExtractRequest{}
req.File.URL = dataURL
req.Config.Schema = schema
req.Config.BaseProcessor = "extraction_performance"
req.Config.AdvancedOptions.ReviewAgent.Enabled = true
req.Config.AdvancedOptions.AdvancedMultimodalEnabled = true
body, _ := json.Marshal(req)
httpReq, _ := http.NewRequest("POST", extendAPIBase+"/api/v1/extract_runs", bytes.NewBuffer(body))
httpReq.Header.Set("Authorization", fmt.Sprintf("Bearer %s", apiKey))
httpReq.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(httpReq)
if err != nil {
return nil, err
}
defer resp.Body.Close()
respBody, _ := io.ReadAll(resp.Body)
var run ExtractRun
json.Unmarshal(respBody, &run)
// Poll until processed
runID := extractIDFromResponse(string(respBody))
for run.Status != "PROCESSED" && run.Status != "FAILED" {
time.Sleep(2 * time.Second)
pollReq, _ := http.NewRequest("GET", extendAPIBase+"/api/v1/extract_runs/"+runID, nil)
pollReq.Header.Set("Authorization", fmt.Sprintf("Bearer %s", apiKey))
pollResp, _ := client.Do(pollReq)
pollBody, _ := io.ReadAll(pollResp.Body)
pollResp.Body.Close()
json.Unmarshal(pollBody, &run)
}
return &run, nil
}
// getCertificateSchema returns the JSON schema for certificate extraction
func getCertificateSchema() map[string]interface{} {
return map[string]interface{}{
"type": "object",
"properties": map[string]interface{}{
"insurers": map[string]interface{}{
"type": "array",
"items": map[string]interface{}{
"type": "object",
"properties": map[string]interface{}{
"naic_number": map[string]interface{}{
"type": []string{"string", "null"},
},
"insurer_name": map[string]interface{}{
"type": []string{"string", "null"},
},
"insurer_letter": map[string]interface{}{
"type": []string{"string", "null"},
},
},
},
},
"policies": map[string]interface{}{
"type": "array",
"items": map[string]interface{}{
"type": "object",
"properties": map[string]interface{}{
"policy_number": map[string]interface{}{
"type": []string{"string", "null"},
},
"insurer_letter": map[string]interface{}{
"type": []string{"string", "null"},
},
"coverage_limits": map[string]interface{}{
"type": "array",
"items": map[string]interface{}{
"type": "object",
"properties": map[string]interface{}{
"limit_amount": map[string]interface{}{
"type": []string{"number", "null"},
},
"coverage_type": map[string]interface{}{
"type": []string{"string", "null"},
},
},
},
},
"type_of_insurance": map[string]interface{}{
"type": []string{"string", "null"},
},
"additional_insured": map[string]interface{}{
"type": []string{"string", "null"},
},
"subrogation_waived": map[string]interface{}{
"type": []string{"string", "null"},
},
"policy_effective_date": map[string]interface{}{
"type": []string{"string", "null"},
},
"policy_expiration_date": map[string]interface{}{
"type": []string{"string", "null"},
},
},
},
},
"insured_name": map[string]interface{}{
"type": []string{"string", "null"},
},
"producer_name": map[string]interface{}{
"type": []string{"string", "null"},
},
"producer_email": map[string]interface{}{
"type": []string{"string", "null"},
},
"producer_phone": map[string]interface{}{
"type": []string{"string", "null"},
},
"insured_address": map[string]interface{}{
"type": []string{"string", "null"},
},
"revision_number": map[string]interface{}{
"type": []string{"string", "null"},
},
"certificate_date": map[string]interface{}{
"type": []string{"string", "null"},
},
"certificate_number": map[string]interface{}{
"type": []string{"string", "null"},
},
"producer_contact_name": map[string]interface{}{
"type": []string{"string", "null"},
},
"certificate_holder_name": map[string]interface{}{
"type": []string{"string", "null"},
},
"authorized_representative": map[string]interface{}{
"type": []string{"string", "null"},
},
"description_of_operations": map[string]interface{}{
"type": []string{"string", "null"},
},
"certificate_holder_address": map[string]interface{}{
"type": []string{"string", "null"},
},
},
}
}
// derefStr safely dereferences a string pointer
func derefStr(s *string) string {
if s == nil {
return ""
}
return *s
}
// extractIDFromResponse extracts the run ID from a JSON response
func extractIDFromResponse(respBody string) string {
var data map[string]interface{}
json.Unmarshal([]byte(respBody), &data)
if id, ok := data["id"].(string); ok {
return id
}
return ""
}
func main() {
filePath := flag.String("file", "", "Path to the certificate PDF file")
flag.Parse()
if *filePath == "" {
if len(os.Args) > 1 {
*filePath = os.Args[1]
} else {
fmt.Fprintf(os.Stderr, "Usage: %s <path-to-certificate.pdf>\n", filepath.Base(os.Args[0]))
os.Exit(1)
}
}
apiKey := os.Getenv("EXTEND_API_KEY")
if apiKey == "" {
fmt.Fprintf(os.Stderr, "Error: EXTEND_API_KEY environment variable not set\n")
os.Exit(1)
}
_, err := processCertificateOfLiabilityInsurance(*filePath, apiKey)
if err != nil {
fmt.Fprintf(os.Stderr, "Error processing certificate: %v\n", err)
os.Exit(1)
}
fmt.Println("\n✓ Processing complete.")
}// Deploy the "Certificate of Liability Insurance" 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/certificate-of-liability-insurance.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: certificate-of-liability-insurance).
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, "certificate-of-liability-insurance.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": "Certificate of Liability Insurance 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": "extraction2"
}
]
},
{
"name": "extraction2",
"type": "EXTRACT",
"config": {
"extractorConfig": {
"schema": {
"type": "object",
"required": [
"insurers",
"policies",
"insured_name",
"producer_name",
"producer_email",
"producer_phone",
"insured_address",
"revision_number",
"certificate_date",
"certificate_number",
"producer_contact_name",
"certificate_holder_name",
"authorized_representative",
"description_of_operations",
"certificate_holder_address"
],
"properties": {
"insurers": {
"type": "array",
"items": {
"type": "object",
"required": [
"naic_number",
"insurer_name",
"insurer_letter"
],
"properties": {
"naic_number": {
"type": [
"string",
"null"
],
"description": "The NAIC (National Association of Insurance Commissioners) number for the insurer, if provided."
},
"insurer_name": {
"type": [
"string",
"null"
],
"description": "The full name of the insurance company providing coverage."
},
"insurer_letter": {
"type": [
"string",
"null"
],
"description": "The letter designation (e.g., 'A', 'B', 'C') used to reference this insurer in the policy table."
}
},
"additionalProperties": false
},
"description": "A list of insurance companies (insurers) providing coverage under the policies referenced in this certificate. Each entry includes the insurer's name, letter designation, and NAIC number if available."
},
"policies": {
"type": "array",
"items": {
"type": "object",
"required": [
"policy_number",
"insurer_letter",
"coverage_limits",
"type_of_insurance",
"additional_insured",
"subrogation_waived",
"policy_effective_date",
"policy_expiration_date"
],
"properties": {
"policy_number": {
"type": [
"string",
"null"
],
"description": "The unique identifier or number assigned to this insurance policy."
},
"insurer_letter": {
"type": [
"string",
"null"
],
"description": "The letter designation (e.g., 'A', 'B', 'C') corresponding to the insurer providing this policy, as referenced in the insurers list."
},
"coverage_limits": {
"type": "array",
"items": {
"type": "object",
"required": [
"limit_amount",
"coverage_type"
],
"properties": {
"limit_amount": {
"type": [
"number",
"null"
],
"description": "The monetary amount of the coverage limit for this coverage type, excluding currency symbols and formatting."
},
"coverage_type": {
"type": [
"string",
"null"
],
"description": "The specific type of coverage or limit (e.g., 'Each Occurrence', 'General Aggregate', 'Bodily Injury', 'Property Damage', etc.)."
}
},
"additionalProperties": false
},
"description": "A list of specific coverage limits and their corresponding amounts for this policy. Each entry represents a particular coverage type and its monetary limit."
},
"type_of_insurance": {
"type": [
"string",
"null"
],
"description": "The type or category of insurance provided by this policy (e.g., 'Commercial General Liability', 'Automobile Liability', 'Workers Compensation', 'Umbrella Liability', etc.)."
},
"additional_insured": {
"type": [
"string",
"null"
],
"description": "Indicates whether this policy includes an additional insured provision. May be marked as 'Y', 'Yes', or similar, or left blank if not applicable."
},
"subrogation_waived": {
"type": [
"string",
"null"
],
"description": "Indicates if subrogation rights are waived for this policy. May be marked as 'Y', 'Yes', or similar, or left blank if not applicable."
},
"policy_effective_date": {
"type": [
"string",
"null"
],
"description": "The date on which this insurance policy becomes effective and coverage begins.",
"extend:type": "date"
},
"policy_expiration_date": {
"type": [
"string",
"null"
],
"description": "The date on which this insurance policy expires and coverage ends.",
"extend:type": "date"
}
},
"additionalProperties": false
},
"description": "A list of insurance policies covered by this certificate. Each entry details a specific policy, including type, insurer, policy number, effective and expiration dates, and coverage limits. This array captures the core insurance coverage information."
},
"insured_name": {
"type": [
"string",
"null"
],
"description": "The full legal name of the insured party or business entity covered by the insurance policies listed in this certificate."
},
"producer_name": {
"type": [
"string",
"null"
],
"description": "The name of the insurance agency, broker, or producer responsible for issuing this certificate. This is the entity facilitating the insurance coverage."
},
"producer_email": {
"type": [
"string",
"null"
],
"description": "The email address for the insurance producer or agency, used for correspondence regarding this certificate."
},
"producer_phone": {
"type": [
"string",
"null"
],
"description": "The phone number for the insurance producer or agency, including area code and any extensions if present."
},
"insured_address": {
"type": [
"string",
"null"
],
"description": "The mailing address of the insured party, including street, city, state, and postal code. This is the address associated with the insured entity."
},
"revision_number": {
"type": [
"string",
"null"
],
"description": "The revision or version number of this certificate, indicating if it has been updated or reissued. May be labeled as 'Revision Number' or similar."
},
"certificate_date": {
"type": [
"string",
"null"
],
"description": "The date on which this certificate of liability insurance was issued. This is the official date of the document and is often found near the top, but may appear elsewhere depending on the layout.",
"extend:type": "date"
},
"certificate_number": {
"type": [
"string",
"null"
],
"description": "The unique identifier assigned to this certificate of insurance. This number is used for tracking and reference purposes and may be labeled as 'Certificate Number', 'Cert No.', or similar."
},
"producer_contact_name": {
"type": [
"string",
"null"
],
"description": "The name of the primary contact person at the producer or agency who can be reached for questions about this certificate."
},
"certificate_holder_name": {
"type": [
"string",
"null"
],
"description": "The name of the certificate holder, i.e., the entity or individual to whom this certificate is issued as evidence of insurance."
},
"authorized_representative": {
"type": [
"string",
"null"
],
"description": "The name or signature of the authorized representative or agent who has validated or signed this certificate."
},
"description_of_operations": {
"type": [
"string",
"null"
],
"description": "Any additional remarks, descriptions of operations, locations, vehicles, or special provisions related to the insurance coverage. This may include notes about additional insureds, exclusions, or endorsements."
},
"certificate_holder_address": {
"type": [
"string",
"null"
],
"description": "The address of the certificate holder, including street, suite, city, state, and postal code."
}
},
"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
from extend_ai import Extend
API_KEY = os.environ.get("EXTEND_API_KEY")
if not API_KEY:
print("Set EXTEND_API_KEY first.")
sys.exit(1)
STATE_DIR = Path.cwd() / ".extend"
STATE_FILE = STATE_DIR / "certificate-of-liability-insurance.json"
def load_state() -> dict:
if STATE_FILE.exists():
return json.loads(STATE_FILE.read_text())
return {}
def save_state(state: dict) -> None:
STATE_DIR.mkdir(parents=True, exist_ok=True)
STATE_FILE.write_text(json.dumps(state, indent=2))
# ── Workflow definition — extractor/classifier/splitter configs inline ──────
WORKFLOW = {
"name": "Certificate of Liability Insurance 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": "extraction2"}],
},
{
"name": "extraction2",
"type": "EXTRACT",
"config": {
"extractorConfig": {
"schema": {
"type": "object",
"required": [
"insurers",
"policies",
"insured_name",
"producer_name",
"producer_email",
"producer_phone",
"insured_address",
"revision_number",
"certificate_date",
"certificate_number",
"producer_contact_name",
"certificate_holder_name",
"authorized_representative",
"description_of_operations",
"certificate_holder_address",
],
"properties": {
"insurers": {
"type": "array",
"items": {
"type": "object",
"required": [
"naic_number",
"insurer_name",
"insurer_letter",
],
"properties": {
"naic_number": {
"type": ["string", "null"],
"description": "The NAIC (National Association of Insurance Commissioners) number for the insurer, if provided.",
},
"insurer_name": {
"type": ["string", "null"],
"description": "The full name of the insurance company providing coverage.",
},
"insurer_letter": {
"type": ["string", "null"],
"description": "The letter designation (e.g., 'A', 'B', 'C') used to reference this insurer in the policy table.",
},
},
"additionalProperties": False,
},
"description": "A list of insurance companies (insurers) providing coverage under the policies referenced in this certificate. Each entry includes the insurer's name, letter designation, and NAIC number if available.",
},
"policies": {
"type": "array",
"items": {
"type": "object",
"required": [
"policy_number",
"insurer_letter",
"coverage_limits",
"type_of_insurance",
"additional_insured",
"subrogation_waived",
"policy_effective_date",
"policy_expiration_date",
],
"properties": {
"policy_number": {
"type": ["string", "null"],
"description": "The unique identifier or number assigned to this insurance policy.",
},
"insurer_letter": {
"type": ["string", "null"],
"description": "The letter designation (e.g., 'A', 'B', 'C') corresponding to the insurer providing this policy, as referenced in the insurers list.",
},
"coverage_limits": {
"type": "array",
"items": {
"type": "object",
"required": ["limit_amount", "coverage_type"],
"properties": {
"limit_amount": {
"type": ["number", "null"],
"description": "The monetary amount of the coverage limit for this coverage type, excluding currency symbols and formatting.",
},
"coverage_type": {
"type": ["string", "null"],
"description": "The specific type of coverage or limit (e.g., 'Each Occurrence', 'General Aggregate', 'Bodily Injury', 'Property Damage', etc.).",
},
},
"additionalProperties": False,
},
"description": "A list of specific coverage limits and their corresponding amounts for this policy. Each entry represents a particular coverage type and its monetary limit.",
},
"type_of_insurance": {
"type": ["string", "null"],
"description": "The type or category of insurance provided by this policy (e.g., 'Commercial General Liability', 'Automobile Liability', 'Workers Compensation', 'Umbrella Liability', etc.).",
},
"additional_insured": {
"type": ["string", "null"],
"description": "Indicates whether this policy includes an additional insured provision. May be marked as 'Y', 'Yes', or similar, or left blank if not applicable.",
},
"subrogation_waived": {
"type": ["string", "null"],
"description": "Indicates if subrogation rights are waived for this policy. May be marked as 'Y', 'Yes', or similar, or left blank if not applicable.",
},
"policy_effective_date": {
"type": ["string", "null"],
"description": "The date on which this insurance policy becomes effective and coverage begins.",
"extend:type": "date",
},
"policy_expiration_date": {
"type": ["string", "null"],
"description": "The date on which this insurance policy expires and coverage ends.",
"extend:type": "date",
},
},
"additionalProperties": False,
},
"description": "A list of insurance policies covered by this certificate. Each entry details a specific policy, including type, insurer, policy number, effective and expiration dates, and coverage limits. This array captures the core insurance coverage information.",
},
"insured_name": {
"type": ["string", "null"],
"description": "The full legal name of the insured party or business entity covered by the insurance policies listed in this certificate.",
},
"producer_name": {
"type": ["string", "null"],
"description": "The name of the insurance agency, broker, or producer responsible for issuing this certificate. This is the entity facilitating the insurance coverage.",
},
"producer_email": {
"type": ["string", "null"],
"description": "The email address for the insurance producer or agency, used for correspondence regarding this certificate.",
},
"producer_phone": {
"type": ["string", "null"],
"description": "The phone number for the insurance producer or agency, including area code and any extensions if present.",
},
"insured_address": {
"type": ["string", "null"],
"description": "The mailing address of the insured party, including street, city, state, and postal code. This is the address associated with the insured entity.",
},
"revision_number": {
"type": ["string", "null"],
"description": "The revision or version number of this certificate, indicating if it has been updated or reissued. May be labeled as 'Revision Number' or similar.",
},
"certificate_date": {
"type": ["string", "null"],
"description": "The date on which this certificate of liability insurance was issued. This is the official date of the document and is often found near the top, but may appear elsewhere depending on the layout.",
"extend:type": "date",
},
"certificate_number": {
"type": ["string", "null"],
"description": "The unique identifier assigned to this certificate of insurance. This number is used for tracking and reference purposes and may be labeled as 'Certificate Number', 'Cert No.', or similar.",
},
"producer_contact_name": {
"type": ["string", "null"],
"description": "The name of the primary contact person at the producer or agency who can be reached for questions about this certificate.",
},
"certificate_holder_name": {
"type": ["string", "null"],
"description": "The name of the certificate holder, i.e., the entity or individual to whom this certificate is issued as evidence of insurance.",
},
"authorized_representative": {
"type": ["string", "null"],
"description": "The name or signature of the authorized representative or agent who has validated or signed this certificate.",
},
"description_of_operations": {
"type": ["string", "null"],
"description": "Any additional remarks, descriptions of operations, locations, vehicles, or special provisions related to the insurance coverage. This may include notes about additional insureds, exclusions, or endorsements.",
},
"certificate_holder_address": {
"type": ["string", "null"],
"description": "The address of the certificate holder, including street, suite, city, state, and postal code.",
},
},
"additionalProperties": False,
},
"baseProcessor": "extraction_performance",
"advancedOptions": {
"reviewAgent": {"enabled": True},
"advancedMultimodalEnabled": True,
},
}
},
},
],
}
async def main():
client = Extend(token=API_KEY)
state = load_state()
print(f'Deploying "{WORKFLOW["name"]}…"')
if state.get("workflowId"):
workflow_id = state["workflowId"]
print(f"✓ workflow already provisioned ({workflow_id}) — updating steps")
await client.workflows.update(
id=workflow_id,
steps=WORKFLOW["steps"],
)
else:
# Reuse an existing workflow with the same name if one exists
try:
workflows = await client.workflows.list(name=WORKFLOW["name"])
items = workflows.data if hasattr(workflows, "data") else workflows.items if hasattr(workflows, "items") else []
existing = next((w for w in items if w.name == WORKFLOW["name"]), None)
if existing and existing.id:
state["workflowId"] = existing.id
save_state(state)
print(f'✓ workflow "{WORKFLOW["name"]}" found in your account ({existing.id}) — updating steps')
await client.workflows.update(
id=existing.id,
steps=WORKFLOW["steps"],
)
except Exception:
pass
if not state.get("workflowId"):
created = await client.workflows.create(**WORKFLOW)
workflow_id = created.id if hasattr(created, "id") else created.workflow.id if hasattr(created, "workflow") else None
if not workflow_id:
raise RuntimeError("Could not read created workflow id from response")
state["workflowId"] = workflow_id
save_state(state)
print(f"+ created workflow ({workflow_id})")
# Deploy the current draft as a new version so the workflow is runnable
try:
await client.workflows.create_version(id=state["workflowId"])
except Exception:
pass
print("\nDone. Run documents through it with:")
print(f' POST https://api.extend.ai/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__":
import asyncio
try:
asyncio.run(main())
except Exception as e:
print(f"Error: {getattr(e, 'message', str(e))}", file=sys.stderr)
sys.exit(1)// This script uses Extend's REST API directly because Extend does not publish
// an official Java SDK. It calls the same endpoints and sends the same JSON
// payloads that the TypeScript SDK wraps.
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;
public class ProvisionCertificateOfLiabilityInsurance {
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("certificate-of-liability-insurance.json");
private static final HttpClient HTTP = HttpClient.newHttpClient();
static class State {
String workflowId;
}
private static State state = new State();
public static void main(String[] args) throws Exception {
if (API_KEY == null || API_KEY.isEmpty()) {
System.err.println("Set EXTEND_API_KEY first.");
System.exit(1);
}
loadState();
String workflowName = "Certificate of Liability Insurance Processing Pipeline";
System.out.println("Deploying \"" + workflowName + "\"…");
if (state.workflowId != null && !state.workflowId.isEmpty()) {
System.out.println("✓ workflow already provisioned (" + state.workflowId + ") — updating steps");
String stepsJson = buildStepsJson();
String body = "{\"steps\":" + stepsJson + "}";
api("POST", "/workflows/" + state.workflowId, body);
} else {
try {
String encoded = URLEncoder.encode(workflowName, StandardCharsets.UTF_8);
String listResponse = api("GET", "/workflows?name=" + encoded, null);
String workflowIdFromList = extractWorkflowIdFromList(listResponse, workflowName);
if (workflowIdFromList != null) {
state.workflowId = workflowIdFromList;
saveState();
System.out.println("✓ workflow \"" + workflowName + "\" found in your account (" + workflowIdFromList + ") — updating steps");
String stepsJson = buildStepsJson();
String body = "{\"steps\":" + stepsJson + "}";
api("POST", "/workflows/" + workflowIdFromList, body);
}
} catch (Exception e) {
// lookup is best-effort; fall through to create
}
if (state.workflowId == null || state.workflowId.isEmpty()) {
String workflowJson = buildWorkflowJson();
String createResponse = api("POST", "/workflows", workflowJson);
String newWorkflowId = extractWorkflowId(createResponse);
if (newWorkflowId == null) {
throw new Exception("Could not read created workflow id from response");
}
state.workflowId = newWorkflowId;
saveState();
System.out.println("+ created workflow (" + newWorkflowId + ")");
}
}
try {
api("POST", "/workflows/" + state.workflowId + "/versions", "{}");
} catch (Exception e) {
// best-effort: some accounts/plans may not require this explicit step
}
System.out.println("\nDone. Run documents through it with:");
System.out.println(" POST " + API + "/workflow_runs { workflow: { id: \"" + state.workflowId + "\" }, file: { url: \"https://…\" } }");
System.out.println("Or open the workflow in the Extend dashboard to review and deploy it.");
}
private static void loadState() throws IOException {
if (Files.exists(STATE_FILE)) {
String content = new String(Files.readAllBytes(STATE_FILE), StandardCharsets.UTF_8);
state.workflowId = extractJsonString(content, "workflowId");
}
}
private static void saveState() throws IOException {
Files.createDirectories(STATE_DIR);
String json = "{\"workflowId\": \"" + escapeJsonString(state.workflowId) + "\"}";
Files.write(STATE_FILE, json.getBytes(StandardCharsets.UTF_8));
}
private static String api(String method, String pathName, String body) throws Exception {
HttpRequest.Builder builder = HttpRequest.newBuilder()
.uri(URI.create(API + pathName))
.method(method, body != null ? HttpRequest.BodyPublishers.ofString(body) : HttpRequest.BodyPublishers.noBody())
.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.send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() < 200 || response.statusCode() >= 300) {
String errorBody = response.body().length() > 300 ? response.body().substring(0, 300) : response.body();
throw new Exception(method + " " + pathName + " failed (" + response.statusCode() + "): " + errorBody);
}
return response.body();
}
private static String buildWorkflowJson() {
return "{" +
"\"name\":\"Certificate of Liability Insurance Processing Pipeline\"," +
"\"steps\":" + buildStepsJson() +
"}";
}
private static String buildStepsJson() {
return "[" +
"{\"name\":\"startTrigger1\",\"type\":\"TRIGGER\",\"next\":[{\"step\":\"parse1\"}]}," +
"{\"name\":\"parse1\",\"type\":\"PARSE\",\"config\":{\"parseConfig\":{\"blockOptions\":{\"text\":{\"agentic\":{\"enabled\":true}}},\"chunkingStrategy\":{\"type\":\"document\"}}},\"next\":[{\"step\":\"extraction2\"}]}," +
"{\"name\":\"extraction2\",\"type\":\"EXTRACT\",\"config\":{\"extractorConfig\":{\"schema\":" + buildSchemaJson() + ",\"baseProcessor\":\"extraction_performance\",\"advancedOptions\":{\"reviewAgent\":{\"enabled\":true},\"advancedMultimodalEnabled\":true}}}}" +
"]";
}
private static String buildSchemaJson() {
return "{\"type\":\"object\",\"required\":[\"insurers\",\"policies\",\"insured_name\",\"producer_name\",\"producer_email\",\"producer_phone\",\"insured_address\",\"revision_number\",\"certificate_date\",\"certificate_number\",\"producer_contact_name\",\"certificate_holder_name\",\"authorized_representative\",\"description_of_operations\",\"certificate_holder_address\"],\"properties\":{\"insurers\":{\"type\":\"array\",\"items\":{\"type\":\"object\",\"required\":[\"naic_number\",\"insurer_name\",\"insurer_letter\"],\"properties\":{\"naic_number\":{\"type\":[\"string\",\"null\"],\"description\":\"The NAIC (National Association of Insurance Commissioners) number for the insurer, if provided.\"},\"insurer_name\":{\"type\":[\"string\",\"null\"],\"description\":\"The full name of the insurance company providing coverage.\"},\"insurer_letter\":{\"type\":[\"string\",\"null\"],\"description\":\"The letter designation (e.g., 'A', 'B', 'C') used to reference this insurer in the policy table.\"}},\"additionalProperties\":false},\"description\":\"A list of insurance companies (insurers) providing coverage under the policies referenced in this certificate. Each entry includes the insurer's name, letter designation, and NAIC number if available.\"},\"policies\":{\"type\":\"array\",\"items\":{\"type\":\"object\",\"required\":[\"policy_number\",\"insurer_letter\",\"coverage_limits\",\"type_of_insurance\",\"additional_insured\",\"subrogation_waived\",\"policy_effective_date\",\"policy_expiration_date\"],\"properties\":{\"policy_number\":{\"type\":[\"string\",\"null\"],\"description\":\"The unique identifier or number assigned to this insurance policy.\"},\"insurer_letter\":{\"type\":[\"string\",\"null\"],\"description\":\"The letter designation (e.g., 'A', 'B', 'C') corresponding to the insurer providing this policy, as referenced in the insurers list.\"},\"coverage_limits\":{\"type\":\"array\",\"items\":{\"type\":\"object\",\"required\":[\"limit_amount\",\"coverage_type\"],\"properties\":{\"limit_amount\":{\"type\":[\"number\",\"null\"],\"description\":\"The monetary amount of the coverage limit for this coverage type, excluding currency symbols and formatting.\"},\"coverage_type\":{\"type\":[\"string\",\"null\"],\"description\":\"The specific type of coverage or limit (e.g., 'Each Occurrence', 'General Aggregate', 'Bodily Injury', 'Property Damage', etc.).\"}},\"additionalProperties\":false},\"description\":\"A list of specific coverage limits and their corresponding amounts for this policy. Each entry represents a particular coverage type and its monetary limit.\"},\"type_of_insurance\":{\"type\":[\"string\",\"null\"],\"description\":\"The type or category of insurance provided by this policy (e.g., 'Commercial General Liability', 'Automobile Liability', 'Workers Compensation', 'Umbrella Liability', etc.).\"},\"additional_insured\":{\"type\":[\"string\",\"null\"],\"description\":\"Indicates whether this policy includes an additional insured provision. May be marked as 'Y', 'Yes', or similar, or left blank if not applicable.\"},\"subrogation_waived\":{\"type\":[\"string\",\"null\"],\"description\":\"Indicates if subrogation rights are waived for this policy. May be marked as 'Y', 'Yes', or similar, or left blank if not applicable.\"},\"policy_effective_date\":{\"type\":[\"string\",\"null\"],\"description\":\"The date on which this insurance policy becomes effective and coverage begins.\",\"extend:type\":\"date\"},\"policy_expiration_date\":{\"type\":[\"string\",\"null\"],\"description\":\"The date on which this insurance policy expires and coverage ends.\",\"extend:type\":\"date\"}},\"additionalProperties\":false},\"description\":\"A list of insurance policies covered by this certificate. Each entry details a specific policy, including type, insurer, policy number, effective and expiration dates, and coverage limits. This array captures the core insurance coverage information.\"},\"insured_name\":{\"type\":[\"string\",\"null\"],\"description\":\"The full legal name of the insured party or business entity covered by the insurance policies listed in this certificate.\"},\"producer_name\":{\"type\":[\"string\",\"null\"],\"description\":\"The name of the insurance agency, broker, or producer responsible for issuing this certificate. This is the entity facilitating the insurance coverage.\"},\"producer_email\":{\"type\":[\"string\",\"null\"],\"description\":\"The email address for the insurance producer or agency, used for correspondence regarding this certificate.\"},\"producer_phone\":{\"type\":[\"string\",\"null\"],\"description\":\"The phone number for the insurance producer or agency, including area code and any extensions if present.\"},\"insured_address\":{\"type\":[\"string\",\"null\"],\"description\":\"The mailing address of the insured party, including street, city, state, and postal code. This is the address associated with the insured entity.\"},\"revision_number\":{\"type\":[\"string\",\"null\"],\"description\":\"The revision or version number of this certificate, indicating if it has been updated or reissued. May be labeled as 'Revision Number' or similar.\"},\"certificate_date\":{\"type\":[\"string\",\"null\"],\"description\":\"The date on which this certificate of liability insurance was issued. This is the official date of the document and is often found near the top, but may appear elsewhere depending on the layout.\",\"extend:type\":\"date\"},\"certificate_number\":{\"type\":[\"string\",\"null\"],\"description\":\"The unique identifier assigned to this certificate of insurance. This number is used for tracking and reference purposes and may be labeled as 'Certificate Number', 'Cert No.', or similar.\"},\"producer_contact_name\":{\"type\":[\"string\",\"null\"],\"description\":\"The name of the primary contact person at the producer or agency who can be reached for questions about this certificate.\"},\"certificate_holder_name\":{\"type\":[\"string\",\"null\"],\"description\":\"The name of the certificate holder, i.e., the entity or individual to whom this certificate is issued as evidence of insurance.\"},\"authorized_representative\":{\"type\":[\"string\",\"null\"],\"description\":\"The name or signature of the authorized representative or agent who has validated or signed this certificate.\"},\"description_of_operations\":{\"type\":[\"string\",\"null\"],\"description\":\"Any additional remarks, descriptions of operations, locations, vehicles, or special provisions related to the insurance coverage. This may include notes about additional insureds, exclusions, or endorsements.\"},\"certificate_holder_address\":{\"type\":[\"string\",\"null\"],\"description\":\"The address of the certificate holder, including street, suite, city, state, and postal code.\"}},\"additionalProperties\":false}";
}
private static String extractWorkflowId(String json) {
String id = extractJsonString(json, "\"id\"");
if (id != null) return id;
int idx = json.indexOf("\"workflow\"");
if (idx >= 0) {
int idIdx = json.indexOf("\"id\"", idx);
if (idIdx >= 0) {
return extractJsonString(json.substring(idIdx), "\"id\"");
}
}
return null;
}
private static String extractWorkflowIdFromList(String json, String workflowName) {
int idx = json.indexOf("\"name\"");
while (idx >= 0) {
String name = extractJsonString(json.substring(idx), "\"name\"");
if (workflowName.equals(name)) {
int idIdx = json.lastIndexOf("\"id\"", idx);
if (idIdx >= 0) {
return extractJsonString(json.substring(idIdx), "\"id\"");
}
}
idx = json.indexOf("\"name\"", idx + 1);
}
return null;
}
private static String extractJsonString(String json, String key) {
int idx = json.indexOf(key);
if (idx < 0) return null;
idx = json.indexOf(':', idx);
if (idx < 0) return null;
idx = json.indexOf('"', idx);
if (idx < 0) return null;
int endIdx = json.indexOf('"', idx + 1);
if (endIdx < 0) return null;
return json.substring(idx + 1, endIdx);
}
private static String escapeJsonString(String s) {
if (s == null) return "";
return s.replace("\\", "\\\\")
.replace("\"", "\\\"")
.replace("\n", "\\n")
.replace("\r", "\\r")
.replace("\t", "\\t");
}
}// This code uses the Extend REST API directly because Extend has no official Go SDK yet.
// It deploys the "Certificate of Liability Insurance" 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: certificate-of-liability-insurance).
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"
)
type State struct {
WorkflowID string `json:"workflowId,omitempty"`
}
func main() {
apiKey := os.Getenv("EXTEND_API_KEY")
if apiKey == "" {
fmt.Fprintln(os.Stderr, "Set EXTEND_API_KEY first.")
os.Exit(1)
}
stateDir := filepath.Join(os.Getenv("PWD"), ".extend")
stateFile := filepath.Join(stateDir, "certificate-of-liability-insurance.json")
state := &State{}
if data, err := os.ReadFile(stateFile); err == nil {
json.Unmarshal(data, state)
}
saveState := func() {
os.MkdirAll(stateDir, 0755)
data, _ := json.MarshalIndent(state, "", " ")
os.WriteFile(stateFile, data, 0644)
}
apiCall := func(method, pathName string, body interface{}) (map[string]interface{}, error) {
var reqBody io.Reader
if body != nil {
b, _ := json.Marshal(body)
reqBody = bytes.NewReader(b)
}
req, _ := http.NewRequest(method, API+pathName, reqBody)
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", apiKey))
req.Header.Set("x-extend-api-version", VERSION)
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
respBody, _ := io.ReadAll(resp.Body)
data := make(map[string]interface{})
json.Unmarshal(respBody, &data)
if resp.StatusCode >= 400 {
errMsg := string(respBody)
if len(errMsg) > 300 {
errMsg = errMsg[:300]
}
return nil, fmt.Errorf("%s %s failed (%d): %s", method, pathName, resp.StatusCode, errMsg)
}
return data, nil
}
workflow := map[string]interface{}{
"name": "Certificate of Liability Insurance 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": "extraction2"},
},
},
{
"name": "extraction2",
"type": "EXTRACT",
"config": map[string]interface{}{
"extractorConfig": map[string]interface{}{
"schema": map[string]interface{}{
"type": "object",
"required": []string{
"insurers", "policies", "insured_name", "producer_name",
"producer_email", "producer_phone", "insured_address",
"revision_number", "certificate_date", "certificate_number",
"producer_contact_name", "certificate_holder_name",
"authorized_representative", "description_of_operations",
"certificate_holder_address",
},
"properties": map[string]interface{}{
"insurers": map[string]interface{}{
"type": "array",
"items": map[string]interface{}{
"type": "object",
"required": []string{"naic_number", "insurer_name", "insurer_letter"},
"properties": map[string]interface{}{
"naic_number": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The NAIC (National Association of Insurance Commissioners) number for the insurer, if provided.",
},
"insurer_name": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The full name of the insurance company providing coverage.",
},
"insurer_letter": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The letter designation (e.g., 'A', 'B', 'C') used to reference this insurer in the policy table.",
},
},
"additionalProperties": false,
},
"description": "A list of insurance companies (insurers) providing coverage under the policies referenced in this certificate. Each entry includes the insurer's name, letter designation, and NAIC number if available.",
},
"policies": map[string]interface{}{
"type": "array",
"items": map[string]interface{}{
"type": "object",
"required": []string{
"policy_number", "insurer_letter", "coverage_limits",
"type_of_insurance", "additional_insured", "subrogation_waived",
"policy_effective_date", "policy_expiration_date",
},
"properties": map[string]interface{}{
"policy_number": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The unique identifier or number assigned to this insurance policy.",
},
"insurer_letter": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The letter designation (e.g., 'A', 'B', 'C') corresponding to the insurer providing this policy, as referenced in the insurers list.",
},
"coverage_limits": map[string]interface{}{
"type": "array",
"items": map[string]interface{}{
"type": "object",
"required": []string{"limit_amount", "coverage_type"},
"properties": map[string]interface{}{
"limit_amount": map[string]interface{}{
"type": []string{"number", "null"},
"description": "The monetary amount of the coverage limit for this coverage type, excluding currency symbols and formatting.",
},
"coverage_type": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The specific type of coverage or limit (e.g., 'Each Occurrence', 'General Aggregate', 'Bodily Injury', 'Property Damage', etc.).",
},
},
"additionalProperties": false,
},
"description": "A list of specific coverage limits and their corresponding amounts for this policy. Each entry represents a particular coverage type and its monetary limit.",
},
"type_of_insurance": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The type or category of insurance provided by this policy (e.g., 'Commercial General Liability', 'Automobile Liability', 'Workers Compensation', 'Umbrella Liability', etc.).",
},
"additional_insured": map[string]interface{}{
"type": []string{"string", "null"},
"description": "Indicates whether this policy includes an additional insured provision. May be marked as 'Y', 'Yes', or similar, or left blank if not applicable.",
},
"subrogation_waived": map[string]interface{}{
"type": []string{"string", "null"},
"description": "Indicates if subrogation rights are waived for this policy. May be marked as 'Y', 'Yes', or similar, or left blank if not applicable.",
},
"policy_effective_date": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The date on which this insurance policy becomes effective and coverage begins.",
"extend:type": "date",
},
"policy_expiration_date": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The date on which this insurance policy expires and coverage ends.",
"extend:type": "date",
},
},
"additionalProperties": false,
},
"description": "A list of insurance policies covered by this certificate. Each entry details a specific policy, including type, insurer, policy number, effective and expiration dates, and coverage limits. This array captures the core insurance coverage information.",
},
"insured_name": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The full legal name of the insured party or business entity covered by the insurance policies listed in this certificate.",
},
"producer_name": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The name of the insurance agency, broker, or producer responsible for issuing this certificate. This is the entity facilitating the insurance coverage.",
},
"producer_email": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The email address for the insurance producer or agency, used for correspondence regarding this certificate.",
},
"producer_phone": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The phone number for the insurance producer or agency, including area code and any extensions if present.",
},
"insured_address": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The mailing address of the insured party, including street, city, state, and postal code. This is the address associated with the insured entity.",
},
"revision_number": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The revision or version number of this certificate, indicating if it has been updated or reissued. May be labeled as 'Revision Number' or similar.",
},
"certificate_date": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The date on which this certificate of liability insurance was issued. This is the official date of the document and is often found near the top, but may appear elsewhere depending on the layout.",
"extend:type": "date",
},
"certificate_number": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The unique identifier assigned to this certificate of insurance. This number is used for tracking and reference purposes and may be labeled as 'Certificate Number', 'Cert No.', or similar.",
},
"producer_contact_name": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The name of the primary contact person at the producer or agency who can be reached for questions about this certificate.",
},
"certificate_holder_name": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The name of the certificate holder, i.e., the entity or individual to whom this certificate is issued as evidence of insurance.",
},
"authorized_representative": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The name or signature of the authorized representative or agent who has validated or signed this certificate.",
},
"description_of_operations": map[string]interface{}{
"type": []string{"string", "null"},
"description": "Any additional remarks, descriptions of operations, locations, vehicles, or special provisions related to the insurance coverage. This may include notes about additional insureds, exclusions, or endorsements.",
},
"certificate_holder_address": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The address of the certificate holder, including street, suite, city, state, and postal code.",
},
},
"additionalProperties": false,
},
"baseProcessor": "extraction_performance",
"advancedOptions": map[string]interface{}{
"reviewAgent": map[string]interface{}{
"enabled": true,
},
"advancedMultimodalEnabled": true,
},
},
},
},
},
}
fmt.Printf("Deploying \"%s\"…\n", workflow["name"])
if state.WorkflowID != "" {
fmt.Printf("✓ workflow already provisioned (%s) — updating steps\n", state.WorkflowID)
apiCall("POST", fmt.Sprintf("/workflows/%s", state.WorkflowID), map[string]interface{}{
"steps": workflow["steps"],
})
} else {
found := false
queryName := url.QueryEscape(workflow["name"].(string))
if list, err := apiCall("GET", fmt.Sprintf("/workflows?name=%s", queryName)); err == nil {
var items []map[string]interface{}
if data, ok := list["data"].([]interface{}); ok {
for _, v := range data {
items = append(items, v.(map[string]interface{}))
}
} else if data, ok := list["items"].([]interface{}); ok {
for _, v := range data {
items = append(items, v.(map[string]interface{}))
}
}
for _, item := range items {
if name, ok := item["name"].(string); ok && name == workflow["name"].(string) {
if id, ok := item["id"].(string); ok {
state.WorkflowID = id
saveState()
fmt.Printf("✓ workflow \"%s\" found in your account (%s) — updating steps\n", workflow["name"], id)
apiCall("POST", fmt.Sprintf("/workflows/%s", id), map[string]interface{}{
"steps": workflow["steps"],
})
found = true
break
}
}
}
}
if !found {
created, err := apiCall("POST", "/workflows", workflow)
if err != nil {
fmt.Fprintln(os.Stderr, 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.Fprintln(os.Stderr, "Could not read created workflow id from response")
os.Exit(1)
}
state.WorkflowID = wfID
saveState()
fmt.Printf("+ created workflow (%s)\n", wfID)
}
}
apiCall("POST", fmt.Sprintf("/workflows/%s/versions", state.WorkflowID), map[string]interface{}{})
fmt.Println("\nDone. Run documents through it with:")
fmt.Printf(" POST %s/workflow_runs { workflow: { id: \"%s\" }, file: { url: \"https://…\" } }\n", API, state.WorkflowID)
fmt.Println("Or open the workflow in the Extend dashboard to review and deploy it.")
}A Certificate of Liability Insurance template that captures key policyholder information, producer details, multiple insurer listings with NAIC codes, and coverage specifics. This ACORD-standard form is commonly used to verify insurance coverage for contractual requirements and risk management purposes.