Skip to content

TypeScript SDK

Installation

Terminal window
npm install @archetypal-ai/govern
# or
pnpm add @archetypal-ai/govern
# or
yarn add @archetypal-ai/govern

Requires Node.js 18+ or any modern browser environment.

Initialization

import { GovernClient } from '@archetypal-ai/govern';
const govern = new GovernClient({
apiKey: process.env.GOVERN_API_KEY!,
orgId: process.env.GOVERN_ORG_ID!,
// Optional: override defaults
baseUrl: 'https://api.govern.archetypal.ai', // default
timeout: 5000, // ms, default: 5000
mode: 'flag', // log | flag | block, default: uses org policy
failOpen: true, // default: true (don't block on SDK errors)
});

Basic assessment

import Anthropic from '@anthropic-ai/sdk';
const client = new Anthropic();
const message = await client.messages.create({
model: 'claude-sonnet-4-20250514',
max_tokens: 1024,
messages: [{ role: 'user', content: userInput }],
});
// Assess the inference
const assessment = await govern.assess({
model: 'claude-sonnet-4-20250514',
prompt: [{ role: 'user', content: userInput }],
response: message.content[0].type === 'text' ? message.content[0].text : '',
metadata: {
userId: currentUser.id,
sessionId: session.id,
feature: 'customer-support',
},
});
// Handle violations
if (assessment.action === 'block') {
throw new Error('Response blocked by governance policy');
}
if (assessment.action === 'flag') {
logger.warn('Governance flag', { violations: assessment.violations });
}
// Use the response
return message.content;

Assessment result

interface AssessmentResult {
assessmentId: string;
action: 'pass' | 'flag' | 'block';
scores: {
security: number; // 0.0–1.0
bias: number;
accuracy: number;
drift: number | null; // null until baseline established
cost: number;
};
violations: Array<{
scorer: 'security' | 'bias' | 'accuracy' | 'drift' | 'cost';
score: number;
threshold: number;
reason: string;
}>;
latencyMs: number;
model: string;
timestamp: string;
}

Streaming support

For streaming responses, use assessStream() which buffers the stream and scores the complete response:

import Anthropic from '@anthropic-ai/sdk';
const client = new Anthropic();
// Wrap streaming with governance
const { stream, assessment } = govern.wrapStream(
client.messages.stream({
model: 'claude-sonnet-4-20250514',
max_tokens: 1024,
messages: [{ role: 'user', content: userInput }],
})
);
// Stream to client as normal
for await (const chunk of stream) {
yield chunk;
}
// Await the assessment (resolves when stream completes)
const result = await assessment;
if (result.action === 'block') {
// Stream already delivered — log the violation for review
logger.error('Blocked content delivered via stream', result.violations);
}

Batch assessment

For CI/CD and test pipelines, assess multiple inferences at once:

const results = await govern.assessBatch([
{
model: 'claude-sonnet-4-20250514',
prompt: [{ role: 'user', content: prompts[0] }],
response: responses[0],
},
{
model: 'claude-sonnet-4-20250514',
prompt: [{ role: 'user', content: prompts[1] }],
response: responses[1],
},
]);
const violations = results.filter(r => r.action !== 'pass');
console.log(`${violations.length}/${results.length} assessments have violations`);

Middleware pattern (Express)

import express from 'express';
import { GovernMiddleware } from '@archetypal-ai/govern/middleware';
const app = express();
app.use('/api/ai', GovernMiddleware({
govern,
extractPrompt: (req) => req.body.messages,
extractResponse: (res) => res.body.content,
onViolation: (req, res, assessment) => {
res.status(422).json({ error: 'Policy violation', violations: assessment.violations });
},
}));

Error handling

import { GovernError, GovernAuthError, GovernRateLimitError } from '@archetypal-ai/govern';
try {
const assessment = await govern.assess({ ... });
} catch (error) {
if (error instanceof GovernAuthError) {
// Invalid API key
} else if (error instanceof GovernRateLimitError) {
// Rate limit hit — retry after error.retryAfterMs
} else if (error instanceof GovernError) {
// Other GOVERN error
}
// With failOpen: true (default), SDK errors never propagate as thrown exceptions
// They are returned as assessment.action === 'pass' with assessment.error set
}

TypeScript types

All types are exported from @archetypal-ai/govern/types:

import type {
AssessmentInput,
AssessmentResult,
GovernClientOptions,
ScorerName,
Violation,
} from '@archetypal-ai/govern/types';