Skip to navigation

Node.js Examples

Node.js Examples

Integrate GovernanceAI with Node.js applications.

Installation

npm install axios dotenv

Basic Setup

require('dotenv').config();
const axios = require('axios');
const API_KEY = process.env.GOVERNANCEAI_API_KEY;
const ORG_ID = process.env.GOVERNANCEAI_ORG_ID;
const BASE_URL = 'https://api.governanceai.com/v1';
const client = axios.create({
baseURL: BASE_URL,
headers: {
'Authorization': `Bearer ${API_KEY}`,
'Content-Type': 'application/json'
}
});

Evaluate Guardrails

async function evaluateGuardrails(userMessage, userId) {
try {
const response = await client.post('/guardrails/evaluate', {
messages: [
{
role: 'user',
content: userMessage
}
],
context: {
org_id: ORG_ID,
user_id: userId
}
});
return {
decision: response.data.decision,
riskScore: response.data.risk_score,
violations: response.data.policy_violations
};
} catch (error) {
console.error('Guardrail evaluation failed:', error.message);
throw error;
}
}
// Usage
const result = await evaluateGuardrails(
"What is the capital of France?",
"user_123"
);
console.log(`Decision: ${result.decision}`);
console.log(`Risk Score: ${result.riskScore}`);

Create Policy

async function createPolicy(policyName, guardrailIds) {
const response = await client.post('/policies', {
name: policyName,
guardrail_ids: guardrailIds,
scope: 'organization',
enforcement: {
mode: 'blocking',
log_violations: true
}
});
return response.data;
}
// Usage
const policy = await createPolicy(
'Production Safety',
['guardrail_pii', 'guardrail_toxic']
);
console.log(`Policy created: ${policy.policy_id}`);

Run Scan with Async/Await

async function runScan(scanType, repositories) {
// Start scan
const scanResponse = await client.post('/scans', {
scan_type: scanType,
repositories: repositories
});
const scanId = scanResponse.data.scan_id;
console.log(`Scan started: ${scanId}`);
// Poll for completion
let completed = false;
let results = null;
while (!completed) {
const statusResponse = await client.get(`/scans/${scanId}`);
const scan = statusResponse.data;
if (scan.status === 'completed') {
completed = true;
results = scan;
} else {
// Wait 5 seconds before polling again
await new Promise(resolve => setTimeout(resolve, 5000));
}
}
return results;
}
// Usage
const scanResults = await runScan('code_scan', ['repo_1', 'repo_2']);
console.log(`Found ${scanResults.models_found} models`);

Error Handling

async function makeRequest(method, endpoint, data = null) {
try {
let response;
if (method === 'GET') {
response = await client.get(endpoint);
} else if (method === 'POST') {
response = await client.post(endpoint, data);
}
return response.data;
} catch (error) {
if (error.response?.status === 401) {
throw new Error('Invalid API key');
} else if (error.response?.status === 403) {
throw new Error('Insufficient permissions');
} else if (error.response?.status >= 500) {
throw new Error('Server error - try again later');
} else if (error.message === 'Network Error') {
throw new Error('Network error - check your connection');
}
throw error;
}
}

TypeScript Support

interface GuardrailEvaluationResult {
decision: 'allow' | 'block' | 'transform';
riskScore: number;
violations: any[];
}
async function evaluateGuardrails(
userMessage: string,
userId: string
): Promise<GuardrailEvaluationResult> {
const response = await client.post('/guardrails/evaluate', {
messages: [{ role: 'user', content: userMessage }],
context: { org_id: ORG_ID, user_id: userId }
});
return {
decision: response.data.decision,
riskScore: response.data.risk_score,
violations: response.data.policy_violations
};
}

Next Steps