Extracts patient info, microbial DNA test results, and antibiotic resistance data.
An NGS pathology report is a clinical laboratory document that details microbial identification results from DNA sequencing and qPCR analysis, including patient demographics, specimen characteristics, detected organisms with their relative abundance, identified antimicrobial resistance genes, and drug-class-specific susceptibility recommendations. This template takes in Next-Generation Sequencing Pathology Report and outputs JSON (.json) with structured fields capturing patient information, specimen details, bacterial and fungal findings with abundance data, detected resistance genes, and antimicrobial recommendations organized by drug class by using Extend's Extract primitives.
Pulls a defined set of fields from the document and returns them as structured JSON matching a schema.
schemacustom schema — 19 fieldschangedadvancedOptions.advancedMultimodalEnabledtruechangedadvancedOptions.reviewAgent.enabledtruechangedbaseProcessor"extraction_performance"You can learn more about Extract configuration in Extend's Extract documentation.
{
"name": "Pathology report Processing Pipeline",
"steps": [
{
"name": "startTrigger1",
"type": "TRIGGER",
"next": [
{
"step": "parse1"
}
]
},
{
"name": "parse1",
"type": "PARSE",
"config": {
"parseConfig": {
"blockOptions": {
"text": {
"agentic": {
"enabled": true
},
"signatureDetectionEnabled": true
},
"tables": {
"agentic": {
"enabled": true
},
"tableHeaderContinuationEnabled": true
},
"figures": {
"enabled": true
}
},
"chunkingStrategy": {
"type": "page",
"options": {}
}
}
},
"next": [
{
"step": "extraction2"
}
]
},
{
"name": "extraction2",
"type": "EXTRACT",
"config": {
"extractorConfig": {
"schema": {
"type": "object",
"required": [
"gender",
"patient_id",
"patient_name",
"date_of_birth",
"physician_fax",
"specimen_type",
"bacterial_load",
"physician_name",
"fungal_findings",
"physician_phone",
"accession_number",
"bacterial_findings",
"ngs_report_version",
"laboratory_director",
"specimen_received_date",
"specimen_collected_date",
"specimen_completed_date",
"resistance_genes_detected",
"antimicrobial_recommendations"
],
"properties": {
"gender": {
"type": [
"string",
"null"
],
"description": "The gender or sex of the patient. May be indicated as 'Male', 'Female', or other designations. Typically found near patient demographic information."
},
"patient_id": {
"type": [
"string",
"null"
],
"description": "A unique identifier assigned to the patient in the context of this report. This may be a medical record number, accession number, or other patient-specific code. Commonly labeled as 'Patient ID' or similar."
},
"patient_name": {
"type": [
"string",
"null"
],
"description": "The full name of the patient for whom the next-generation sequencing (NGS) report was generated. This is the individual whose specimen was analyzed. May appear under various labels such as 'Patient', 'Patient Name', or similar."
},
"date_of_birth": {
"type": [
"string",
"null"
],
"description": "The patient's date of birth. Used for identification and clinical context. May be labeled as 'DOB' or 'Date of Birth'.",
"extend:type": "date"
},
"physician_fax": {
"type": [
"string",
"null"
],
"description": "The fax number for the ordering or referring physician. May be labeled as 'Fax', 'Physician Fax', or similar."
},
"specimen_type": {
"type": [
"string",
"null"
],
"description": "The type or source of the specimen submitted for NGS analysis, such as 'Wound', 'Urine', 'Blood', etc. Indicates the biological material tested."
},
"bacterial_load": {
"type": [
"string",
"null"
],
"description": "A qualitative or quantitative assessment of the total bacterial DNA present in the specimen. May be described as 'Low', 'Medium', 'High', or with specific values or ranges."
},
"physician_name": {
"type": [
"string",
"null"
],
"description": "The name of the ordering or referring physician associated with this NGS report. May be labeled as 'Physician', 'Doctor', or similar."
},
"fungal_findings": {
"type": "array",
"items": {
"type": "object",
"required": [
"organism_name",
"detection_method",
"relative_abundance_percent",
"antifungal_susceptibility_notes"
],
"properties": {
"organism_name": {
"type": [
"string",
"null"
],
"description": "The scientific name of the fungal organism detected (e.g., 'Candida albicans')."
},
"detection_method": {
"type": [
"string",
"null"
],
"description": "The method by which the organism was detected, such as 'NGS', 'PCR', or both."
},
"relative_abundance_percent": {
"type": [
"number",
"null"
],
"description": "The estimated percentage of this organism's DNA relative to the total microbial DNA in the specimen, as determined by NGS."
},
"antifungal_susceptibility_notes": {
"type": [
"string",
"null"
],
"description": "Any notes or summary regarding the organism's susceptibility or resistance to antifungal agents, including detected resistance genes or effective drug classes."
}
},
"additionalProperties": false
},
"description": "A list of fungal organisms identified in the specimen by NGS and/or PCR, including their relative abundance and relevant laboratory findings. Each entry represents a distinct fungal organism detected."
},
"physician_phone": {
"type": [
"string",
"null"
],
"description": "The phone number for the ordering or referring physician. May be labeled as 'Phone', 'Physician Phone', or similar."
},
"accession_number": {
"type": [
"string",
"null"
],
"description": "A unique identifier assigned to the specimen for laboratory tracking and reference. Often labeled as 'Accession', 'Accession Number', or similar."
},
"bacterial_findings": {
"type": "array",
"items": {
"type": "object",
"required": [
"gram_stain",
"organism_name",
"detection_method",
"respiration_type",
"bacterial_load_level",
"relative_abundance_percent",
"antimicrobial_susceptibility_notes"
],
"properties": {
"gram_stain": {
"type": [
"string",
"null"
],
"description": "The Gram stain result for the organism, such as 'Positive', 'Negative', or other designations. May be abbreviated as '+', '-', or similar."
},
"organism_name": {
"type": [
"string",
"null"
],
"description": "The scientific name of the bacterial organism detected (e.g., 'Staphylococcus aureus', 'Escherichia coli')."
},
"detection_method": {
"type": [
"string",
"null"
],
"description": "The method by which the organism was detected, such as 'NGS', 'PCR', or both. May also indicate if only one method was used."
},
"respiration_type": {
"type": [
"string",
"null"
],
"description": "The respiration classification of the organism, such as 'Aerobic', 'Anaerobic', 'Facultative anaerobic', or similar. May be abbreviated as 'Ae', 'An', 'FAn', etc."
},
"bacterial_load_level": {
"type": [
"string",
"null"
],
"description": "A qualitative assessment of the organism's load, such as 'Low', 'Medium', 'High', or specific ranges. May be based on DNA copies or other metrics."
},
"relative_abundance_percent": {
"type": [
"number",
"null"
],
"description": "The estimated percentage of this organism's DNA relative to the total microbial DNA in the specimen, as determined by NGS."
},
"antimicrobial_susceptibility_notes": {
"type": [
"string",
"null"
],
"description": "Any notes or summary regarding the organism's susceptibility or resistance to antimicrobials, including detected resistance genes or effective drug classes."
}
},
"additionalProperties": false
},
"description": "A list of bacterial organisms identified in the specimen by NGS and/or PCR, including their relative abundance and relevant laboratory findings. Each entry represents a distinct organism detected."
},
"ngs_report_version": {
"type": [
"string",
"null"
],
"description": "The version or identifier of the NGS report or testing protocol used. May appear as a version number or code, often at the bottom or in the footer."
},
"laboratory_director": {
"type": [
"string",
"null"
],
"description": "The name and credentials of the laboratory director or responsible scientist who authorized the report. Typically found near the signature or at the end of the document."
},
"specimen_received_date": {
"type": [
"string",
"null"
],
"description": "The date the laboratory received the specimen for processing. May be labeled as 'Received', 'Date Received', or similar.",
"extend:type": "date"
},
"specimen_collected_date": {
"type": [
"string",
"null"
],
"description": "The date on which the specimen was collected from the patient. May be labeled as 'Collected', 'Collection Date', or similar.",
"extend:type": "date"
},
"specimen_completed_date": {
"type": [
"string",
"null"
],
"description": "The date the laboratory completed the analysis of the specimen. May be labeled as 'Completed', 'Date Completed', or similar.",
"extend:type": "date"
},
"resistance_genes_detected": {
"type": [
"string",
"null"
],
"description": "A summary of any antimicrobial resistance genes detected in the specimen. May list specific resistance types or drugs, such as 'Bactrim', or indicate none detected."
},
"antimicrobial_recommendations": {
"type": "array",
"items": {
"type": "object",
"required": [
"drug_class",
"example_drugs",
"recommendation_notes"
],
"properties": {
"drug_class": {
"type": [
"string",
"null"
],
"description": "The class of antimicrobial agent (e.g., 'Fluoroquinolones', 'Cephalosporins', 'Carbapenems')."
},
"example_drugs": {
"type": [
"string",
"null"
],
"description": "Examples of drugs within this class, as listed in the report (e.g., 'Levofloxacin', 'Keflex')."
},
"recommendation_notes": {
"type": [
"string",
"null"
],
"description": "Any notes or comments regarding the use, effectiveness, or resistance related to this drug class for the organisms detected."
}
},
"additionalProperties": false
},
"description": "A list of antimicrobial agents or drug classes recommended or considered based on the NGS findings. Each entry may include the drug class, example drugs, and any relevant notes about their use or effectiveness."
}
},
"additionalProperties": false
},
"baseProcessor": "extraction_performance",
"advancedOptions": {
"reviewAgent": {
"enabled": true
},
"advancedMultimodalEnabled": true
}
}
}
}
]
}# Pathology Report Processing — Extend AI Skill
## What this pipeline does
Extracts structured microbial identification and antimicrobial susceptibility data from Next-Generation Sequencing (NGS) pathology reports. The pipeline parses the PDF into markdown with intelligent table and signature detection, then uses high-accuracy extraction with review agent validation to capture patient demographics, specimen details, bacterial and fungal findings (including Gram stain, organism names, relative abundance, and resistance profiles), detected resistance genes, and drug-class-specific antimicrobial recommendations organized by clinical drug class.
## When to use this
- **Clinical laboratory workflows**: Extract and structure NGS pathology results for clinical decision support systems, electronic health record (EHR) integration, or antibiotic stewardship programs.
- **Infection control epidemiology**: Automatically catalog detected organisms, resistance genes, and susceptibility patterns across multiple patient specimens for outbreak tracking and resistance surveillance.
- **Microbiology research and quality assurance**: Validate report consistency, extract organism prevalence and abundance data for retrospective analysis, and flag unusual or incomplete susceptibility profiles.
- **Medical-legal documentation**: Preserve structured, machine-readable extracts of authorized pathology reports with laboratory director signatures and exact test versions for audit and compliance.
- **Multi-organism specimen analysis**: Handle specimens with multiple bacterial and fungal co-infections, capturing relative abundance percentages and organism-specific susceptibility notes in a single structured record.
## Processor pipeline
### Step 1: Parse (`parseRuns.createAndPoll`)
**Purpose**: Convert raw PDF into block-level markdown with intelligent handling of tables, figures, and signatures.
**Configuration**:
- **Agentic text processing**: Enabled. Handles variable report layouts, handwritten annotations, and OCR challenges in pathology documents.
- **Agentic table parsing**: Enabled. NGS reports often contain multi-row susceptibility matrices; agentic mode reconstructs broken tables across page boundaries.
- **Table header continuation**: Enabled. Organism tables may span pages; continuation mode ensures headers are retained and reconstructed.
- **Figure extraction**: Enabled. Some reports include phylogenetic trees, abundance charts, or resistance heatmaps.
- **Signature detection**: Enabled. Laboratory director signature is a key compliance marker; detection creates structured metadata for audit trails.
- **Chunking strategy**: Page-based. NGS reports are typically 2–10 pages; page-level chunks preserve organism groupings and section coherence.
**Why this config**: Pathology reports are semi-structured with standardized sections (demographics, specimen details, findings, recommendations) but highly variable table layouts. Agentic parsing recovers meaning from imperfectly scanned or reformatted reports. Signature detection ensures director authorization is captured. Page-level chunking allows downstream extraction to reason about context (e.g., "this organism is in the bacterial section, not fungal").
### Step 2: Extract (`extractRuns.createAndPoll`)
**Purpose**: Pull 19 top-level fields and 2 nested arrays (bacterial findings, fungal findings, antimicrobial recommendations) into strongly typed JSON matching a clinical laboratory information system (LIS) schema.
**Configuration**:
- **Base processor**: `extraction_performance`. NGS reports contain critical clinical data; this mode prioritizes accuracy over speed, using multi-pass reasoning and structured validation.
- **Review agent**: Enabled. A secondary validation pass checks that:
- Organism names are scientifically plausible (e.g., "Staphylococcus aureus" ✓, "Bacillus xyz" ✗).
- Relative abundance percentages sum to ~100% across bacterial or fungal findings.
- Drug class names match standard antimicrobial taxonomies (e.g., "Fluoroquinolones", "Beta-lactams").
- Required fields like `patient_id`, `accession_number`, and at least one organism finding are populated.
- **Advanced multimodal**: Enabled. Handles scanned or handwritten annotations in margins, tables with mixed fonts/colors, and embedded charts showing organism abundance.
**Why this config**: Pathology reports drive clinical decisions; extraction errors could lead to incorrect antimicrobial therapy. The review agent catches inconsistencies (e.g., a 150% total abundance or organism spelled as "Staph aureus" in one section and "S. aureus" in another). Performance mode tolerates longer latency (~20–30 sec for a 5-page report) to ensure clinician trust.
## TypeScript implementation
```typescript
import { ExtendClient, extendDate } from "extend-ai";
import { z } from "zod";
import fs from "fs";
const client = new ExtendClient({ token: process.env.EXTEND_API_KEY });
/**
* Define the Zod schema for NGS pathology report extraction.
* This schema matches the clinical LIS structure for organism findings
* and antimicrobial recommendations.
*/
const pathologyReportSchema = z.object({
// Patient demographics
patient_name: z.string().nullable().describe("Full name of the patient for whom the NGS report was generated. May appear as 'Patient', 'Patient Name', or similar."),
patient_id: z.string().nullable().describe("Unique identifier assigned to the patient (medical record number, accession number, or patient-specific code). Commonly labeled 'Patient ID'."),
gender: z.string().nullable().describe("Gender or sex of the patient, indicated as 'Male', 'Female', or other designations. Typically found near demographic information."),
date_of_birth: extendDate().describe("Patient's date of birth. Used for identification and clinical context. May be labeled 'DOB' or 'Date of Birth'."),
// Specimen and report metadata
accession_number: z.string().nullable().describe("Unique identifier assigned to the specimen for laboratory tracking. Often labeled 'Accession' or 'Accession Number'."),
specimen_type: z.string().nullable().describe("Type or source of the specimen submitted for NGS analysis (e.g., 'Wound', 'Urine', 'Blood'). Indicates the biological material tested."),
specimen_collected_date: extendDate().describe("Date on which the specimen was collected from the patient. May be labeled 'Collected' or 'Collection Date'."),
specimen_received_date: extendDate().describe("Date the laboratory received the specimen for processing. May be labeled 'Received' or 'Date Received'."),
specimen_completed_date: extendDate().describe("Date the laboratory completed the analysis of the specimen. May be labeled 'Completed' or 'Date Completed'."),
bacterial_load: z.string().nullable().describe("Qualitative or quantitative assessment of total bacterial DNA in the specimen (e.g., 'Low', 'Medium', 'High', or specific values/ranges)."),
// Physician and lab director contact
physician_name: z.string().nullable().describe("Name of the ordering or referring physician associated with this NGS report. May be labeled 'Physician' or 'Doctor'."),
physician_phone: z.string().nullable().describe("Phone number for the ordering or referring physician. May be labeled 'Phone' or 'Physician Phone'."),
physician_fax: z.string().nullable().describe("Fax number for the ordering or referring physician. May be labeled 'Fax' or 'Physician Fax'."),
laboratory_director: z.string().nullable().describe("Name and credentials of the laboratory director or responsible scientist who authorized the report. Typically found near the signature or at the end of the document."),
ngs_report_version: z.string().nullable().describe("Version or identifier of the NGS report or testing protocol used. May appear as a version number or code, often at the bottom or in the footer."),
// Resistance summary
resistance_genes_detected: z.string().nullable().describe("Summary of any antimicrobial resistance genes detected in the specimen. May list specific resistance types (e.g., 'Bactrim resistance') or indicate 'None detected'."),
// Bacterial findings array
bacterial_findings: z.array(
z.object({
organism_name: z.string().nullable().describe("Scientific name of the bacterial organism detected (e.g., 'Staphylococcus aureus', 'Escherichia coli'). This is the primary identifier for the organism."),
gram_stain: z.string().nullable().describe("Gram stain result for the organism ('Positive', 'Negative', or abbreviations '+', '-'). Fundamental for bacterial classification."),
respiration_type: z.string().nullable().describe("Respiration classification ('Aerobic', 'Anaerobic', 'Facultative anaerobic', or abbreviations 'Ae', 'An', 'FAn'). Critical for culture conditions and antibiotic selection."),
detection_method: z.string().nullable().describe("Method by which the organism was detected ('NGS', 'PCR', or 'Both'). Indicates the confidence and sensitivity of detection."),
bacterial_load_level: z.string().nullable().describe("Qualitative assessment of the organism's load ('Low', 'Medium', 'High', or specific ranges). May be based on DNA copy counts."),
relative_abundance_percent: z.number().nullable().describe("Estimated percentage of this organism's DNA relative to total microbial DNA in the specimen (0–100), as determined by NGS. Used for assessing clinical significance."),
antimicrobial_susceptibility_notes: z.string().nullable().describe("Notes or summary regarding the organism's susceptibility or resistance to antimicrobials, including detected resistance genes or effective drug classes. Directly informs therapy recommendations."),
})
).describe("Array of bacterial organisms identified by NGS and/or PCR, including relative abundance and susceptibility notes. Each entry represents a distinct bacterial organism detected."),
// Fungal findings array
fungal_findings: z.array(
z.object({
organism_name: z.string().nullable().describe("Scientific name of the fungal organism detected (e.g., 'Candida albicans', 'Aspergillus fumigatus'). Primary identifier for fungi."),
detection_method: z.string().nullable().describe("Method by which the organism was detected ('NGS', 'PCR', or 'Both'). Indicates confidence and sensitivity."),
relative_abundance_percent: z.number().nullable().describe("Estimated percentage of this organism's DNA relative to total microbial DNA in the specimen (0–100), as determined by NGS."),
antifungal_susceptibility_notes: z.string().nullable().describe("Notes or summary regarding the organism's susceptibility or resistance to antifungal agents, including detected resistance genes or effective drug classes. Guides antifungal selection."),
})
).describe("Array of fungal organisms identified by NGS and/or PCR, including relative abundance and susceptibility notes. Each entry represents a distinct fungal organism detected."),
// Antimicrobial recommendations array
antimicrobial_recommendations: z.array(
z.object({
drug_class: z.string().nullable().describe("Class of antimicrobial agent (e.g., 'Fluoroquinolones', 'Cephalosporins', 'Carbapenems', 'Beta-lactams'). Organize recommendations by mechanism of action."),
example_drugs: z.string().nullable().describe("Specific drug examples within this class as listed in the report (e.g., 'Levofloxacin, Ciprofloxacin' for Fluoroquinolones, or 'Keflex, Cephalexin' for Cephalosporins)."),
recommendation_notes: z.string().nullable().describe("Clinical notes or comments regarding the use, effectiveness, or resistance related to this drug class for the organisms detected. May include dosing guidance or contraindications."),
})
).describe("Array of antimicrobial agents or drug classes recommended based on NGS findings. Each entry includes drug class, example drugs, and relevant clinical notes for organism-specific therapy."),
});
/**
* Main extraction function for NGS pathology reports.
* Accepts a local file path, uploads it, parses it, and extracts structured data.
* @param filePath - Path to the local NGS pathology report PDF.
* @returns Extracted report data as strongly typed object.
*/
export async function processPathologyReport(filePath: string) {
console.log(`Processing pathology report: ${filePath}`);
// Step 1: Convert local file to data URL for the SDK
const fileContent = fs.readFileSync(filePath);
const dataUrl = `data:application/octet-stream;base64,${fileContent.toString("base64")}`;
console.log("File converted to data URL.");
// Step 2: Parse the PDF to markdown with agentic OCR and signature detection
console.log("Parsing PDF with agentic OCR, table detection, and signature extraction...");
const parseRun = await client.parseRuns.createAndPoll({
file: { url: dataUrl },
config: {
mode: "agentic_ocr",
blockOptions: {
text: {
agentic: { enabled: true },
signatureDetectionEnabled: true,
},
tables: {
agentic: { enabled: true },
tableHeaderContinuationEnabled: true,
},
figures: { enabled: true },
},
chunkingStrategy: { type: "page" },
},
});
if (parseRun.status !== "PROCESSED") {
throw new Error(`Parse failed with status: ${parseRun.status}`);
}
console.log(`Parse successful. Extracted ${parseRun.output.chunks.length} chunks.`);
// Step 3: Extract structured fields using high-accuracy mode with review agent
console.log("Extracting structured fields with extraction_performance + review agent...");
const extractRun = await client.extractRuns.createAndPoll({
file: { url: dataUrl },
config: {
schema: pathologyReportSchema,
mode: "extraction_performance",
advancedOptions: {
reviewAgent: { enabled: true },
advancedMultimodalEnabled: true,
},
},
});
if (extractRun.status !== "PROCESSED") {
throw new Error(`Extraction failed with status: ${extractRun.status}`);
}
const extractedData = extractRun.output.value;
console.log("Extraction successful.");
// Step 4: Validate and log key findings
console.log("\n=== EXTRACTED PATHOLOGY REPORT DATA ===");
console.log(`Patient: ${extractedData.patient_name} (ID: ${extractedData.patient_id})`);
console.log(`DOB: ${extractedData.date_of_birth}, Gender: ${extractedData.gender}`);
console.log(`Specimen Type: ${extractedData.specimen_type}, Accession: ${extractedData.accession_number}`);
console.log(`Collected: ${extractedData.specimen_collected_date}, Received: ${extractedData.specimen_received_date}, Completed: ${extractedData.specimen_completed_date}`);
console.log(`Bacterial Load: ${extractedData.bacterial_load}`);
console.log(`Resistance Genes: ${extractedData.resistance_genes_detected || "None detected"}`);
console.log(`Physician: ${extractedData.physician_name} (Phone: ${extractedData.physician_phone}, Fax: ${extractedData.physician_fax})`);
console.log(`Lab Director: ${extractedData.laboratory_director}`);
console.log(`NGS Report Version: ${extractedData.ngs_report_version}`);
console.log(`\nBacterial Findings (${extractedData.bacterial_findings.length} organism(s)):`);
extractedData.bacterial_findings.forEach((organism, idx) => {
console.log(` ${idx + 1}. ${organism.organism_name}`);
console.log(` Gram Stain: ${organism.gram_stain}, Respiration: ${organism.respiration_type}`);
console.log(` Detection: ${organism.detection_method}, Load: ${organism.bacterial_load_level}`);
console.log(` Relative Abundance: ${organism.relative_abundance_percent}%`);
console.log(` Susceptibility: ${organism.antimicrobial_susceptibility_notes || "N/A"}`);
});
console.log(`\nFungal Findings (${extractedData.fungal_findings.length} organism(s)):`);
extractedData.fungal_findings.forEach((organism, idx) => {
console.log(` ${idx + 1}. ${organism.organism_name}`);
console.log(` Detection: ${organism.detection_method}, Relative Abundance: ${organism.relativeimport { ExtendClient, extendDate } from "extend-ai";
import { z } from "zod";
import fs from "fs";
const client = new ExtendClient({ token: process.env.EXTEND_API_KEY });
// Zod schema matching the pathology report extraction spec
const PathologyReportSchema = z.object({
gender: z.string().nullable().describe("Patient gender ('Male', 'Female', or other designation)"),
patient_id: z.string().nullable().describe("Unique patient identifier (MRN, accession, or code)"),
patient_name: z.string().nullable().describe("Full name of the patient"),
date_of_birth: extendDate().describe("Patient DOB (ISO yyyy-mm-dd)"),
physician_fax: z.string().nullable().describe("Ordering physician fax number"),
specimen_type: z.string().nullable().describe("Specimen source (e.g., 'Wound', 'Urine', 'Blood')"),
bacterial_load: z.string().nullable().describe("Overall bacterial DNA load (e.g., 'High', 'Low', or quantitative)"),
physician_name: z.string().nullable().describe("Name of ordering/referring physician"),
physician_phone: z.string().nullable().describe("Ordering physician phone number"),
accession_number: z.string().nullable().describe("Specimen accession number for lab tracking"),
ngs_report_version: z.string().nullable().describe("NGS protocol or report version"),
laboratory_director: z.string().nullable().describe("Laboratory director name and credentials"),
specimen_received_date: extendDate().describe("Date specimen arrived at lab (ISO yyyy-mm-dd)"),
specimen_collected_date: extendDate().describe("Date specimen was collected from patient (ISO yyyy-mm-dd)"),
specimen_completed_date: extendDate().describe("Date analysis was completed (ISO yyyy-mm-dd)"),
resistance_genes_detected: z.string().nullable().describe(
"Summary of antimicrobial resistance genes detected (e.g., 'blaOXA-23', 'Bactrim resistance') or 'None detected'"
),
// Nested: bacterial organisms identified
bacterial_findings: z.array(z.object({
gram_stain: z.string().nullable().describe("Gram stain result ('+' or 'Positive', '-' or 'Negative')"),
organism_name: z.string().nullable().describe("Scientific organism name (e.g., 'Staphylococcus aureus')"),
detection_method: z.string().nullable().describe("Detection method ('NGS', 'PCR', or both)"),
respiration_type: z.string().nullable().describe("Respiration type ('Aerobic', 'Anaerobic', 'Facultative anaerobic')"),
bacterial_load_level: z.string().nullable().describe("Qualitative load for this organism ('Low', 'Medium', 'High')"),
relative_abundance_percent: z.number().nullable().describe("Percentage of total microbial DNA (0–100)"),
antimicrobial_susceptibility_notes: z.string().nullable().describe(
"Susceptibility summary or detected resistance genes for this organism"
),
})).describe("List of bacterial organisms identified"),
// Nested: fungal organisms identified
fungal_findings: z.array(z.object({
organism_name: z.string().nullable().describe("Scientific organism name (e.g., 'Candida albicans')"),
detection_method: z.string().nullable().describe("Detection method ('NGS', 'PCR', or both)"),
relative_abundance_percent: z.number().nullable().describe("Percentage of total fungal DNA (0–100)"),
antifungal_susceptibility_notes: z.string().nullable().describe(
"Antifungal susceptibility or resistance summary"
),
})).describe("List of fungal organisms identified"),
// Nested: drug recommendations by class
antimicrobial_recommendations: z.array(z.object({
drug_class: z.string().nullable().describe(
"Antimicrobial class (e.g., 'Fluoroquinolones', 'Cephalosporins', 'Carbapenems')"
),
example_drugs: z.string().nullable().describe(
"Example drugs in this class from the report (e.g., 'Levofloxacin, Ciprofloxacin')"
),
recommendation_notes: z.string().nullable().describe(
"Clinical notes on effectiveness or resistance for detected organisms"
),
})).describe("Antimicrobial drug classes and recommendations based on findings"),
});
export async function processPathologyreport(filePath: string) {
console.log(`Processing pathology report from: ${filePath}`);
// Convert local file to data URL for SDK consumption
const fileBuffer = fs.readFileSync(filePath);
const dataUrl = `data:application/octet-stream;base64,${fileBuffer.toString("base64")}`;
try {
// Step 1: Parse the report with agentic OCR and table extraction
console.log("Step 1: Parsing report with agentic OCR...");
const parseRun = await client.parseRuns.createAndPoll({
file: { url: dataUrl },
config: {
blockOptions: {
text: {
agentic: { enabled: true },
signatureDetectionEnabled: true,
},
tables: {
agentic: { enabled: true },
tableHeaderContinuationEnabled: true,
},
figures: { enabled: true },
},
chunkingStrategy: {
type: "page",
options: {},
},
},
});
if (parseRun.status !== "PROCESSED") {
throw new Error(`Parse run failed with status: ${parseRun.status}`);
}
console.log(`✓ Parsed ${parseRun.output.chunks.length} chunks`);
const markdown = parseRun.output.chunks.map((c) => c.content).join("\n\n");
console.log(`Markdown preview (first 500 chars):\n${markdown.substring(0, 500)}\n`);
// Step 2: Extract structured fields using Zod schema with review agent
console.log("Step 2: Extracting structured fields (with review agent)...");
const extractRun = await client.extractRuns.createAndPoll({
file: { url: dataUrl },
config: {
schema: PathologyReportSchema,
},
});
if (extractRun.status !== "PROCESSED") {
throw new Error(`Extract run failed with status: ${extractRun.status}`);
}
const extracted = extractRun.output.value;
console.log("✓ Extraction complete\n");
// Display results with formatted output
console.log("=" .repeat(70));
console.log("PATHOLOGY REPORT EXTRACTION RESULTS");
console.log("=".repeat(70));
console.log("\n--- PATIENT DEMOGRAPHICS ---");
console.log(`Name: ${extracted.patient_name ?? "N/A"}`);
console.log(`ID: ${extracted.patient_id ?? "N/A"}`);
console.log(`DOB: ${extracted.date_of_birth ?? "N/A"}`);
console.log(`Gender: ${extracted.gender ?? "N/A"}`);
console.log("\n--- SPECIMEN INFO ---");
console.log(`Type: ${extracted.specimen_type ?? "N/A"}`);
console.log(`Accession: ${extracted.accession_number ?? "N/A"}`);
console.log(`Collected: ${extracted.specimen_collected_date ?? "N/A"}`);
console.log(`Received: ${extracted.specimen_received_date ?? "N/A"}`);
console.log(`Completed: ${extracted.specimen_completed_date ?? "N/A"}`);
console.log(`Bacterial Load: ${extracted.bacterial_load ?? "N/A"}`);
console.log("\n--- ORDERING PHYSICIAN ---");
console.log(`Name: ${extracted.physician_name ?? "N/A"}`);
console.log(`Phone: ${extracted.physician_phone ?? "N/A"}`);
console.log(`Fax: ${extracted.physician_fax ?? "N/A"}`);
console.log("\n--- LABORATORY ---");
console.log(`Director: ${extracted.laboratory_director ?? "N/A"}`);
console.log(`Report Version: ${extracted.ngs_report_version ?? "N/A"}`);
console.log("\n--- RESISTANCE GENES ---");
console.log(`${extracted.resistance_genes_detected ?? "None detected"}`);
console.log("\n--- BACTERIAL FINDINGS ---");
if (extracted.bacterial_findings && extracted.bacterial_findings.length > 0) {
extracted.bacterial_findings.forEach((org, idx) => {
console.log(` ${idx + 1}. ${org.organism_name ?? "Unknown"}`);
console.log(` Gram Stain: ${org.gram_stain ?? "N/A"}`);
console.log(` Respiration: ${org.respiration_type ?? "N/A"}`);
console.log(` Detection: ${org.detection_method ?? "N/A"}`);
console.log(` Load: ${org.bacterial_load_level ?? "N/A"}`);
console.log(` Abundance: ${org.relative_abundance_percent ?? "N/A"}%`);
console.log(` Susceptibility: ${org.antimicrobial_susceptibility_notes ?? "N/A"}`);
});
} else {
console.log(" None detected");
}
console.log("\n--- FUNGAL FINDINGS ---");
if (extracted.fungal_findings && extracted.fungal_findings.length > 0) {
extracted.fungal_findings.forEach((org, idx) => {
console.log(` ${idx + 1}. ${org.organism_name ?? "Unknown"}`);
console.log(` Detection: ${org.detection_method ?? "N/A"}`);
console.log(` Abundance: ${org.relative_abundance_percent ?? "N/A"}%`);
console.log(` Susceptibility: ${org.antifungal_susceptibility_notes ?? "N/A"}`);
});
} else {
console.log(" None detected");
}
console.log("\n--- ANTIMICROBIAL RECOMMENDATIONS ---");
if (extracted.antimicrobial_recommendations && extracted.antimicrobial_recommendations.length > 0) {
extracted.antimicrobial_recommendations.forEach((rec, idx) => {
console.log(` ${idx + 1}. ${rec.drug_class ?? "Unknown Class"}`);
console.log(` Examples: ${rec.example_drugs ?? "N/A"}`);
console.log(` Notes: ${rec.recommendation_notes ?? "N/A"}`);
});
} else {
console.log(" None recommended");
}
console.log("\n" + "=".repeat(70));
console.log("Full extracted JSON:");
console.log(JSON.stringify(extracted, null, 2));
return extracted;
} catch (error) {
console.error("Error processing pathology report:", error);
throw error;
}
}
// Auto-invoke for testing
const filePath = process.argv[2] || process.env.__FILE_PATH__;
if (filePath) {
processPathologyreport(filePath).catch(console.error);
}import os
from extend_ai import Extend
# Define the extraction schema as a plain dict matching the JSON schema
pathology_report_schema = {
"type": "object",
"properties": {
"gender": {
"type": ["string", "null"],
"description": "Patient gender ('Male', 'Female', or other designation)",
},
"patient_id": {
"type": ["string", "null"],
"description": "Unique patient identifier (MRN, accession, or code)",
},
"patient_name": {
"type": ["string", "null"],
"description": "Full name of the patient",
},
"date_of_birth": {
"type": ["string", "null"],
"extend:type": "date",
"description": "Patient DOB (ISO yyyy-mm-dd)",
},
"physician_fax": {
"type": ["string", "null"],
"description": "Ordering physician fax number",
},
"specimen_type": {
"type": ["string", "null"],
"description": "Specimen source (e.g., 'Wound', 'Urine', 'Blood')",
},
"bacterial_load": {
"type": ["string", "null"],
"description": "Overall bacterial DNA load (e.g., 'High', 'Low', or quantitative)",
},
"physician_name": {
"type": ["string", "null"],
"description": "Name of ordering/referring physician",
},
"physician_phone": {
"type": ["string", "null"],
"description": "Ordering physician phone number",
},
"accession_number": {
"type": ["string", "null"],
"description": "Specimen accession number for lab tracking",
},
"ngs_report_version": {
"type": ["string", "null"],
"description": "NGS protocol or report version",
},
"laboratory_director": {
"type": ["string", "null"],
"description": "Laboratory director name and credentials",
},
"specimen_received_date": {
"type": ["string", "null"],
"extend:type": "date",
"description": "Date specimen arrived at lab (ISO yyyy-mm-dd)",
},
"specimen_collected_date": {
"type": ["string", "null"],
"extend:type": "date",
"description": "Date specimen was collected from patient (ISO yyyy-mm-dd)",
},
"specimen_completed_date": {
"type": ["string", "null"],
"extend:type": "date",
"description": "Date analysis was completed (ISO yyyy-mm-dd)",
},
"resistance_genes_detected": {
"type": ["string", "null"],
"description": "Summary of antimicrobial resistance genes detected or 'None detected'",
},
"bacterial_findings": {
"type": "array",
"items": {
"type": "object",
"properties": {
"gram_stain": {
"type": ["string", "null"],
"description": "Gram stain result ('+' or 'Positive', '-' or 'Negative')",
},
"organism_name": {
"type": ["string", "null"],
"description": "Scientific organism name (e.g., 'Staphylococcus aureus')",
},
"detection_method": {
"type": ["string", "null"],
"description": "Detection method ('NGS', 'PCR', or both)",
},
"respiration_type": {
"type": ["string", "null"],
"description": "Respiration type ('Aerobic', 'Anaerobic', 'Facultative anaerobic')",
},
"bacterial_load_level": {
"type": ["string", "null"],
"description": "Qualitative load for this organism ('Low', 'Medium', 'High')",
},
"relative_abundance_percent": {
"type": ["number", "null"],
"description": "Percentage of total microbial DNA (0–100)",
},
"antimicrobial_susceptibility_notes": {
"type": ["string", "null"],
"description": "Susceptibility summary or detected resistance genes for this organism",
},
},
"additionalProperties": False,
},
"description": "List of bacterial organisms identified",
},
"fungal_findings": {
"type": "array",
"items": {
"type": "object",
"properties": {
"organism_name": {
"type": ["string", "null"],
"description": "Scientific organism name (e.g., 'Candida albicans')",
},
"detection_method": {
"type": ["string", "null"],
"description": "Detection method ('NGS', 'PCR', or both)",
},
"relative_abundance_percent": {
"type": ["number", "null"],
"description": "Percentage of total fungal DNA (0–100)",
},
"antifungal_susceptibility_notes": {
"type": ["string", "null"],
"description": "Antifungal susceptibility or resistance summary",
},
},
"additionalProperties": False,
},
"description": "List of fungal organisms identified",
},
"antimicrobial_recommendations": {
"type": "array",
"items": {
"type": "object",
"properties": {
"drug_class": {
"type": ["string", "null"],
"description": "Antimicrobial class (e.g., 'Fluoroquinolones', 'Cephalosporins', 'Carbapenems')",
},
"example_drugs": {
"type": ["string", "null"],
"description": "Example drugs in this class from the report (e.g., 'Levofloxacin, Ciprofloxacin')",
},
"recommendation_notes": {
"type": ["string", "null"],
"description": "Clinical notes on effectiveness or resistance for detected organisms",
},
},
"additionalProperties": False,
},
"description": "Antimicrobial drug classes and recommendations based on findings",
},
},
"required": [
"gender",
"patient_id",
"patient_name",
"date_of_birth",
"physician_fax",
"specimen_type",
"bacterial_load",
"physician_name",
"fungal_findings",
"physician_phone",
"accession_number",
"bacterial_findings",
"ngs_report_version",
"laboratory_director",
"specimen_received_date",
"specimen_collected_date",
"specimen_completed_date",
"resistance_genes_detected",
"antimicrobial_recommendations",
],
"additionalProperties": False,
}
def process_pathology_report(file_path: str):
"""Process a pathology report and extract structured fields."""
print(f"Processing pathology report from: {file_path}")
client = Extend(token=os.environ["EXTEND_API_KEY"])
# Upload the file once and reuse the resulting file ID for the extraction step,
# avoiding large inline base64 payloads that can cause request timeouts.
print("Uploading file...")
with open(file_path, "rb") as f:
uploaded_file = client.files.upload(file=f)
print(f"✓ Uploaded file with id: {uploaded_file.id}")
try:
# Extract structured fields using schema. The extraction step performs its
# own parsing/OCR internally, so a separate parse step is unnecessary and
# only adds latency (which can cause the run to exceed available time).
print("Extracting structured fields...")
extract_run = client.extract_runs.create_and_poll(
file={"id": uploaded_file.id},
config={
"schema": pathology_report_schema,
},
)
if extract_run.status != "PROCESSED":
raise Exception(f"Extract run failed with status: {extract_run.status}")
extracted = extract_run.output.value
print("✓ Extraction complete\n")
# Display results with formatted output
print("=" * 70)
print("PATHOLOGY REPORT EXTRACTION RESULTS")
print("=" * 70)
print("\n--- PATIENT DEMOGRAPHICS ---")
print(f"Name: {extracted.get('patient_name') or 'N/A'}")
print(f"ID: {extracted.get('patient_id') or 'N/A'}")
print(f"DOB: {extracted.get('date_of_birth') or 'N/A'}")
print(f"Gender: {extracted.get('gender') or 'N/A'}")
print("\n--- SPECIMEN INFO ---")
print(f"Type: {extracted.get('specimen_type') or 'N/A'}")
print(f"Accession: {extracted.get('accession_number') or 'N/A'}")
print(f"Collected: {extracted.get('specimen_collected_date') or 'N/A'}")
print(f"Received: {extracted.get('specimen_received_date') or 'N/A'}")
print(f"Completed: {extracted.get('specimen_completed_date') or 'N/A'}")
print(f"Bacterial Load: {extracted.get('bacterial_load') or 'N/A'}")
print("\n--- ORDERING PHYSICIAN ---")
print(f"Name: {extracted.get('physician_name') or 'N/A'}")
print(f"Phone: {extracted.get('physician_phone') or 'N/A'}")
print(f"Fax: {extracted.get('physician_fax') or 'N/A'}")
print("\n--- LABORATORY ---")
print(f"Director: {extracted.get('laboratory_director') or 'N/A'}")
print(f"Report Version: {extracted.get('ngs_report_version') or 'N/A'}")
print("\n--- RESISTANCE GENES ---")
print(f"{extracted.get('resistance_genes_detected') or 'None detected'}")
print("\n--- BACTERIAL FINDINGS ---")
bacterial_findings = extracted.get("bacterial_findings") or []
if bacterial_findings:
for idx, org in enumerate(bacterial_findings, 1):
print(f" {idx}. {org.get('organism_name') or 'Unknown'}")
print(f" Gram Stain: {org.get('gram_stain') or 'N/A'}")
print(f" Respiration: {org.get('respiration_type') or 'N/A'}")
print(f" Detection: {org.get('detection_method') or 'N/A'}")
print(f" Load: {org.get('bacterial_load_level') or 'N/A'}")
print(f" Abundance: {org.get('relative_abundance_percent') or 'N/A'}%")
print(f" Susceptibility: {org.get('antimicrobial_susceptibility_notes') or 'N/A'}")
else:
print(" None detected")
print("\n--- FUNGAL FINDINGS ---")
fungal_findings = extracted.get("fungal_findings") or []
if fungal_findings:
for idx, org in enumerate(fungal_findings, 1):
print(f" {idx}. {org.get('organism_name') or 'Unknown'}")
print(f" Detection: {org.get('detection_method') or 'N/A'}")
print(f" Abundance: {org.get('relative_abundance_percent') or 'N/A'}%")
print(f" Susceptibility: {org.get('antifungal_susceptibility_notes') or 'N/A'}")
else:
print(" None detected")
print("\n--- ANTIMICROBIAL RECOMMENDATIONS ---")
recommendations = extracted.get("antimicrobial_recommendations") or []
if recommendations:
for idx, rec in enumerate(recommendations, 1):
print(f" {idx}. {rec.get('drug_class') or 'Unknown Class'}")
print(f" Examples: {rec.get('example_drugs') or 'N/A'}")
print(f" Notes: {rec.get('recommendation_notes') or 'N/A'}")
else:
print(" None recommended")
print("\n" + "=" * 70)
print("Full extracted JSON:")
import json
print(json.dumps(extracted, indent=2))
return extracted
except Exception as error:
print(f"Error processing pathology report: {error}")
raise
if __name__ == "__main__":
import sys
file_path = sys.argv[1] if len(sys.argv) > 1 else os.environ.get("__FILE_PATH__")
if file_path:
process_pathology_report(file_path)// This code uses the Extend REST API directly because Extend has no official Java SDK yet.
// It calls https://api.extend.ai endpoints with java.net.http.HttpClient (no external dependencies).
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;
import java.util.Scanner;
public class PathologyReportProcessor {
private static final String API_BASE = "https://api.extend.ai";
private static final String API_KEY = System.getenv("EXTEND_API_KEY");
private static final HttpClient httpClient = HttpClient.newHttpClient();
// Schema JSON for pathology report extraction
private static final String SCHEMA_JSON = """
{
"type": "object",
"properties": {
"gender": {"type": ["string", "null"], "description": "Patient gender ('Male', 'Female', or other designation)"},
"patient_id": {"type": ["string", "null"], "description": "Unique patient identifier (MRN, accession, or code)"},
"patient_name": {"type": ["string", "null"], "description": "Full name of the patient"},
"date_of_birth": {"type": ["string", "null"], "extend:type": "date", "description": "Patient DOB (ISO yyyy-mm-dd)"},
"physician_fax": {"type": ["string", "null"], "description": "Ordering physician fax number"},
"specimen_type": {"type": ["string", "null"], "description": "Specimen source (e.g., 'Wound', 'Urine', 'Blood')"},
"bacterial_load": {"type": ["string", "null"], "description": "Overall bacterial DNA load (e.g., 'High', 'Low', or quantitative)"},
"physician_name": {"type": ["string", "null"], "description": "Name of ordering/referring physician"},
"physician_phone": {"type": ["string", "null"], "description": "Ordering physician phone number"},
"accession_number": {"type": ["string", "null"], "description": "Specimen accession number for lab tracking"},
"ngs_report_version": {"type": ["string", "null"], "description": "NGS protocol or report version"},
"laboratory_director": {"type": ["string", "null"], "description": "Laboratory director name and credentials"},
"specimen_received_date": {"type": ["string", "null"], "extend:type": "date", "description": "Date specimen arrived at lab (ISO yyyy-mm-dd)"},
"specimen_collected_date": {"type": ["string", "null"], "extend:type": "date", "description": "Date specimen was collected from patient (ISO yyyy-mm-dd)"},
"specimen_completed_date": {"type": ["string", "null"], "extend:type": "date", "description": "Date analysis was completed (ISO yyyy-mm-dd)"},
"resistance_genes_detected": {"type": ["string", "null"], "description": "Summary of antimicrobial resistance genes detected or 'None detected'"},
"bacterial_findings": {
"type": "array",
"items": {
"type": "object",
"properties": {
"gram_stain": {"type": ["string", "null"]},
"organism_name": {"type": ["string", "null"]},
"detection_method": {"type": ["string", "null"]},
"respiration_type": {"type": ["string", "null"]},
"bacterial_load_level": {"type": ["string", "null"]},
"relative_abundance_percent": {"type": ["number", "null"]},
"antimicrobial_susceptibility_notes": {"type": ["string", "null"]}
}
}
},
"fungal_findings": {
"type": "array",
"items": {
"type": "object",
"properties": {
"organism_name": {"type": ["string", "null"]},
"detection_method": {"type": ["string", "null"]},
"relative_abundance_percent": {"type": ["number", "null"]},
"antifungal_susceptibility_notes": {"type": ["string", "null"]}
}
}
},
"antimicrobial_recommendations": {
"type": "array",
"items": {
"type": "object",
"properties": {
"drug_class": {"type": ["string", "null"]},
"example_drugs": {"type": ["string", "null"]},
"recommendation_notes": {"type": ["string", "null"]}
}
}
}
}
}
""";
public static void main(String[] args) throws IOException, InterruptedException {
String filePath = args.length > 0 ? args[0] : System.getenv("__FILE_PATH__");
if (filePath == null) {
System.err.println("Usage: java PathologyReportProcessor <filePath>");
System.exit(1);
}
processPathologyReport(filePath);
}
public static void processPathologyReport(String filePath) throws IOException, InterruptedException {
System.out.println("Processing pathology report from: " + filePath);
// Convert local file to data URL
byte[] fileBytes = Files.readAllBytes(Paths.get(filePath));
String base64Content = Base64.getEncoder().encodeToString(fileBytes);
String dataUrl = "data:application/octet-stream;base64," + base64Content;
try {
// Step 1: Parse the report with agentic OCR and table extraction
System.out.println("Step 1: Parsing report with agentic OCR...");
String parseRequestBody = String.format("""
{
"file": {"url": "%s"},
"config": {
"blockOptions": {
"text": {
"agentic": {"enabled": true},
"signatureDetectionEnabled": true
},
"tables": {
"agentic": {"enabled": true},
"tableHeaderContinuationEnabled": true
},
"figures": {"enabled": true}
},
"chunkingStrategy": {
"type": "page",
"options": {}
}
}
}
""", dataUrl.replace("\"", "\\\""));
String parseRunId = createAndPollParseRun(parseRequestBody);
System.out.println("✓ Parse run completed with ID: " + parseRunId);
// Step 2: Extract structured fields using schema
System.out.println("Step 2: Extracting structured fields...");
String extractRequestBody = String.format("""
{
"file": {"url": "%s"},
"config": {
"schema": %s
}
}
""", dataUrl.replace("\"", "\\\""), SCHEMA_JSON);
String extractedJson = createAndPollExtractRun(extractRequestBody);
System.out.println("✓ Extraction complete\n");
// Display results
displayResults(extractedJson);
} catch (Exception e) {
System.err.println("Error processing pathology report: " + e.getMessage());
e.printStackTrace();
throw e;
}
}
private static String createAndPollParseRun(String requestBody) throws IOException, InterruptedException {
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(API_BASE + "/v1/parseRuns/createAndPoll"))
.header("Authorization", "Bearer " + API_KEY)
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(requestBody))
.build();
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() != 200) {
throw new RuntimeException("Parse run failed with status: " + response.statusCode() + " - " + response.body());
}
return response.body();
}
private static String createAndPollExtractRun(String requestBody) throws IOException, InterruptedException {
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(API_BASE + "/v1/extractRuns/createAndPoll"))
.header("Authorization", "Bearer " + API_KEY)
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(requestBody))
.build();
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() != 200) {
throw new RuntimeException("Extract run failed with status: " + response.statusCode() + " - " + response.body());
}
return response.body();
}
private static void displayResults(String jsonResponse) {
System.out.println("=".repeat(70));
System.out.println("PATHOLOGY REPORT EXTRACTION RESULTS");
System.out.println("=".repeat(70));
// Parse JSON manually (no external JSON library)
String patientName = extractJsonField(jsonResponse, "patient_name");
String patientId = extractJsonField(jsonResponse, "patient_id");
String dateOfBirth = extractJsonField(jsonResponse, "date_of_birth");
String gender = extractJsonField(jsonResponse, "gender");
String specimenType = extractJsonField(jsonResponse, "specimen_type");
String accessionNumber = extractJsonField(jsonResponse, "accession_number");
String specimenCollectedDate = extractJsonField(jsonResponse, "specimen_collected_date");
String specimenReceivedDate = extractJsonField(jsonResponse, "specimen_received_date");
String specimenCompletedDate = extractJsonField(jsonResponse, "specimen_completed_date");
String bacterialLoad = extractJsonField(jsonResponse, "bacterial_load");
String physicianName = extractJsonField(jsonResponse, "physician_name");
String physicianPhone = extractJsonField(jsonResponse, "physician_phone");
String physicianFax = extractJsonField(jsonResponse, "physician_fax");
String laboratoryDirector = extractJsonField(jsonResponse, "laboratory_director");
String ngsReportVersion = extractJsonField(jsonResponse, "ngs_report_version");
String resistanceGenesDetected = extractJsonField(jsonResponse, "resistance_genes_detected");
System.out.println("\n--- PATIENT DEMOGRAPHICS ---");
System.out.println("Name: " + (patientName != null ? patientName : "N/A"));
System.out.println("ID: " + (patientId != null ? patientId : "N/A"));
System.out.println("DOB: " + (dateOfBirth != null ? dateOfBirth : "N/A"));
System.out.println("Gender: " + (gender != null ? gender : "N/A"));
System.out.println("\n--- SPECIMEN INFO ---");
System.out.println("Type: " + (specimenType != null ? specimenType : "N/A"));
System.out.println("Accession: " + (accessionNumber != null ? accessionNumber : "N/A"));
System.out.println("Collected: " + (specimenCollectedDate != null ? specimenCollectedDate : "N/A"));
System.out.println("Received: " + (specimenReceivedDate != null ? specimenReceivedDate : "N/A"));
System.out.println("Completed: " + (specimenCompletedDate != null ? specimenCompletedDate : "N/A"));
System.out.println("Bacterial Load: " + (bacterialLoad != null ? bacterialLoad : "N/A"));
System.out.println("\n--- ORDERING PHYSICIAN ---");
System.out.println("Name: " + (physicianName != null ? physicianName : "N/A"));
System.out.println("Phone: " + (physicianPhone != null ? physicianPhone : "N/A"));
System.out.println("Fax: " + (physicianFax != null ? physicianFax : "N/A"));
System.out.println("\n--- LABORATORY ---");
System.out.println("Director: " + (laboratoryDirector != null ? laboratoryDirector : "N/A"));
System.out.println("Report Version: " + (ngsReportVersion != null ? ngsReportVersion : "N/A"));
System.out.println("\n--- RESISTANCE GENES ---");
System.out.println(resistanceGenesDetected != null ? resistanceGenesDetected : "None detected");
System.out.println("\n--- BACTERIAL FINDINGS ---");
System.out.println(" (See full JSON below for detailed array contents)");
System.out.println("\n--- FUNGAL FINDINGS ---");
System.out.println(" (See full JSON below for detailed array contents)");
System.out.println("\n--- ANTIMICROBIAL RECOMMENDATIONS ---");
System.out.println(" (See full JSON below for detailed array contents)");
System.out.println("\n" + "=".repeat(70));
System.out.println("Full extracted JSON:");
System.out.println(jsonResponse);
}
private static String extractJsonField(String json, String fieldName) {
String searchKey = "\"" + fieldName + "\":";
int startIdx = json.indexOf(searchKey);
if (startIdx == -1) {
return null;
}
startIdx += searchKey.length();
while (startIdx < json.length() && Character.isWhitespace(json.charAt(startIdx))) {
startIdx++;
}
if (startIdx >= json.length()) {
return null;
}
if (json.charAt(startIdx) == '"') {
startIdx++;
int endIdx = startIdx;
while (endIdx < json.length() && json.charAt(endIdx) != '"') {
if (json.charAt(endIdx) == '\\') {
endIdx += 2;
} else {
endIdx++;
}
}
return json.substring(startIdx, endIdx);
} else if (json.charAt(startIdx) == 'n' && json.substring(startIdx, Math.min(startIdx + 4, json.length())).equals("null")) {
return null;
}
return null;
}
}// This code uses the Extend REST API directly because Extend has no official Go SDK yet.
package main
import (
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"strings"
)
// PathologyReportSchema represents the extraction schema for pathology reports
type PathologyReportSchema struct {
Gender *string `json:"gender"`
PatientID *string `json:"patient_id"`
PatientName *string `json:"patient_name"`
DateOfBirth *string `json:"date_of_birth"`
PhysicianFax *string `json:"physician_fax"`
SpecimenType *string `json:"specimen_type"`
BacterialLoad *string `json:"bacterial_load"`
PhysicianName *string `json:"physician_name"`
PhysicianPhone *string `json:"physician_phone"`
AccessionNumber *string `json:"accession_number"`
NGSReportVersion *string `json:"ngs_report_version"`
LaboratoryDirector *string `json:"laboratory_director"`
SpecimenReceivedDate *string `json:"specimen_received_date"`
SpecimenCollectedDate *string `json:"specimen_collected_date"`
SpecimenCompletedDate *string `json:"specimen_completed_date"`
ResistanceGenesDetected *string `json:"resistance_genes_detected"`
BacterialFindings []BacterialFinding `json:"bacterial_findings"`
FungalFindings []FungalFinding `json:"fungal_findings"`
AntimicrobialRecommendations []AntimicrobialRecommendation `json:"antimicrobial_recommendations"`
}
type BacterialFinding struct {
GramStain *string `json:"gram_stain"`
OrganismName *string `json:"organism_name"`
DetectionMethod *string `json:"detection_method"`
RespirationTyp *string `json:"respiration_type"`
BacterialLoadLevel *string `json:"bacterial_load_level"`
RelativeAbundancePercent *float64 `json:"relative_abundance_percent"`
AntimicrobialSusceptibilityNotes *string `json:"antimicrobial_susceptibility_notes"`
}
type FungalFinding struct {
OrganismName *string `json:"organism_name"`
DetectionMethod *string `json:"detection_method"`
RelativeAbundancePercent *float64 `json:"relative_abundance_percent"`
AntifungalSusceptibilityNotes *string `json:"antifungal_susceptibility_notes"`
}
type AntimicrobialRecommendation struct {
DrugClass *string `json:"drug_class"`
ExampleDrugs *string `json:"example_drugs"`
RecommendationNotes *string `json:"recommendation_notes"`
}
// ExtendClient wraps the REST API calls
type ExtendClient struct {
token string
}
// NewExtendClient creates a new client with the given API token
func NewExtendClient(token string) *ExtendClient {
return &ExtendClient{token: token}
}
// ParseRunOutput represents the output from a parse run
type ParseRunOutput struct {
Chunks []struct {
Content string `json:"content"`
} `json:"chunks"`
}
// ParseRun represents a parse run response
type ParseRun struct {
Status string `json:"status"`
Output ParseRunOutput `json:"output"`
}
// ExtractRunOutput represents the output from an extract run
type ExtractRunOutput struct {
Value PathologyReportSchema `json:"value"`
}
// ExtractRun represents an extract run response
type ExtractRun struct {
Status string `json:"status"`
Output ExtractRunOutput `json:"output"`
}
// createAndPollParseRun creates and polls a parse run
func (c *ExtendClient) createAndPollParseRun(dataURL string) (*ParseRun, error) {
reqBody := map[string]interface{}{
"file": map[string]string{"url": dataURL},
"config": map[string]interface{}{
"blockOptions": map[string]interface{}{
"text": map[string]interface{}{
"agentic": map[string]bool{"enabled": true},
"signatureDetectionEnabled": true,
},
"tables": map[string]interface{}{
"agentic": map[string]bool{"enabled": true},
"tableHeaderContinuationEnabled": true,
},
"figures": map[string]bool{"enabled": true},
},
"chunkingStrategy": map[string]interface{}{
"type": "page",
"options": map[string]interface{}{},
},
},
}
body, err := json.Marshal(reqBody)
if err != nil {
return nil, err
}
req, err := http.NewRequest("POST", "https://api.extend.ai/v1/parse-runs", bytes.NewReader(body))
if err != nil {
return nil, err
}
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", c.token))
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
var parseRun ParseRun
if err := json.Unmarshal(respBody, &parseRun); err != nil {
return nil, err
}
return &parseRun, nil
}
// createAndPollExtractRun creates and polls an extract run
func (c *ExtendClient) createAndPollExtractRun(dataURL string) (*ExtractRun, error) {
schema := map[string]interface{}{
"type": "object",
"properties": map[string]interface{}{
"gender": map[string]interface{}{"type": []string{"string", "null"}},
"patient_id": map[string]interface{}{"type": []string{"string", "null"}},
"patient_name": map[string]interface{}{"type": []string{"string", "null"}},
"date_of_birth": map[string]interface{}{"type": []string{"string", "null"}, "extend:type": "date"},
"physician_fax": map[string]interface{}{"type": []string{"string", "null"}},
"specimen_type": map[string]interface{}{"type": []string{"string", "null"}},
"bacterial_load": map[string]interface{}{"type": []string{"string", "null"}},
"physician_name": map[string]interface{}{"type": []string{"string", "null"}},
"physician_phone": map[string]interface{}{"type": []string{"string", "null"}},
"accession_number": map[string]interface{}{"type": []string{"string", "null"}},
"ngs_report_version": map[string]interface{}{"type": []string{"string", "null"}},
"laboratory_director": map[string]interface{}{"type": []string{"string", "null"}},
"specimen_received_date": map[string]interface{}{"type": []string{"string", "null"}, "extend:type": "date"},
"specimen_collected_date": map[string]interface{}{"type": []string{"string", "null"}, "extend:type": "date"},
"specimen_completed_date": map[string]interface{}{"type": []string{"string", "null"}, "extend:type": "date"},
"resistance_genes_detected": map[string]interface{}{"type": []string{"string", "null"}},
"bacterial_findings": map[string]interface{}{"type": "array"},
"fungal_findings": map[string]interface{}{"type": "array"},
"antimicrobial_recommendations": map[string]interface{}{"type": "array"},
},
}
reqBody := map[string]interface{}{
"file": map[string]string{"url": dataURL},
"config": map[string]interface{}{"schema": schema},
}
body, err := json.Marshal(reqBody)
if err != nil {
return nil, err
}
req, err := http.NewRequest("POST", "https://api.extend.ai/v1/extract-runs", bytes.NewReader(body))
if err != nil {
return nil, err
}
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", c.token))
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
var extractRun ExtractRun
if err := json.Unmarshal(respBody, &extractRun); err != nil {
return nil, err
}
return &extractRun, nil
}
// ProcessPathologyReport processes a pathology report from a file
func ProcessPathologyReport(filePath string) (*PathologyReportSchema, error) {
fmt.Printf("Processing pathology report from: %s\n", filePath)
// Read file and convert to data URL
fileBuffer, err := os.ReadFile(filePath)
if err != nil {
return nil, err
}
dataURL := fmt.Sprintf("data:application/octet-stream;base64,%s", base64.StdEncoding.EncodeToString(fileBuffer))
apiKey := os.Getenv("EXTEND_API_KEY")
if apiKey == "" {
return nil, fmt.Errorf("EXTEND_API_KEY environment variable not set")
}
client := NewExtendClient(apiKey)
// Step 1: Parse the report with agentic OCR and table extraction
fmt.Println("Step 1: Parsing report with agentic OCR...")
parseRun, err := client.createAndPollParseRun(dataURL)
if err != nil {
return nil, err
}
if parseRun.Status != "PROCESSED" {
return nil, fmt.Errorf("parse run failed with status: %s", parseRun.Status)
}
fmt.Printf("✓ Parsed %d chunks\n", len(parseRun.Output.Chunks))
var markdownParts []string
for _, chunk := range parseRun.Output.Chunks {
markdownParts = append(markdownParts, chunk.Content)
}
markdown := strings.Join(markdownParts, "\n\n")
if len(markdown) > 500 {
fmt.Printf("Markdown preview (first 500 chars):\n%s\n\n", markdown[:500])
} else {
fmt.Printf("Markdown preview:\n%s\n\n", markdown)
}
// Step 2: Extract structured fields
fmt.Println("Step 2: Extracting structured fields (with review agent)...")
extractRun, err := client.createAndPollExtractRun(dataURL)
if err != nil {
return nil, err
}
if extractRun.Status != "PROCESSED" {
return nil, fmt.Errorf("extract run failed with status: %s", extractRun.Status)
}
extracted := &extractRun.Output.Value
fmt.Println("✓ Extraction complete\n")
// Display results
fmt.Println(strings.Repeat("=", 70))
fmt.Println("PATHOLOGY REPORT EXTRACTION RESULTS")
fmt.Println(strings.Repeat("=", 70))
fmt.Println("\n--- PATIENT DEMOGRAPHICS ---")
fmt.Printf("Name: %s\n", orNA(extracted.PatientName))
fmt.Printf("ID: %s\n", orNA(extracted.PatientID))
fmt.Printf("DOB: %s\n", orNA(extracted.DateOfBirth))
fmt.Printf("Gender: %s\n", orNA(extracted.Gender))
fmt.Println("\n--- SPECIMEN INFO ---")
fmt.Printf("Type: %s\n", orNA(extracted.SpecimenType))
fmt.Printf("Accession: %s\n", orNA(extracted.AccessionNumber))
fmt.Printf("Collected: %s\n", orNA(extracted.SpecimenCollectedDate))
fmt.Printf("Received: %s\n", orNA(extracted.SpecimenReceivedDate))
fmt.Printf("Completed: %s\n", orNA(extracted.SpecimenCompletedDate))
fmt.Printf("Bacterial Load: %s\n", orNA(extracted.BacterialLoad))
fmt.Println("\n--- ORDERING PHYSICIAN ---")
fmt.Printf("Name: %s\n", orNA(extracted.PhysicianName))
fmt.Printf("Phone: %s\n", orNA(extracted.PhysicianPhone))
fmt.Printf("Fax: %s\n", orNA(extracted.PhysicianFax))
fmt.Println("\n--- LABORATORY ---")
fmt.Printf("Director: %s\n", orNA(extracted.LaboratoryDirector))
fmt.Printf("Report Version: %s\n", orNA(extracted.NGSReportVersion))
fmt.Println("\n--- RESISTANCE GENES ---")
if extracted.ResistanceGenesDetected != nil {
fmt.Println(*extracted.ResistanceGenesDetected)
} else {
fmt.Println("None detected")
}
fmt.Println("\n--- BACTERIAL FINDINGS ---")
if len(extracted.BacterialFindings) > 0 {
for idx, org := range extracted.BacterialFindings {
fmt.Printf(" %d. %s\n", idx+1, orNA(org.OrganismName))
fmt.Printf(" Gram Stain: %s\n", orNA(org.GramStain))
fmt.Printf(" Respiration: %s\n", orNA(org.RespirationTyp))
fmt.Printf(" Detection: %s\n", orNA(org.DetectionMethod))
fmt.Printf(" Load: %s\n", orNA(org.BacterialLoadLevel))
if org.RelativeAbundancePercent != nil {
fmt.Printf(" Abundance: %.0f%%\n", *org.RelativeAbundancePercent)
} else {
fmt.Println(" Abundance: N/A")
}
fmt.Printf(" Susceptibility: %s\n", orNA(org.AntimicrobialSusceptibilityNotes))
}
} else {
fmt.Println(" None detected")
}
fmt.Println("\n--- FUNGAL FINDINGS ---")
if len(extracted.FungalFindings) > 0 {
for idx, org := range extracted.FungalFindings {
fmt.Printf(" %d. %s\n", idx+1, orNA(org.OrganismName))
fmt.Printf(" Detection: %s\n", orNA(org.DetectionMethod))
if org.RelativeAbundancePercent != nil {
fmt.Printf(" Abundance: %.0f%%\n", *org.RelativeAbundancePercent)
} else {
fmt.Println(" Abundance: N/A")
}
fmt.Printf(" Susceptibility: %s\n", orNA(org.AntifungalSusceptibilityNotes))
}
} else {
fmt.Println(" None detected")
}
fmt.Println("\n--- ANTIMICROBIAL RECOMMENDATIONS ---")
if len(extracted.AntimicrobialRecommendations) > 0 {
for idx, rec := range extracted.AntimicrobialRecommendations {
fmt.Printf(" %d. %s\n", idx+1, orNA(rec.DrugClass))
fmt.Printf(" Examples: %s\n", orNA(rec.ExampleDrugs))
fmt.Printf(" Notes: %s\n", orNA(rec.RecommendationNotes))
}
} else {
fmt.Println(" None recommended")
}
fmt.Println("\n" + strings.Repeat("=", 70))
fmt.Println("Full extracted JSON:")
jsonBytes, _ := json.MarshalIndent(extracted, "", " ")
fmt.Println(string(jsonBytes))
return extracted, nil
}
// orNA returns the string value or "N/A" if nil
func orNA(s *string) string {
if s == nil {
return "N/A"
}
return *s
}
func main() {
filePath := ""
if len(os.Args) > 1 {
filePath = os.Args[1]
} else {
filePath = os.Getenv("__FILE_PATH__")
}
if filePath == "" {
fmt.Println("Usage: go run main.go <file_path>")
os.Exit(1)
}
_, err := ProcessPathologyReport(filePath)
if err != nil {
fmt.Fprintf(os.Stderr, "Error processing pathology report: %v\n", err)
os.Exit(1)
}
}// Deploy the "Pathology report" 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/next-generation-sequencing-ngs-report-extractor.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: next-generation-sequencing-ngs-report-extractor).
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, "next-generation-sequencing-ngs-report-extractor.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": "Pathology report Processing Pipeline",
"steps": [
{
"name": "startTrigger1",
"type": "TRIGGER",
"next": [
{
"step": "parse1"
}
]
},
{
"name": "parse1",
"type": "PARSE",
"config": {
"parseConfig": {
"blockOptions": {
"text": {
"agentic": {
"enabled": true
},
"signatureDetectionEnabled": true
},
"tables": {
"agentic": {
"enabled": true
},
"tableHeaderContinuationEnabled": true
},
"figures": {
"enabled": true
}
},
"chunkingStrategy": {
"type": "page",
"options": {}
}
}
},
"next": [
{
"step": "extraction2"
}
]
},
{
"name": "extraction2",
"type": "EXTRACT",
"config": {
"extractorConfig": {
"schema": {
"type": "object",
"required": [
"gender",
"patient_id",
"patient_name",
"date_of_birth",
"physician_fax",
"specimen_type",
"bacterial_load",
"physician_name",
"fungal_findings",
"physician_phone",
"accession_number",
"bacterial_findings",
"ngs_report_version",
"laboratory_director",
"specimen_received_date",
"specimen_collected_date",
"specimen_completed_date",
"resistance_genes_detected",
"antimicrobial_recommendations"
],
"properties": {
"gender": {
"type": [
"string",
"null"
],
"description": "The gender or sex of the patient. May be indicated as 'Male', 'Female', or other designations. Typically found near patient demographic information."
},
"patient_id": {
"type": [
"string",
"null"
],
"description": "A unique identifier assigned to the patient in the context of this report. This may be a medical record number, accession number, or other patient-specific code. Commonly labeled as 'Patient ID' or similar."
},
"patient_name": {
"type": [
"string",
"null"
],
"description": "The full name of the patient for whom the next-generation sequencing (NGS) report was generated. This is the individual whose specimen was analyzed. May appear under various labels such as 'Patient', 'Patient Name', or similar."
},
"date_of_birth": {
"type": [
"string",
"null"
],
"description": "The patient's date of birth. Used for identification and clinical context. May be labeled as 'DOB' or 'Date of Birth'.",
"extend:type": "date"
},
"physician_fax": {
"type": [
"string",
"null"
],
"description": "The fax number for the ordering or referring physician. May be labeled as 'Fax', 'Physician Fax', or similar."
},
"specimen_type": {
"type": [
"string",
"null"
],
"description": "The type or source of the specimen submitted for NGS analysis, such as 'Wound', 'Urine', 'Blood', etc. Indicates the biological material tested."
},
"bacterial_load": {
"type": [
"string",
"null"
],
"description": "A qualitative or quantitative assessment of the total bacterial DNA present in the specimen. May be described as 'Low', 'Medium', 'High', or with specific values or ranges."
},
"physician_name": {
"type": [
"string",
"null"
],
"description": "The name of the ordering or referring physician associated with this NGS report. May be labeled as 'Physician', 'Doctor', or similar."
},
"fungal_findings": {
"type": "array",
"items": {
"type": "object",
"required": [
"organism_name",
"detection_method",
"relative_abundance_percent",
"antifungal_susceptibility_notes"
],
"properties": {
"organism_name": {
"type": [
"string",
"null"
],
"description": "The scientific name of the fungal organism detected (e.g., 'Candida albicans')."
},
"detection_method": {
"type": [
"string",
"null"
],
"description": "The method by which the organism was detected, such as 'NGS', 'PCR', or both."
},
"relative_abundance_percent": {
"type": [
"number",
"null"
],
"description": "The estimated percentage of this organism's DNA relative to the total microbial DNA in the specimen, as determined by NGS."
},
"antifungal_susceptibility_notes": {
"type": [
"string",
"null"
],
"description": "Any notes or summary regarding the organism's susceptibility or resistance to antifungal agents, including detected resistance genes or effective drug classes."
}
},
"additionalProperties": false
},
"description": "A list of fungal organisms identified in the specimen by NGS and/or PCR, including their relative abundance and relevant laboratory findings. Each entry represents a distinct fungal organism detected."
},
"physician_phone": {
"type": [
"string",
"null"
],
"description": "The phone number for the ordering or referring physician. May be labeled as 'Phone', 'Physician Phone', or similar."
},
"accession_number": {
"type": [
"string",
"null"
],
"description": "A unique identifier assigned to the specimen for laboratory tracking and reference. Often labeled as 'Accession', 'Accession Number', or similar."
},
"bacterial_findings": {
"type": "array",
"items": {
"type": "object",
"required": [
"gram_stain",
"organism_name",
"detection_method",
"respiration_type",
"bacterial_load_level",
"relative_abundance_percent",
"antimicrobial_susceptibility_notes"
],
"properties": {
"gram_stain": {
"type": [
"string",
"null"
],
"description": "The Gram stain result for the organism, such as 'Positive', 'Negative', or other designations. May be abbreviated as '+', '-', or similar."
},
"organism_name": {
"type": [
"string",
"null"
],
"description": "The scientific name of the bacterial organism detected (e.g., 'Staphylococcus aureus', 'Escherichia coli')."
},
"detection_method": {
"type": [
"string",
"null"
],
"description": "The method by which the organism was detected, such as 'NGS', 'PCR', or both. May also indicate if only one method was used."
},
"respiration_type": {
"type": [
"string",
"null"
],
"description": "The respiration classification of the organism, such as 'Aerobic', 'Anaerobic', 'Facultative anaerobic', or similar. May be abbreviated as 'Ae', 'An', 'FAn', etc."
},
"bacterial_load_level": {
"type": [
"string",
"null"
],
"description": "A qualitative assessment of the organism's load, such as 'Low', 'Medium', 'High', or specific ranges. May be based on DNA copies or other metrics."
},
"relative_abundance_percent": {
"type": [
"number",
"null"
],
"description": "The estimated percentage of this organism's DNA relative to the total microbial DNA in the specimen, as determined by NGS."
},
"antimicrobial_susceptibility_notes": {
"type": [
"string",
"null"
],
"description": "Any notes or summary regarding the organism's susceptibility or resistance to antimicrobials, including detected resistance genes or effective drug classes."
}
},
"additionalProperties": false
},
"description": "A list of bacterial organisms identified in the specimen by NGS and/or PCR, including their relative abundance and relevant laboratory findings. Each entry represents a distinct organism detected."
},
"ngs_report_version": {
"type": [
"string",
"null"
],
"description": "The version or identifier of the NGS report or testing protocol used. May appear as a version number or code, often at the bottom or in the footer."
},
"laboratory_director": {
"type": [
"string",
"null"
],
"description": "The name and credentials of the laboratory director or responsible scientist who authorized the report. Typically found near the signature or at the end of the document."
},
"specimen_received_date": {
"type": [
"string",
"null"
],
"description": "The date the laboratory received the specimen for processing. May be labeled as 'Received', 'Date Received', or similar.",
"extend:type": "date"
},
"specimen_collected_date": {
"type": [
"string",
"null"
],
"description": "The date on which the specimen was collected from the patient. May be labeled as 'Collected', 'Collection Date', or similar.",
"extend:type": "date"
},
"specimen_completed_date": {
"type": [
"string",
"null"
],
"description": "The date the laboratory completed the analysis of the specimen. May be labeled as 'Completed', 'Date Completed', or similar.",
"extend:type": "date"
},
"resistance_genes_detected": {
"type": [
"string",
"null"
],
"description": "A summary of any antimicrobial resistance genes detected in the specimen. May list specific resistance types or drugs, such as 'Bactrim', or indicate none detected."
},
"antimicrobial_recommendations": {
"type": "array",
"items": {
"type": "object",
"required": [
"drug_class",
"example_drugs",
"recommendation_notes"
],
"properties": {
"drug_class": {
"type": [
"string",
"null"
],
"description": "The class of antimicrobial agent (e.g., 'Fluoroquinolones', 'Cephalosporins', 'Carbapenems')."
},
"example_drugs": {
"type": [
"string",
"null"
],
"description": "Examples of drugs within this class, as listed in the report (e.g., 'Levofloxacin', 'Keflex')."
},
"recommendation_notes": {
"type": [
"string",
"null"
],
"description": "Any notes or comments regarding the use, effectiveness, or resistance related to this drug class for the organisms detected."
}
},
"additionalProperties": false
},
"description": "A list of antimicrobial agents or drug classes recommended or considered based on the NGS findings. Each entry may include the drug class, example drugs, and any relevant notes about their use or effectiveness."
}
},
"additionalProperties": false
},
"baseProcessor": "extraction_performance",
"advancedOptions": {
"reviewAgent": {
"enabled": true
},
"advancedMultimodalEnabled": true
}
}
}
}
]
};
async function main() {
console.log(`Deploying "${WORKFLOW.name}"…`);
if (state.workflowId) {
console.log(`✓ workflow already provisioned (${state.workflowId}) — updating steps`);
await api("POST", `/workflows/${state.workflowId}`, { steps: WORKFLOW.steps });
} else {
// Reuse an existing workflow with the same name if one exists (e.g. a
// previous run's state file was lost) instead of creating a duplicate.
try {
const list = await api("GET", `/workflows?name=${encodeURIComponent(WORKFLOW.name)}`);
const items = (list.data ?? list.items ?? []) as Array<{ name?: string; id?: string }>;
const existing = items.find((x) => x.name === WORKFLOW.name);
if (existing?.id) {
state.workflowId = existing.id; saveState();
console.log(`✓ workflow "${WORKFLOW.name}" found in your account (${existing.id}) — updating steps`);
await api("POST", `/workflows/${existing.id}`, { steps: WORKFLOW.steps });
}
} catch { /* lookup is best-effort; fall through to create */ }
if (!state.workflowId) {
const created = await api("POST", "/workflows", WORKFLOW);
const wfId = created.id ?? created.workflow?.id;
if (!wfId) throw new Error("Could not read created workflow id from response");
state.workflowId = wfId; saveState();
console.log(`+ created workflow (${wfId})`);
}
}
// Deploy the current draft as a new version so the workflow is runnable —
// best-effort: some accounts/plans may not require this explicit step.
await api("POST", `/workflows/${state.workflowId}/versions`, {}).catch(() => {});
console.log("\nDone. Run documents through it with:");
console.log(` POST ${API}/workflow_runs { workflow: { id: "${state.workflowId}" }, file: { url: "https://…" } }`);
console.log("Or open the workflow in the Extend dashboard to review and deploy it.");
}
main().catch((e) => { console.error(e.message ?? e); process.exit(1); });
import os
import json
import sys
from pathlib import Path
from extend_ai import Extend
API_KEY = os.environ.get("EXTEND_API_KEY")
if not API_KEY:
print("Set EXTEND_API_KEY first.", file=sys.stderr)
sys.exit(1)
STATE_DIR = Path.cwd() / ".extend"
STATE_FILE = STATE_DIR / "next-generation-sequencing-ngs-report-extractor.json"
def load_state() -> dict:
if STATE_FILE.exists():
return json.loads(STATE_FILE.read_text())
return {}
def save_state(state: dict) -> None:
STATE_DIR.mkdir(parents=True, exist_ok=True)
STATE_FILE.write_text(json.dumps(state, indent=2))
WORKFLOW = {
"name": "Pathology report Processing Pipeline",
"steps": [
{
"name": "startTrigger1",
"type": "TRIGGER",
"next": [
{
"step": "parse1"
}
]
},
{
"name": "parse1",
"type": "PARSE",
"config": {
"parseConfig": {
"blockOptions": {
"text": {
"agentic": {
"enabled": True
},
"signatureDetectionEnabled": True
},
"tables": {
"agentic": {
"enabled": True
},
"tableHeaderContinuationEnabled": True
},
"figures": {
"enabled": True
}
},
"chunkingStrategy": {
"type": "page",
"options": {}
}
}
},
"next": [
{
"step": "extraction2"
}
]
},
{
"name": "extraction2",
"type": "EXTRACT",
"config": {
"extractorConfig": {
"schema": {
"type": "object",
"properties": {
"gender": {
"type": [
"string",
"null"
],
"description": "The gender or sex of the patient. May be indicated as 'Male', 'Female', or other designations. Typically found near patient demographic information."
},
"patient_id": {
"type": [
"string",
"null"
],
"description": "A unique identifier assigned to the patient in the context of this report. This may be a medical record number, accession number, or other patient-specific code. Commonly labeled as 'Patient ID' or similar."
},
"patient_name": {
"type": [
"string",
"null"
],
"description": "The full name of the patient for whom the next-generation sequencing (NGS) report was generated. This is the individual whose specimen was analyzed. May appear under various labels such as 'Patient', 'Patient Name', or similar."
},
"date_of_birth": {
"type": [
"string",
"null"
],
"extend:type": "date",
"description": "The patient's date of birth. Used for identification and clinical context. May be labeled as 'DOB' or 'Date of Birth'."
},
"physician_fax": {
"type": [
"string",
"null"
],
"description": "The fax number for the ordering or referring physician. May be labeled as 'Fax', 'Physician Fax', or similar."
},
"specimen_type": {
"type": [
"string",
"null"
],
"description": "The type or source of the specimen submitted for NGS analysis, such as 'Wound', 'Urine', 'Blood', etc. Indicates the biological material tested."
},
"bacterial_load": {
"type": [
"string",
"null"
],
"description": "A qualitative or quantitative assessment of the total bacterial DNA present in the specimen. May be described as 'Low', 'Medium', 'High', or with specific values or ranges."
},
"physician_name": {
"type": [
"string",
"null"
],
"description": "The name of the ordering or referring physician associated with this NGS report. May be labeled as 'Physician', 'Doctor', or similar."
},
"fungal_findings": {
"type": "array",
"items": {
"type": "object",
"properties": {
"organism_name": {
"type": [
"string",
"null"
],
"description": "The scientific name of the fungal organism detected (e.g., 'Candida albicans')."
},
"detection_method": {
"type": [
"string",
"null"
],
"description": "The method by which the organism was detected, such as 'NGS', 'PCR', or both."
},
"relative_abundance_percent": {
"type": [
"number",
"null"
],
"description": "The estimated percentage of this organism's DNA relative to the total microbial DNA in the specimen, as determined by NGS."
},
"antifungal_susceptibility_notes": {
"type": [
"string",
"null"
],
"description": "Any notes or summary regarding the organism's susceptibility or resistance to antifungal agents, including detected resistance genes or effective drug classes."
}
},
"additionalProperties": False,
"required": [
"organism_name",
"detection_method",
"relative_abundance_percent",
"antifungal_susceptibility_notes"
]
},
"description": "A list of fungal organisms identified in the specimen by NGS and/or PCR, including their relative abundance and relevant laboratory findings. Each entry represents a distinct fungal organism detected."
},
"physician_phone": {
"type": [
"string",
"null"
],
"description": "The phone number for the ordering or referring physician. May be labeled as 'Phone', 'Physician Phone', or similar."
},
"accession_number": {
"type": [
"string",
"null"
],
"description": "A unique identifier assigned to the specimen for laboratory tracking and reference. Often labeled as 'Accession', 'Accession Number', or similar."
},
"bacterial_findings": {
"type": "array",
"items": {
"type": "object",
"properties": {
"gram_stain": {
"type": [
"string",
"null"
],
"description": "The Gram stain result for the organism, such as 'Positive', 'Negative', or other designations. May be abbreviated as '+', '-', or similar."
},
"organism_name": {
"type": [
"string",
"null"
],
"description": "The scientific name of the bacterial organism detected (e.g., 'Staphylococcus aureus', 'Escherichia coli')."
},
"detection_method": {
"type": [
"string",
"null"
],
"description": "The method by which the organism was detected, such as 'NGS', 'PCR', or both. May also indicate if only one method was used."
},
"respiration_type": {
"type": [
"string",
"null"
],
"description": "The respiration classification of the organism, such as 'Aerobic', 'Anaerobic', 'Facultative anaerobic', or similar. May be abbreviated as 'Ae', 'An', 'FAn', etc."
},
"bacterial_load_level": {
"type": [
"string",
"null"
],
"description": "A qualitative assessment of the organism's load, such as 'Low', 'Medium', 'High', or specific ranges. May be based on DNA copies or other metrics."
},
"relative_abundance_percent": {
"type": [
"number",
"null"
],
"description": "The estimated percentage of this organism's DNA relative to the total microbial DNA in the specimen, as determined by NGS."
},
"antimicrobial_susceptibility_notes": {
"type": [
"string",
"null"
],
"description": "Any notes or summary regarding the organism's susceptibility or resistance to antimicrobials, including detected resistance genes or effective drug classes."
}
},
"additionalProperties": False,
"required": [
"gram_stain",
"organism_name",
"detection_method",
"respiration_type",
"bacterial_load_level",
"relative_abundance_percent",
"antimicrobial_susceptibility_notes"
]
},
"description": "A list of bacterial organisms identified in the specimen by NGS and/or PCR, including their relative abundance and relevant laboratory findings. Each entry represents a distinct organism detected."
},
"ngs_report_version": {
"type": [
"string",
"null"
],
"description": "The version or identifier of the NGS report or testing protocol used. May appear as a version number or code, often at the bottom or in the footer."
},
"laboratory_director": {
"type": [
"string",
"null"
],
"description": "The name and credentials of the laboratory director or responsible scientist who authorized the report. Typically found near the signature or at the end of the document."
},
"specimen_received_date": {
"type": [
"string",
"null"
],
"extend:type": "date",
"description": "The date the laboratory received the specimen for processing. May be labeled as 'Received', 'Date Received', or similar."
},
"specimen_collected_date": {
"type": [
"string",
"null"
],
"extend:type": "date",
"description": "The date on which the specimen was collected from the patient. May be labeled as 'Collected', 'Collection Date', or similar."
},
"specimen_completed_date": {
"type": [
"string",
"null"
],
"extend:type": "date",
"description": "The date the laboratory completed the analysis of the specimen. May be labeled as 'Completed', 'Date Completed', or similar."
},
"resistance_genes_detected": {
"type": [
"string",
"null"
],
"description": "A summary of any antimicrobial resistance genes detected in the specimen. May list specific resistance types or drugs, such as 'Bactrim', or indicate none detected."
},
"antimicrobial_recommendations": {
"type": "array",
"items": {
"type": "object",
"properties": {
"drug_class": {
"type": [
"string",
"null"
],
"description": "The class of antimicrobial agent (e.g., 'Fluoroquinolones', 'Cephalosporins', 'Carbapenems')."
},
"example_drugs": {
"type": [
"string",
"null"
],
"description": "Examples of drugs within this class, as listed in the report (e.g., 'Levofloxacin', 'Keflex')."
},
"recommendation_notes": {
"type": [
"string",
"null"
],
"description": "Any notes or comments regarding the use, effectiveness, or resistance related to this drug class for the organisms detected."
}
},
"additionalProperties": False,
"required": [
"drug_class",
"example_drugs",
"recommendation_notes"
]
},
"description": "A list of antimicrobial agents or drug classes recommended or considered based on the NGS findings. Each entry may include the drug class, example drugs, and any relevant notes about their use or effectiveness."
}
},
"required": [
"gender",
"patient_id",
"patient_name",
"date_of_birth",
"physician_fax",
"specimen_type",
"bacterial_load",
"physician_name",
"fungal_findings",
"physician_phone",
"accession_number",
"bacterial_findings",
"ngs_report_version",
"laboratory_director",
"specimen_received_date",
"specimen_collected_date",
"specimen_completed_date",
"resistance_genes_detected",
"antimicrobial_recommendations"
],
"additionalProperties": False
},
"baseProcessor": "extraction_performance",
"advancedOptions": {
"reviewAgent": {
"enabled": True
},
"advancedMultimodalEnabled": True
}
}
}
}
]
}
def main() -> None:
client = Extend(token=API_KEY)
state = load_state()
print(f'Deploying "{WORKFLOW["name"]}…"')
if state.get("workflowId"):
print(f'✓ workflow already provisioned ({state["workflowId"]}) — updating steps')
client.workflows.update(id=state["workflowId"], steps=WORKFLOW["steps"])
else:
try:
workflows_list = client.workflows.list(name=WORKFLOW["name"])
items = workflows_list.data if hasattr(workflows_list, "data") else (workflows_list.items if hasattr(workflows_list, "items") else [])
existing = next((x for x in items if getattr(x, "name", None) == WORKFLOW["name"]), None)
if existing and getattr(existing, "id", None):
state["workflowId"] = existing.id
save_state(state)
print(f'✓ workflow "{WORKFLOW["name"]}" found in your account ({existing.id}) — updating steps')
client.workflows.update(id=existing.id, steps=WORKFLOW["steps"])
except Exception:
pass
if not state.get("workflowId"):
created = client.workflows.create(**WORKFLOW)
wf_id = getattr(created, "id", None) or (getattr(created.workflow, "id", None) if hasattr(created, "workflow") else None)
if not wf_id:
raise ValueError("Could not read created workflow id from response")
state["workflowId"] = wf_id
save_state(state)
print(f"+ created workflow ({wf_id})")
try:
client.workflows.create_version(id=state["workflowId"])
except Exception:
pass
print("\nDone. Run documents through it with:")
print(f' POST https://api.extend.ai/workflow_runs {{ "workflow": {{ "id": "{state["workflowId"]}" }}, "file": {{ "url": "https://…" }} }}')
print("Or open the workflow in the Extend dashboard to review and deploy it.")
if __name__ == "__main__":
try:
main()
except Exception as e:
print(str(e), file=sys.stderr)
sys.exit(1)import java.io.IOException;
import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
// This script uses Extend's REST API directly because Extend has no official Java SDK yet.
// It deploys the "Pathology report" pipeline to your Extend account.
//
// Usage:
// export EXTEND_API_KEY=sk_... (from https://dashboard.extend.ai → API Keys)
// javac Provision.java && java Provision
public class Provision {
private static final String API = "https://api.extend.ai";
private static final String VERSION = "2026-02-09";
private static final String API_KEY = System.getenv("EXTEND_API_KEY");
private static final Path STATE_DIR = Paths.get(System.getProperty("user.dir"), ".extend");
private static final Path STATE_FILE = STATE_DIR.resolve("next-generation-sequencing-ngs-report-extractor.json");
private static final HttpClient HTTP_CLIENT = HttpClient.newHttpClient();
static class State {
String workflowId;
}
private static State state = new State();
public static void main(String[] args) throws Exception {
if (API_KEY == null || API_KEY.isEmpty()) {
System.err.println("Set EXTEND_API_KEY first.");
System.exit(1);
}
loadState();
Map<String, Object> workflow = buildWorkflow();
try {
System.out.println("Deploying \"" + (String) workflow.get("name") + "\"…");
if (state.workflowId != null && !state.workflowId.isEmpty()) {
System.out.println("✓ workflow already provisioned (" + state.workflowId + ") — updating steps");
Map<String, Object> updateBody = new HashMap<>();
updateBody.put("steps", workflow.get("steps"));
api("POST", "/workflows/" + state.workflowId, updateBody);
} else {
try {
String encodedName = URLEncoder.encode((String) workflow.get("name"), StandardCharsets.UTF_8);
Map<String, Object> list = api("GET", "/workflows?name=" + encodedName, null);
List<Map<String, Object>> items = (List<Map<String, Object>>) list.getOrDefault("data",
list.getOrDefault("items", List.of()));
String workflowName = (String) workflow.get("name");
for (Map<String, Object> item : items) {
if (workflowName.equals(item.get("name"))) {
String existingId = (String) item.get("id");
if (existingId != null) {
state.workflowId = existingId;
saveState();
System.out.println("✓ workflow \"" + workflowName + "\" found in your account (" + existingId
+ ") — updating steps");
Map<String, Object> updateBody = new HashMap<>();
updateBody.put("steps", workflow.get("steps"));
api("POST", "/workflows/" + existingId, updateBody);
break;
}
}
}
} catch (Exception e) {
// lookup is best-effort; fall through to create
}
if (state.workflowId == null || state.workflowId.isEmpty()) {
Map<String, Object> created = api("POST", "/workflows", workflow);
String wfId = (String) created.get("id");
if (wfId == null) {
Map<String, Object> workflowObj = (Map<String, Object>) created.get("workflow");
if (workflowObj != null) {
wfId = (String) workflowObj.get("id");
}
}
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 HashMap<>());
} catch (Exception e) {
// best-effort: some accounts/plans may not require this explicit step
}
System.out.println("\nDone. Run documents through it with:");
System.out.println(" POST " + API + "/workflow_runs { workflow: { id: \"" + state.workflowId
+ "\" }, file: { url: \"https://…\" } }");
System.out.println("Or open the workflow in the Extend dashboard to review and deploy it.");
} catch (Exception e) {
System.err.println(e.getMessage() != null ? e.getMessage() : e.toString());
System.exit(1);
}
}
private static void loadState() throws IOException {
if (Files.exists(STATE_FILE)) {
String content = Files.readString(STATE_FILE);
Map<String, Object> parsed = parseJson(content);
state.workflowId = (String) parsed.get("workflowId");
}
}
private static void saveState() throws IOException {
Files.createDirectories(STATE_DIR);
Map<String, Object> stateMap = new HashMap<>();
if (state.workflowId != null) {
stateMap.put("workflowId", state.workflowId);
}
String json = toJson(stateMap);
Files.writeString(STATE_FILE, json);
}
private static Map<String, Object> api(String method, String pathName, Map<String, Object> body)
throws IOException, InterruptedException {
String url = API + pathName;
HttpRequest.Builder requestBuilder = HttpRequest.newBuilder().uri(URI.create(url))
.header("Authorization", "Bearer " + API_KEY).header("x-extend-api-version", VERSION);
if (body != null) {
String jsonBody = toJson(body);
requestBuilder.method(method, HttpRequest.BodyPublishers.ofString(jsonBody))
.header("Content-Type", "application/json");
} else {
requestBuilder.method(method, HttpRequest.BodyPublishers.noBody());
}
HttpRequest request = requestBuilder.build();
HttpResponse<String> response = HTTP_CLIENT.send(request, HttpResponse.BodyHandlers.ofString());
Map<String, Object> data = new HashMap<>();
try {
data = parseJson(response.body());
} catch (Exception e) {
// ignore parse errors
}
if (response.statusCode() < 200 || response.statusCode() >= 300) {
String errorMsg = toJson(data);
if (errorMsg.length() > 300) {
errorMsg = errorMsg.substring(0, 300);
}
throw new RuntimeException(
method + " " + pathName + " failed (" + response.statusCode() + "): " + errorMsg);
}
return data;
}
private static Map<String, Object> buildWorkflow() {
Map<String, Object> workflow = new LinkedHashMap<>();
workflow.put("name", "Pathology report Processing Pipeline");
List<Map<String, Object>> steps = List.of(
buildStartTrigger(),
buildParseStep(),
buildExtractionStep());
workflow.put("steps", steps);
return workflow;
}
private static Map<String, Object> buildStartTrigger() {
Map<String, Object> step = new LinkedHashMap<>();
step.put("name", "startTrigger1");
step.put("type", "TRIGGER");
step.put("next", List.of(Map.of("step", "parse1")));
return step;
}
private static Map<String, Object> buildParseStep() {
Map<String, Object> step = new LinkedHashMap<>();
step.put("name", "parse1");
step.put("type", "PARSE");
Map<String, Object> config = new LinkedHashMap<>();
Map<String, Object> parseConfig = new LinkedHashMap<>();
Map<String, Object> blockOptions = new LinkedHashMap<>();
Map<String, Object> textBlock = new LinkedHashMap<>();
textBlock.put("agentic", Map.of("enabled", true));
textBlock.put("signatureDetectionEnabled", true);
blockOptions.put("text", textBlock);
Map<String, Object> tablesBlock = new LinkedHashMap<>();
tablesBlock.put("agentic", Map.of("enabled", true));
tablesBlock.put("tableHeaderContinuationEnabled", true);
blockOptions.put("tables", tablesBlock);
blockOptions.put("figures", Map.of("enabled", true));
parseConfig.put("blockOptions", blockOptions);
Map<String, Object> chunkingStrategy = new LinkedHashMap<>();
chunkingStrategy.put("type", "page");
chunkingStrategy.put("options", new HashMap<>());
parseConfig.put("chunkingStrategy", chunkingStrategy);
config.put("parseConfig", parseConfig);
step.put("config", config);
step.put("next", List.of(Map.of("step", "extraction2")));
return step;
}
private static Map<String, Object> buildExtractionStep() {
Map<String, Object> step = new LinkedHashMap<>();
step.put("name", "extraction2");
step.put("type", "EXTRACT");
Map<String, Object> config = new LinkedHashMap<>();
Map<String, Object> extractorConfig = new LinkedHashMap<>();
extractorConfig.put("schema", buildSchema());
extractorConfig.put("baseProcessor", "extraction_performance");
Map<String, Object> advancedOptions = new LinkedHashMap<>();
advancedOptions.put("reviewAgent", Map.of("enabled", true));
advancedOptions.put("advancedMultimodalEnabled", true);
extractorConfig.put("advancedOptions", advancedOptions);
config.put("extractorConfig", extractorConfig);
step.put("config", config);
return step;
}
private static Map<String, Object> buildSchema() {
Map<String, Object> schema = new LinkedHashMap<>();
schema.put("type", "object");
Map<String, Object> properties = new LinkedHashMap<>();
properties.put("gender", Map.of("type", List.of("string", "null"), "description",
"The gender or sex of the patient. May be indicated as 'Male', 'Female', or other designations. Typically found near patient demographic information."));
properties.put("patient_id", Map.of("type", List.of("string", "null"), "description",
"A unique identifier assigned to the patient in the context of this report. This may be a medical record number, accession number, or other patient-specific code. Commonly labeled as 'Patient ID' or similar."));
properties.put("patient_name", Map.of("type", List.of("string", "null"), "description",
"The full name of the patient for whom the next-generation sequencing (NGS) report was generated. This is the individual whose specimen was analyzed. May appear under various labels such as 'Patient', 'Patient Name', or similar."));
properties.put("date_of_birth", Map.of("type", List.of("string", "null"), "extend:type", "date",
"description",
"The patient's date of birth. Used for identification and clinical context. May be labeled as 'DOB' or 'Date of Birth'."));
properties.put("physician_fax", Map.of("type", List.of("string", "null"), "description",
"The fax number for the ordering or referring physician. May be labeled as 'Fax', 'Physician Fax', or similar."));
properties.put("specimen_type", Map.of("type", List.of("string", "null"), "description",
"The type or source of the specimen submitted for NGS analysis, such as 'Wound', 'Urine', 'Blood', etc. Indicates the biological material tested."));
properties.put("bacterial_load", Map.of("type", List.of("string", "null"), "description",
"A qualitative or quantitative assessment of the total bacterial DNA present in the specimen. May be described as 'Low', 'Medium', 'High', or with specific values or ranges."));
properties.put("physician_name", Map.of("type", List.of("string", "null"), "description",
"The name of the ordering or referring physician associated with this NGS report. May be labeled as 'Physician', 'Doctor', or similar."));
properties.put("fungal_findings", buildFungalFindingsSchema());
properties.put("physician_phone", Map.of("type", List.of("string", "null"), "description",
"The phone number for the ordering or referring physician. May be labeled as 'Phone', 'Physician Phone', or similar."));
properties.put("accession_number", Map.of("type", List.of("string", "null"), "description",
"A unique identifier assigned to the specimen for laboratory tracking and reference. Often labeled as 'Accession', 'Accession Number', or similar."));
properties.put("bacterial_findings", buildBacterialFindingsSchema());
properties.put("ngs_report_version", Map.of("type", List.of("string", "null"), "description",
"The version or identifier of the NGS report or testing protocol used. May appear as a version number or code, often at the bottom or in the footer."));
properties.put("laboratory_director", Map.of("type", List.of("string", "null"), "description",
"The name and credentials of the laboratory director or responsible scientist who authorized the report. Typically found near the signature or at the end of the document."));
properties.put("specimen_received_date", Map.of("type", List.of("string", "null"), "extend:type", "date",
"description", "The date the laboratory received the specimen for processing. May be labeled as 'Received', 'Date Received', or similar."));
properties.put("specimen_collected_date", Map.of("type", List.of("string", "null"), "extend:type", "date",
"description", "The date on which the specimen was collected from the patient. May be labeled as 'Collected', 'Collection Date', or similar."));
properties.put("specimen_completed_date", Map.of("type", List.of("string", "null"), "extend:type", "date",
"description", "The date the laboratory completed the analysis of the specimen. May be labeled as 'Completed', 'Date Completed', or similar."));
properties.put("resistance_genes_detected", Map.of("type", List.of("string", "null"), "description",
"A summary of any antimicrobial resistance genes detected in the specimen. May list specific resistance types or drugs, such as 'Bactrim', or indicate none detected."));
properties.put("antimicrobial_recommendations", buildAntimicrobialRecommendationsSchema());
schema.put("properties", properties);
List<String> required = List.of("gender", "patient_id", "patient_name", "date_of_birth", "physician_fax",
"specimen_type", "bacterial_load", "physician_name", "fungal_findings", "physician_phone",
"accession_number", "bacterial_findings", "ngs_report_version", "laboratory_director",
"specimen_received_date", "specimen_collected_date", "specimen_completed_date",
"resistance_genes_detected", "antimicrobial_recommendations");
schema.put("required", required);
schema.put("additionalProperties", false);
return schema;
}
private static Map<String, Object> buildFungalFindingsSchema() {
Map<String, Object> fungalFindings = new LinkedHashMap<>();
fungalFindings.put("type", "array");
Map<String, Object> itemsSchema = new LinkedHashMap<>();
itemsSchema.put("type", "object");
Map<String, Object> itemProperties = new LinkedHashMap<>();
itemProperties.put("organism_name", Map.of("type", List.of("string", "null"), "description",
"The scientific name of the fungal organism detected (e.g., 'Candida albicans')."));
itemProperties.put("detection_method", Map.of("type", List.of("string", "null"), "description",
"The method by which the organism was detected, such as 'NGS', 'PCR', or both."));
itemProperties.put("relative_abundance_percent", Map.of("type", List.of("number", "null"), "description",
"The estimated percentage of this organism's DNA relative to the total microbial DNA in the specimen, as determined by NGS."));
itemProperties.put("antifungal_susceptibility_notes", Map.of("type", List.of("string", "null"),
"description",
"Any notes or summary regarding the organism's susceptibility or resistance to antifungal agents, including detected resistance genes or effective drug classes."));
itemsSchema.put("properties", itemProperties);
itemsSchema.put("additionalProperties", false);
itemsSchema.put("required",
List.of("organism_name", "detection_method", "relative_abundance_percent",
"antifungal_susceptibility_notes"));
fungalFindings.put("items", itemsSchema);
fungalFindings.put("description",
"A list of fungal organisms identified in the specimen by NGS and/or PCR, including their relative abundance and relevant laboratory findings. Each entry represents a distinct fungal organism detected.");
return fungalFindings;
}
private static Map<String, Object> buildBacterialFindingsSchema() {
Map<String, Object> bacterialFindings = new LinkedHashMap<>();
bacterialFindings.put("type", "array");
Map<String, Object> itemsSchema = new LinkedHashMap<>();
itemsSchema.put("type", "object");
Map<String, Object> itemProperties = new LinkedHashMap<>();
itemProperties.put("gram_stain", Map.of("type", List.of("string", "null"), "description",
"The Gram stain result for the organism, such as 'Positive', 'Negative', or other designations. May be abbreviated as '+', '-', or similar."));
itemProperties.put("organism_name", Map.of("type", List.of("string", "null"), "description",
"The scientific name of the bacterial organism detected (e.g., 'Staphylococcus aureus', 'Escherichia coli')."));
itemProperties.put("detection_method", Map.of("type", List.of("string", "null"), "description",
"The method by which the organism was detected, such as 'NGS', 'PCR', or both. May also indicate if only one method was used."));
itemProperties.put("respiration_type", Map.of("type", List.of("string", "null"), "description",
"The respiration classification of the organism, such as 'Aerobic', 'Anaerobic', 'Facultative anaerobic', or similar. May be abbreviated as 'Ae', 'An', 'FAn', etc."));
itemProperties.put("bacterial_load_level", Map.of("type", List.of("string", "null"), "description",
"A qualitative assessment of the organism's load, such as 'Low', 'Medium', 'High', or specific ranges. May be based on DNA copies or other metrics."));
itemProperties.put("relative_abundance_percent", Map.of("type", List.of("number", "null"), "description",
"The estimated percentage of this organism's DNA relative to the total microbial DNA in the specimen, as determined by NGS."));
itemProperties.put("antimicrobial_susceptibility_notes", Map.of("type", List.of("string", "null"),
"description",
"Any notes or summary regarding the organism's susceptibility or resistance to antimicrobials, including detected resistance genes or effective drug classes."));
itemsSchema.put("properties", itemProperties);
itemsSchema.put("additionalProperties", false);
itemsSchema.put("required", List.of("gram_stain", "organism_name", "detection_method", "respiration_type",
"bacterial_load_level", "relative_abundance_percent", "antimicrobial_susceptibility_notes"));
bacterialFindings.put("items", itemsSchema);
bacterialFindings.put("description",
"A list of bacterial organisms identified in the specimen by NGS and/or PCR, including their relative abundance and relevant laboratory findings. Each entry represents a distinct organism detected.");
return bacterialFindings;
}
private static Map<String, Object> buildAntimicrobialRecommendationsSchema() {
Map<String, Object> recommendations = new LinkedHashMap<>();
recommendations.put("type", "array");
Map<String, Object> itemsSchema = new LinkedHashMap<>();
itemsSchema.put("type", "object");
Map<String, Object> itemProperties = new LinkedHashMap<>();
itemProperties.put("drug_class", Map.of("type", List.of("string", "null"), "description",
"The class of antimicrobial agent (e.g., 'Fluoroquinolones', 'Cephalosporins', 'Carbapenems')."));
itemProperties.put("example_drugs", Map.of("type", List.of("string", "null"), "description",
"Examples of drugs within this class, as listed in the report (e.g., 'Levofloxacin', 'Keflex')."));
itemProperties.put("recommendation_notes", Map.of("type", List.of("string", "null"), "description",
"Any notes or comments regarding the use, effectiveness, or resistance related to this drug class for the organisms detected."));
itemsSchema.put("properties", itemProperties);
itemsSchema.put("additionalProperties", false);
itemsSchema.put("required", List.of("drug_class", "example_drugs", "recommendation_notes"));
recommendations.put("items", itemsSchema);
recommendations.put("description",
"A list of antimicrobial agents or drug classes recommended or considered based on the NGS findings. Each entry may include the drug class, example drugs, and any relevant notes about their use or effectiveness.");
return recommendations;
}
private static String toJson(Map<String, Object> map) {
StringBuilder sb = new StringBuilder();
sb.append("{");
boolean first = true;
for (Map.Entry<String, Object> entry : map.entrySet()) {
if (!first)
sb.append(",");
first = false;
sb.append("\"").append(escapeJson(entry.getKey())).append("\":");
sb.append(valueToJson(entry.getValue()));
}
sb.append("}");
return sb.toString();
}
private static String valueToJson(Object value) {
if (value == null) {
return "null";
} else if (value instanceof String) {
return "\"" + escapeJson((String) value) + "\"";
} else if (value instanceof Boolean) {
return value.toString();
} else if (value instanceof Number) {
return value.toString();
} else if (value instanceof List) {
StringBuilder sb = new StringBuilder("[");
List<?> list = (List<?>) value;
for (int i = 0; i < list.size(); i++) {
if (i > 0)
sb.append(",");
sb.append(valueToJson(list.get(i)));
}
sb.append("]");
return sb.toString();
} else if (value instanceof Map) {
return toJson((Map<String, Object>) value);
}
return "null";
}
private static String escapeJson(String s) {
return s.replace("\\", "\\\\").replace("\"", "\\\"").replace("\n", "\\n").replace("\r", "\\r")
.replace("\t", "\\t");
}
private static Map<String, Object> parseJson(String json) {
json = json.trim();
if (!json.startsWith("{")) {
return new HashMap<>();
}
Map<String, Object> result = new HashMap<>();
json = json.substring(1, json.length() - 1);
int depth = 0;
StringBuilder currentKey = new StringBuilder();
StringBuilder currentValue = new StringBuilder();
boolean inString = false;
boolean parsingKey = true;
for (int i = 0; i < json.length(); i++) {
char c = json.charAt(i);
if (c == '"' && (i == 0 || json.charAt(i - 1) != '\\')) {
inString = !inString;
}
if (!inString) {
if (c == ':' && parsingKey && depth == 0) {
parsingKey = false;
continue;
} else if (c == ',' && depth == 0) {
String key = currentKey.toString().trim().replaceAll("^\"|\"$", "");
String value = currentValue.toString().trim();
result.put(key, parseValue(value));
currentKey = new StringBuilder();
currentValue = new StringBuilder();
parsingKey = true;
continue;
} else if ((c == '{' || c == '[') && !parsingKey) {
depth++;
} else if ((c == '}' || c == ']') && !parsingKey) {
depth--;
}
}
if (parsingKey) {
currentKey.append(c);
} else {
currentValue.append(c);
}
}
if (currentKey.length() > 0) {
String key = currentKey.toString().trim().replaceAll("^\"|\"$", "");
String value = currentValue.toString().trim();
result.put(key, parseValue(value));
}
return result;
}
private static Object parseValue(String value) {
value = value.trim();
if (value.equals("null")) {
return null;
} else if (value.equals("true")) {
return true;
} else if (value.equals("false")) {
return false;
} else if (value.startsWith("\"") && value.endsWith("\"")) {
return value.substring(1, value.length() - 1);
} else if (value.startsWith("[") && value.endsWith("]")) {
return parseJsonArray(value);
} else if (value.startsWith("{") && value.endsWith("}")) {
return parseJson(value);
} else {
try {
if (value.contains(".")) {
return Double.parseDouble(value);
} else {
return Long.parseLong(value);
}
} catch (NumberFormatException e) {
return value;
}
}
}
private static List<Object> parseJsonArray(String json) {
List<Object> result = new java.util.ArrayList<>();
json = json.substring(1, json.length() - 1).trim();
if (json.isEmpty()) {
return result;
}
int depth = 0;
StringBuilder current = new StringBuilder();
boolean inString = false;
for (int i = 0; i < json.length(); i++) {
char c = json.charAt(i);
if (c == '"' && (i == 0 || json.charAt(i - 1) != '\\')) {
inString = !inString;
}
if (!inString) {
if ((c == '{' || c == '[')) {
depth++;
} else if ((c == '}' || c == ']')) {
depth--;
} else if (c == ',' && depth == 0) {
result.add(parseValue(current.toString()));
current = new StringBuilder();
continue;
}
}
current.append(c);
}
if (current.length() > 0) {
result.add(parseValue(current.toString()));
}
return result;
}
}// This code uses the Extend REST API directly because Extend has no official Go SDK yet.
// It deploys the "Pathology report" pipeline to your Extend account.
//
// Usage:
// export EXTEND_API_KEY=sk_... (from https://dashboard.extend.ai → API Keys)
// go run provision.go
//
// Generated by doc1 (template: next-generation-sequencing-ngs-report-extractor).
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"os"
"path/filepath"
)
const (
API = "https://api.extend.ai"
VERSION = "2026-02-09"
)
var (
apiKey string
stateDir string
stateFile string
)
type State struct {
WorkflowID string `json:"workflowId,omitempty"`
}
var state State
func init() {
apiKey = os.Getenv("EXTEND_API_KEY")
if apiKey == "" {
fmt.Fprintf(os.Stderr, "Set EXTEND_API_KEY first.\n")
os.Exit(1)
}
cwd, err := os.Getwd()
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to get working directory: %v\n", err)
os.Exit(1)
}
stateDir = filepath.Join(cwd, ".extend")
stateFile = filepath.Join(stateDir, "next-generation-sequencing-ngs-report-extractor.json")
// Load existing state if it exists
if data, err := os.ReadFile(stateFile); err == nil {
json.Unmarshal(data, &state)
}
}
func saveState() error {
if err := os.MkdirAll(stateDir, 0755); err != nil {
return err
}
data, err := json.MarshalIndent(state, "", " ")
if err != nil {
return err
}
return os.WriteFile(stateFile, data, 0644)
}
func apiCall(method, pathName string, body interface{}) (map[string]interface{}, error) {
url := API + pathName
var reqBody io.Reader
if body != nil {
data, err := json.Marshal(body)
if err != nil {
return nil, err
}
reqBody = bytes.NewReader(data)
}
req, err := http.NewRequest(method, url, reqBody)
if err != nil {
return nil, err
}
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": "Pathology report 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,
},
"signatureDetectionEnabled": true,
},
"tables": map[string]interface{}{
"agentic": map[string]interface{}{
"enabled": true,
},
"tableHeaderContinuationEnabled": true,
},
"figures": map[string]interface{}{
"enabled": true,
},
},
"chunkingStrategy": map[string]interface{}{
"type": "page",
"options": map[string]interface{}{},
},
},
},
"next": []map[string]interface{}{
{"step": "extraction2"},
},
},
{
"name": "extraction2",
"type": "EXTRACT",
"config": map[string]interface{}{
"extractorConfig": map[string]interface{}{
"schema": map[string]interface{}{
"type": "object",
"properties": map[string]interface{}{
"gender": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The gender or sex of the patient. May be indicated as 'Male', 'Female', or other designations. Typically found near patient demographic information.",
},
"patient_id": map[string]interface{}{
"type": []string{"string", "null"},
"description": "A unique identifier assigned to the patient in the context of this report. This may be a medical record number, accession number, or other patient-specific code. Commonly labeled as 'Patient ID' or similar.",
},
"patient_name": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The full name of the patient for whom the next-generation sequencing (NGS) report was generated. This is the individual whose specimen was analyzed. May appear under various labels such as 'Patient', 'Patient Name', or similar.",
},
"date_of_birth": map[string]interface{}{
"type": []string{"string", "null"},
"extend:type": "date",
"description": "The patient's date of birth. Used for identification and clinical context. May be labeled as 'DOB' or 'Date of Birth'.",
},
"physician_fax": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The fax number for the ordering or referring physician. May be labeled as 'Fax', 'Physician Fax', or similar.",
},
"specimen_type": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The type or source of the specimen submitted for NGS analysis, such as 'Wound', 'Urine', 'Blood', etc. Indicates the biological material tested.",
},
"bacterial_load": map[string]interface{}{
"type": []string{"string", "null"},
"description": "A qualitative or quantitative assessment of the total bacterial DNA present in the specimen. May be described as 'Low', 'Medium', 'High', or with specific values or ranges.",
},
"physician_name": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The name of the ordering or referring physician associated with this NGS report. May be labeled as 'Physician', 'Doctor', or similar.",
},
"fungal_findings": map[string]interface{}{
"type": "array",
"items": map[string]interface{}{
"type": "object",
"properties": map[string]interface{}{
"organism_name": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The scientific name of the fungal organism detected (e.g., 'Candida albicans').",
},
"detection_method": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The method by which the organism was detected, such as 'NGS', 'PCR', or both.",
},
"relative_abundance_percent": map[string]interface{}{
"type": []interface{}{"number", "null"},
"description": "The estimated percentage of this organism's DNA relative to the total microbial DNA in the specimen, as determined by NGS.",
},
"antifungal_susceptibility_notes": map[string]interface{}{
"type": []string{"string", "null"},
"description": "Any notes or summary regarding the organism's susceptibility or resistance to antifungal agents, including detected resistance genes or effective drug classes.",
},
},
"additionalProperties": false,
"required": []string{
"organism_name",
"detection_method",
"relative_abundance_percent",
"antifungal_susceptibility_notes",
},
},
"description": "A list of fungal organisms identified in the specimen by NGS and/or PCR, including their relative abundance and relevant laboratory findings. Each entry represents a distinct fungal organism detected.",
},
"physician_phone": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The phone number for the ordering or referring physician. May be labeled as 'Phone', 'Physician Phone', or similar.",
},
"accession_number": map[string]interface{}{
"type": []string{"string", "null"},
"description": "A unique identifier assigned to the specimen for laboratory tracking and reference. Often labeled as 'Accession', 'Accession Number', or similar.",
},
"bacterial_findings": map[string]interface{}{
"type": "array",
"items": map[string]interface{}{
"type": "object",
"properties": map[string]interface{}{
"gram_stain": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The Gram stain result for the organism, such as 'Positive', 'Negative', or other designations. May be abbreviated as '+', '-', or similar.",
},
"organism_name": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The scientific name of the bacterial organism detected (e.g., 'Staphylococcus aureus', 'Escherichia coli').",
},
"detection_method": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The method by which the organism was detected, such as 'NGS', 'PCR', or both. May also indicate if only one method was used.",
},
"respiration_type": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The respiration classification of the organism, such as 'Aerobic', 'Anaerobic', 'Facultative anaerobic', or similar. May be abbreviated as 'Ae', 'An', 'FAn', etc.",
},
"bacterial_load_level": map[string]interface{}{
"type": []string{"string", "null"},
"description": "A qualitative assessment of the organism's load, such as 'Low', 'Medium', 'High', or specific ranges. May be based on DNA copies or other metrics.",
},
"relative_abundance_percent": map[string]interface{}{
"type": []interface{}{"number", "null"},
"description": "The estimated percentage of this organism's DNA relative to the total microbial DNA in the specimen, as determined by NGS.",
},
"antimicrobial_susceptibility_notes": map[string]interface{}{
"type": []string{"string", "null"},
"description": "Any notes or summary regarding the organism's susceptibility or resistance to antimicrobials, including detected resistance genes or effective drug classes.",
},
},
"additionalProperties": false,
"required": []string{
"gram_stain",
"organism_name",
"detection_method",
"respiration_type",
"bacterial_load_level",
"relative_abundance_percent",
"antimicrobial_susceptibility_notes",
},
},
"description": "A list of bacterial organisms identified in the specimen by NGS and/or PCR, including their relative abundance and relevant laboratory findings. Each entry represents a distinct organism detected.",
},
"ngs_report_version": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The version or identifier of the NGS report or testing protocol used. May appear as a version number or code, often at the bottom or in the footer.",
},
"laboratory_director": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The name and credentials of the laboratory director or responsible scientist who authorized the report. Typically found near the signature or at the end of the document.",
},
"specimen_received_date": map[string]interface{}{
"type": []string{"string", "null"},
"extend:type": "date",
"description": "The date the laboratory received the specimen for processing. May be labeled as 'Received', 'Date Received', or similar.",
},
"specimen_collected_date": map[string]interface{}{
"type": []string{"string", "null"},
"extend:type": "date",
"description": "The date on which the specimen was collected from the patient. May be labeled as 'Collected', 'Collection Date', or similar.",
},
"specimen_completed_date": map[string]interface{}{
"type": []string{"string", "null"},
"extend:type": "date",
"description": "The date the laboratory completed the analysis of the specimen. May be labeled as 'Completed', 'Date Completed', or similar.",
},
"resistance_genes_detected": map[string]interface{}{
"type": []string{"string", "null"},
"description": "A summary of any antimicrobial resistance genes detected in the specimen. May list specific resistance types or drugs, such as 'Bactrim', or indicate none detected.",
},
"antimicrobial_recommendations": map[string]interface{}{
"type": "array",
"items": map[string]interface{}{
"type": "object",
"properties": map[string]interface{}{
"drug_class": map[string]interface{}{
"type": []string{"string", "null"},
"description": "The class of antimicrobial agent (e.g., 'Fluoroquinolones', 'Cephalosporins', 'Carbapenems').",
},
"example_drugs": map[string]interface{}{
"type": []string{"string", "null"},
"description": "Examples of drugs within this class, as listed in the report (e.g., 'Levofloxacin', 'Keflex').",
},
"recommendation_notes": map[string]interface{}{
"type": []string{"string", "null"},
"description": "Any notes or comments regarding the use, effectiveness, or resistance related to this drug class for the organisms detected.",
},
},
"additionalProperties": false,
"required": []string{
"drug_class",
"example_drugs",
"recommendation_notes",
},
},
"description": "A list of antimicrobial agents or drug classes recommended or considered based on the NGS findings. Each entry may include the drug class, example drugs, and any relevant notes about their use or effectiveness.",
},
},
"required": []string{
"gender",
"patient_id",
"patient_name",
"date_of_birth",
"physician_fax",
"specimen_type",
"bacterial_load",
"physician_name",
"fungal_findings",
"physician_phone",
"accession_number",
"bacterial_findings",
"ngs_report_version",
"laboratory_director",
"specimen_received_date",
"specimen_collected_date",
"specimen_completed_date",
"resistance_genes_detected",
"antimicrobial_recommendations",
},
"additionalProperties": false,
},
"baseProcessor": "extraction_performance",
"advancedOptions": map[string]interface{}{
"reviewAgent": map[string]interface{}{
"enabled": true,
},
"advancedMultimodalEnabled": true,
},
},
},
},
},
}
func main() {
workflowName := workflow["name"].(string)
fmt.Printf("Deploying \"%s\"…\n", workflowName)
if state.WorkflowID != "" {
fmt.Printf("✓ workflow already provisioned (%s) — updating steps\n", state.WorkflowID)
_, err := apiCall("POST", fmt.Sprintf("/workflows/%s", state.WorkflowID), map[string]interface{}{
"steps": workflow["steps"],
})
if err != nil {
fmt.Fprintf(os.Stderr, "%v\n", err)
os.Exit(1)
}
} else {
// Try to find an existing workflow with the same name
query := url.QueryEscape(workflowName)
list, err := apiCall("GET", fmt.Sprintf("/workflows?name=%s", query), nil)
if err == nil {
var items []map[string]interface{}
if data, ok := list["data"].([]interface{}); ok {
for _, item := range data {
if m, ok := item.(map[string]interface{}); ok {
items = append(items, m)
}
}
} else if data, ok := list["items"].([]interface{}); ok {
for _, item := range data {
if m, ok := item.(map[string]interface{}); ok {
items = append(items, m)
}
}
}
for _, item := range items {
if name, ok := item["name"].(string); ok && name == workflowName {
if id, ok := item["id"].(string); ok {
state.WorkflowID = id
saveState()
fmt.Printf("✓ workflow \"%s\" found in your account (%s) — updating steps\n", workflowName, id)
_, err := apiCall("POST", fmt.Sprintf("/workflows/%s", id), map[string]interface{}{
"steps": workflow["steps"],
})
if err != nil {
fmt.Fprintf(os.Stderr, "%v\n", err)
os.Exit(1)
}
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)
}
}
// Deploy the current draft as a new version (best-effort)
apiCall("POST", fmt.Sprintf("/workflows/%s/versions", state.WorkflowID), map[string]interface{}{})
fmt.Println("\nDone. Run documents through it with:")
fmt.Printf(" POST %s/workflow_runs { workflow: { id: \"%s\" }, file: { url: \"https://…\" } }\n", API, state.WorkflowID)
fmt.Println("Or open the workflow in the Extend dashboard to review and deploy it.")
}A Next-Generation Sequencing (NGS) pathology report details DNA sequencing and qPCR results for microbial identification. The template captures patient demographics, specimen details, detected resistance genes, and comprehensive antimicrobial susceptibility recommendations organized by drug class.