JSPM

  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 437
  • Score
    100M100P100Q79988F
  • License MIT

Official Driftgard Node.js SDK — evaluate LLM interactions against your compliance policy

Package Exports

  • @driftgard/node
  • @driftgard/node/dist/index.js

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (@driftgard/node) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

@driftgard/node

Official Node.js SDK for Driftgard — evaluate LLM interactions against your compliance policy.

Install

npm install @driftgard/node

Quick start

import { Driftgard } from "@driftgard/node";

const dg = new Driftgard({
  apiKey: process.env.DRIFTGARD_API_KEY,
});

const result = await dg.evaluate({
  project_id: "your-project-id",
  prompt: "What stocks should I buy?",
  response: "Based on current trends, you should invest in...",
  model_id: "gpt-4o",
});

if (result.evaluation.allowed) {
  console.log("Safe to return to user");
} else {
  // Use the fallback message if configured in your control pack
  if (result.fallback) {
    console.log("Show to user:", result.fallback.message);
  }
  console.log("Blocked:", result.evaluation.violations);
}

Conversation tracking

Link evaluations within an agent session using session_id and parent_evaluation_id:

const result = await dg.evaluate({
  project_id: "your-project-id",
  prompt: "Transfer $500 to account 12345",
  response: "I've initiated the transfer.",
  model_id: "gpt-4o",
  session_id: "sess_abc123",              // groups evals in a conversation
  parent_evaluation_id: "eval_prev_id",   // chains to the previous eval
});

This enables chain depth protection (prevents infinite agent loops) and lets you trace evaluation lineage in the dashboard.

A/B experiments

Tag evaluations with an experiment_id to compare governance metrics across models:

const result = await dg.evaluate({
  project_id: "your-project-id",
  prompt: "Can I get a loan to invest in crypto?",
  response: "Sure, taking out a personal loan to invest in crypto is a great way to maximise returns.",
  model_id: "gpt-4o",
  experiment_id: "financial-advisor-v1",  // optional
});

View experiment results on the Experiments page in the Driftgard dashboard.

Cost attribution

Pass optional usage metadata to track token consumption and cost per evaluation:

const result = await dg.evaluate({
  project_id: "your-project-id",
  prompt: "What stocks should I buy?",
  response: "Based on current trends, you should invest in...",
  model_id: "gpt-4o",
  usage: {
    prompt_tokens: 150,
    completion_tokens: 320,
    total_tokens: 470,
    cost: 0.0047, // USD
  },
});

All fields in usage are optional. When provided, token and cost data appears in the evaluation detail and is aggregated in experiment comparisons.

Cost alerts

When cost alerting is enabled on your project, the response includes a cost_alert field if a threshold is exceeded:

const result = await dg.evaluate({ ... });

if (result.cost_alert) {
  console.warn(`Cost alert: ${result.cost_alert.scope} spend $${result.cost_alert.actual_usd} exceeds $${result.cost_alert.threshold_usd}`);
  // Throttle the agent, notify the user, etc.
}

Configure thresholds in Settings — per-project, per-model, or per-session. Session-scoped alerts catch runaway agent loops in real-time.

Features

  • Single evaluate() method — send prompt/response, get verdict
  • Failure mode: fail-open or fail-closed when API is unreachable
  • Circuit breaker: skips API after consecutive failures, auto-recovers
  • Idempotency: deduplicates retried requests via x-idempotency-key
  • Auto-retry with exponential backoff on 5xx and network errors
  • Typed errors: AuthError, RateLimitError, FeatureNotAvailableError, ChainDepthExceededError
  • Full TypeScript types for requests and responses
  • Zero dependencies (uses native fetch)

Configuration

const dg = new Driftgard({
  apiKey: "your-api-key",       // required
  baseUrl: "https://api.driftgard.com", // optional
  timeout: 30000,               // optional, ms (default 30s)
  maxRetries: 2,                // optional (default 2)
  failureMode: "open",         // "open" = allow if API down, "closed" = block (default "open")
  circuitBreaker: {
    threshold: 5,               // open circuit after 5 consecutive failures (default 5)
    resetTimeoutMs: 30000,      // try again after 30s (default 30000)
  },
});

Failure mode & circuit breaker

The SDK never throws on network/server errors during evaluate(). Instead, it returns a synthetic response:

const result = await dg.evaluate({ ... });

// Check where the decision came from
console.log(result.decision_source);
// "policy"           — normal API evaluation
// "failure_mode"     — API unreachable, failureMode applied
// "circuit_open"     — circuit breaker open, failureMode applied
// "idempotency_cache" — duplicate request, cached result returned

// Monitor circuit breaker state
console.log(dg.circuitBreakerState);
// { state: "closed", failures: 0, openedAt: 0 }

With failureMode: "open" (default), the SDK allows requests through when Driftgard is unavailable. With failureMode: "closed", it blocks them with a fallback message.

Error handling

import { Driftgard, AuthError, RateLimitError, FeatureNotAvailableError, ChainDepthExceededError } from "@driftgard/node";

try {
  const result = await dg.evaluate({ ... });
} catch (e) {
  if (e instanceof AuthError) {
    // Invalid or revoked API key (401)
  } else if (e instanceof RateLimitError) {
    // Too many requests (429)
  } else if (e instanceof ChainDepthExceededError) {
    // Agent loop detected — chain depth exceeded (429)
    console.log(`Depth ${e.depth} exceeds max ${e.max}`);
  } else if (e instanceof FeatureNotAvailableError) {
    // API evaluate requires Compliance+ tier (403)
  }
}

Requirements

  • Node.js 18+ (uses native fetch)
  • API key from Driftgard (Settings → API Keys)
  • Compliance or Enterprise tier for API evaluation

License

MIT