Guides

Getting Started: Mode 2 (Submit + Poll)

Submit documents directly and poll for evidence-backed extraction results

Overview

Mode 2 lets you submit documents directly to the processing API, then poll for results or receive them via webhook. You control the document collection; Klarefi handles the extraction.

Prerequisites

  • A Klarefi API key (sk_live_... or sk_test_...)
  • A publicly accessible document URL

Step 1: Install the SDK

TypeScript

npm install @klarefi/sdk

Python

pip install klarefi

Step 2: Submit a Document

TypeScript

import { KlarefiClient } from "@klarefi/sdk";

const klarefi = new KlarefiClient({
  apiKey: "sk_live_your_api_key",
});

const result = await klarefi.process({
  document_url: "https://your-storage.com/claim-form.pdf",
  skill_ids: ["incident_date", "policy_number", "claimant_name"],
  webhook_url: "https://your-app.com/webhooks/klarefi", // optional
});

console.log("Case ID:", result.case_id);
console.log("Status:", result.status); // "queued"

Python

from klarefi import KlarefiClient

client = KlarefiClient(api_key="sk_live_your_api_key")

result = client.process(
    document_url="https://your-storage.com/claim-form.pdf",
    skill_ids=["incident_date", "policy_number", "claimant_name"],
    webhook_url="https://your-app.com/webhooks/klarefi",
)

print("Case ID:", result["case_id"])

Step 3: Poll for Results

TypeScript

// Poll until processing completes
async function waitForResults(caseId: string) {
  let cursor = 0;

  while (true) {
    const { events, next_cursor } = await klarefi.getEvents(caseId, cursor);

    for (const event of events) {
      console.log(`Event: ${event.event_type}`);

      if (event.event_type === "session.complete") {
        // Get final results
        const caseData = await klarefi.getCaseStatus(caseId);
        return caseData;
      }
    }

    cursor = next_cursor;
    // Wait before next poll
    await new Promise((r) => setTimeout(r, 2000));
  }
}

const results = await waitForResults(result.case_id);

Python

import time

def wait_for_results(case_id: str):
    cursor = 0
    while True:
        response = client.get_events(case_id, after_cursor=cursor)
        for event in response["events"]:
            print(f"Event: {event['event_type']}")
            if event["event_type"] == "session.complete":
                return client.get_case_status(case_id)
        cursor = response["next_cursor"]
        time.sleep(2)

results = wait_for_results(result["case_id"])

Step 4: Use the Results

The case response contains evidence-backed extraction results organized by skill:

const features = results.features;

for (const [skillId, feature] of Object.entries(features ?? {})) {
  const decision = feature.decision;
  console.log(`${skillId}: ${decision?.decision}`);

  if (decision?.decision === "keep") {
    const candidate = feature.candidates?.[0];
    console.log(`  Value: ${candidate?.value_normalized}`);
    console.log(`  Confidence: ${candidate?.confidence}`);

    // Evidence citations
    for (const evidence of feature.evidence ?? []) {
      console.log(
        `  Evidence: "${evidence.quote}" (page ${evidence.page_index})`,
      );
    }
  }
}

Error Handling

TypeScript

import { KlarefiApiError } from "@klarefi/sdk";

try {
  await klarefi.process({ ... });
} catch (err) {
  if (err instanceof KlarefiApiError) {
    console.error(`API Error [${err.code}]: ${err.message}`);
    console.error(`Request ID: ${err.requestId}`);
  }
}

Python

from klarefi import KlarefiApiError

try:
    client.process(...)
except KlarefiApiError as e:
    print(f"API Error [{e.code}]: {e}")
    print(f"Request ID: {e.request_id}")

On this page