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

# Node SDK

> @prysmai/sdk — a fully-typed OpenAI drop-in for Node/TypeScript with routing, cost, proof, and BRAIN.md auto-discovery.

`@prysmai/sdk` extends the `openai` client, so all your existing OpenAI code works
unchanged — plus typed helpers for routing previews, usage, savings, proof verification,
and BRAIN.md auto-discovery.

```bash theme={null}
npm install @prysmai/sdk
```

## Drop-in replacement for OpenAI

```typescript theme={null}
import { Prysm } from "@prysmai/sdk";

const client = new Prysm(); // apiKey from $PRYSM_API_KEY, baseURL from $PRYSM_BASE_URL

const resp = await client.chat.completions.create({
  model: "auto",            // let PRYSM pick the best model
  messages: [{ role: "user", content: "Write a TypeScript quicksort" }],
});
console.log(resp.choices[0].message.content);
```

## Access the PRYSM extensions

Every response carries a `prysm` block (routing, cost, latency, proof). Use
`extension()` for clean, typed access:

```typescript theme={null}
import { extension } from "@prysmai/sdk";

const ext = extension(resp);
console.log(ext?.routing?.model_display); // "DeepSeek V4 Flash"
console.log(ext?.routing?.reason);        // why this model was chosen
console.log(ext?.cost?.total_usd);        // 0.000042
console.log(ext?.proof?.proof_hash);      // "sha256:a1b2c3d4..."
```

`extension()` returns `null` for responses without a `prysm` block. The shortcuts
`routing()`, `cost()`, and `proof()` are also exported.

## BRAIN.md auto-discovery

Drop a [`BRAIN.md`](/concepts/brain-md) in your project root and the SDK finds it
automatically, applying your routing rules, cost caps, and blocked models:

```typescript theme={null}
const client = new Prysm();                          // discovers ./BRAIN.md (walks up from cwd)
const resp = await client.complete("Summarize this contract"); // BRAIN.md applied
```

Point it explicitly, pass an object, or disable:

```typescript theme={null}
new Prysm({ brain: "path/to/BRAIN.md" });
new Prysm({ brain: { max_cost: 0.005, model: "deepseek-v4-flash" } });
new Prysm({ brain: null });                          // ignore BRAIN.md
```

## Orchestration (v2)

Beyond routing to one model, `orchestrate()` runs a prompt across **several** models —
cascading, ensembling, decomposing, or debating — and returns one synthesized answer plus
a [PrysmProof v2](/concepts/prysmproof). Pick the objective with a `policy`; PRYSM plans
the strategy (or you force one). See [How orchestration works](/concepts/orchestration).

```typescript theme={null}
const r = await client.orchestrate(
  "Compare three database designs for a 40-person team",
  { policy: "depth" },          // "efficiency" | "balanced" | "depth"
);
console.log(r.choices[0].message.content);
console.log(r.prysm.orchestration.models_used); // which models contributed
console.log(r.prysm.orchestration.agreement);   // how strongly they agreed
```

Force a strategy, widen the ensemble, or cap spend — and the `{ messages }` form is
accepted too:

```typescript theme={null}
const r = await client.orchestrate({
  messages: [{ role: "user", content: "Prove that the square root of 2 is irrational" }],
  policy: "depth",
  strategy: "debate",           // single | cascade | ensemble_moa | rank_fuse |
                                // decompose_and_route | self_consistency | debate
  k: 3,                         // ensemble / sample width
  maxCostUsd: 0.05,             // soft budget hint, USD
});
```

## Code Mode (v2)

`code()` writes code, reviews it with a **separate** critic model, and repairs against that
feedback until the review passes or a budget/iteration cap is hit. In `depth`, several
diverse coders run in parallel and the best candidate is kept. PRYSM never executes the
generated code. See [How Code Mode works](/concepts/code-mode).

```typescript theme={null}
const r = await client.code(
  "Write a thread-safe LRU cache in TypeScript with tests",
  { policy: "depth" },          // "efficiency" | "balanced" | "depth"
);
for (const f of r.files) { console.log(f.path); console.log(f.content); }
console.log(r.passed);                          // did the critic pass?
console.log(r.prysm.code.coder_models);         // who wrote it
console.log(r.prysm.proof.proof_hash);          // verifiable proof
```

Force the models, cap iterations, or skip the critic loop — and the `{ task }` form is
accepted too:

```typescript theme={null}
const r = await client.code({
  task: "Implement rate limiting middleware",
  coderModel: "claude-sonnet-4.5",  // who writes the code
  reviewerModel: "deepseek-v4-pro",     // who critiques it
  maxIters: 4,                      // generate + up to 3 repairs
  maxCostUsd: 0.1,                  // soft budget hint, USD
});

const quick = await client.code("Write a hello world", { review: false }); // single shot
```

## Compliance (v2)

Load the providers your organization approves and PRYSM routes **only** to models that
satisfy your policy — non-compliant models are filtered out before scoring. See
[compliance routing](/concepts/compliance).

