Skip to content

TypeScript SDK

The TruthVouch TypeScript SDK provides drop-in replacements for OpenAI, Anthropic, and Google Gemini providers. Route all LLM calls through the Governance Gateway with zero runtime dependencies.

Installation

Terminal window
npm install @truthvouch/sdk

Or with other package managers:

Terminal window
yarn add @truthvouch/sdk
pnpm add @truthvouch/sdk

Requires Node.js 18+.


Quick Start

1. Initialize the Client

import { TruthVouch } from '@truthvouch/sdk';
const client = new TruthVouch({
apiKey: process.env.TRUTHVOUCH_API_KEY,
gatewayUrl: 'https://gateway.truthvouch.com',
failMode: 'open', // or 'closed'
});

2. Call an LLM Provider

// OpenAI
const response = await client.chat.create({
model: 'gpt-4o',
messages: [{ role: 'user', content: 'Explain quantum computing' }],
});
console.log(response.content);
console.log(response.governance.verdict);

3. Check Governance Results

const { governance } = response;
if (governance.verdict === 'blocked') {
console.warn('Request blocked by governance policy');
console.warn('Violations:', governance.policyViolations);
}
if (governance.piiDetected) {
console.warn('PII detected in response');
}
if (governance.truthScan) {
console.log(`Hallucination confidence: ${governance.truthScan.confidence}`);
}

Provider Examples

OpenAI

const response = await client.chat.create({
model: 'gpt-4o',
messages: [{ role: 'user', content: 'Hello' }],
temperature: 0.7,
maxTokens: 1024,
});
console.log(response.content);
console.log(`Governance verdict: ${response.governance.verdict}`);

Streaming (OpenAI)

const stream = await client.chat.createStream({
model: 'gpt-4o',
messages: [{ role: 'user', content: 'Write a poem' }],
});
for await (const chunk of stream) {
if (!chunk.isLast) {
process.stdout.write(chunk.content ?? '');
}
}
// Governance report available after streaming completes
const governance = stream.getGovernanceReport();
console.log(`Final verdict: ${governance?.verdict}`);

Anthropic

const response = await client.messages.create({
model: 'claude-3-5-sonnet-20241022',
maxTokens: 1024,
messages: [{ role: 'user', content: 'What is machine learning?' }],
system: 'You are a helpful AI assistant.',
});
console.log(response.content);
console.log(response.governance.piiDetected);

Google Gemini

const response = await client.google.generateContent({
model: 'gemini-1.5-pro',
contents: [{ role: 'user', parts: 'Translate "hello" to French' }],
});
console.log(response.text);
console.log(response.governance.verdict);

Manual Scanning

Verify text without routing through an LLM:

const scanResult = await client.scan.scan({
prompt: 'User input here',
response: 'LLM output here',
});
console.log(scanResult.governance.verdict);
console.log(scanResult.alerts);

Batch Scanning

Submit a document corpus for offline governance analysis:

// Submit batch job
const job = await client.batch.submit({
sourceUrl: 's3://my-bucket/documents.jsonl',
format: 'jsonl',
scanMode: 'deep', // 'fast' | 'standard' | 'deep'
callbackUrl: 'https://example.com/webhook',
});
console.log(`Batch job submitted: ${job.id}`);
console.log(`Estimated completion: ${job.estimatedCompletion}`);
// Poll for status
const status = await client.batch.getStatus(job.id);
console.log(`Progress: ${status.progressPercent}%`);
console.log(`Flagged documents: ${status.flaggedCount}`);

Configuration

Configuration resolves in priority order:

  1. Constructor options (highest)
  2. Environment variables
  3. .truthvouch.json file (in process.cwd())
  4. Defaults (lowest)

Configuration Reference

