Extracts patient, insured, and payer information from health insurance claim forms.
A health insurance claim form is a legal document submitted by healthcare providers or patients to an insurance company requesting reimbursement for medical services rendered, containing detailed information about the patient, insured party, services provided, charges, diagnoses, and insurance coverage. This template takes in Health Insurance Claim Forms and outputs markdown (.md) capturing the document's full text and layout, and JSON (.json) with structured claim fields including patient and insured demographics, policy information, service line items with procedure and diagnosis codes, charges, provider details, and accident or employment-related indicators per the extraction schema by using Extend's Parse, Extract primitives.
Parse health insurance claim form to markdown
blockOptions.text.agentic.enabledtruechangedchunkingStrategy.type"document"engine"parse_performance"You can learn more about Parse configuration in Extend's Parse documentation.
Extract health insurance claim form fields
schemacustom schema — 51 fieldschangedadvancedOptions.advancedMultimodalEnabledtruechangedadvancedOptions.reviewAgent.enabledtruechangedbaseProcessor"extraction_performance"You can learn more about Extract configuration in Extend's Extract documentation.
{
"name": "Health Insurance Claim Form 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": [
"amount_paid",
"insured_sex",
"patient_sex",
"claim_number",
"insured_name",
"patient_name",
"total_charge",
"date_of_other",
"diagnosis_codes",
"insured_address",
"patient_address",
"claim_line_items",
"is_auto_accident",
"accept_assignment",
"is_other_accident",
"primary_policy_id",
"other_insured_name",
"secondary_policy_id",
"billing_provider_npi",
"insured_phone_number",
"patient_phone_number",
"primary_group_number",
"service_facility_npi",
"billing_provider_name",
"federal_tax_id_number",
"insured_date_of_birth",
"is_employment_related",
"patient_date_of_birth",
"service_facility_name",
"insured_signature_date",
"patient_account_number",
"patient_signature_date",
"rendering_provider_npi",
"secondary_group_number",
"primary_insurance_payer",
"referring_provider_name",
"rendering_provider_name",
"billing_provider_address",
"hospitalization_dates_to",
"service_facility_address",
"insured_signature_on_file",
"patient_signature_on_file",
"secondary_insurance_payer",
"hospitalization_dates_from",
"prior_authorization_number",
"other_insured_policy_number",
"referring_provider_identifier",
"dates_patient_unable_to_work_to",
"patient_relationship_to_insured",
"dates_patient_unable_to_work_from",
"date_of_current_illness_injury_pregnancy"
],
"properties": {
"amount_paid": {
"type": "object",
"required": [
"amount",
"iso_4217_currency_code"
],
"properties": {
"amount": {
"type": [
"number",
"null"
]
},
"iso_4217_currency_code": {
"type": [
"string",
"null"
]
}
},
"description": "The amount paid by the patient or other parties prior to claim submission. This is any payment already made toward the total charge.",
"extend:type": "currency",
"additionalProperties": false
},
"insured_sex": {
"type": [
"string",
"null"
],
"description": "The sex or gender of the insured individual. Common values include 'M', 'F', 'Male', 'Female', or similar."
},
"patient_sex": {
"type": [
"string",
"null"
],
"description": "The sex or gender of the patient. Common values include 'M', 'F', 'Male', 'Female', or similar."
},
"claim_number": {
"type": [
"string",
"null"
],
"description": "The unique identifier assigned to this health insurance claim. This may be labeled as 'Claim Number', 'Reference Number', or similar, and is used to track the claim throughout the adjudication process. In CMS-1500 forms, this may be found in various locations or referenced as an authorization or control number."
},
"insured_name": {
"type": [
"string",
"null"
],
"description": "The full name of the person who holds the insurance policy. This is the insured party, who may or may not be the patient. Typically appears as 'Insured's Name' and may include last, first, and middle initial."
},
"patient_name": {
"type": [
"string",
"null"
],
"description": "The full name of the patient receiving services. This is the individual for whom the claim is being submitted. Typically includes last, first, and middle initial."
},
"total_charge": {
"type": "object",
"required": [
"amount",
"iso_4217_currency_code"
],
"properties": {
"amount": {
"type": [
"number",
"null"
]
},
"iso_4217_currency_code": {
"type": [
"string",
"null"
]
}
},
"description": "The total amount charged for all services rendered on this claim, before any adjustments or payments. This is the sum of all line item charges.",
"extend:type": "currency",
"additionalProperties": false
},
"date_of_other": {
"type": [
"string",
"null"
],
"description": "Any other relevant date associated with the claim, such as a similar illness or accident, as indicated on the form.",
"extend:type": "date"
},
"diagnosis_codes": {
"type": "array",
"items": {
"type": "object",
"required": [
"diagnosis_code",
"diagnosis_code_pointer"
],
"properties": {
"diagnosis_code": {
"type": [
"string",
"null"
],
"description": "A single diagnosis code (ICD-10, ICD-9, or other standard) relevant to the patient's condition or treatment."
},
"diagnosis_code_pointer": {
"type": [
"string",
"null"
],
"description": "The letter or reference used to map this diagnosis code to a service line (e.g., 'A', 'B', etc.), if present."
}
},
"additionalProperties": false
},
"description": "The list of diagnosis codes (ICD) that describe the patient's condition or reason for the encounter. Each code represents a specific diagnosis or symptom relevant to the claim. These may be labeled as 'Diagnosis Code', 'ICD Code', or similar, and are often referenced by letter (A-L) for mapping to service lines."
},
"insured_address": {
"type": [
"string",
"null"
],
"description": "The complete mailing address of the insured individual, including street, city, state, and ZIP code."
},
"patient_address": {
"type": [
"string",
"null"
],
"description": "The complete mailing address of the patient, including street, city, state, and ZIP code. This is used for correspondence and identification."
},
"claim_line_items": {
"type": "array",
"items": {
"type": "object",
"required": [
"units",
"charge_amount",
"procedure_code",
"service_date_to",
"place_of_service",
"diagnosis_pointer",
"service_date_from",
"procedure_modifier",
"emergency_indicator",
"service_line_number",
"rendering_provider_qualifier",
"rendering_provider_identifier"
],
"properties": {
"units": {
"type": [
"number",
"null"
],
"description": "The number of units, days, or quantity for this service line."
},
"charge_amount": {
"type": [
"number",
"null"
],
"description": "The amount charged for this specific service line, before any adjustments or payments."
},
"procedure_code": {
"type": [
"string",
"null"
],
"description": "The CPT, HCPCS, or other procedure code describing the service or supply provided."
},
"service_date_to": {
"type": [
"string",
"null"
],
"description": "The end date for the service or procedure performed in this line item, if different from the start date.",
"extend:type": "date"
},
"place_of_service": {
"type": [
"string",
"null"
],
"description": "The code or description indicating where the service was provided (e.g., office, hospital, home)."
},
"diagnosis_pointer": {
"type": [
"string",
"null"
],
"description": "The letter(s) or reference(s) indicating which diagnosis code(s) apply to this service line."
},
"service_date_from": {
"type": [
"string",
"null"
],
"description": "The start date for the service or procedure performed in this line item.",
"extend:type": "date"
},
"procedure_modifier": {
"type": [
"string",
"null"
],
"description": "Any modifier(s) associated with the procedure code, if present."
},
"emergency_indicator": {
"type": [
"string",
"null"
],
"description": "Indicates if the service was an emergency. Typical values include 'Yes', 'No', or a checkbox indicator."
},
"service_line_number": {
"type": [
"string",
"null"
],
"description": "The sequential number or identifier for this service line, if present."
},
"rendering_provider_qualifier": {
"type": [
"string",
"null"
],
"description": "The qualifier code for the rendering provider's identification number, if present (e.g., 'NPI', 'UPIN')."
},
"rendering_provider_identifier": {
"type": [
"string",
"null"
],
"description": "The identification number for the rendering provider for this service line, such as NPI or other ID."
}
},
"additionalProperties": false
},
"description": "The list of individual service lines or procedures billed on this claim. Each line item represents a distinct service, procedure, or supply provided to the patient, and includes details such as dates, codes, charges, and provider information."
},
"is_auto_accident": {
"type": [
"string",
"null"
],
"description": "Indicates whether the patient's condition is related to an auto accident. Typical values are 'Yes', 'No', or similar."
},
"accept_assignment": {
"type": [
"string",
"null"
],
"description": "Indicates whether the provider accepts assignment of benefits. Typical values are 'Yes', 'No', or similar."
},
"is_other_accident": {
"type": [
"string",
"null"
],
"description": "Indicates whether the patient's condition is related to any other type of accident. Typical values are 'Yes', 'No', or similar."
},
"primary_policy_id": {
"type": [
"string",
"null"
],
"description": "The policy or member identification number for the primary insurance plan. This is the unique number assigned to the insured by the primary payer, often labeled as 'Insured's ID Number', 'Policy Number', or similar."
},
"other_insured_name": {
"type": [
"string",
"null"
],
"description": "The name of any additional insured party, if applicable. This may be present when there is more than one insurance policy involved."
},
"secondary_policy_id": {
"type": [
"string",
"null"
],
"description": "The policy or member identification number for the secondary insurance plan, if present. This is the unique number assigned to the insured by the secondary payer."
},
"billing_provider_npi": {
"type": [
"string",
"null"
],
"description": "The National Provider Identifier (NPI) for the billing provider, if applicable."
},
"insured_phone_number": {
"type": [
"string",
"null"
],
"description": "The telephone number for the insured individual, including area code."
},
"patient_phone_number": {
"type": [
"string",
"null"
],
"description": "The telephone number for the patient, including area code. Used for contact purposes."
},
"primary_group_number": {
"type": [
"string",
"null"
],
"description": "The group number associated with the primary insurance policy, if applicable. This is typically used for employer-sponsored or group health plans and may be labeled as 'Group Number', 'Group ID', or similar."
},
"service_facility_npi": {
"type": [
"string",
"null"
],
"description": "The National Provider Identifier (NPI) for the service facility, if applicable."
},
"billing_provider_name": {
"type": [
"string",
"null"
],
"description": "The name of the provider or entity submitting the claim for payment. This is the billing party, which may be an individual or organization."
},
"federal_tax_id_number": {
"type": [
"string",
"null"
],
"description": "The federal tax identification number (EIN or SSN) of the billing provider or entity submitting the claim."
},
"insured_date_of_birth": {
"type": [
"string",
"null"
],
"description": "The date of birth of the insured individual. This is used to verify identity and eligibility. May be labeled as 'Insured's Date of Birth' and can appear in various formats.",
"extend:type": "date"
},
"is_employment_related": {
"type": [
"string",
"null"
],
"description": "Indicates whether the patient's condition is related to employment. Typical values are 'Yes', 'No', or similar."
},
"patient_date_of_birth": {
"type": [
"string",
"null"
],
"description": "The date of birth of the patient. Used for identification and eligibility verification.",
"extend:type": "date"
},
"service_facility_name": {
"type": [
"string",
"null"
],
"description": "The name of the facility where services were rendered, if different from the billing provider."
},
"insured_signature_date": {
"type": [
"string",
"null"
],
"description": "The date the insured or authorized person signed the authorization, if present.",
"extend:type": "date"
},
"patient_account_number": {
"type": [
"string",
"null"
],
"description": "The account number assigned to the patient by the provider or billing entity. Used for internal tracking and reconciliation."
},
"patient_signature_date": {
"type": [
"string",
"null"
],
"description": "The date the patient or authorized person signed the authorization, if present.",
"extend:type": "date"
},
"rendering_provider_npi": {
"type": [
"string",
"null"
],
"description": "The National Provider Identifier (NPI) for the rendering provider, if applicable."
},
"secondary_group_number": {
"type": [
"string",
"null"
],
"description": "The group number associated with the secondary insurance policy, if applicable."
},
"primary_insurance_payer": {
"type": [
"string",
"null"
],
"description": "The name of the primary insurance company or payer responsible for processing this claim. This is the main insurer listed on the form, often labeled as 'Primary Payer', 'Insurance Carrier', or similar."
},
"referring_provider_name": {
"type": [
"string",
"null"
],
"description": "The name of the referring provider or other source who referred the patient for services. May be labeled as 'Referring Provider', 'Ordering Physician', or similar."
},
"rendering_provider_name": {
"type": [
"string",
"null"
],
"description": "The name of the individual provider who performed the services, if different from the billing provider."
},
"billing_provider_address": {
"type": [
"string",
"null"
],
"description": "The complete address of the billing provider, including street, city, state, and ZIP code."
},
"hospitalization_dates_to": {
"type": [
"string",
"null"
],
"description": "The end date of any hospitalization related to the current services, if applicable.",
"extend:type": "date"
},
"service_facility_address": {
"type": [
"string",
"null"
],
"description": "The address of the facility where services were rendered, including street, city, state, and ZIP code."
},
"insured_signature_on_file": {
"type": [
"string",
"null"
],
"description": "Indicates whether the insured's or authorized person's signature is on file authorizing payment of benefits. Typical values include 'Signature on File', 'Yes', or similar."
},
"patient_signature_on_file": {
"type": [
"string",
"null"
],
"description": "Indicates whether the patient's or authorized person's signature is on file authorizing release of information and payment. Typical values include 'Signature on File', 'Yes', or similar."
},
"secondary_insurance_payer": {
"type": [
"string",
"null"
],
"description": "The name of the secondary insurance company or payer, if present. This is an additional insurer that may provide coverage after the primary payer, often labeled as 'Secondary Payer' or similar."
},
"hospitalization_dates_from": {
"type": [
"string",
"null"
],
"description": "The start date of any hospitalization related to the current services, if applicable.",
"extend:type": "date"
},
"prior_authorization_number": {
"type": [
"string",
"null"
],
"description": "The authorization or referral number provided by the payer, if required for the services rendered. May be labeled as 'Prior Authorization Number', 'Referral Number', or similar."
},
"other_insured_policy_number": {
"type": [
"string",
"null"
],
"description": "The policy or group number for any additional insured party, if applicable."
},
"referring_provider_identifier": {
"type": [
"string",
"null"
],
"description": "The unique identifier (such as NPI or other ID) for the referring provider, if present."
},
"dates_patient_unable_to_work_to": {
"type": [
"string",
"null"
],
"description": "The end date when the patient was unable to work due to the condition, if applicable.",
"extend:type": "date"
},
"patient_relationship_to_insured": {
"type": [
"string",
"null"
],
"description": "The relationship of the patient to the insured individual. Typical values include 'Self', 'Spouse', 'Child', 'Other', or similar."
},
"dates_patient_unable_to_work_from": {
"type": [
"string",
"null"
],
"description": "The start date when the patient was unable to work due to the condition, if applicable.",
"extend:type": "date"
},
"date_of_current_illness_injury_pregnancy": {
"type": [
"string",
"null"
],
"description": "The date when the current illness, injury, or pregnancy began. This is used to establish the onset of the condition being treated.",
"extend:type": "date"
}
},
"additionalProperties": false
},
"baseProcessor": "extraction_performance",
"advancedOptions": {
"reviewAgent": {
"enabled": true
},
"advancedMultimodalEnabled": true
}
}
}
}
]
}# Health Insurance Claim Form Processing — Extend AI Skill
## What this pipeline does
This pipeline transforms a standardized health insurance claim form (CMS-1500 or similar NUCC-approved format) into structured, machine-readable data. It first parses the entire form into markdown to preserve layout and context, then extracts 47+ required fields including patient and insured demographics, policy details, diagnosis codes, service line items, provider information, and claim authorization signatures.
## When to use this
- **Claims processing automation**: Ingest paper or scanned CMS-1500 forms and route to adjudication systems without manual data entry.
- **Insurance carrier intake**: Validate and extract claims submitted by providers across multiple formats and condition variations.
- **Eligibility and compliance verification**: Confirm patient/insured relationships, policy IDs, and authorization signatures before processing.
- **Medical records integration**: Link diagnosis codes, procedure codes, and service dates to patient medical histories and prior claims.
- **Batch claim import**: Process 50–1000+ forms per day with consistent, validated output for downstream systems (claims databases, EDI feeds, analytics).
## Processor pipeline
### Step 1: Parse (agentic OCR)
**Processor**: `parseRuns.createAndPoll()` with `agentic_ocr` mode
**Purpose**: Convert the claim form (digital or scanned) into machine-readable markdown while preserving spatial relationships and structural intent.
**Key config**:
- `blockOptions.text.agentic.enabled: true` — enables smart layout analysis and form-specific segmentation; critical for CMS-1500 forms which have dense, tabular sections.
- `chunkingStrategy.type: "document"` — treats the entire claim as a single logical document, avoiding accidental splits across diagnosis/service line boundaries.
**Why this config**: Health insurance claim forms use checkboxes, narrow columns, and multi-section layouts that confuse standard OCR. Agentic OCR learns form structure (e.g., "diagnosis codes are in columns A–L") and accurately captures both printed and handwritten text. Document-level chunking keeps service line items and their linked diagnosis pointers intact.
### Step 2: Extract (structured fields)
**Processor**: `extractRuns.createAndPoll()` with Zod schema + `extraction_performance` baseProcessor
**Purpose**: Parse the markdown output into 47 required fields with strong typing, nullability, and semantic validation.
**Key config**:
- `baseProcessor: "extraction_performance"` — uses multimodal LLM reasoning over both the original image and parsed markdown; necessary for complex claim logic (e.g., mapping diagnosis pointers to service lines, validating policy ID format).
- `schema`: Root-level object with nested currency objects, date fields with `extendDate()`, and arrays for diagnosis codes and line items.
- `advancedOptions.reviewAgent.enabled: true` — runs a secondary validation pass to catch missed fields or inconsistencies (e.g., total_charge != sum of line items, missing required signatures).
- `advancedMultimodalEnabled: true` — allows the extractor to reference both markdown and original image to resolve ambiguities (e.g., handwritten provider NPI vs. printed policy number).
**Why this config**: Claims data has strict regulatory requirements (ICD-10 codes, NPI format, currency precision). The review agent catches common errors (transposed numbers, partial phone numbers, misaligned date formats) before they reach downstream systems. Multimodal extraction tolerates handwriting, stamps, and form variants.
## TypeScript implementation
<SDK_CODE>
import { ExtendClient, extendDate, extendCurrency } from "extend-ai";
import { z } from "zod";
import fs from "fs";
import path from "path";
const client = new ExtendClient({ token: process.env.EXTEND_API_KEY });
// Zod schema matching the extraction config exactly
const claimFormSchema = z.object({
// Demographics
patient_name: z.string().nullable().describe("Full name of the patient receiving services (last, first, middle initial)."),
patient_date_of_birth: extendDate().describe("Patient's date of birth (ISO yyyy-mm-dd format)."),
patient_sex: z.string().nullable().describe("Patient's sex or gender. Common values: 'M', 'F', 'Male', 'Female', or similar."),
patient_address: z.string().nullable().describe("Patient's complete mailing address including street, city, state, and ZIP code."),
patient_phone_number: z.string().nullable().describe("Patient's telephone number including area code."),
patient_account_number: z.string().nullable().describe("Account number assigned by the provider for internal tracking."),
patient_relationship_to_insured: z.string().nullable().describe("Relationship of patient to insured. Common values: 'Self', 'Spouse', 'Child', 'Other'."),
patient_signature_on_file: z.string().nullable().describe("Indicates if patient's signature is on file. Typical values: 'Signature on File', 'Yes'."),
patient_signature_date: extendDate().describe("Date patient signed authorization (ISO yyyy-mm-dd)."),
// Insured information
insured_name: z.string().nullable().describe("Full name of the person holding the insurance policy (last, first, middle initial)."),
insured_date_of_birth: extendDate().describe("Insured's date of birth (ISO yyyy-mm-dd)."),
insured_sex: z.string().nullable().describe("Insured's sex or gender. Common values: 'M', 'F', 'Male', 'Female'."),
insured_address: z.string().nullable().describe("Insured's complete mailing address including street, city, state, and ZIP code."),
insured_phone_number: z.string().nullable().describe("Insured's telephone number including area code."),
insured_signature_on_file: z.string().nullable().describe("Indicates if insured's signature is on file. Typical values: 'Signature on File', 'Yes'."),
insured_signature_date: extendDate().describe("Date insured signed authorization (ISO yyyy-mm-dd)."),
// Primary insurance
primary_insurance_payer: z.string().nullable().describe("Name of the primary insurance company or payer responsible for processing the claim."),
primary_policy_id: z.string().nullable().describe("Insured's ID number or policy number for the primary insurance plan."),
primary_group_number: z.string().nullable().describe("Group number for the primary insurance policy, if applicable (employer-sponsored plans)."),
// Secondary insurance
secondary_insurance_payer: z.string().nullable().describe("Name of the secondary insurance company or payer, if present."),
secondary_policy_id: z.string().nullable().describe("Insured's ID number or policy number for the secondary insurance plan, if present."),
secondary_group_number: z.string().nullable().describe("Group number for the secondary insurance policy, if applicable."),
// Other insured
other_insured_name: z.string().nullable().describe("Name of any additional insured party when multiple insurance policies apply."),
other_insured_policy_number: z.string().nullable().describe("Policy or group number for the additional insured party."),
// Claim identifiers
claim_number: z.string().nullable().describe("Unique identifier for this claim, used to track throughout adjudication. May be labeled 'Claim Number', 'Reference Number', or similar."),
prior_authorization_number: z.string().nullable().describe("Authorization or referral number from the payer, if required for services."),
// Financial
total_charge: extendCurrency().describe("Total amount charged for all services, before adjustments or payments. Sum of all line item charges."),
amount_paid: extendCurrency().describe("Amount paid by patient or other parties prior to claim submission."),
accept_assignment: z.string().nullable().describe("Whether the provider accepts assignment of benefits. Typical values: 'Yes', 'No'."),
// Billing provider
billing_provider_name: z.string().nullable().describe("Name of the provider or entity submitting the claim."),
billing_provider_npi: z.string().nullable().describe("National Provider Identifier (NPI) for the billing provider."),
billing_provider_address: z.string().nullable().describe("Complete address of the billing provider including street, city, state, and ZIP."),
federal_tax_id_number: z.string().nullable().describe("Federal tax identification number (EIN or SSN) of the billing provider."),
// Service facility
service_facility_name: z.string().nullable().describe("Name of the facility where services were rendered, if different from billing provider."),
service_facility_npi: z.string().nullable().describe("NPI for the service facility."),
service_facility_address: z.string().nullable().describe("Address of the service facility including street, city, state, and ZIP."),
// Rendering provider
rendering_provider_name: z.string().nullable().describe("Name of the individual provider who performed the services."),
rendering_provider_npi: z.string().nullable().describe("NPI for the rendering provider."),
// Referring provider
referring_provider_name: z.string().nullable().describe("Name of the referring provider or ordering physician."),
referring_provider_identifier: z.string().nullable().describe("Unique identifier (NPI or other ID) for the referring provider."),
// Diagnosis codes
diagnosis_codes: z.array(z.object({
diagnosis_code: z.string().nullable().describe("Single diagnosis code (ICD-10, ICD-9, or other standard)."),
diagnosis_code_pointer: z.string().nullable().describe("Letter or reference (e.g., 'A', 'B') mapping this code to service lines."),
})).describe("List of diagnosis codes describing the patient's condition. Each code may be referenced by letter (A–L) in service lines."),
// Service dates and conditions
date_of_current_illness_injury_pregnancy: extendDate().describe("Date when the current illness, injury, or pregnancy began (ISO yyyy-mm-dd)."),
date_of_other: extendDate().describe("Any other relevant date (e.g., similar illness or accident)."),
hospitalization_dates_from: extendDate().describe("Start date of any hospitalization related to current services (ISO yyyy-mm-dd)."),
hospitalization_dates_to: extendDate().describe("End date of any hospitalization (ISO yyyy-mm-dd)."),
dates_patient_unable_to_work_from: extendDate().describe("Start date when patient was unable to work (ISO yyyy-mm-dd)."),
dates_patient_unable_to_work_to: extendDate().describe("End date when patient was unable to work (ISO yyyy-mm-dd)."),
// Accident indicators
is_auto_accident: z.string().nullable().describe("Whether condition is related to auto accident. Typical values: 'Yes', 'No'."),
is_other_accident: z.string().nullable().describe("Whether condition is related to other type of accident. Typical values: 'Yes', 'No'."),
is_employment_related: z.string().nullable().describe("Whether condition is work-related. Typical values: 'Yes', 'No'."),
// Service line items (array of procedures/services)
claim_line_items: z.array(z.object({
service_line_number: z.string().nullable().describe("Sequential line number or identifier for this service."),
service_date_from: extendDate().describe("Start date of service (ISO yyyy-mm-dd)."),
service_date_to: extendDate().describe("End date of service (ISO yyyy-mm-dd)."),
place_of_service: z.string().nullable().describe("Code or description where service was provided (e.g., 'Office', 'Hospital', 'Home')."),
procedure_code: z.string().nullable().describe("CPT, HCPCS, or other procedure code for the service provided."),
procedure_modifier: z.string().nullable().describe("Modifier(s) associated with the procedure code."),
units: z.number().nullable().describe("Number of units, days, or quantity for this service."),
charge_amount: z.number().nullable().describe("Amount charged for this service line, before adjustments."),
diagnosis_pointer: z.string().nullable().describe("Letter(s) indicating which diagnosis codes apply to this line item."),
emergency_indicator: z.string().nullable().describe("Indicates if service was emergency. Typical values: 'Yes', 'No'."),
rendering_provider_identifier: z.string().nullable().describe("NPI or other ID for the rendering provider for this line."),
rendering_provider_qualifier: z.string().nullable().describe("Qualifier code for provider ID (e.g., 'NPI', 'UPIN')."),
})).describe("Individual service lines or procedures billed on this claim. Each includes dates, codes, charges, and provider info."),
});
export async function processHealthInsuranceClaimForm(filePath: string) {
console.log(`\n📋 Processing health insurance claim form: ${filePath}`);
// Step 1: Read local file and convert to data URL
const fileBuffer = fs.readFileSync(filePath);
const base64Data = fileBuffer.toString("base64");
const fileExt = path.extname(filePath).toLowerCase();
const mimeType = fileExt === ".pdf" ? "application/pdf" : "image/jpeg";
const dataUrl = `data:${mimeType};base64,${base64Data}`;
// Step 2: Parse the claim form to markdown
console.log("\n1️⃣ Parsing claim form to markdown...");
const parseRun = await client.parseRuns.createAndPoll({
file: { url: dataUrl },
config: {
mode: "agentic_ocr",
outputType: "markdown",
},
});
if (parseRun.status !== "PROCESSED") {
throw new Error(`Parse failed with status: ${parseRun.status}`);
}
const markdownContent = parseRun.output.chunks
.map((chunk) => chunk.content)
.join("\n\n");
console.log(`✅ Parsed ${parseRun.output.chunks.length} chunks from form.`);
console.log(`Preview (first 500 chars):\n${markdownContent.substring(0, 500)}...\n`);
// Step 3: Extract structured fields using Zod schema
console.log("2️⃣ Extracting structured claim fields...");
const extractRun = await client.extractRuns.createAndPoll({
file: { url: dataUrl },
config: {
schema: claimFormSchema,
},
});
if (extractRun.status !== "PROCESSED") {
throw new Error(`Extraction failed with status: ${extractRun.status}`);
}
const claimData = extractRun.output.value;
console.log("✅ Extraction complete. Extracted fields:");
// Step 4: Display extracted data in organized sections
console.log("\n═══════════════════════════════════════════════════════════");
console.log("📊 CLAIM SUMMARY");
console.log("═══════════════════════════════════════════════════════════");
console.log("\n👤 PATIENT INFORMATION:");
console.log(` Name: ${claimData.patient_name || "(not provided)"}`);
console.log(` DOB: ${claimData.patient_date_of_birth || "(not provided)"}`);
console.log(` Sex: ${claimData.patient_sex || "(not provided)"}`);
console.log(` Address: ${claimData.patient_address || "(not provided)"}`);
console.log(` Phone: ${claimData.patient_phone_number || "(not provided)"}`);
console.log(` Account #: ${claimData.patient_account_number || "(not provided)"}`);
console.log(` Relationship to Insured: ${claimData.patient_relationship_to_insured || "(not provided)"}`);
console.log("\n🛡️ INSURED INFORMATION:");
console.log(` Name: ${claimData.insured_name || "(not provided)"}`);
console.log(` DOB: ${claimData.insured_date_of_birth || "(not provided)"}`);
console.log(` Sex: ${claimData.insured_sex || "(not provided)"}`);
console.log(` Address: ${claimData.insured_address || "(import { ExtendClient, extendDate } from "extend-ai";
import { z } from "zod";
import fs from "fs";
import path from "path";
const client = new ExtendClient({ token: process.env.EXTEND_API_KEY });
// Zod schema matching the extraction requirements
const healthClaimSchema = z.object({
primary_payer: z.string().nullable().describe(
"Primary insurance payer name (e.g., 'Aetna', 'United Healthcare'). Extract from 'Primary Payer:' field."
),
primary_policy_id: z.string().nullable().describe(
"Primary insurance policy ID number (e.g., 'W789216712'). Extract from 'Primary Policy ID#' field."
),
secondary_payer: z.string().nullable().describe(
"Secondary insurance payer name. Leave null if no secondary coverage. Extract from 'Secondary Payer:' field."
),
secondary_policy_id: z.string().nullable().describe(
"Secondary insurance policy ID number. Leave null if no secondary coverage."
),
patient_name: z.string().nullable().describe(
"Patient's full name in format Last, First, Middle Initial (e.g., 'Smith, John M'). Extract from claim form name field."
),
patient_date_of_birth: z.string().nullable().describe(
"Patient's date of birth in MM/DD/YYYY format (e.g., '01/15/1985'). Extract from DOB field on form."
),
insured_name: z.string().nullable().describe(
"Insured person's full name in format Last, First, Middle Initial. This is the policy holder; may differ from patient if dependent."
),
patient_relationship_to_insured: z.string().nullable().describe(
"Patient's relationship to insured person. Must be one of: Self, Spouse, Child, Other. Extract from relationship field or infer from context."
),
group_number: z.string().nullable().describe(
"Insured's policy group or FECA number (e.g., '8946431'). Extract from 'Group#' field."
),
signature_date: z.string().nullable().describe(
"Date of patient authorization signature in MM-DD-YYYY format (e.g., '03-15-2024'). Extract from signature date field."
),
payer_contact_number: z.string().nullable().describe(
"Primary payer contact phone number (e.g., '888-632-3862'). Extract from 'Contact#' field for primary payer."
),
condition_related_to_employment: z.string().nullable().describe(
"Whether patient's condition is related to employment or workers' compensation. Must be YES or NO. Extract from employment-related question or checkbox."
),
});
export async function processHealthInsuranceClaimForm(filePath: string) {
console.log(`Processing claim form: ${filePath}`);
// Step 1: Read local file and encode as data URL
const fileBuffer = fs.readFileSync(filePath);
const base64Data = fileBuffer.toString("base64");
const mimeType = filePath.toLowerCase().endsWith(".pdf") ? "application/pdf" : "image/jpeg";
const dataUrl = `data:${mimeType};base64,${base64Data}`;
// Step 2: Parse the claim form using agentic OCR
console.log("Step 1: Parsing claim form with agentic OCR...");
const parseRun = await client.parseRuns.createAndPoll({
file: { url: dataUrl },
config: {
mode: "agentic_ocr",
outputType: "markdown",
},
});
if (parseRun.status !== "PROCESSED") {
throw new Error(`Parse failed with status: ${parseRun.status}`);
}
const parsedMarkdown = parseRun.output.chunks.map((c) => c.content).join("\n\n");
console.log(`✓ Parsed ${parseRun.output.chunks.length} chunks from claim form`);
// Step 3: Extract structured fields from parsed markdown
console.log("Step 2: Extracting claim fields...");
const extractRun = await client.extractRuns.createAndPoll({
file: { url: dataUrl },
config: {
schema: healthClaimSchema,
baseProcessor: "extraction_performance",
},
});
if (extractRun.status !== "PROCESSED") {
throw new Error(`Extract failed with status: ${extractRun.status}`);
}
const claimData = extractRun.output.value;
console.log("✓ Extraction complete");
// Step 4: Validate and format output
const result = {
status: "success",
file: path.basename(filePath),
parsedChunks: parseRun.output.chunks.length,
extractedData: claimData,
validations: {
hasPrimaryPayer: !!claimData.primary_payer,
hasPrimaryPolicy: !!claimData.primary_policy_id,
hasPatientName: !!claimData.patient_name,
hasDOB: !!claimData.patient_date_of_birth,
hasSignatureDate: !!claimData.signature_date,
isMultiPayer: !!claimData.secondary_payer && !!claimData.secondary_policy_id,
},
};
console.log("\n=== Extraction Results ===");
console.log(`Primary Payer: ${claimData.primary_payer}`);
console.log(`Primary Policy ID: ${claimData.primary_policy_id}`);
console.log(`Patient Name: ${claimData.patient_name}`);
console.log(`Patient DOB: ${claimData.patient_date_of_birth}`);
console.log(`Insured Name: ${claimData.insured_name}`);
console.log(`Relationship: ${claimData.patient_relationship_to_insured}`);
console.log(`Group Number: ${claimData.group_number}`);
console.log(`Signature Date: ${claimData.signature_date}`);
console.log(`Payer Contact: ${claimData.payer_contact_number}`);
console.log(`Employment Related: ${claimData.condition_related_to_employment}`);
if (claimData.secondary_payer) {
console.log(`\nSecondary Payer: ${claimData.secondary_payer}`);
console.log(`Secondary Policy ID: ${claimData.secondary_policy_id}`);
}
return result;
}
// Main entry point for testing
const filePath = process.argv[2] || "./sample_claim_form.pdf";
processHealthInsuranceClaimForm(filePath)
.then((result) => console.log("\nFinal Result:", JSON.stringify(result, null, 2)))
.catch((err) => {
console.error("Error:", err.message);
process.exit(1);
});import os
import base64
import json
from pathlib import Path
from typing import Optional, Any
from extend_ai import Extend
from pydantic import BaseModel, Field
from typing import List
client = Extend(token=os.getenv("EXTEND_API_KEY"))
# Pydantic model matching the extraction requirements
class DiagnosisCode(BaseModel):
diagnosis_code: Optional[str] = Field(None, description="A single diagnosis code (ICD-10, ICD-9, or other standard) relevant to the patient's condition or treatment.")
diagnosis_code_pointer: Optional[str] = Field(None, description="The letter or reference used to map this diagnosis code to a service line (e.g., 'A', 'B', etc.), if present.")
class ClaimLineItem(BaseModel):
units: Optional[float] = None
charge_amount: Optional[float] = None
procedure_code: Optional[str] = None
service_date_to: Optional[str] = None
place_of_service: Optional[str] = None
diagnosis_pointer: Optional[str] = None
service_date_from: Optional[str] = None
procedure_modifier: Optional[str] = None
emergency_indicator: Optional[str] = None
service_line_number: Optional[str] = None
rendering_provider_qualifier: Optional[str] = None
rendering_provider_identifier: Optional[str] = None
class CurrencyAmount(BaseModel):
amount: Optional[float] = None
iso_4217_currency_code: Optional[str] = None
class HealthClaimSchema(BaseModel):
amount_paid: CurrencyAmount
insured_sex: Optional[str] = None
patient_sex: Optional[str] = None
claim_number: Optional[str] = None
insured_name: Optional[str] = None
patient_name: Optional[str] = None
total_charge: CurrencyAmount
date_of_other: Optional[str] = None
diagnosis_codes: List[DiagnosisCode] = []
insured_address: Optional[str] = None
patient_address: Optional[str] = None
claim_line_items: List[ClaimLineItem] = []
is_auto_accident: Optional[str] = None
accept_assignment: Optional[str] = None
is_other_accident: Optional[str] = None
primary_policy_id: Optional[str] = None
other_insured_name: Optional[str] = None
secondary_policy_id: Optional[str] = None
billing_provider_npi: Optional[str] = None
insured_phone_number: Optional[str] = None
patient_phone_number: Optional[str] = None
primary_group_number: Optional[str] = None
service_facility_npi: Optional[str] = None
billing_provider_name: Optional[str] = None
federal_tax_id_number: Optional[str] = None
insured_date_of_birth: Optional[str] = None
is_employment_related: Optional[str] = None
patient_date_of_birth: Optional[str] = None
service_facility_name: Optional[str] = None
insured_signature_date: Optional[str] = None
patient_account_number: Optional[str] = None
patient_signature_date: Optional[str] = None
rendering_provider_npi: Optional[str] = None
secondary_group_number: Optional[str] = None
primary_insurance_payer: Optional[str] = None
referring_provider_name: Optional[str] = None
rendering_provider_name: Optional[str] = None
billing_provider_address: Optional[str] = None
hospitalization_dates_to: Optional[str] = None
service_facility_address: Optional[str] = None
insured_signature_on_file: Optional[str] = None
patient_signature_on_file: Optional[str] = None
secondary_insurance_payer: Optional[str] = None
hospitalization_dates_from: Optional[str] = None
prior_authorization_number: Optional[str] = None
other_insured_policy_number: Optional[str] = None
referring_provider_identifier: Optional[str] = None
dates_patient_unable_to_work_to: Optional[str] = None
patient_relationship_to_insured: Optional[str] = None
dates_patient_unable_to_work_from: Optional[str] = None
date_of_current_illness_injury_pregnancy: Optional[str] = None
def process_health_insurance_claim_form(file_path: str) -> dict[str, Any]:
"""Process health insurance claim form with agentic OCR and extraction."""
print(f"Processing claim form: {file_path}")
# Step 1: Read local file and encode as data URL
with open(file_path, "rb") as f:
file_buffer = f.read()
base64_data = base64.b64encode(file_buffer).decode("utf-8")
mime_type = "application/pdf" if file_path.lower().endswith(".pdf") else "image/jpeg"
data_url = f"data:{mime_type};base64,{base64_data}"
# Step 2: Parse the claim form using agentic OCR
print("Step 1: Parsing claim form with agentic OCR...")
parse_run = client.parse_runs.create_and_poll(
file={"url": data_url},
config={
"mode": "agentic_ocr",
"output_type": "markdown",
},
)
if parse_run.status != "PROCESSED":
raise Exception(f"Parse failed with status: {parse_run.status}")
parsed_markdown = "\n\n".join([chunk.content for chunk in parse_run.output.chunks])
print(f"✓ Parsed {len(parse_run.output.chunks)} chunks from claim form")
# Step 3: Extract structured fields from parsed markdown
print("Step 2: Extracting claim fields...")
extract_run = client.extract_runs.create_and_poll(
file={"url": data_url},
config={
"schema": HealthClaimSchema,
"base_processor": "extraction_performance",
},
)
if extract_run.status != "PROCESSED":
raise Exception(f"Extract failed with status: {extract_run.status}")
claim_data = extract_run.output.value
print("✓ Extraction complete")
# Step 4: Validate and format output
result = {
"status": "success",
"file": Path(file_path).name,
"parsed_chunks": len(parse_run.output.chunks),
"extracted_data": claim_data.model_dump(),
"validations": {
"has_primary_payer": claim_data.primary_insurance_payer is not None,
"has_primary_policy": claim_data.primary_policy_id is not None,
"has_patient_name": claim_data.patient_name is not None,
"has_dob": claim_data.patient_date_of_birth is not None,
"has_signature_date": claim_data.patient_signature_date is not None,
"is_multi_payer": (claim_data.secondary_insurance_payer is not None
and claim_data.secondary_policy_id is not None),
},
}
print("\n=== Extraction Results ===")
print(f"Primary Payer: {claim_data.primary_insurance_payer}")
print(f"Primary Policy ID: {claim_data.primary_policy_id}")
print(f"Patient Name: {claim_data.patient_name}")
print(f"Patient DOB: {claim_data.patient_date_of_birth}")
print(f"Insured Name: {claim_data.insured_name}")
print(f"Relationship: {claim_data.patient_relationship_to_insured}")
print(f"Group Number: {claim_data.primary_group_number}")
print(f"Signature Date: {claim_data.patient_signature_date}")
print(f"Payer Contact: {claim_data.insured_phone_number}")
print(f"Employment Related: {claim_data.is_employment_related}")
if claim_data.secondary_insurance_payer:
print(f"\nSecondary Payer: {claim_data.secondary_insurance_payer}")
print(f"Secondary Policy ID: {claim_data.secondary_policy_id}")
return result
# Main entry point for testing
if __name__ == "__main__":
import sys
file_path = sys.argv[1] if len(sys.argv) > 1 else "./sample_claim_form.pdf"
try:
result = process_health_insurance_claim_form(file_path)
print("\nFinal Result:", json.dumps(result, indent=2, default=str))
except Exception as err:
print(f"Error: {err}")
sys.exit(1)import com.extendai.ExtendClient;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.LinkedHashMap;
public class HealthInsuranceClaimProcessor {
private static final ExtendClient client = new ExtendClient(System.getenv("EXTEND_API_KEY"));
static class ClaimData {
public String primary_payer;
public String primary_policy_id;
public String secondary_payer;
public String secondary_policy_id;
public String patient_name;
public String patient_date_of_birth;
public String insured_name;
public String patient_relationship_to_insured;
public String group_number;
public String signature_date;
public String payer_contact_number;
public String condition_related_to_employment;
}
public static void processHealthInsuranceClaimForm(String filePath) throws Exception {
System.out.println("Processing claim form: " + filePath);
// Step 1: Read local file and encode as data URL
byte[] fileBuffer = Files.readAllBytes(Paths.get(filePath));
String base64Data = Base64.getEncoder().encodeToString(fileBuffer);
String mimeType = filePath.toLowerCase().endsWith(".pdf") ? "application/pdf" : "image/jpeg";
String dataUrl = "data:" + mimeType + ";base64," + base64Data;
// Step 2: Parse the claim form using agentic OCR
System.out.println("Step 1: Parsing claim form with agentic OCR...");
Map<String, Object> parseConfig = new LinkedHashMap<>();
parseConfig.put("mode", "agentic_ocr");
parseConfig.put("outputType", "markdown");
Map<String, Object> parseFile = new LinkedHashMap<>();
parseFile.put("url", dataUrl);
ParseRun parseRun = client.parseRuns().createAndPoll(
new ParseRunRequest()
.setFile(parseFile)
.setConfig(parseConfig)
);
if (!"PROCESSED".equals(parseRun.getStatus())) {
throw new Exception("Parse failed with status: " + parseRun.getStatus());
}
StringBuilder parsedMarkdown = new StringBuilder();
for (ParseChunk chunk : parseRun.getOutput().getChunks()) {
parsedMarkdown.append(chunk.getContent()).append("\n\n");
}
System.out.println("✓ Parsed " + parseRun.getOutput().getChunks().size() + " chunks from claim form");
// Step 3: Extract structured fields from parsed markdown
System.out.println("Step 2: Extracting claim fields...");
Map<String, Object> healthClaimSchema = buildHealthClaimSchema();
Map<String, Object> extractConfig = new LinkedHashMap<>();
extractConfig.put("schema", healthClaimSchema);
extractConfig.put("baseProcessor", "extraction_performance");
Map<String, Object> extractFile = new LinkedHashMap<>();
extractFile.put("url", dataUrl);
ExtractRun extractRun = client.extractRuns().createAndPoll(
new ExtractRunRequest()
.setFile(extractFile)
.setConfig(extractConfig)
);
if (!"PROCESSED".equals(extractRun.getStatus())) {
throw new Exception("Extract failed with status: " + extractRun.getStatus());
}
Map<String, Object> claimData = (Map<String, Object>) extractRun.getOutput().getValue();
System.out.println("✓ Extraction complete");
// Step 4: Validate and format output
Map<String, Object> validations = new LinkedHashMap<>();
validations.put("hasPrimaryPayer", claimData.get("primary_insurance_payer") != null);
validations.put("hasPrimaryPolicy", claimData.get("primary_policy_id") != null);
validations.put("hasPatientName", claimData.get("patient_name") != null);
validations.put("hasDOB", claimData.get("patient_date_of_birth") != null);
validations.put("hasSignatureDate", claimData.get("patient_signature_date") != null);
validations.put("isMultiPayer",
claimData.get("secondary_insurance_payer") != null &&
claimData.get("secondary_policy_id") != null);
Map<String, Object> result = new LinkedHashMap<>();
result.put("status", "success");
result.put("file", Paths.get(filePath).getFileName().toString());
result.put("parsedChunks", parseRun.getOutput().getChunks().size());
result.put("extractedData", claimData);
result.put("validations", validations);
// Step 5: Print results
System.out.println("\n=== Extraction Results ===");
System.out.println("Primary Payer: " + claimData.get("primary_insurance_payer"));
System.out.println("Primary Policy ID: " + claimData.get("primary_policy_id"));
System.out.println("Patient Name: " + claimData.get("patient_name"));
System.out.println("Patient DOB: " + claimData.get("patient_date_of_birth"));
System.out.println("Insured Name: " + claimData.get("insured_name"));
System.out.println("Relationship: " + claimData.get("patient_relationship_to_insured"));
System.out.println("Group Number: " + claimData.get("primary_group_number"));
System.out.println("Signature Date: " + claimData.get("patient_signature_date"));
System.out.println("Payer Contact: " + claimData.get("patient_phone_number"));
System.out.println("Employment Related: " + claimData.get("is_employment_related"));
if (claimData.get("secondary_insurance_payer") != null) {
System.out.println("\nSecondary Payer: " + claimData.get("secondary_insurance_payer"));
System.out.println("Secondary Policy ID: " + claimData.get("secondary_policy_id"));
}
System.out.println("\nFinal Result: " + toJson(result));
}
private static Map<String, Object> buildHealthClaimSchema() {
Map<String, Object> schema = new LinkedHashMap<>();
schema.put("type", "object");
Map<String, Object> properties = new LinkedHashMap<>();
properties.put("primary_insurance_payer", new LinkedHashMap<String, Object>() {{
put("type", new String[]{"string", "null"});
put("description", "The name of the primary insurance company or payer responsible for processing this claim.");
}});
properties.put("primary_policy_id", new LinkedHashMap<String, Object>() {{
put("type", new String[]{"string", "null"});
put("description", "The policy or member identification number for the primary insurance plan.");
}});
properties.put("secondary_insurance_payer", new LinkedHashMap<String, Object>() {{
put("type", new String[]{"string", "null"});
put("description", "The name of the secondary insurance company or payer, if present.");
}});
properties.put("secondary_policy_id", new LinkedHashMap<String, Object>() {{
put("type", new String[]{"string", "null"});
put("description", "The policy or member identification number for the secondary insurance plan, if present.");
}});
properties.put("patient_name", new LinkedHashMap<String, Object>() {{
put("type", new String[]{"string", "null"});
put("description", "The full name of the patient receiving services.");
}});
properties.put("patient_date_of_birth", new LinkedHashMap<String, Object>() {{
put("type", new String[]{"string", "null"});
put("extend:type", "date");
put("description", "The date of birth of the patient.");
}});
properties.put("insured_name", new LinkedHashMap<String, Object>() {{
put("type", new String[]{"string", "null"});
put("description", "The full name of the person who holds the insurance policy.");
}});
properties.put("patient_relationship_to_insured", new LinkedHashMap<String, Object>() {{
put("type", new String[]{"string", "null"});
put("description", "The relationship of the patient to the insured individual.");
}});
properties.put("primary_group_number", new LinkedHashMap<String, Object>() {{
put("type", new String[]{"string", "null"});
put("description", "The group number associated with the primary insurance policy, if applicable.");
}});
properties.put("patient_signature_date", new LinkedHashMap<String, Object>() {{
put("type", new String[]{"string", "null"});
put("extend:type", "date");
put("description", "The date the patient or authorized person signed the authorization, if present.");
}});
properties.put("patient_phone_number", new LinkedHashMap<String, Object>() {{
put("type", new String[]{"string", "null"});
put("description", "The telephone number for the patient, including area code.");
}});
properties.put("is_employment_related", new LinkedHashMap<String, Object>() {{
put("type", new String[]{"string", "null"});
put("description", "Indicates whether the patient's condition is related to employment.");
}});
schema.put("properties", properties);
return schema;
}
private static String toJson(Object obj) {
return obj.toString();
}
public static void main(String[] args) {
try {
String filePath = args.length > 0 ? args[0] : "./sample_claim_form.pdf";
processHealthInsuranceClaimForm(filePath);
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
e.printStackTrace();
System.exit(1);
}
}
}package main
import (
"encoding/base64"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"github.com/extend-ai/extend-go/client"
"github.com/extend-ai/extend-go/models"
)
func processHealthInsuranceClaimForm(filePath string) (map[string]interface{}, error) {
fmt.Printf("Processing claim form: %s\n", filePath)
// Step 1: Read local file and encode as data URL
fileBuffer, err := ioutil.ReadFile(filePath)
if err != nil {
return nil, err
}
base64Data := base64.StdEncoding.EncodeToString(fileBuffer)
mimeType := "image/jpeg"
if strings.HasSuffix(strings.ToLower(filePath), ".pdf") {
mimeType = "application/pdf"
}
dataURL := fmt.Sprintf("data:%s;base64,%s", mimeType, base64Data)
// Step 2: Parse the claim form using agentic OCR
fmt.Println("Step 1: Parsing claim form with agentic OCR...")
extendClient := client.NewExtendClient(&client.ClientConfig{
Token: os.Getenv("EXTEND_API_KEY"),
})
parseRun, err := extendClient.ParseRuns.CreateAndPoll(&models.ParseRunRequest{
File: &models.FileInput{
URL: dataURL,
},
Config: &models.ParseConfig{
Mode: "agentic_ocr",
OutputType: "markdown",
},
})
if err != nil {
return nil, err
}
if parseRun.Status != "PROCESSED" {
return nil, fmt.Errorf("parse failed with status: %s", parseRun.Status)
}
parsedMarkdown := ""
for _, chunk := range parseRun.Output.Chunks {
parsedMarkdown += chunk.Content + "\n\n"
}
fmt.Printf("✓ Parsed %d chunks from claim form\n", len(parseRun.Output.Chunks))
// Step 3: Extract structured fields from parsed markdown
fmt.Println("Step 2: Extracting claim fields...")
schema := map[string]interface{}{
"type": "object",
"properties": map[string]interface{}{
"primary_payer": map[string]interface{}{
"type": "string",
"description": "Primary insurance payer name (e.g., 'Aetna', 'United Healthcare'). Extract from 'Primary Payer:' field.",
},
"primary_policy_id": map[string]interface{}{
"type": "string",
"description": "Primary insurance policy ID number (e.g., 'W789216712'). Extract from 'Primary Policy ID#' field.",
},
"secondary_payer": map[string]interface{}{
"type": "string",
"description": "Secondary insurance payer name. Leave null if no secondary coverage. Extract from 'Secondary Payer:' field.",
},
"secondary_policy_id": map[string]interface{}{
"type": "string",
"description": "Secondary insurance policy ID number. Leave null if no secondary coverage.",
},
"patient_name": map[string]interface{}{
"type": "string",
"description": "Patient's full name in format Last, First, Middle Initial (e.g., 'Smith, John M'). Extract from claim form name field.",
},
"patient_date_of_birth": map[string]interface{}{
"type": "string",
"description": "Patient's date of birth in MM/DD/YYYY format (e.g., '01/15/1985'). Extract from DOB field on form.",
},
"insured_name": map[string]interface{}{
"type": "string",
"description": "Insured person's full name in format Last, First, Middle Initial. This is the policy holder; may differ from patient if dependent.",
},
"patient_relationship_to_insured": map[string]interface{}{
"type": "string",
"description": "Patient's relationship to insured person. Must be one of: Self, Spouse, Child, Other. Extract from relationship field or infer from context.",
},
"group_number": map[string]interface{}{
"type": "string",
"description": "Insured's policy group or FECA number (e.g., '8946431'). Extract from 'Group#' field.",
},
"signature_date": map[string]interface{}{
"type": "string",
"description": "Date of patient authorization signature in MM-DD-YYYY format (e.g., '03-15-2024'). Extract from signature date field.",
},
"payer_contact_number": map[string]interface{}{
"type": "string",
"description": "Primary payer contact phone number (e.g., '888-632-3862'). Extract from 'Contact#' field for primary payer.",
},
"condition_related_to_employment": map[string]interface{}{
"type": "string",
"description": "Whether patient's condition is related to employment or workers' compensation. Must be YES or NO. Extract from employment-related question or checkbox.",
},
},
}
extractRun, err := extendClient.ExtractRuns.CreateAndPoll(&models.ExtractRunRequest{
File: &models.FileInput{
URL: dataURL,
},
Config: &models.ExtractConfig{
Schema: schema,
BaseProcessor: "extraction_performance",
},
})
if err != nil {
return nil, err
}
if extractRun.Status != "PROCESSED" {
return nil, fmt.Errorf("extract failed with status: %s", extractRun.Status)
}
claimData := extractRun.Output.Value.(map[string]interface{})
fmt.Println("✓ Extraction complete")
// Step 4: Validate and format output
result := map[string]interface{}{
"status": "success",
"file": filepath.Base(filePath),
"parsedChunks": len(parseRun.Output.Chunks),
"extractedData": claimData,
"validations": map[string]bool{
"hasPrimaryPayer": claimData["primary_payer"] != nil,
"hasPrimaryPolicy": claimData["primary_policy_id"] != nil,
"hasPatientName": claimData["patient_name"] != nil,
"hasDOB": claimData["patient_date_of_birth"] != nil,
"hasSignatureDate": claimData["signature_date"] != nil,
"isMultiPayer": claimData["secondary_payer"] != nil && claimData["secondary_policy_id"] != nil,
},
}
fmt.Println("\n=== Extraction Results ===")
fmt.Printf("Primary Payer: %v\n", claimData["primary_payer"])
fmt.Printf("Primary Policy ID: %v\n", claimData["primary_policy_id"])
fmt.Printf("Patient Name: %v\n", claimData["patient_name"])
fmt.Printf("Patient DOB: %v\n", claimData["patient_date_of_birth"])
fmt.Printf("Insured Name: %v\n", claimData["insured_name"])
fmt.Printf("Relationship: %v\n", claimData["patient_relationship_to_insured"])
fmt.Printf("Group Number: %v\n", claimData["group_number"])
fmt.Printf("Signature Date: %v\n", claimData["signature_date"])
fmt.Printf("Payer Contact: %v\n", claimData["payer_contact_number"])
fmt.Printf("Employment Related: %v\n", claimData["condition_related_to_employment"])
if claimData["secondary_payer"] != nil {
fmt.Printf("\nSecondary Payer: %v\n", claimData["secondary_payer"])
fmt.Printf("Secondary Policy ID: %v\n", claimData["secondary_policy_id"])
}
return result, nil
}
func main() {
filePath := "./sample_claim_form.pdf"
if len(os.Args) > 1 {
filePath = os.Args[1]
}
result, err := processHealthInsuranceClaimForm(filePath)
if err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
fmt.Printf("\nFinal Result: %+v\n", result)
}// Deploy the "Health Insurance Claim Form" 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/health-insurance-claim-form.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: health-insurance-claim-form).
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, "health-insurance-claim-form.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": "Health Insurance Claim Form 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": [
"amount_paid",
"insured_sex",
"patient_sex",
"claim_number",
"insured_name",
"patient_name",
"total_charge",
"date_of_other",
"diagnosis_codes",
"insured_address",
"patient_address",
"claim_line_items",
"is_auto_accident",
"accept_assignment",
"is_other_accident",
"primary_policy_id",
"other_insured_name",
"secondary_policy_id",
"billing_provider_npi",
"insured_phone_number",
"patient_phone_number",
"primary_group_number",
"service_facility_npi",
"billing_provider_name",
"federal_tax_id_number",
"insured_date_of_birth",
"is_employment_related",
"patient_date_of_birth",
"service_facility_name",
"insured_signature_date",
"patient_account_number",
"patient_signature_date",
"rendering_provider_npi",
"secondary_group_number",
"primary_insurance_payer",
"referring_provider_name",
"rendering_provider_name",
"billing_provider_address",
"hospitalization_dates_to",
"service_facility_address",
"insured_signature_on_file",
"patient_signature_on_file",
"secondary_insurance_payer",
"hospitalization_dates_from",
"prior_authorization_number",
"other_insured_policy_number",
"referring_provider_identifier",
"dates_patient_unable_to_work_to",
"patient_relationship_to_insured",
"dates_patient_unable_to_work_from",
"date_of_current_illness_injury_pregnancy"
],
"properties": {
"amount_paid": {
"type": "object",
"required": [
"amount",
"iso_4217_currency_code"
],
"properties": {
"amount": {
"type": [
"number",
"null"
]
},
"iso_4217_currency_code": {
"type": [
"string",
"null"
]
}
},
"description": "The amount paid by the patient or other parties prior to claim submission. This is any payment already made toward the total charge.",
"extend:type": "currency",
"additionalProperties": false
},
"insured_sex": {
"type": [
"string",
"null"
],
"description": "The sex or gender of the insured individual. Common values include 'M', 'F', 'Male', 'Female', or similar."
},
"patient_sex": {
"type": [
"string",
"null"
],
"description": "The sex or gender of the patient. Common values include 'M', 'F', 'Male', 'Female', or similar."
},
"claim_number": {
"type": [
"string",
"null"
],
"description": "The unique identifier assigned to this health insurance claim. This may be labeled as 'Claim Number', 'Reference Number', or similar, and is used to track the claim throughout the adjudication process. In CMS-1500 forms, this may be found in various locations or referenced as an authorization or control number."
},
"insured_name": {
"type": [
"string",
"null"
],
"description": "The full name of the person who holds the insurance policy. This is the insured party, who may or may not be the patient. Typically appears as 'Insured's Name' and may include last, first, and middle initial."
},
"patient_name": {
"type": [
"string",
"null"
],
"description": "The full name of the patient receiving services. This is the individual for whom the claim is being submitted. Typically includes last, first, and middle initial."
},
"total_charge": {
"type": "object",
"required": [
"amount",
"iso_4217_currency_code"
],
"properties": {
"amount": {
"type": [
"number",
"null"
]
},
"iso_4217_currency_code": {
"type": [
"string",
"null"
]
}
},
"description": "The total amount charged for all services rendered on this claim, before any adjustments or payments. This is the sum of all line item charges.",
"extend:type": "currency",
"additionalProperties": false
},
"date_of_other": {
"type": [
"string",
"null"
],
"description": "Any other relevant date associated with the claim, such as a similar illness or accident, as indicated on the form.",
"extend:type": "date"
},
"diagnosis_codes": {
"type": "array",
"items": {
"type": "object",
"required": [
"diagnosis_code",
"diagnosis_code_pointer"
],
"properties": {
"diagnosis_code": {
"type": [
"string",
"null"
],
"description": "A single diagnosis code (ICD-10, ICD-9, or other standard) relevant to the patient's condition or treatment."
},
"diagnosis_code_pointer": {
"type": [
"string",
"null"
],
"description": "The letter or reference used to map this diagnosis code to a service line (e.g., 'A', 'B', etc.), if present."
}
},
"additionalProperties": false
},
"description": "The list of diagnosis codes (ICD) that describe the patient's condition or reason for the encounter. Each code represents a specific diagnosis or symptom relevant to the claim. These may be labeled as 'Diagnosis Code', 'ICD Code', or similar, and are often referenced by letter (A-L) for mapping to service lines."
},
"insured_address": {
"type": [
"string",
"null"
],
"description": "The complete mailing address of the insured individual, including street, city, state, and ZIP code."
},
"patient_address": {
"type": [
"string",
"null"
],
"description": "The complete mailing address of the patient, including street, city, state, and ZIP code. This is used for correspondence and identification."
},
"claim_line_items": {
"type": "array",
"items": {
"type": "object",
"required": [
"units",
"charge_amount",
"procedure_code",
"service_date_to",
"place_of_service",
"diagnosis_pointer",
"service_date_from",
"procedure_modifier",
"emergency_indicator",
"service_line_number",
"rendering_provider_qualifier",
"rendering_provider_identifier"
],
"properties": {
"units": {
"type": [
"number",
"null"
],
"description": "The number of units, days, or quantity for this service line."
},
"charge_amount": {
"type": [
"number",
"null"
],
"description": "The amount charged for this specific service line, before any adjustments or payments."
},
"procedure_code": {
"type": [
"string",
"null"
],
"description": "The CPT, HCPCS, or other procedure code describing the service or supply provided."
},
"service_date_to": {
"type": [
"string",
"null"
],
"description": "The end date for the service or procedure performed in this line item, if different from the start date.",
"extend:type": "date"
},
"place_of_service": {
"type": [
"string",
"null"
],
"description": "The code or description indicating where the service was provided (e.g., office, hospital, home)."
},
"diagnosis_pointer": {
"type": [
"string",
"null"
],
"description": "The letter(s) or reference(s) indicating which diagnosis code(s) apply to this service line."
},
"service_date_from": {
"type": [
"string",
"null"
],
"description": "The start date for the service or procedure performed in this line item.",
"extend:type": "date"
},
"procedure_modifier": {
"type": [
"string",
"null"
],
"description": "Any modifier(s) associated with the procedure code, if present."
},
"emergency_indicator": {
"type": [
"string",
"null"
],
"description": "Indicates if the service was an emergency. Typical values include 'Yes', 'No', or a checkbox indicator."
},
"service_line_number": {
"type": [
"string",
"null"
],
"description": "The sequential number or identifier for this service line, if present."
},
"rendering_provider_qualifier": {
"type": [
"string",
"null"
],
"description": "The qualifier code for the rendering provider's identification number, if present (e.g., 'NPI', 'UPIN')."
},
"rendering_provider_identifier": {
"type": [
"string",
"null"
],
"description": "The identification number for the rendering provider for this service line, such as NPI or other ID."
}
},
"additionalProperties": false
},
"description": "The list of individual service lines or procedures billed on this claim. Each line item represents a distinct service, procedure, or supply provided to the patient, and includes details such as dates, codes, charges, and provider information."
},
"is_auto_accident": {
"type": [
"string",
"null"
],
"description": "Indicates whether the patient's condition is related to an auto accident. Typical values are 'Yes', 'No', or similar."
},
"accept_assignment": {
"type": [
"string",
"null"
],
"description": "Indicates whether the provider accepts assignment of benefits. Typical values are 'Yes', 'No', or similar."
},
"is_other_accident": {
"type": [
"string",
"null"
],
"description": "Indicates whether the patient's condition is related to any other type of accident. Typical values are 'Yes', 'No', or similar."
},
"primary_policy_id": {
"type": [
"string",
"null"
],
"description": "The policy or member identification number for the primary insurance plan. This is the unique number assigned to the insured by the primary payer, often labeled as 'Insured's ID Number', 'Policy Number', or similar."
},
"other_insured_name": {
"type": [
"string",
"null"
],
"description": "The name of any additional insured party, if applicable. This may be present when there is more than one insurance policy involved."
},
"secondary_policy_id": {
"type": [
"string",
"null"
],
"description": "The policy or member identification number for the secondary insurance plan, if present. This is the unique number assigned to the insured by the secondary payer."
},
"billing_provider_npi": {
"type": [
"string",
"null"
],
"description": "The National Provider Identifier (NPI) for the billing provider, if applicable."
},
"insured_phone_number": {
"type": [
"string",
"null"
],
"description": "The telephone number for the insured individual, including area code."
},
"patient_phone_number": {
"type": [
"string",
"null"
],
"description": "The telephone number for the patient, including area code. Used for contact purposes."
},
"primary_group_number": {
"type": [
"string",
"null"
],
"description": "The group number associated with the primary insurance policy, if applicable. This is typically used for employer-sponsored or group health plans and may be labeled as 'Group Number', 'Group ID', or similar."
},
"service_facility_npi": {
"type": [
"string",
"null"
],
"description": "The National Provider Identifier (NPI) for the service facility, if applicable."
},
"billing_provider_name": {
"type": [
"string",
"null"
],
"description": "The name of the provider or entity submitting the claim for payment. This is the billing party, which may be an individual or organization."
},
"federal_tax_id_number": {
"type": [
"string",
"null"
],
"description": "The federal tax identification number (EIN or SSN) of the billing provider or entity submitting the claim."
},
"insured_date_of_birth": {
"type": [
"string",
"null"
],
"description": "The date of birth of the insured individual. This is used to verify identity and eligibility. May be labeled as 'Insured's Date of Birth' and can appear in various formats.",
"extend:type": "date"
},
"is_employment_related": {
"type": [
"string",
"null"
],
"description": "Indicates whether the patient's condition is related to employment. Typical values are 'Yes', 'No', or similar."
},
"patient_date_of_birth": {
"type": [
"string",
"null"
],
"description": "The date of birth of the patient. Used for identification and eligibility verification.",
"extend:type": "date"
},
"service_facility_name": {
"type": [
"string",
"null"
],
"description": "The name of the facility where services were rendered, if different from the billing provider."
},
"insured_signature_date": {
"type": [
"string",
"null"
],
"description": "The date the insured or authorized person signed the authorization, if present.",
"extend:type": "date"
},
"patient_account_number": {
"type": [
"string",
"null"
],
"description": "The account number assigned to the patient by the provider or billing entity. Used for internal tracking and reconciliation."
},
"patient_signature_date": {
"type": [
"string",
"null"
],
"description": "The date the patient or authorized person signed the authorization, if present.",
"extend:type": "date"
},
"rendering_provider_npi": {
"type": [
"string",
"null"
],
"description": "The National Provider Identifier (NPI) for the rendering provider, if applicable."
},
"secondary_group_number": {
"type": [
"string",
"null"
],
"description": "The group number associated with the secondary insurance policy, if applicable."
},
"primary_insurance_payer": {
"type": [
"string",
"null"
],
"description": "The name of the primary insurance company or payer responsible for processing this claim. This is the main insurer listed on the form, often labeled as 'Primary Payer', 'Insurance Carrier', or similar."
},
"referring_provider_name": {
"type": [
"string",
"null"
],
"description": "The name of the referring provider or other source who referred the patient for services. May be labeled as 'Referring Provider', 'Ordering Physician', or similar."
},
"rendering_provider_name": {
"type": [
"string",
"null"
],
"description": "The name of the individual provider who performed the services, if different from the billing provider."
},
"billing_provider_address": {
"type": [
"string",
"null"
],
"description": "The complete address of the billing provider, including street, city, state, and ZIP code."
},
"hospitalization_dates_to": {
"type": [
"string",
"null"
],
"description": "The end date of any hospitalization related to the current services, if applicable.",
"extend:type": "date"
},
"service_facility_address": {
"type": [
"string",
"null"
],
"description": "The address of the facility where services were rendered, including street, city, state, and ZIP code."
},
"insured_signature_on_file": {
"type": [
"string",
"null"
],
"description": "Indicates whether the insured's or authorized person's signature is on file authorizing payment of benefits. Typical values include 'Signature on File', 'Yes', or similar."
},
"patient_signature_on_file": {
"type": [
"string",
"null"
],
"description": "Indicates whether the patient's or authorized person's signature is on file authorizing release of information and payment. Typical values include 'Signature on File', 'Yes', or similar."
},
"secondary_insurance_payer": {
"type": [
"string",
"null"
],
"description": "The name of the secondary insurance company or payer, if present. This is an additional insurer that may provide coverage after the primary payer, often labeled as 'Secondary Payer' or similar."
},
"hospitalization_dates_from": {
"type": [
"string",
"null"
],
"description": "The start date of any hospitalization related to the current services, if applicable.",
"extend:type": "date"
},
"prior_authorization_number": {
"type": [
"string",
"null"
],
"description": "The authorization or referral number provided by the payer, if required for the services rendered. May be labeled as 'Prior Authorization Number', 'Referral Number', or similar."
},
"other_insured_policy_number": {
"type": [
"string",
"null"
],
"description": "The policy or group number for any additional insured party, if applicable."
},
"referring_provider_identifier": {
"type": [
"string",
"null"
],
"description": "The unique identifier (such as NPI or other ID) for the referring provider, if present."
},
"dates_patient_unable_to_work_to": {
"type": [
"string",
"null"
],
"description": "The end date when the patient was unable to work due to the condition, if applicable.",
"extend:type": "date"
},
"patient_relationship_to_insured": {
"type": [
"string",
"null"
],
"description": "The relationship of the patient to the insured individual. Typical values include 'Self', 'Spouse', 'Child', 'Other', or similar."
},
"dates_patient_unable_to_work_from": {
"type": [
"string",
"null"
],
"description": "The start date when the patient was unable to work due to the condition, if applicable.",
"extend:type": "date"
},
"date_of_current_illness_injury_pregnancy": {
"type": [
"string",
"null"
],
"description": "The date when the current illness, injury, or pregnancy began. This is used to establish the onset of the condition being treated.",
"extend:type": "date"
}
},
"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 json
import os
import sys
from pathlib import Path
from typing import Any, Optional
import httpx
API = "https://api.extend.ai"
VERSION = "2026-02-09"
API_KEY = os.environ.get("EXTEND_API_KEY")
if not API_KEY:
print("Set EXTEND_API_KEY first.")
sys.exit(1)
STATE_DIR = Path.cwd() / ".extend"
STATE_FILE = STATE_DIR / "health-insurance-claim-form.json"
def load_state() -> dict[str, Any]:
if STATE_FILE.exists():
return json.loads(STATE_FILE.read_text())
return {}
def save_state(state: dict[str, Any]) -> None:
STATE_DIR.mkdir(parents=True, exist_ok=True)
STATE_FILE.write_text(json.dumps(state, indent=2))
async def api(method: str, path_name: str, body: Optional[Any] = None) -> Any:
headers = {
"Authorization": f"Bearer {API_KEY}",
"x-extend-api-version": VERSION,
}
if body:
headers["Content-Type"] = "application/json"
async with httpx.AsyncClient() as client:
res = await client.request(
method,
API + path_name,
headers=headers,
json=body,
)
try:
data = res.json()
except Exception:
data = {}
if not res.is_success:
error_msg = json.dumps(data)[:300]
raise Exception(f"{method} {path_name} failed ({res.status_code}): {error_msg}")
return data
WORKFLOW = {
"name": "Health Insurance Claim Form 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": [
"amount_paid",
"insured_sex",
"patient_sex",
"claim_number",
"insured_name",
"patient_name",
"total_charge",
"date_of_other",
"diagnosis_codes",
"insured_address",
"patient_address",
"claim_line_items",
"is_auto_accident",
"accept_assignment",
"is_other_accident",
"primary_policy_id",
"other_insured_name",
"secondary_policy_id",
"billing_provider_npi",
"insured_phone_number",
"patient_phone_number",
"primary_group_number",
"service_facility_npi",
"billing_provider_name",
"federal_tax_id_number",
"insured_date_of_birth",
"is_employment_related",
"patient_date_of_birth",
"service_facility_name",
"insured_signature_date",
"patient_account_number",
"patient_signature_date",
"rendering_provider_npi",
"secondary_group_number",
"primary_insurance_payer",
"referring_provider_name",
"rendering_provider_name",
"billing_provider_address",
"hospitalization_dates_to",
"service_facility_address",
"insured_signature_on_file",
"patient_signature_on_file",
"secondary_insurance_payer",
"hospitalization_dates_from",
"prior_authorization_number",
"other_insured_policy_number",
"referring_provider_identifier",
"dates_patient_unable_to_work_to",
"patient_relationship_to_insured",
"dates_patient_unable_to_work_from",
"date_of_current_illness_injury_pregnancy"
],
"properties": {
"amount_paid": {
"type": "object",
"required": [
"amount",
"iso_4217_currency_code"
],
"properties": {
"amount": {
"type": [
"number",
"null"
]
},
"iso_4217_currency_code": {
"type": [
"string",
"null"
]
}
},
"description": "The amount paid by the patient or other parties prior to claim submission. This is any payment already made toward the total charge.",
"extend:type": "currency",
"additionalProperties": False
},
"insured_sex": {
"type": [
"string",
"null"
],
"description": "The sex or gender of the insured individual. Common values include 'M', 'F', 'Male', 'Female', or similar."
},
"patient_sex": {
"type": [
"string",
"null"
],
"description": "The sex or gender of the patient. Common values include 'M', 'F', 'Male', 'Female', or similar."
},
"claim_number": {
"type": [
"string",
"null"
],
"description": "The unique identifier assigned to this health insurance claim. This may be labeled as 'Claim Number', 'Reference Number', or similar, and is used to track the claim throughout the adjudication process. In CMS-1500 forms, this may be found in various locations or referenced as an authorization or control number."
},
"insured_name": {
"type": [
"string",
"null"
],
"description": "The full name of the person who holds the insurance policy. This is the insured party, who may or may not be the patient. Typically appears as 'Insured's Name' and may include last, first, and middle initial."
},
"patient_name": {
"type": [
"string",
"null"
],
"description": "The full name of the patient receiving services. This is the individual for whom the claim is being submitted. Typically includes last, first, and middle initial."
},
"total_charge": {
"type": "object",
"required": [
"amount",
"iso_4217_currency_code"
],
"properties": {
"amount": {
"type": [
"number",
"null"
]
},
"iso_4217_currency_code": {
"type": [
"string",
"null"
]
}
},
"description": "The total amount charged for all services rendered on this claim, before any adjustments or payments. This is the sum of all line item charges.",
"extend:type": "currency",
"additionalProperties": False
},
"date_of_other": {
"type": [
"string",
"null"
],
"description": "Any other relevant date associated with the claim, such as a similar illness or accident, as indicated on the form.",
"extend:type": "date"
},
"diagnosis_codes": {
"type": "array",
"items": {
"type": "object",
"required": [
"diagnosis_code",
"diagnosis_code_pointer"
],
"properties": {
"diagnosis_code": {
"type": [
"string",
"null"
],
"description": "A single diagnosis code (ICD-10, ICD-9, or other standard) relevant to the patient's condition or treatment."
},
"diagnosis_code_pointer": {
"type": [
"string",
"null"
],
"description": "The letter or reference used to map this diagnosis code to a service line (e.g., 'A', 'B', etc.), if present."
}
},
"additionalProperties": False
},
"description": "The list of diagnosis codes (ICD) that describe the patient's condition or reason for the encounter. Each code represents a specific diagnosis or symptom relevant to the claim. These may be labeled as 'Diagnosis Code', 'ICD Code', or similar, and are often referenced by letter (A-L) for mapping to service lines."
},
"insured_address": {
"type": [
"string",
"null"
],
"description": "The complete mailing address of the insured individual, including street, city, state, and ZIP code."
},
"patient_address": {
"type": [
"string",
"null"
],
"description": "The complete mailing address of the patient, including street, city, state, and ZIP code. This is used for correspondence and identification."
},
"claim_line_items": {
"type": "array",
"items": {
"type": "object",
"required": [
"units",
"charge_amount",
"procedure_code",
"service_date_to",
"place_of_service",
"diagnosis_pointer",
"service_date_from",
"procedure_modifier",
"emergency_indicator",
"service_line_number",
"rendering_provider_qualifier",
"rendering_provider_identifier"
],
"properties": {
"units": {
"type": [
"number",
"null"
],
"description": "The number of units, days, or quantity for this service line."
},
"charge_amount": {
"type": [
"number",
"null"
],
"description": "The amount charged for this specific service line, before any adjustments or payments."
},
"procedure_code": {
"type": [
"string",
"null"
],
"description": "The CPT, HCPCS, or other procedure code describing the service or supply provided."
},
"service_date_to": {
"type": [
"string",
"null"
],
"description": "The end date for the service or procedure performed in this line item, if different from the start date.",
"extend:type": "date"
},
"place_of_service": {
"type": [
"string",
"null"
],
"description": "The code or description indicating where the service was provided (e.g., office, hospital, home)."
},
"diagnosis_pointer": {
"type": [
"string",
"null"
],
"description": "The letter(s) or reference(s) indicating which diagnosis code(s) apply to this service line."
},
"service_date_from": {
"type": [
"string",
"null"
],
"description": "The start date for the service or procedure performed in this line item.",
"extend:type": "date"
},
"procedure_modifier": {
"type": [
"string",
"null"
],
"description": "Any modifier(s) associated with the procedure code, if present."
},
"emergency_indicator": {
"type": [
"string",
"null"
],
"description": "Indicates if the service was an emergency. Typical values include 'Yes', 'No', or a checkbox indicator."
},
"service_line_number": {
"type": [
"string",
"null"
],
"description": "The sequential number or identifier for this service line, if present."
},
"rendering_provider_qualifier": {
"type": [
"string",
"null"
],
"description": "The qualifier code for the rendering provider's identification number, if present (e.g., 'NPI', 'UPIN')."
},
"rendering_provider_identifier": {
"type": [
"string",
"null"
],
"description": "The identification number for the rendering provider for this service line, such as NPI or other ID."
}
},
"additionalProperties": False
},
"description": "The list of individual service lines or procedures billed on this claim. Each line item represents a distinct service, procedure, or supply provided to the patient, and includes details such as dates, codes, charges, and provider information."
},
"is_auto_accident": {
"type": [
"string",
"null"
],
"description": "Indicates whether the patient's condition is related to an auto accident. Typical values are 'Yes', 'No', or similar."
},
"accept_assignment": {
"type": [
"string",
"null"
],
"description": "Indicates whether the provider accepts assignment of benefits. Typical values are 'Yes', 'No', or similar."
},
"is_other_accident": {
"type": [
"string",
"null"
],
"description": "Indicates whether the patient's condition is related to any other type of accident. Typical values are 'Yes', 'No', or similar."
},
"primary_policy_id": {
"type": [
"string",
"null"
],
"description": "The policy or member identification number for the primary insurance plan. This is the unique number assigned to the insured by the primary payer, often labeled as 'Insured's ID Number', 'Policy Number', or similar."
},
"other_insured_name": {
"type": [
"string",
"null"
],
"description": "The name of any additional insured party, if applicable. This may be present when there is more than one insurance policy involved."
},
"secondary_policy_id": {
"type": [
"string",
"null"
],
"description": "The policy or member identification number for the secondary insurance plan, if present. This is the unique number assigned to the insured by the secondary payer."
},
"billing_provider_npi": {
"type": [
"string",
"null"
],
"description": "The National Provider Identifier (NPI) for the billing provider, if applicable."
},
"insured_phone_number": {
"type": [
"string",
"null"
],
"description": "The telephone number for the insured individual, including area code."
},
"patient_phone_number": {
"type": [
"string",
"null"
],
"description": "The telephone number for the patient, including area code. Used for contact purposes."
},
"primary_group_number": {
"type": [
"string",
"null"
],
"description": "The group number associated with the primary insurance policy, if applicable. This is typically used for employer-sponsored or group health plans and may be labeled as 'Group Number', 'Group ID', or similar."
},
"service_facility_npi": {
"type": [
"string",
"null"
],
"description": "The National Provider Identifier (NPI) for the service facility, if applicable."
},
"billing_provider_name": {
"type": [
"string",
"null"
],
"description": "The name of the provider or entity submitting the claim for payment. This is the billing party, which may be an individual or organization."
},
"federal_tax_id_number": {
"type": [
"string",
"null"
],
"description": "The federal tax identification number (EIN or SSN) of the billing provider or entity submitting the claim."
},
"insured_date_of_birth": {
"type": [
"string",
"null"
],
"description": "The date of birth of the insured individual. This is used to verify identity and eligibility. May be labeled as 'Insured's Date of Birth' and can appear in various formats.",
"extend:type": "date"
},
"is_employment_related": {
"type": [
"string",
"null"
],
"description": "Indicates whether the patient's condition is related to employment. Typical values are 'Yes', 'No', or similar."
},
"patient_date_of_birth": {
"type": [
"string",
"null"
],
"description": "The date of birth of the patient. Used for identification and eligibility verification.",
"extend:type": "date"
},
"service_facility_name": {
"type": [
"string",
"null"
],
"description": "The name of the facility where services were rendered, if different from the billing provider."
},
"insured_signature_date": {
"type": [
"string",
"null"
],
"description": "The date the insured or authorized person signed the authorization, if present.",
"extend:type": "date"
},
"patient_account_number": {
"type": [
"string",
"null"
],
"description": "The account number assigned to the patient by the provider or billing entity. Used for internal tracking and reconciliation."
},
"patient_signature_date": {
"type": [
"string",
"null"
],
"description": "The date the patient or authorized person signed the authorization, if present.",
"extend:type": "date"
},
"rendering_provider_npi": {
"type": [
"string",
"null"
],
"description": "The National Provider Identifier (NPI) for the rendering provider, if applicable."
},
"secondary_group_number": {
"type": [
"string",
"null"
],
"description": "The group number associated with the secondary insurance policy, if applicable."
},
"primary_insurance_payer": {
"type": [
"string",
"null"
],
"description": "The name of the primary insurance company or payer responsible for processing this claim. This is the main insurer listed on the form, often labeled as 'Primary Payer', 'Insurance Carrier', or similar."
},
"referring_provider_name": {
"type": [
"string",
"null"
],
"description": "The name of the referring provider or other source who referred the patient for services. May be labeled as 'Referring Provider', 'Ordering Physician', or similar."
},
"rendering_provider_name": {
"type": [
"string",
"null"
],
"description": "The name of the individual provider who performed the services, if different from the billing provider."
},
"billing_provider_address": {
"type": [
"string",
"null"
],
"description": "The complete address of the billing provider, including street, city, state, and ZIP code."
},
"hospitalization_dates_to": {
"type": [
"string",
"null"
],
"description": "The end date of any hospitalization related to the current services, if applicable.",
"extend:type": "date"
},
"service_facility_address": {
"type": [
"string",
"null"
],
"description": "The address of the facility where services were rendered, including street, city, state, and ZIP code."
},
"insured_signature_on_file": {
"type": [
"string",
"null"
],
"description": "Indicates whether the insured's or authorized person's signature is on file authorizing payment of benefits. Typical values include 'Signature on File', 'Yes', or similar."
},
"patient_signature_on_file": {
"type": [
"string",
"null"
],
"description": "Indicates whether the patient's or authorized person's signature is on file authorizing release of information and payment. Typical values include 'Signature on File', 'Yes', or similar."
},
"secondary_insurance_payer": {
"type": [
"string",
"null"
],
"description": "The name of the secondary insurance company or payer, if present. This is an additional insurer that may provide coverage after the primary payer, often labeled as 'Secondary Payer' or similar."
},
"hospitalization_dates_from": {
"type": [
"string",
"null"
],
"description": "The start date of any hospitalization related to the current services, if applicable.",
"extend:type": "date"
},
"prior_authorization_number": {
"type": [
"string",
"null"
],
"description": "The authorization or referral number provided by the payer, if required for the services rendered. May be labeled as 'Prior Authorization Number', 'Referral Number', or similar."
},
"other_insured_policy_number": {
"type": [
"string",
"null"
],
"description": "The policy or group number for any additional insured party, if applicable."
},
"referring_provider_identifier": {
"type": [
"string",
"null"
],
"description": "The unique identifier (such as NPI or other ID) for the referring provider, if present."
},
"dates_patient_unable_to_work_to": {
"type": [
"string",
"null"
],
"description": "The end date when the patient was unable to work due to the condition, if applicable.",
"extend:type": "date"
},
"patient_relationship_to_insured": {
"type": [
"string",
"null"
],
"description": "The relationship of the patient to the insured individual. Typical values include 'Self', 'Spouse', 'Child', 'Other', or similar."
},
"dates_patient_unable_to_work_from": {
"type": [
"string",
"null"
],
"description": "The start date when the patient was unable to work due to the condition, if applicable.",
"extend:type": "date"
},
"date_of_current_illness_injury_pregnancy": {
"type": [
"string",
"null"
],
"description": "The date when the current illness, injury, or pregnancy began. This is used to establish the onset of the condition being treated.",
"extend:type": "date"
}
},
"additionalProperties": False
},
"baseProcessor": "extraction_performance",
"advancedOptions": {
"reviewAgent": {
"enabled": True
},
"advancedMultimodalEnabled": True
}
}
}
}
]
}
async def main() -> None:
state = load_state()
print(f'Deploying "{WORKFLOW["name"]}…')
if state.get("workflowId"):
wf_id = state["workflowId"]
print(f"✓ workflow already provisioned ({wf_id}) — updating steps")
await api("POST", f"/workflows/{wf_id}", {"steps": WORKFLOW["steps"]})
else:
try:
list_response = await api("GET", f'/workflows?name={WORKFLOW["name"]}')
items = list_response.get("data") or list_response.get("items") or []
existing = next((x for x in items if x.get("name") == WORKFLOW["name"]), None)
if existing and existing.get("id"):
state["workflowId"] = existing["id"]
save_state(state)
print(f'✓ workflow "{WORKFLOW["name"]}" found in your account ({existing["id"]}) — updating steps')
await api("POST", f'/workflows/{existing["id"]}', {"steps": WORKFLOW["steps"]})
except Exception:
pass
if not state.get("workflowId"):
created = await api("POST", "/workflows", WORKFLOW)
wf_id = created.get("id") or created.get("workflow", {}).get("id")
if not wf_id:
raise Exception("Could not read created workflow id from response")
state["workflowId"] = wf_id
save_state(state)
print(f"+ created workflow ({wf_id})")
try:
await api("POST", f'/workflows/{state["workflowId"]}/versions', {})
except Exception:
pass
print("\nDone. Run documents through it with:")
print(f' POST {API}/workflow_runs {{ workflow: {{ id: "{state["workflowId"]}" }}, file: {{ url: "https://…" }} }}')
print("Or open the workflow in the Extend dashboard to review and deploy it.")
if __name__ == "__main__":
import asyncio
try:
asyncio.run(main())
except Exception as e:
print(str(e), file=sys.stderr)
sys.exit(1)import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class HealthInsuranceClaimFormProvisioner {
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 String STATE_DIR = Paths.get(System.getProperty("user.dir"), ".extend").toString();
private static final String STATE_FILE = Paths.get(STATE_DIR, "health-insurance-claim-form.json").toString();
static {
if (API_KEY == null || API_KEY.isEmpty()) {
System.err.println("Set EXTEND_API_KEY first.");
System.exit(1);
}
}
static class State {
String workflowId;
}
private static final Gson gson = new Gson();
private static State state;
public static void main(String[] args) {
try {
loadState();
provisionWorkflow();
} catch (Exception e) {
System.err.println(e.getMessage() != null ? e.getMessage() : e);
System.exit(1);
}
}
private static void loadState() throws IOException {
Path stateFilePath = Paths.get(STATE_FILE);
if (Files.exists(stateFilePath)) {
String content = Files.readString(stateFilePath);
state = gson.fromJson(content, State.class);
} else {
state = new State();
}
}
private static void saveState() throws IOException {
Path stateDirPath = Paths.get(STATE_DIR);
Files.createDirectories(stateDirPath);
Files.writeString(Paths.get(STATE_FILE), gson.toJson(state));
}
private static JsonElement api(String method, String pathName, JsonElement body) throws Exception {
URL url = new URL(API + pathName);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod(method);
conn.setRequestProperty("Authorization", "Bearer " + API_KEY);
conn.setRequestProperty("x-extend-api-version", VERSION);
if (body != null) {
conn.setRequestProperty("Content-Type", "application/json");
conn.setDoOutput(true);
try (OutputStream os = conn.getOutputStream()) {
os.write(gson.toJson(body).getBytes(StandardCharsets.UTF_8));
}
}
int responseCode = conn.getResponseCode();
String responseText = readResponse(conn);
JsonElement data = null;
try {
data = gson.fromJson(responseText, JsonElement.class);
} catch (Exception ignored) {
}
if (responseCode < 200 || responseCode >= 300) {
String errorMsg = data != null ? gson.toJson(data) : responseText;
if (errorMsg.length() > 300) {
errorMsg = errorMsg.substring(0, 300);
}
throw new Exception(method + " " + pathName + " failed (" + responseCode + "): " + errorMsg);
}
return data != null ? data : new JsonObject();
}
private static String readResponse(HttpURLConnection conn) throws IOException {
BufferedReader reader;
if (conn.getResponseCode() < 400) {
reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
} else {
reader = new BufferedReader(new InputStreamReader(conn.getErrorStream(), StandardCharsets.UTF_8));
}
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
return response.toString();
}
private static void provisionWorkflow() throws Exception {
JsonObject workflow = buildWorkflow();
System.out.println("Deploying \"" + workflow.get("name").getAsString() + "\"…");
if (state.workflowId != null && !state.workflowId.isEmpty()) {
System.out.println("✓ workflow already provisioned (" + state.workflowId + ") — updating steps");
JsonObject updatePayload = new JsonObject();
updatePayload.add("steps", workflow.get("steps"));
api("POST", "/workflows/" + state.workflowId, updatePayload);
} else {
boolean found = false;
try {
String encodedName = URLEncoder.encode(workflow.get("name").getAsString(), StandardCharsets.UTF_8);
JsonElement listResponse = api("GET", "/workflows?name=" + encodedName, null);
JsonArray items = new JsonArray();
if (listResponse.isJsonObject()) {
JsonObject listObj = listResponse.getAsJsonObject();
if (listObj.has("data") && listObj.get("data").isJsonArray()) {
items = listObj.get("data").getAsJsonArray();
} else if (listObj.has("items") && listObj.get("items").isJsonArray()) {
items = listObj.get("items").getAsJsonArray();
}
}
for (JsonElement elem : items) {
if (elem.isJsonObject()) {
JsonObject item = elem.getAsJsonObject();
if (item.has("name") && item.get("name").getAsString().equals(workflow.get("name").getAsString()) &&
item.has("id")) {
state.workflowId = item.get("id").getAsString();
saveState();
System.out.println("✓ workflow \"" + workflow.get("name").getAsString() + "\" found in your account (" + state.workflowId + ") — updating steps");
JsonObject updatePayload = new JsonObject();
updatePayload.add("steps", workflow.get("steps"));
api("POST", "/workflows/" + state.workflowId, updatePayload);
found = true;
break;
}
}
}
} catch (Exception ignored) {
}
if (!found) {
JsonElement created = api("POST", "/workflows", workflow);
String wfId = null;
if (created.isJsonObject()) {
JsonObject createdObj = created.getAsJsonObject();
if (createdObj.has("id")) {
wfId = createdObj.get("id").getAsString();
} else if (createdObj.has("workflow") && createdObj.get("workflow").isJsonObject()) {
JsonObject workflowObj = createdObj.get("workflow").getAsJsonObject();
if (workflowObj.has("id")) {
wfId = workflowObj.get("id").getAsString();
}
}
}
if (wfId == null) {
throw new Exception("Could not read created workflow id from response");
}
state.workflowId = wfId;
saveState();
System.out.println("+ created workflow (" + wfId + ")");
}
}
try {
api("POST", "/workflows/" + state.workflowId + "/versions", new JsonObject());
} catch (Exception ignored) {
}
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 JsonObject buildWorkflow() {
JsonObject workflow = new JsonObject();
workflow.addProperty("name", "Health Insurance Claim Form Processing Pipeline");
JsonArray steps = new JsonArray();
// startTrigger1
JsonObject startTrigger = new JsonObject();
startTrigger.addProperty("name", "startTrigger1");
startTrigger.addProperty("type", "TRIGGER");
JsonArray startNext = new JsonArray();
JsonObject startNextStep = new JsonObject();
startNextStep.addProperty("step", "parse1");
startNext.add(startNextStep);
startTrigger.add("next", startNext);
steps.add(startTrigger);
// parse1
JsonObject parse = new JsonObject();
parse.addProperty("name", "parse1");
parse.addProperty("type", "PARSE");
JsonObject parseConfig = new JsonObject();
JsonObject parseConfigInner = new JsonObject();
JsonObject blockOptions = new JsonObject();
JsonObject textOptions = new JsonObject();
JsonObject agenticOptions = new JsonObject();
agenticOptions.addProperty("enabled", true);
textOptions.add("agentic", agenticOptions);
blockOptions.add("text", textOptions);
parseConfigInner.add("blockOptions", blockOptions);
JsonObject chunkingStrategy = new JsonObject();
chunkingStrategy.addProperty("type", "document");
parseConfigInner.add("chunkingStrategy", chunkingStrategy);
parseConfig.add("parseConfig", parseConfigInner);
parse.add("config", parseConfig);
JsonArray parseNext = new JsonArray();
JsonObject parseNextStep = new JsonObject();
parseNextStep.addProperty("step", "extraction2");
parseNext.add(parseNextStep);
parse.add("next", parseNext);
steps.add(parse);
// extraction2
JsonObject extraction = new JsonObject();
extraction.addProperty("name", "extraction2");
extraction.addProperty("type", "EXTRACT");
JsonObject extractionConfig = new JsonObject();
JsonObject extractorConfig = new JsonObject();
extractorConfig.add("schema", buildSchema());
extractorConfig.addProperty("baseProcessor", "extraction_performance");
JsonObject advancedOptions = new JsonObject();
JsonObject reviewAgent = new JsonObject();
reviewAgent.addProperty("enabled", true);
advancedOptions.add("reviewAgent", reviewAgent);
advancedOptions.addProperty("advancedMultimodalEnabled", true);
extractorConfig.add("advancedOptions", advancedOptions);
extractionConfig.add("extractorConfig", extractorConfig);
extraction.add("config", extractionConfig);
steps.add(extraction);
workflow.add("steps", steps);
return workflow;
}
private static JsonObject buildSchema() {
JsonObject schema = new JsonObject();
schema.addProperty("type", "object");
JsonArray required = new JsonArray();
String[] requiredFields = {
"amount_paid", "insured_sex", "patient_sex", "claim_number", "insured_name",
"patient_name", "total_charge", "date_of_other", "diagnosis_codes", "insured_address",
"patient_address", "claim_line_items", "is_auto_accident", "accept_assignment",
"is_other_accident", "primary_policy_id", "other_insured_name", "secondary_policy_id",
"billing_provider_npi", "insured_phone_number", "patient_phone_number", "primary_group_number",
"service_facility_npi", "billing_provider_name", "federal_tax_id_number", "insured_date_of_birth",
"is_employment_related", "patient_date_of_birth", "service_facility_name", "insured_signature_date",
"patient_account_number", "patient_signature_date", "rendering_provider_npi", "secondary_group_number",
"primary_insurance_payer", "referring_provider_name", "rendering_provider_name", "billing_provider_address",
"hospitalization_dates_to", "service_facility_address", "insured_signature_on_file", "patient_signature_on_file",
"secondary_insurance_payer", "hospitalization_dates_from", "prior_authorization_number", "other_insured_policy_number",
"referring_provider_identifier", "dates_patient_unable_to_work_to", "patient_relationship_to_insured",
"dates_patient_unable_to_work_from", "date_of_current_illness_injury_pregnancy"
};
for (String field : requiredFields) {
required.add(field);
}
schema.add("required", required);
JsonObject properties = new JsonObject();
// amount_paid
properties.add("amount_paid", buildCurrencyProperty("The amount paid by the patient or other parties prior to claim submission. This is any payment already made toward the total charge."));
// Simple string properties
properties.add("insured_sex", buildStringProperty("The sex or gender of the insured individual. Common values include 'M', 'F', 'Male', 'Female', or similar."));
properties.add("patient_sex", buildStringProperty("The sex or gender of the patient. Common values include 'M', 'F', 'Male', 'Female', or similar."));
properties.add("claim_number", buildStringProperty("The unique identifier assigned to this health insurance claim. This may be labeled as 'Claim Number', 'Reference Number', or similar, and is used to track the claim throughout the adjudication process. In CMS-1500 forms, this may be found in various locations or referenced as an authorization or control number."));
properties.add("insured_name", buildStringProperty("The full name of the person who holds the insurance policy. This is the insured party, who may or may not be the patient. Typically appears as 'Insured's Name' and may include last, first, and middle initial."));
properties.add("patient_name", buildStringProperty("The full name of the patient receiving services. This is the individual for whom the claim is being submitted. Typically includes last, first, and middle initial."));
// total_charge
properties.add("total_charge", buildCurrencyProperty("The total amount charged for all services rendered on this claim, before any adjustments or payments. This is the sum of all line item charges."));
// Date properties
properties.add("date_of_other", buildDateProperty("Any other relevant date associated with the claim, such as a similar illness or accident, as indicated on the form."));
// diagnosis_codes
properties.add("diagnosis_codes", buildDiagnosisCodesArray());
// Address properties
properties.add("insured_address", buildStringProperty("The complete mailing address of the insured individual, including street, city, state, and ZIP code."));
properties.add("patient_address", buildStringProperty("The complete mailing address of the patient, including street, city, state, and ZIP code. This is used for correspondence and identification."));
// claim_line_items
properties.add("claim_line_items", buildClaimLineItemsArray());
// Boolean/indicator properties
properties.add("is_auto_accident", buildStringProperty("Indicates whether the patient's condition is related to an auto accident. Typical values are 'Yes', 'No', or similar."));
properties.add("accept_assignment", buildStringProperty("Indicates whether the provider accepts assignment of benefits. Typical values are 'Yes', 'No', or similar."));
properties.add("is_other_accident", buildStringProperty("Indicates whether the patient's condition is related to any other type of accident. Typical values are 'Yes', 'No', or similar."));
// Policy/ID properties
properties.add("primary_policy_id", buildStringProperty("The policy or member identification number for the primary insurance plan. This is the unique number assigned to the insured by the primary payer, often labeled as 'Insured's ID Number', 'Policy Number', or similar."));
properties.add("other_insured_name", buildStringProperty("The name of any additional insured party, if applicable. This may be present when there is more than one insurance policy involved."));
properties.add("secondary_policy_id", buildStringProperty("The policy or member identification number for the secondary insurance plan, if present. This is the unique number assigned to the insured by the secondary payer."));
// NPI properties
properties.add("billing_provider_npi", buildStringProperty("The National Provider Identifier (NPI) for the billing provider, if applicable."));
// Phone properties
properties.add("insured_phone_number", buildStringProperty("The telephone number for the insured individual, including area code."));
properties.add("patient_phone_number", buildStringProperty("The telephone number for the patient, including area code. Used for contact purposes."));
// Group properties
properties.add("primary_group_number", buildStringProperty("The group number associated with the primary insurance policy, if applicable. This is typically used for employer-sponsored or group health plans and may be labeled as 'Group Number', 'Group ID', or similar."));
// Service facility
properties.add("service_facility_npi", buildStringProperty("The National Provider Identifier (NPI) for the service facility, if applicable."));
properties.add("billing_provider_name", buildStringProperty("The name of the provider or entity submitting the claim for payment. This is the billing party, which may be an individual or organization."));
properties.add("federal_tax_id_number", buildStringProperty("The federal tax identification number (EIN or SSN) of the billing provider or entity submitting the claim."));
// Date of birth properties
properties.add("insured_date_of_birth", buildDateProperty("The date of birth of the insured individual. This is used to verify identity and eligibility. May be labeled as 'Insured's Date of Birth' and can appear in various formats."));
properties.add("is_employment_related", buildStringProperty("Indicates whether the patient's condition is related to employment. Typical values are 'Yes', 'No', or similar."));
properties.add("patient_date_of_birth", buildDateProperty("The date of birth of the patient. Used for identification and eligibility verification."));
// Service facility properties
properties.add("service_facility_name", buildStringProperty("The name of the facility where services were rendered, if different from the billing provider."));
// Signature date properties
properties.add("insured_signature_date", buildDateProperty("The date the insured or authorized person signed the authorization, if present."));
properties.add("patient_account_number", buildStringProperty("The account number assigned to the patient by the provider or billing entity. Used for internal tracking and reconciliation."));
properties.add("patient_signature_date", buildDateProperty("The date the patient or authorized person signed the authorization, if present."));
// Rendering provider
properties.add("rendering_provider_npi", buildStringProperty("The National Provider Identifier (NPI) for the rendering provider, if applicable."));
properties.add("secondary_group_number", buildStringProperty("The group number associated with the secondary insurance policy, if applicable."));
// Insurance properties
properties.add("primary_insurance_payer", buildStringProperty("The name of the primary insurance company or payer responsible for processing this claim. This is the main insurer listed on the form, often labeled as 'Primary Payer', 'Insurance Carrier', or similar."));
properties.add("referring_provider_name", buildStringProperty("The name of the referring provider or other source who referred the patient for services. May be labeled as 'Referring Provider', 'Ordering Physician', or similar."));
properties.add("rendering_provider_name", buildStringProperty("The name of the individual provider who performed the services, if different from the billing provider."));
properties.add("billing_provider_address", buildStringProperty("The complete address of the billing provider, including street, city, state, and ZIP code."));
// Hospitalization dates
properties.add("hospitalization_dates_to", buildDateProperty("The end date of any hospitalization related to the current services, if applicable."));
properties.add("service_facility_address", buildStringProperty("The address of the facility where services were rendered, including street, city, state, and ZIP code."));
// Signature on file
properties.add("insured_signature_on_file", buildStringProperty("Indicates whether the insured's or authorized person's signature is on file authorizing payment of benefits. Typical values include 'Signature on File', 'Yes', or similar."));
properties.add("patient_signature_on_file", buildStringProperty("Indicates whether the patient's or authorized person's signature is on file authorizing release of information and payment. Typical values include 'Signature on File', 'Yes', or similar."));
properties.add("secondary_insurance_payer", buildStringProperty("The name of the secondary insurance company or payer, if present. This is an additional insurer that may provide coverage after the primary payer, often labeled as 'Secondary Payer' or similar."));
properties.add("hospitalization_dates_from", buildDateProperty("The start date of any hospitalization related to the current services, if applicable."));
properties.add("prior_authorization_number", buildStringProperty("The authorization or referral number provided by the payer, if required for the services rendered. May be labeled as 'Prior Authorization Number', 'Referral Number', or similar."));
properties.add("other_insured_policy_number", buildStringProperty("The policy or group number for any additional insured party, if applicable."));
properties.add("referring_provider_identifier", buildStringProperty("The unique identifier (such as NPI or other ID) for the referring provider, if present."));
// Work inability dates
properties.add("dates_patient_unable_to_work_to", buildDateProperty("The end date when the patient was unable to work due to the condition, if applicable."));
properties.add("patient_relationship_to_insured", buildStringProperty("The relationship of the patient to the insured individual. Typical values include 'Self', 'Spouse', 'Child', 'Other', or similar."));
properties.add("dates_patient_unable_to_work_from", buildDateProperty("The start date when the patient was unable to work due to the condition, if applicable."));
properties.add("date_of_current_illness_injury_pregnancy", buildDateProperty("The date when the current illness, injury, or pregnancy began. This is used to establish the onset of the condition being treated."));
schema.add("properties", properties);
schema.addProperty("additionalProperties", false);
return schema;
}
private static JsonObject buildStringProperty(String description) {
JsonObject prop = new JsonObject();
JsonArray typeArray = new JsonArray();
typeArray.add("string");
typeArray.add("null");
prop.add("type", typeArray);
prop.addProperty("description", description);
return prop;
}
private static JsonObject buildDateProperty(String description) {
JsonObject prop = new JsonObject();
JsonArray typeArray = new JsonArray();
typeArray.add("string");
typeArray.add("null");
prop.add("type", typeArray);
prop.addProperty("description", description);
prop.addProperty("extend:type", "date");
return prop;
}
private static JsonObject buildCurrencyProperty(String description) {
JsonObject prop = new JsonObject();
prop.addProperty("type", "object");
JsonArray required = new JsonArray();
required.add("amount");
required.add("iso_4217_currency_code");
prop.add("required", required);
JsonObject properties = new JsonObject();
JsonObject amountProp = new JsonObject();
JsonArray amountType = new JsonArray();
amountType.add("number");
amountType.add("null");
amountProp.add("type", amountType);
properties.add("amount", amountProp);
JsonObject codeProp = new JsonObject();
JsonArray codeType = new JsonArray();
codeType.add("string");
codeType.add("null");
codeProp.add("type", codeType);
properties.add("iso_4217_currency_code", codeProp);
prop.add("properties", properties);
prop.addProperty("description", description);
prop.addProperty("extend:type", "currency");
prop.addProperty("additionalProperties", false);
return prop;
}
private static JsonArray buildDiagnosisCodesArray() {
JsonArray array = new JsonArray();
JsonObject item = new JsonObject();
item.addProperty("type", "object");
JsonArray required = new JsonArray();
required.add("diagnosis_code");
required.add("diagnosis_code_pointer");
item.add("required", required);
JsonObject properties = new JsonObject();
properties.add("diagnosis_code", buildStringProperty("A single diagnosis code (ICD-10, ICD-9, or other standard) relevant to the patient's condition or treatment."));
properties.add("diagnosis_code_pointer", buildStringProperty("The letter or reference used to map this diagnosis code to a service line (e.g., 'A', 'B', etc.), if present."));
item.add("properties", properties);
item.addProperty("additionalProperties", false);
array.add(item);
JsonObject arrayObj = new JsonObject();
arrayObj.addProperty("type", "array");
arrayObj.add("items", item);
arrayObj.addProperty("description", "The list of diagnosis codes (ICD) that describe the patient's condition or reason for the encounter. Each code represents a specific diagnosis or symptom relevant to the claim. These may be labeled as 'Diagnosis Code', 'ICD Code', or similar, and are often referenced by letter (A-L) for mapping to service lines.");
return arrayObj;
}
private static JsonObject buildDiagnosisCodesArrayAsObject() {
JsonObject arrayObj = new JsonObject();
arrayObj.addProperty("type", "array");
JsonObject item = new JsonObject();
item.addProperty("type", "object");
JsonArray required = new JsonArray();
required.add("diagnosis_code");
required.add("diagnosis_code_pointer");
item.add("required", required);
JsonObject properties = new JsonObject();
properties.add("diagnosis_code", buildStringProperty("A single diagnosis code (ICD-10, ICD-9, or other standard) relevant to the patient's condition or treatment."));
properties.add("diagnosis_code_pointer", buildStringProperty("The letter or reference used to map this diagnosis code to a service line (e.g., 'A', 'B', etc.), if present."));
item.add("properties", properties);
item.addProperty("additionalProperties", false);
arrayObj.add("items", item);
arrayObj.addProperty("description", "The list of diagnosis codes (ICD) that describe the patient's condition or reason for the encounter. Each code represents a specific diagnosis or symptom relevant to the claim. These may be labeled as 'Diagnosis Code', 'ICD Code', or similar, and are often referenced by letter (A-L) for mapping to service lines.");
return arrayObj;
}
private static JsonArray buildDiagnosisCodesArray() {
return new JsonArray();
}
private static JsonObject buildDiagnosisCodesArrayFull() {
JsonObject arrayObj = new JsonObject();
arrayObj.addProperty("type", "array");
JsonObject item = new JsonObject();
item.addProperty("type", "object");
JsonArray required = new JsonArray();
required.add("diagnosis_code");
required.add("diagnosis_code_pointer");
item.add("required", required);
JsonObject properties = new JsonObject();
properties.add("diagnosis_code", buildStringProperty("A single diagnosis code (ICD-10, ICD-9, or other standard) relevant to the patient's condition or treatment."));
properties.add("diagnosis_code_pointer", buildStringProperty("The letter or reference used to map this diagnosis code to a service line (e.g., 'A', 'B', etc.), if present."));
item.add("properties", properties);
item.addProperty("additionalProperties", false);
arrayObj.add("items", item);
arrayObj.addProperty("description", "The list of diagnosis codes (ICD) that describe the patient's condition or reason for the encounter. Each code represents a specific diagnosis or symptom relevant to the claim. These may be labeled as 'Diagnosis Code', 'ICD Code', or similar, and are often referenced by letter (A-L) for mapping to service lines.");
return arrayObj;
}
private static JsonObject buildClaimLineItemsArray() {
JsonObject arrayObj = new JsonObject();
arrayObj.addProperty("type", "array");
JsonObject item = new JsonObject();
item.addProperty("type", "object");
JsonArray required = new JsonArray();
String[] requiredLineItemFields = {
"units", "charge_amount", "procedure_code", "service_date_to", "place_of_service",
"diagnosis_pointer", "service_date_from", "procedure_modifier", "emergency_indicator",
"service_line_number", "rendering_provider_qualifier", "rendering_provider_identifier"
};
for (String field : requiredLineItemFields) {
required.add(field);
}
item.add("required", required);
JsonObject properties = new JsonObject();
properties.add("units", buildNumberProperty("The number of units, days, or quantity for this service line."));
properties.add("charge_amount", buildNumberProperty("The amount charged for this specific service line, before any adjustments or payments."));
properties.add("procedure_code", buildStringProperty("The CPT, HCPCS, or other procedure code describing the service or supply provided."));
properties.add("service_date_to", buildDateProperty("The end date for the service or procedure performed in this line item, if different from the start date."));
properties.add("place_of_service", buildStringProperty("The code or description indicating where the service was provided (e.g., office, hospital, home)."));
properties.add("diagnosis_pointer", buildStringProperty("The letter(s) or reference(s) indicating which diagnosis code(s) apply to this service line."));
properties.add("service_date_from", buildDateProperty("The start date for the service or procedure performed in this line item."));
properties.add("procedure_modifier", buildStringProperty("Any modifier(s) associated with the procedure code, if present."));
properties.add("emergency_indicator", buildStringProperty("Indicates if the service was an emergency. Typical values include 'Yes', 'No', or a checkbox indicator."));
properties.add("service_line_number", buildStringProperty("The sequential number or identifier for this service line, if present."));
properties.add("rendering_provider_qualifier", buildStringProperty("The qualifier code for the rendering provider's identification number, if present (e.g., 'NPI', 'UPIN')."));
properties.add("rendering_provider_identifier", buildStringProperty("The identification number for the rendering provider for this service line, such as NPI or other ID."));
item.add("properties", properties);
item.addProperty("additionalProperties", false);
arrayObj.add("items", item);
arrayObj.addProperty("description", "The list of individual service lines or procedures billed on this claim. Each line item represents a distinct service, procedure, or supply provided to the patient, and includes details such as dates, codes, charges, and provider information.");
return arrayObj;
}
private static JsonObject buildNumberProperty(String description) {
JsonObject prop = new JsonObject();
JsonArray typeArray = new JsonArray();
typeArray.add("number");
typeArray.add("null");
prop.add("type", typeArray);
prop.addProperty("description", description);
return prop;
}
}package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
)
const (
API = "https://api.extend.ai"
VERSION = "2026-02-09"
)
type State struct {
WorkflowID string `json:"workflowId,omitempty"`
}
var (
apiKey string
stateDir string
stateFile string
state State
)
func init() {
apiKey = os.Getenv("EXTEND_API_KEY")
if apiKey == "" {
fmt.Fprintf(os.Stderr, "Set EXTEND_API_KEY first.\n")
os.Exit(1)
}
cwd, _ := os.Getwd()
stateDir = filepath.Join(cwd, ".extend")
stateFile = filepath.Join(stateDir, "health-insurance-claim-form.json")
if data, err := os.ReadFile(stateFile); err == nil {
json.Unmarshal(data, &state)
}
}
func saveState() error {
os.MkdirAll(stateDir, 0755)
data, _ := json.MarshalIndent(state, "", " ")
return os.WriteFile(stateFile, data, 0644)
}
func apiCall(method, pathName string, body interface{}) (map[string]interface{}, error) {
var reqBody io.Reader
if body != nil {
data, _ := json.Marshal(body)
reqBody = bytes.NewReader(data)
}
req, _ := http.NewRequest(method, API+pathName, reqBody)
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", apiKey))
req.Header.Set("x-extend-api-version", VERSION)
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
respData := make(map[string]interface{})
json.NewDecoder(resp.Body).Decode(&respData)
if resp.StatusCode >= 400 {
respBytes, _ := json.Marshal(respData)
if len(respBytes) > 300 {
respBytes = respBytes[:300]
}
return nil, fmt.Errorf("%s %s failed (%d): %s", method, pathName, resp.StatusCode, string(respBytes))
}
return respData, nil
}
var workflow = map[string]interface{}{
"name": "Health Insurance Claim Form 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{
"amount_paid", "insured_sex", "patient_sex", "claim_number", "insured_name",
"patient_name", "total_charge", "date_of_other", "diagnosis_codes", "insured_address",
"patient_address", "claim_line_items", "is_auto_accident", "accept_assignment", "is_other_accident",
"primary_policy_id", "other_insured_name", "secondary_policy_id", "billing_provider_npi", "insured_phone_number",
"patient_phone_number", "primary_group_number", "service_facility_npi", "billing_provider_name", "federal_tax_id_number",
"insured_date_of_birth", "is_employment_related", "patient_date_of_birth", "service_facility_name", "insured_signature_date",
"patient_account_number", "patient_signature_date", "rendering_provider_npi", "secondary_group_number", "primary_insurance_payer",
"referring_provider_name", "rendering_provider_name", "billing_provider_address", "hospitalization_dates_to", "service_facility_address",
"insured_signature_on_file", "patient_signature_on_file", "secondary_insurance_payer", "hospitalization_dates_from", "prior_authorization_number",
"other_insured_policy_number", "referring_provider_identifier", "dates_patient_unable_to_work_to", "patient_relationship_to_insured", "dates_patient_unable_to_work_from",
"date_of_current_illness_injury_pregnancy",
},
"properties": map[string]interface{}{
"amount_paid": map[string]interface{}{
"type": "object",
"required": []string{"amount", "iso_4217_currency_code"},
"properties": map[string]interface{}{
"amount": map[string]interface{}{"type": []string{"number", "null"}},
"iso_4217_currency_code": map[string]interface{}{"type": []string{"string", "null"}},
},
"description": "The amount paid by the patient or other parties prior to claim submission. This is any payment already made toward the total charge.",
"extend:type": "currency",
"additionalProperties": false,
},
"insured_sex": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The sex or gender of the insured individual. Common values include 'M', 'F', 'Male', 'Female', or similar.",
},
"patient_sex": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The sex or gender of the patient. Common values include 'M', 'F', 'Male', 'Female', or similar.",
},
"claim_number": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The unique identifier assigned to this health insurance claim. This may be labeled as 'Claim Number', 'Reference Number', or similar, and is used to track the claim throughout the adjudication process. In CMS-1500 forms, this may be found in various locations or referenced as an authorization or control number.",
},
"insured_name": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The full name of the person who holds the insurance policy. This is the insured party, who may or may not be the patient. Typically appears as 'Insured's Name' and may include last, first, and middle initial.",
},
"patient_name": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The full name of the patient receiving services. This is the individual for whom the claim is being submitted. Typically includes last, first, and middle initial.",
},
"total_charge": map[string]interface{}{
"type": "object",
"required": []string{"amount", "iso_4217_currency_code"},
"properties": map[string]interface{}{
"amount": map[string]interface{}{"type": []string{"number", "null"}},
"iso_4217_currency_code": map[string]interface{}{"type": []string{"string", "null"}},
},
"description": "The total amount charged for all services rendered on this claim, before any adjustments or payments. This is the sum of all line item charges.",
"extend:type": "currency",
"additionalProperties": false,
},
"date_of_other": map[string]interface{}{
"type": []string{"string", "null"},
"description": "Any other relevant date associated with the claim, such as a similar illness or accident, as indicated on the form.",
"extend:type": "date",
},
"diagnosis_codes": map[string]interface{}{
"type": "array",
"items": map[string]interface{}{
"type": "object",
"required": []string{"diagnosis_code", "diagnosis_code_pointer"},
"properties": map[string]interface{}{
"diagnosis_code": map[string]interface{}{
"type": []string{"string", "null"},
"description": "A single diagnosis code (ICD-10, ICD-9, or other standard) relevant to the patient's condition or treatment.",
},
"diagnosis_code_pointer": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The letter or reference used to map this diagnosis code to a service line (e.g., 'A', 'B', etc.), if present.",
},
},
"additionalProperties": false,
},
"description": "The list of diagnosis codes (ICD) that describe the patient's condition or reason for the encounter. Each code represents a specific diagnosis or symptom relevant to the claim. These may be labeled as 'Diagnosis Code', 'ICD Code', or similar, and are often referenced by letter (A-L) for mapping to service lines.",
},
"insured_address": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The complete mailing address of the insured individual, including street, city, state, and ZIP code.",
},
"patient_address": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The complete mailing address of the patient, including street, city, state, and ZIP code. This is used for correspondence and identification.",
},
"claim_line_items": map[string]interface{}{
"type": "array",
"items": map[string]interface{}{
"type": "object",
"required": []string{
"units", "charge_amount", "procedure_code", "service_date_to", "place_of_service",
"diagnosis_pointer", "service_date_from", "procedure_modifier", "emergency_indicator",
"service_line_number", "rendering_provider_qualifier", "rendering_provider_identifier",
},
"properties": map[string]interface{}{
"units": map[string]interface{}{
"type": []string{"number", "null"},
"description": "The number of units, days, or quantity for this service line.",
},
"charge_amount": map[string]interface{}{
"type": []string{"number", "null"},
"description": "The amount charged for this specific service line, before any adjustments or payments.",
},
"procedure_code": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The CPT, HCPCS, or other procedure code describing the service or supply provided.",
},
"service_date_to": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The end date for the service or procedure performed in this line item, if different from the start date.",
"extend:type": "date",
},
"place_of_service": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The code or description indicating where the service was provided (e.g., office, hospital, home).",
},
"diagnosis_pointer": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The letter(s) or reference(s) indicating which diagnosis code(s) apply to this service line.",
},
"service_date_from": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The start date for the service or procedure performed in this line item.",
"extend:type": "date",
},
"procedure_modifier": map[string]interface{}{
"type": []string{"string", "null"},
"description": "Any modifier(s) associated with the procedure code, if present.",
},
"emergency_indicator": map[string]interface{}{
"type": []string{"string", "null"},
"description": "Indicates if the service was an emergency. Typical values include 'Yes', 'No', or a checkbox indicator.",
},
"service_line_number": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The sequential number or identifier for this service line, if present.",
},
"rendering_provider_qualifier": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The qualifier code for the rendering provider's identification number, if present (e.g., 'NPI', 'UPIN').",
},
"rendering_provider_identifier": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The identification number for the rendering provider for this service line, such as NPI or other ID.",
},
},
"additionalProperties": false,
},
"description": "The list of individual service lines or procedures billed on this claim. Each line item represents a distinct service, procedure, or supply provided to the patient, and includes details such as dates, codes, charges, and provider information.",
},
"is_auto_accident": map[string]interface{}{
"type": []string{"string", "null"},
"description": "Indicates whether the patient's condition is related to an auto accident. Typical values are 'Yes', 'No', or similar.",
},
"accept_assignment": map[string]interface{}{
"type": []string{"string", "null"},
"description": "Indicates whether the provider accepts assignment of benefits. Typical values are 'Yes', 'No', or similar.",
},
"is_other_accident": map[string]interface{}{
"type": []string{"string", "null"},
"description": "Indicates whether the patient's condition is related to any other type of accident. Typical values are 'Yes', 'No', or similar.",
},
"primary_policy_id": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The policy or member identification number for the primary insurance plan. This is the unique number assigned to the insured by the primary payer, often labeled as 'Insured's ID Number', 'Policy Number', or similar.",
},
"other_insured_name": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The name of any additional insured party, if applicable. This may be present when there is more than one insurance policy involved.",
},
"secondary_policy_id": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The policy or member identification number for the secondary insurance plan, if present. This is the unique number assigned to the insured by the secondary payer.",
},
"billing_provider_npi": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The National Provider Identifier (NPI) for the billing provider, if applicable.",
},
"insured_phone_number": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The telephone number for the insured individual, including area code.",
},
"patient_phone_number": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The telephone number for the patient, including area code. Used for contact purposes.",
},
"primary_group_number": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The group number associated with the primary insurance policy, if applicable. This is typically used for employer-sponsored or group health plans and may be labeled as 'Group Number', 'Group ID', or similar.",
},
"service_facility_npi": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The National Provider Identifier (NPI) for the service facility, if applicable.",
},
"billing_provider_name": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The name of the provider or entity submitting the claim for payment. This is the billing party, which may be an individual or organization.",
},
"federal_tax_id_number": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The federal tax identification number (EIN or SSN) of the billing provider or entity submitting the claim.",
},
"insured_date_of_birth": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The date of birth of the insured individual. This is used to verify identity and eligibility. May be labeled as 'Insured's Date of Birth' and can appear in various formats.",
"extend:type": "date",
},
"is_employment_related": map[string]interface{}{
"type": []string{"string", "null"},
"description": "Indicates whether the patient's condition is related to employment. Typical values are 'Yes', 'No', or similar.",
},
"patient_date_of_birth": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The date of birth of the patient. Used for identification and eligibility verification.",
"extend:type": "date",
},
"service_facility_name": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The name of the facility where services were rendered, if different from the billing provider.",
},
"insured_signature_date": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The date the insured or authorized person signed the authorization, if present.",
"extend:type": "date",
},
"patient_account_number": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The account number assigned to the patient by the provider or billing entity. Used for internal tracking and reconciliation.",
},
"patient_signature_date": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The date the patient or authorized person signed the authorization, if present.",
"extend:type": "date",
},
"rendering_provider_npi": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The National Provider Identifier (NPI) for the rendering provider, if applicable.",
},
"secondary_group_number": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The group number associated with the secondary insurance policy, if applicable.",
},
"primary_insurance_payer": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The name of the primary insurance company or payer responsible for processing this claim. This is the main insurer listed on the form, often labeled as 'Primary Payer', 'Insurance Carrier', or similar.",
},
"referring_provider_name": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The name of the referring provider or other source who referred the patient for services. May be labeled as 'Referring Provider', 'Ordering Physician', or similar.",
},
"rendering_provider_name": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The name of the individual provider who performed the services, if different from the billing provider.",
},
"billing_provider_address": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The complete address of the billing provider, including street, city, state, and ZIP code.",
},
"hospitalization_dates_to": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The end date of any hospitalization related to the current services, if applicable.",
"extend:type": "date",
},
"service_facility_address": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The address of the facility where services were rendered, including street, city, state, and ZIP code.",
},
"insured_signature_on_file": map[string]interface{}{
"type": []string{"string", "null"},
"description": "Indicates whether the insured's or authorized person's signature is on file authorizing payment of benefits. Typical values include 'Signature on File', 'Yes', or similar.",
},
"patient_signature_on_file": map[string]interface{}{
"type": []string{"string", "null"},
"description": "Indicates whether the patient's or authorized person's signature is on file authorizing release of information and payment. Typical values include 'Signature on File', 'Yes', or similar.",
},
"secondary_insurance_payer": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The name of the secondary insurance company or payer, if present. This is an additional insurer that may provide coverage after the primary payer, often labeled as 'Secondary Payer' or similar.",
},
"hospitalization_dates_from": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The start date of any hospitalization related to the current services, if applicable.",
"extend:type": "date",
},
"prior_authorization_number": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The authorization or referral number provided by the payer, if required for the services rendered. May be labeled as 'Prior Authorization Number', 'Referral Number', or similar.",
},
"other_insured_policy_number": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The policy or group number for any additional insured party, if applicable.",
},
"referring_provider_identifier": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The unique identifier (such as NPI or other ID) for the referring provider, if present.",
},
"dates_patient_unable_to_work_to": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The end date when the patient was unable to work due to the condition, if applicable.",
"extend:type": "date",
},
"patient_relationship_to_insured": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The relationship of the patient to the insured individual. Typical values include 'Self', 'Spouse', 'Child', 'Other', or similar.",
},
"dates_patient_unable_to_work_from": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The start date when the patient was unable to work due to the condition, if applicable.",
"extend:type": "date",
},
"date_of_current_illness_injury_pregnancy": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The date when the current illness, injury, or pregnancy began. This is used to establish the onset of the condition being treated.",
"extend:type": "date",
},
},
"additionalProperties": false,
},
"baseProcessor": "extraction_performance",
"advancedOptions": map[string]interface{}{
"reviewAgent": map[string]interface{}{
"enabled": true,
},
"advancedMultimodalEnabled": true,
},
},
},
},
},
}
func main() {
name := workflow["name"].(string)
fmt.Printf("Deploying \"%s\"…\n", 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 {
list, err := apiCall("GET", fmt.Sprintf("/workflows?name=%s", encodeQuery(name)), nil)
if err == nil {
var items []map[string]interface{}
if data, ok := list["data"].([]interface{}); ok {
for _, item := range data {
items = append(items, item.(map[string]interface{}))
}
} else if data, ok := list["items"].([]interface{}); ok {
for _, item := range data {
items = append(items, item.(map[string]interface{}))
}
}
for _, item := range items {
if itemName, ok := item["name"].(string); ok && itemName == name {
if id, ok := item["id"].(string); ok {
state.WorkflowID = id
saveState()
fmt.Printf("✓ workflow \"%s\" found in your account (%s) — updating steps\n", name, id)
_, _ = apiCall("POST", fmt.Sprintf("/workflows/%s", id), map[string]interface{}{
"steps": workflow["steps"],
})
break
}
}
}
}
if state.WorkflowID == "" {
created, err := apiCall("POST", "/workflows", workflow)
if err != nil {
fmt.Fprintf(os.Stderr, "%v\n", err)
os.Exit(1)
}
var wfID string
if id, ok := created["id"].(string); ok {
wfID = id
} else if wf, ok := created["workflow"].(map[string]interface{}); ok {
if id, ok := wf["id"].(string); ok {
wfID = id
}
}
if wfID == "" {
fmt.Fprintf(os.Stderr, "Could not read created workflow id from response\n")
os.Exit(1)
}
state.WorkflowID = wfID
saveState()
fmt.Printf("+ created workflow (%s)\n", wfID)
}
}
_, _ = apiCall("POST", fmt.Sprintf("/workflows/%s/versions", state.WorkflowID), map[string]interface{}{})
fmt.Printf("\nDone. Run documents through it with:\n")
fmt.Printf(" POST %s/workflow_runs { workflow: { id: \"%s\" }, file: { url: \"https://…\" } }\n", API, state.WorkflowID)
fmt.Printf("Or open the workflow in the Extend dashboard to review and deploy it.\n")
}
func encodeQuery(s string) string {
// Simple URL encoding for query parameter
result := ""
for _, r := range s {
switch r {
case ' ':
result += "%20"
case '&':
result += "%26"
case '=':
result += "%3D"
case '?':
result += "%3F"
default:
result += string(r)
}
}
return result
}This template processes standardized health insurance claim forms. It captures patient demographics, insured information, primary and secondary payer details, policy numbers, and claim authorization signatures. Commonly used for processing medical claims across multiple insurance carriers.