`compliancePreview()` is a pure dry-run (no model call, no keys needed): it shows which
models a policy allows vs excludes, the Compliance Cost Premium, and a sample attestation.

```typescript theme={null}
const p = await client.compliancePreview("summarize this report", {
  compliance: { jurisdiction: ["EU"], frameworks: ["GDPR"], data_residency: ["EU"] },
});
console.log(p.allowed_models);            // only EU/GDPR providers survive
console.log(p.compliance_cost_premium);   // what compliance costs vs. unrestricted
```

Then enforce the same policy on a real run — `orchestrate()` accepts a `compliance` spec.
Excluded models can never be selected, and the result carries a compliance decision plus an
attestation in its [PrysmProof](/concepts/prysmproof):

```typescript theme={null}
const r = await client.orchestrate("Explain photosynthesis.", {
  policy: "balanced",
  compliance: { provider_allowlist: ["anthropic"] },  // confine to approved providers
});
console.log(r.prysm.compliance);                 // the exclusion decision
console.log(r.prysm.proof.compliance);           // the attestation
```

<Tip>
  Prefer to declare it once and version it: put a `compliance:` block in your
  [BRAIN.md](/concepts/brain-md) and it applies to every request automatically.
</Tip>

## Helpers

| Method                                    | Description                                                                                                                                           |
| ----------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- |
| `client.complete(prompt, opts?)`          | One-shot chat with `model: "auto"` + BRAIN.md auto-applied.                                                                                           |
| `client.orchestrate(prompt, opts?)`       | [Multi-model orchestration (v2)](/api-reference/orchestrate): cascade / ensemble / debate + PrysmProof.                                               |
| `client.code(task, opts?)`                | [Code Mode (v2)](/api-reference/code): self-correcting, multi-model code generation + PrysmProof.                                                     |
| `client.compliancePreview(prompt, opts?)` | [Compliance preview (v2)](/api-reference/compliance-preview): dry-run the policy gate — allowed/excluded models, CCP, attestation. **No model call**. |
| `client.agents.run({ goal, ... })`        | [Cost-bounded agent run](/concepts/for-ai-agents) — hard `maxCostUsd` ceiling, verifiable trajectory.                                                 |
| `client.route(prompt, mode?, brain?)`     | Dry run: which model + estimated cost, **no model call**.                                                                                             |
| `client.usage()`                          | Usage stats for your key.                                                                                                                             |
| `client.savings(baseline?)`               | Estimated `$` saved vs. an all-premium baseline.                                                                                                      |
| `client.verifyProof(requestId)`           | Verify a [PrysmProof](/concepts/prysmproof).                                                                                                          |
| `client.validateBrain(textOrObject)`      | Validate a BRAIN.md config.                                                                                                                           |
| `client.modelsCatalog()`                  | The full model catalog with pricing.                                                                                                                  |

```typescript theme={null}
await client.route("debug this function");   // dry-run: which model, est. cost (no call)
await client.usage();                        // your usage stats
await client.savings("gpt-5.2");             // est. $ saved vs. an all-premium baseline
await client.verifyProof(requestId);         // verify a PrysmProof
await client.modelsCatalog();                // 27 models with pricing
```

### Validate a BRAIN.md before shipping

```typescript theme={null}
import { readFileSync } from "node:fs";

console.log(await client.validateBrain(readFileSync("BRAIN.md", "utf-8")));
// { valid: true, errors: [], warnings: [], normalized: {...} }
```

## TypeScript

The package ships type declarations. Result and option types are exported for use in your
own signatures:

```typescript theme={null}
import type {
  PrysmOptions,
  RouteResult,
  ModelEntry,
  UsageResult,
  SavingsResult,
  BrainValidateResult,
  PrysmExtension,
  Policy,
  Strategy,
  OrchestrateOptions,
  OrchestrationResult,
  CompliancePreviewOptions,
  CompliancePreviewResult,
} from "@prysmai/sdk";
```

## Configuration

| Setting  | Option     | Env var          | Default                     |
| -------- | ---------- | ---------------- | --------------------------- |
| API key  | `apiKey:`  | `PRYSM_API_KEY`  | —                           |
| Base URL | `baseURL:` | `PRYSM_BASE_URL` | `https://api.prysm1.com/v1` |
| BRAIN.md | `brain:`   | —                | `"auto"` (discover)         |

<Note>
  If `PRYSM_API_KEY` is unset, the SDK falls back to `OPENAI_API_KEY` — so migrating
  existing code can be a one-line base-URL change.
</Note>

## Next steps

<CardGroup cols={2}>
  <Card title="MCP server" icon="robot" href="/sdks/mcp">
    Give Claude Desktop, Cursor, or Windsurf cost-aware routing as a native tool.
  </Card>

  <Card title="API reference" icon="code" href="/api-reference/introduction">
    The endpoints these helpers call, documented field by field.
  </Card>
</CardGroup>