OptionTypeDefaultDescription
apiKeystring(required)TruthVouch API key
gatewayUrlstringhttps://gateway.truthvouch.comGateway base URL
failMode’open’ | ‘closed''open’Behavior when gateway unreachable
timeoutMsnumber30000HTTP request timeout
maxRetriesnumber3Retry attempts for transient errors
circuitBreakerFailureThresholdnumber5Failures before circuit opens
circuitBreakerRecoveryMsnumber60000Time before recovery probe
telemetryEnabledbooleanfalseEnable OpenTelemetry recording

Error Handling

import {
TruthVouchError,
GatewayUnreachableError,
PolicyBlockedError,
AuthenticationError,
QuotaExceededError,
InvalidRequestError,
UpstreamProviderError,
} from '@truthvouch/sdk';
try {
const response = await client.chat.create({
model: 'gpt-4o',
messages: [{ role: 'user', content: 'Hello' }],
});
} catch (error) {
if (error instanceof PolicyBlockedError) {
console.error('Governance policy violation:', error.governanceReport?.policyViolations);
} else if (error instanceof QuotaExceededError) {
console.error(`Rate limited. Retry after ${error.retryAfterMs}ms`);
} else if (error instanceof AuthenticationError) {
console.error('Invalid API key. Check your credentials.');
} else if (error instanceof GatewayUnreachableError) {
console.error('Gateway connection failed');
} else if (error instanceof UpstreamProviderError) {
console.error(`Upstream error (HTTP ${error.upstreamStatusCode})`);
} else {
throw error;
}
}

Webhook Verification

Verify signatures on incoming webhooks:

import { verifyWebhook } from '@truthvouch/sdk/webhooks';
export async function handleWebhook(req: Request): Promise<Response> {
const signature = req.headers.get('X-TruthVouch-Signature');
const secret = process.env.TRUTHVOUCH_WEBHOOK_SECRET;
if (!signature || !secret) {
return new Response('Missing signature or secret', { status: 401 });
}
const payload = await req.text();
const isValid = verifyWebhook({
payload,
signature,
secret,
});
if (!isValid) {
return new Response('Invalid signature', { status: 401 });
}
const event = JSON.parse(payload);
console.log('Webhook verified:', event);
return new Response('OK', { status: 200 });
}

Features

  • Multi-provider support — OpenAI, Anthropic, Google Gemini
  • Streaming SSE — Real-time governance with streamed responses
  • Batch scanning — Submit document corpora for offline analysis
  • Circuit breaker resilience — Automatic failover with configurable fallback modes
  • Comprehensive error handling — Typed exceptions for all failure scenarios
  • Webhook verification — Secure HMAC-SHA256 validation for webhooks
  • OpenTelemetry ready — Optional trace propagation and span recording
  • Zero runtime dependencies — Uses native fetch and crypto only

Verification API

Verify content independently of the gateway proxy — call the Trust API and data verification endpoints directly.

Verify Data Grounding

const result = await client.verify.dataGrounding({
query: 'What country had the highest uplift?',
response: 'Germany had the highest uplift at 23%.',
sql: 'SELECT country, uplift FROM sales ORDER BY uplift DESC',
rawResults: '[{"country": "France", "uplift": 0.181}]',
});
console.log(result.overallScore); // 0.15
console.log(result.verdict); // "contradicted"
for (const claim of result.claims) {
console.log(` ${claim.text}: ${claim.verdict} (score=${claim.score})`);
}

Verify a Claim

const result = await client.verify.claim('Paris is the capital of France', 'standard');
console.log(result.trustScore); // 0.97
console.log(result.verdict); // "accurate"

Check Faithfulness

const result = await client.verify.faithfulness(
'The project was completed in March 2026.',
'The project wrapped up during March 2026 after 3 months of development.',
'moderate',
);
console.log(result.score); // 0.95
console.log(result.faithful); // true

Evaluate Prompt Quality

const result = await client.verify.promptQuality(
'You are a financial advisor who can access customer account balances and make transfers...'
);
console.log(result.riskLevel); // "high"
console.log(result.issues); // ["privilege_escalation", "data_access_risk"]

License

Apache-2.0


Next Steps