@driftgard/node
v1.31.0
Published
Official DriftGard Node.js SDK — evaluate LLM interactions against your compliance policy
Maintainers
Readme
@driftgard/node
Official Node.js SDK for DriftGard.
Use it to control what production AI can say and do: evaluate prompts and responses, run OpenAI-compatible gateway calls through DriftGard, validate agent tool calls, and record audit evidence.
Agent Assurance
The SDK includes a separate AssuranceClient for reviewed
agent checks: create a run, read JSON evidence and wait for its terminal result.
It uses a dedicated project-scoped Assurance CI key, never retries run creation,
and has no fail-open fallback. Baselines, repeated trials and ordered conversation
evidence use the same backend contracts as the console. Human release decisions
remain in the console. See Agent Assurance setup and examples.
Version 1.29.7 validates scenario totals and outcomes before accepting a passing
result. Setup instructions and CI examples are in the guide.
Release clearance
SDK 1.30.0 adds deployment preflights and release identity for live guarded actions. Use one reviewed clearance at both boundaries, bind application keys in the console, and enable required-clearance operation to withhold dispatch on outages or missing evidence. Deployment keys are separate from live keys. See release clearance setup and examples.
Install
npm install @driftgard/nodeRequires Node.js 18 or newer.
Quick Start
import { Driftgard } from "@driftgard/node";
const dg = new Driftgard({
apiKey: process.env.DRIFTGARD_API_KEY,
});
const result = await dg.evaluate({
project_id: "proj_...",
prompt: "What stocks should I buy?",
response: "You should invest everything in...",
model_id: "gpt-4o",
});
if (!result.evaluation.allowed) {
console.log("Blocked:", result.fallback?.message);
} else if (result.evaluation.sanitized) {
console.log("Use sanitized response:", result.evaluation.sanitized_response);
} else {
console.log("Allowed");
}Inline Gateway
Use the gateway when DriftGard should sit in the request path, call the provider, enforce policy, and return the final response.
const completion = await dg.gatewayChatCompletions({
project_id: "proj_...",
model: "gpt-4o-mini",
messages: [
{ role: "system", content: "You are a support assistant." },
{ role: "user", content: "Summarize the refund process." },
],
driftgard: {
gateway_mode: "enforce",
agent_id: "support-agent",
agent_role: "customer_support",
session_id: "sess_123",
},
});
console.log(completion.choices?.[0]?.message?.content);
console.log(completion.driftgard?.gateway_decision);Streaming is also supported:
const stream = await dg.streamGatewayChatCompletions({
project_id: "proj_...",
model: "gpt-4o-mini",
messages,
driftgard: { gateway_mode: "observe" },
});Tool Call Validation
Validate agent tool calls against Control Pack tool_rules.
const result = await dg.evaluate({
project_id: "proj_...",
eval_mode: "tool_call",
tool_call: {
tool_name: "transfer_money",
parameters: { amount: 500, to_account: "acct_123" },
},
agent_role: "payments_agent",
model_id: "agent-runtime",
});
if (!result.evaluation.allowed) {
throw new Error(result.fallback?.message || "Tool call blocked");
}You can also wrap a function:
const guardedTransfer = dg.guard(transferMoney, "transfer_money", "proj_...");
await guardedTransfer(500, "acct_123");Local Evaluation
For sensitive environments, the SDK can evaluate locally through DriftGard's WASM evaluator.
const dg = new Driftgard({
apiKey: process.env.DRIFTGARD_API_KEY,
mode: "local",
projectId: "proj_...",
});
await dg.init();
const result = await dg.evaluate({ prompt, response, model_id: "local-model" });Modes:
| Mode | Behavior |
| --- | --- |
| remote | Send prompt/response to DriftGard API |
| local | Evaluate locally; no prompt/response leaves your environment |
| local-with-audit | Evaluate locally and report verdict metadata only |
Framework Integrations
Included integrations:
- LangChain response guardrail
- LangChain tool guard
- local semantic matching for local mode
import { DriftGardGuardrail, DriftGardToolGuard } from "@driftgard/node";Pass the exact response model as modelId to both LangChain guards. Tool-call evaluations otherwise retain the backward-compatible langchain_agent label.
Response adapters apply DG's decision before returning text. Deliver their return value, not the original model output. A sanitized response may legitimately be an empty string; missing or non-string replacement text raises even in fallback mode. Tool adapters stop blocked calls before execution. Use failOpen: false to stop when DG is unavailable.
Documentation
- Gateway
- Tool calls
- Local evaluation
- Governed Knowledge
- Configuration and failure modes
- Framework integrations
- Model usage and cost reporting
Requirements
- Node.js 18+
- DriftGard API key
- DriftGard project ID
License
MIT
Business-agent model cost estimates
In AI Cost Governance, add a Business agents (SDK/API) pricing profile for the reported model ID. Configure service-tier multipliers if the provider reports a tier. Capture model usage once per response, including responses proposing tools:
import { Driftgard, modelUsageCallback } from "@driftgard/node";
import { ChatOpenAI } from "@langchain/openai";
const dg = new Driftgard({ apiKey, timeout: 5000, maxRetries: 1 });
// Explicit: OpenAI ChatCompletion or LangChain AIMessage.
await dg.reportModelResponse(projectId, response);
// Or automatic LangChain capture; choose one capture method per model.
const model = new ChatOpenAI({ model: modelId, callbacks: [modelUsageCallback(dg, projectId)] });The callback receives complete model results, including tool proposals. Tool execution is still controlled by the existing tool guard. Capture sends usage facts only, never prompt/response text or tool arguments. The server deduplicates project/provider/response IDs, so several tools from one response do not multiply the model cost. A reporting failure is logged by the callback without changing model output or authorization. Explicit reporting methods raise errors for the application to handle/retry.
reportModelUsage also accepts normalized usage from other frameworks/providers:
project_id, provider, stable call_id, model_id, output_type (text or
tool_call), usage, and optional service_tier. Input includes cache reads/writes;
output includes reasoning. cached_input_tokens must be explicitly reported; unknown
counts remain unknown. Do not submit cumulative session totals for individual calls.
Estimates appear in Estimated model cost, separately from reported monetary costs.
Missing usage/prices remain unavailable. New prices apply to future reports; old costs
are not recomputed. Usage reporting does not run policy checks or consume evaluation
allowance. This requires a backend version supporting /audit/model-usage.
See the complete cost reporting guide
for normalized payloads, retry handling, missing data, and reporting an already-known
USD amount through usage.cost.
