> ## Documentation Index
> Fetch the complete documentation index at: https://docs.precipiq.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Precipiq TypeScript SDK reference

> Install the precipiq npm package, configure the constructor, call logDecision and linkOutcome, and handle errors in Node, Bun, or Deno projects.

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

```bash theme={null}
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?)`

```typescript theme={null}
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
});
```

| Option                 | Type                   | Description                                                                                 |
| ---------------------- | ---------------------- | ------------------------------------------------------------------------------------------- |
| `baseUrl`              | `string`               | Override the default API root for self-hosted deployments.                                  |
| `flushThreshold`       | `number`               | Number of queued decisions that trigger a forced flush. Default: `50`.                      |
| `flushIntervalSeconds` | `number`               | Seconds between background flushes. Default: `5`.                                           |
| `enableBatching`       | `boolean`              | When `false`, every `logDecision` ships immediately and returns a receipt. Default: `true`. |
| `raiseOnError`         | `boolean`              | When `true`, API failures throw instead of routing to `onError`. Default: `false`.          |
| `timeoutMs`            | `number`               | Per-request timeout in milliseconds. Default: `10000`.                                      |
| `onError`              | `(err: Error) => void` | Callback invoked when a request fails and `raiseOnError` is `false`.                        |

<Note>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.</Note>

## 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`.

```typescript theme={null}
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);
}
```

| Param          | Type       | Description                                                   |
| -------------- | ---------- | ------------------------------------------------------------- |
| `agentId`      | `string`   | Identifier for the AI agent that made the decision.           |
| `actionType`   | `string`   | Category or name of the action taken.                         |
| `inputs`       | `object`   | Input context the agent received.                             |
| `outputs`      | `object`   | Output or action the agent produced.                          |
| `confidence`   | `number`   | Confidence score between `0` and `1`.                         |
| `humanInLoop`  | `boolean`  | Whether a human reviewed the decision before it was executed. |
| `alternatives` | `object[]` | Optional list of alternatives the agent considered.           |
| `metadata`     | `object`   | Arbitrary 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.

```typescript theme={null}
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.

```typescript theme={null}
await pq.linkOutcome(
  'd5e7a3b0-0000-0000-0000-000000000001',
  'fev_abc',
  {
    correlationStrength: 1.0,
    linkType: 'revenue',
    attributionMethod: 'direct',
    notes: 'upsell offer accepted',
  },
);
```

| Option                | Type                | Description                                                                     |
| --------------------- | ------------------- | ------------------------------------------------------------------------------- |
| `correlationStrength` | `number`            | Probability between `0` and `1` that the decision caused the financial outcome. |
| `linkType`            | `LinkType`          | Economic character of the link — e.g., `"revenue"`, `"cost"`, `"liability"`.    |
| `attributionMethod`   | `AttributionMethod` | How attribution was determined — e.g., `"direct"`, `"ml_suggested"`.            |
| `notes`               | `string`            | Optional 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`.

```typescript theme={null}
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`.

```typescript theme={null}
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'`:

```typescript theme={null}
import type {
  AIPnLResponse,
  AttributionMethod,
  DateRange,
  DecisionReceipt,
  FinancialEventSource,
  FinancialEventType,
  LinkReceipt,
  LinkType,
  LogDecisionParams,
  PrecipiqOptions,
} from 'precipiq';
```

## Errors

```typescript theme={null}
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
  }
}
```

| Export                   | Description                                                                          |
| ------------------------ | ------------------------------------------------------------------------------------ |
| `PrecipiqError`          | Base class for all SDK errors. Catch this to handle every SDK failure in one branch. |
| `PrecipiqAuthError`      | Thrown on 401 or 403 responses.                                                      |
| `PrecipiqAPIError`       | Thrown on any other non-2xx response.                                                |
| `PrecipiqTransportError` | Thrown when the network request fails before a response is received.                 |
| `redactApiKey`           | Utility that redacts an API key string for safe logging.                             |

<Warning>Errors are only thrown when `raiseOnError: true`. With the default `raiseOnError: false`, failures are routed to the `onError` callback and swallowed.</Warning>

## Adapters

<CardGroup cols={2}>
  <Card title="LangChain adapter" href="/integrations/langchain" icon="brain">
    Automatically track every LLM, tool, and chain call in a LangChain application.
  </Card>

  <Card title="CrewAI adapter" href="/integrations/crewai" icon="users">
    Track every agent task execution in a CrewAI workflow via the `step_callback` hook.
  </Card>
</CardGroup>
