@doc-intelligence/sdk
v0.2.0
Published
JavaScript/TypeScript SDK for the Document Intelligence Platform — AI-native document processing for Insurance, Healthcare, and Legal sectors.
Maintainers
Readme
@doc-intelligence/sdk
JavaScript/TypeScript SDK for the Document Intelligence Platform — AI-native document processing for Insurance, Healthcare, and Legal sectors.
Upload PDF/Audio → Extract fields → Cross-check history → Generate draft → Human approvalInstall
npm install @doc-intelligence/sdk
# or
pnpm add @doc-intelligence/sdkReact hooks (optional peer dep):
npm install @doc-intelligence/sdk reactQuick start
import { DocumentIntelligenceClient } from '@doc-intelligence/sdk'
const client = new DocumentIntelligenceClient({
baseUrl: 'https://your-api-host.com', // URL of the deployed API
// apiKey: 'sk-...', // optional, if auth is enabled
// timeout: 120_000, // ms, default 120s
})Authentication
If the API has authentication enabled (production deployments), include your JWT token:
// 1. Login to get a token
const res = await fetch('https://your-api/auth/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email: '[email protected]', password: 'demo1234' }),
})
const { access_token } = await res.json()
// 2. Pass the token to the client
const client = new DocumentIntelligenceClient({
baseUrl: 'https://your-api',
apiKey: access_token,
})Token expiry: 8h. Roles: admin · reviewer · uploader · auditor
Documents
// Upload a file and start the full AI pipeline
const { documentId } = await client.documents.upload(file, {
sector: 'insurance', // 'insurance' | 'healthcare' | 'legal'
filename: 'claim.pdf',
})
// Poll for processing status
const doc = await client.documents.getDocument(documentId)
// doc.status:
// 'uploaded' → 'ingesting' → 'extracting' → 'validating'
// → 'generating' → 'pending_review' → 'approved' | 'rejected' | 'failed'
// Review the AI output and approve
await client.documents.approve(documentId)
// Or reject with correction notes (triggers reprocessing)
await client.documents.reject(documentId, [
{ field: 'claimAmount', value: '50000', note: 'Exceeds policy limit' },
])
// List documents with optional filters
const { items, total } = await client.documents.list({
sector: 'insurance',
status: 'pending_review',
limit: 20,
offset: 0,
})
// Reprocess with corrected field values
await client.documents.reprocess(documentId, {
policyNumber: 'APD-2024-99001',
claimAmount: 45000,
})Insurance
// Process an insurance claim document
const { documentId } = await client.insurance.processDocument(file, 'claim.pdf')
// Retrieve triage report (available once status = 'pending_review')
const report = await client.insurance.getTriageReport(documentId)
// {
// priority: 'low' | 'medium' | 'high' | 'urgent'
// fraudRiskLevel: 'low' | 'medium' | 'high'
// fraudSignals: string[]
// coverageMismatch: boolean
// coverageNotes: string[]
// summary: string
// recommendedAction: string
// extractedFields: InsuranceClaim
// validationFlags: ValidationFlag[]
// }Healthcare
// Upload consultation audio or text transcript
const { documentId } = await client.healthcare.transcribeConsultation(audioFile, 'consult.mp3')
// Retrieve generated SOAP note (available once status = 'pending_review')
const note = await client.healthcare.getSOAPNote(documentId)
// {
// subjective: { chiefComplaint, historyOfPresentIllness, medications, allergies, ... }
// objective: { vitalSigns, physicalExamination, diagnosticResults }
// assessment: { primaryDiagnosis, icd10Codes: [{ code, description }], ... }
// plan: { treatment, medications, followUp, referrals, patientEducation }
// drugInteractionWarnings: string[]
// physicianSignature: '[SIGNATURE REQUIRED]'
// }Legal
import type { NotarialFormInput } from '@doc-intelligence/sdk'
// Upload a legal document PDF directly
const { documentId } = await client.documents.upload(legalPdf, { sector: 'legal' })
// Or submit structured form data to generate a notarial act
const form: NotarialFormInput = {
actType: 'power_of_attorney',
actDate: '2025-03-15',
jurisdiction: 'Ciudad de México',
parties: [
{
role: 'grantor',
fullName: 'Alejandro Marcos Villanueva Reyes',
nationalId: 'VIRA-800312-HDF',
address: 'Av. Insurgentes Sur 1234, CDMX',
},
{
role: 'grantee',
fullName: 'Carmen Lucia Estrada Montes',
nationalId: 'EAMC-850621-MDF',
address: 'Calle Reforma 567, CDMX',
},
{
role: 'notary',
fullName: 'Roberto Fuentes Sandoval',
nationalId: 'FUSR-700115-HDF',
address: 'Notaría No. 47, CDMX',
},
],
terms: ['Power valid until 2026-12-31', 'Limit: MXN 2,000,000'],
specialClauses: ['Limited to real estate transactions only'],
governingLaw: 'Código Civil Federal',
}
const { documentId } = await client.legal.processNotarialForm(form)
// Retrieve generated notarial act
const act = await client.legal.getNotarialAct(documentId)
// {
// actType, actDate, jurisdiction
// openingClause, partiesSection, subjectMatterSection
// termsSection, specialClausesSection, closingClause, witnessSection
// missingElements: string[] ← fields the AI couldn't populate
// legalWarnings: string[]
// }Chat (archive query)
Query across all indexed and approved documents using natural language:
for await (const token of client.chat.query('How many claims were filed this month?')) {
if (token.type === 'text') process.stdout.write(token.content ?? '')
if (token.type === 'done') console.log('\nSources:', token.citations)
}
// Scope to a specific sector
for await (const token of client.chat.query('Any ICD-10 J18.9 cases?', { sector: 'healthcare' })) {
// ...
}React hook
import { useDocumentQuery } from '@doc-intelligence/sdk/react'
function ArchiveChat() {
const { messages, sendMessage, isLoading, error } = useDocumentQuery({
client,
sector: 'insurance', // optional sector filter
})
return (
<div>
{messages.map((m) => (
<p key={m.id}>
<strong>{m.role}:</strong> {m.content}
</p>
))}
<button disabled={isLoading} onClick={() => sendMessage('Show high-priority claims')}>
Ask
</button>
{error && <p style={{ color: 'red' }}>{error.message}</p>}
</div>
)
}| Property | Type | Description |
|---|---|---|
| messages | ChatMessage[] | Full conversation history |
| sendMessage | (text: string) => Promise<void> | Send a message and stream the response |
| isLoading | boolean | True while the response is streaming |
| error | Error \| null | Last error, if any |
| reset | () => void | Clear conversation history |
Error handling
import { DocumentIntelligenceError } from '@doc-intelligence/sdk'
try {
const doc = await client.documents.getDocument('unknown-id')
} catch (err) {
if (err instanceof DocumentIntelligenceError) {
console.log(err.code) // 'NOT_FOUND' | 'TIMEOUT' | 'NETWORK_ERROR' | 'PIPELINE_ERROR'
console.log(err.retryable) // true if safe to retry
}
}TypeScript types
All types ship bundled with the SDK — no separate install needed:
import type {
Sector,
DocumentStatus,
DocumentDetail,
ExtractionResult,
ValidationFlag,
// Insurance
InsuranceClaim,
TriageReport,
// Healthcare
ClinicalEncounter,
SOAPNote,
// Legal
NotarialFormInput,
NotarialAct,
NotarialParty,
// Chat
ChatToken,
} from '@doc-intelligence/sdk'Requirements
- Node.js >= 18 (uses native
fetchandReadableStream) - React >= 18 — only if using the
/reactentry point
Architecture
The SDK wraps a self-hosted NestJS API that runs a local AI pipeline:
Upload → Ingest (PDF/Audio) → Router Agent → Extraction Agent ─┐
├→ Validation → Generation → Human Review
Graph Agent (KG) ────┘- LLM: Ollama (llama3.1:8b) — runs fully local, no data leaves the deployment
- Embeddings: nomic-embed-text (768-dim vectors) via Ollama
- Vector search: PostgreSQL + pgvector (ivfflat index)
- Knowledge graph: PostgreSQL JSONB + recursive CTEs
- Keyword search: PostgreSQL ILIKE (BM25/OpenSearch in production)
