Skip to main content
The Precipiq TypeScript SDK is the official client library for the AI Consequences Ledger. It has zero runtime dependencies beyond the host’s native fetch, ships ESM and CJS side by side, and is fully tree-shakeable.

Install

npm install precipiq
# or:  pnpm add precipiq   /   yarn add precipiq
The SDK runs on Node 18+, Bun, and Deno. It also works in modern browsers when bundled with type declarations.

Constructor

new Precipiq(apiKey, options?)

import { Precipiq } from 'precipiq';

const pq = new Precipiq('pq_test_demo_key_REPLACE_ME', {
  baseUrl: 'https://api.precipiq.dev',   // override for self-hosted
  flushThreshold: 50,                    // queued items before forced flush
  flushIntervalSeconds: 5,               // background-flush cadence
  enableBatching: true,                  // false => ship synchronously
  raiseOnError: false,                   // true => throw on API failures
  timeoutMs: 10_000,                     // per-request timeout
  onError: (err) => console.warn(err),   // fallback handler
});
OptionTypeDescription
baseUrlstringOverride the default API root for self-hosted deployments.
flushThresholdnumberNumber of queued decisions that trigger a forced flush. Default: 50.
flushIntervalSecondsnumberSeconds between background flushes. Default: 5.
enableBatchingbooleanWhen false, every logDecision ships immediately and returns a receipt. Default: true.
raiseOnErrorbooleanWhen true, API failures throw instead of routing to onError. Default: false.
timeoutMsnumberPer-request timeout in milliseconds. Default: 10000.
onError(err: Error) => voidCallback invoked when a request fails and raiseOnError is false.
With raiseOnError: false (the default), failed requests fall through to onError instead of throwing. Install the SDK on a hot request path without fear of a Precipiq outage crashing your app.

Methods

logDecision(params)Promise<DecisionReceipt | null>

Queues a decision for a batched ship (default) or POSTs it immediately when enableBatching: false. Returns null when batching is enabled because the decision is queued; returns a DecisionReceipt when enableBatching: false.
const receipt = await pq.logDecision({
  agentId: 'pricing-bot',
  actionType: 'discount_offer',
  inputs: { customer_id: 'cust_123', tier: 'gold' },
  outputs: { discount_pct: 15 },
  confidence: 0.82,
  humanInLoop: false,
  alternatives: [{ action: 'no_discount', score: 0.48 }],
  metadata: { model_version: 'v2.3.1' },
});
if (receipt) {
  console.log(receipt.decisionId, receipt.hash, receipt.timestamp);
}
ParamTypeDescription
agentIdstringIdentifier for the AI agent that made the decision.
actionTypestringCategory or name of the action taken.
inputsobjectInput context the agent received.
outputsobjectOutput or action the agent produced.
confidencenumberConfidence score between 0 and 1.
humanInLoopbooleanWhether a human reviewed the decision before it was executed.
alternativesobject[]Optional list of alternatives the agent considered.
metadataobjectArbitrary key-value pairs for deployment context.

flush()Promise<void>

Drain the in-memory buffer immediately. Call this during graceful shutdown to ensure no decisions are lost.
process.on('SIGTERM', async () => {
  await pq.flush();
  process.exit(0);
});

linkOutcome(decisionId, financialEventId, options)Promise<LinkReceipt | null>

Link a previously logged decision to a financial event.
await pq.linkOutcome(
  'd5e7a3b0-0000-0000-0000-000000000001',
  'fev_abc',
  {
    correlationStrength: 1.0,
    linkType: 'revenue',
    attributionMethod: 'direct',
    notes: 'upsell offer accepted',
  },
);
OptionTypeDescription
correlationStrengthnumberProbability between 0 and 1 that the decision caused the financial outcome.
linkTypeLinkTypeEconomic character of the link — e.g., "revenue", "cost", "liability".
attributionMethodAttributionMethodHow attribution was determined — e.g., "direct", "ml_suggested".
notesstringOptional free-text annotation.

getAiPnl(range, agentId?)Promise<AIPnLResponse | null>

Fetch the aggregated AI P&L for the authenticated org. Returns null when the request fails and raiseOnError is false.
const pnl = await pq.getAiPnl({
  start: '2026-04-01',
  end: '2026-04-30',
});
if (pnl) {
  console.log(pnl.totalRevenueAttributed, pnl.netAiImpact, pnl.currency);
}

track(agentId, actionType, handler) → wrapped handler

Wraps an async function so that every call automatically produces a decision record. The arguments become inputs and the return value becomes outputs.
const computeDiscount = pq.track(
  'pricing-bot',
  'discount_offer',
  async (args: { customerId: string; tier: string }) => {
    return { discountPct: args.tier === 'gold' ? 15 : 5 };
  },
);

await computeDiscount({ customerId: 'cust_456', tier: 'silver' });

Types

All core types are re-exported from the package root so you can import them directly from 'precipiq':
import type {
  AIPnLResponse,
  AttributionMethod,
  DateRange,
  DecisionReceipt,
  FinancialEventSource,
  FinancialEventType,
  LinkReceipt,
  LinkType,
  LogDecisionParams,
  PrecipiqOptions,
} from 'precipiq';

Errors

import {
  PrecipiqAPIError,
  PrecipiqAuthError,
  PrecipiqError,
  PrecipiqTransportError,
  redactApiKey,
} from 'precipiq';

try {
  await pq.logDecision({ /* … */ });
} catch (err) {
  if (err instanceof PrecipiqAuthError) {
    // 401 / 403 — rotate or validate the API key
  } else if (err instanceof PrecipiqAPIError) {
    // 4xx / 5xx with a structured error body
  } else if (err instanceof PrecipiqTransportError) {
    // Network / timeout
  }
}
ExportDescription
PrecipiqErrorBase class for all SDK errors. Catch this to handle every SDK failure in one branch.
PrecipiqAuthErrorThrown on 401 or 403 responses.
PrecipiqAPIErrorThrown on any other non-2xx response.
PrecipiqTransportErrorThrown when the network request fails before a response is received.
redactApiKeyUtility that redacts an API key string for safe logging.
Errors are only thrown when raiseOnError: true. With the default raiseOnError: false, failures are routed to the onError callback and swallowed.

Adapters

LangChain adapter

Automatically track every LLM, tool, and chain call in a LangChain application.

CrewAI adapter

Track every agent task execution in a CrewAI workflow via the step_callback hook.