JavaScript/TypeScript SDK
Official JavaScript client for the Creed Space Safety API.
Installation
bash
npm install @creed-space/sdk
# or
yarn add @creed-space/sdk
# or
pnpm add @creed-space/sdkQuick Start
typescript
import { CreedSpace } from '@creed-space/sdk';
const client = new CreedSpace({ apiKey: 'cs_live_...' });
const result = await client.safety.evaluate('Hello, how can I help?');
console.log(`Risk score: ${result.riskScore}`);
console.log(`Decision: ${result.decision}`);
console.log(`Blocked: ${result.isBlocked}`);Configuration
typescript
import { CreedSpace } from '@creed-space/sdk';
const client = new CreedSpace({
apiKey: 'cs_live_...',
baseUrl: 'https://api.creed.space', // Optional
timeout: 30000 // Request timeout in ms
});Environment Variables
typescript
const client = new CreedSpace({
apiKey: process.env.CREED_API_KEY!
});Safety Evaluation
Basic Evaluation
typescript
const result = await client.safety.evaluate('User message here');
if (result.decision === 'permit') {
// Safe to proceed
processMessage(message);
} else if (result.decision === 'forbid') {
// Block the content
console.log('Content blocked');
}With Context
typescript
const result = await client.safety.evaluate('I want to kill the boss', {
context: {
topic: 'video_game',
platform: 'gaming'
},
sessionId: 'user-123-session-456'
});Response Type
typescript
interface EvaluateResponse {
riskScore: number; // 0.0 - 1.0
decision: 'permit' | 'forbid' | 'divert' | 'depends';
isBlocked: boolean;
matchedRules: string[];
decisionTimeMs: number;
}PDP Adjudication
For complex policy decisions:
typescript
const decision = await client.pdp.adjudicate({
content: 'Content to evaluate',
context: { key: 'value' }
});
console.log(`Verdict: ${decision.verdict}`);
console.log(`Findings:`, decision.findings);Constitutions
List Available Constitutions
typescript
const constitutions = await client.constitutions.list();
constitutions.forEach(c => {
console.log(`${c.id}: ${c.name}`);
});Get Merged Constitution
typescript
const merged = await client.constitutions.getMerged('ambassador');
console.log(merged.principles);Error Handling
typescript
import { CreedSpace, CreedSpaceError, AuthenticationError, RateLimitError } from '@creed-space/sdk';
const client = new CreedSpace({ apiKey: '...' });
try {
const result = await client.safety.evaluate(text);
} catch (error) {
if (error instanceof AuthenticationError) {
console.log('Invalid API key');
} else if (error instanceof RateLimitError) {
console.log(`Rate limited. Retry after ${error.retryAfter}s`);
} else if (error instanceof CreedSpaceError) {
console.log(`API error: ${error.message}`);
}
}TypeScript Support
The SDK is written in TypeScript with full type definitions:
typescript
import { CreedSpace, EvaluateResponse, PDPDecision } from '@creed-space/sdk';
function processResult(result: EvaluateResponse): void {
if (result.riskScore > 0.5) {
console.log('High risk content');
}
}Examples
Express Middleware
typescript
import express from 'express';
import { CreedSpace } from '@creed-space/sdk';
const app = express();
const client = new CreedSpace({ apiKey: process.env.CREED_API_KEY! });
// Safety middleware
app.use('/api/chat', async (req, res, next) => {
const { message } = req.body;
try {
const result = await client.safety.evaluate(message);
if (result.decision === 'forbid') {
return res.status(400).json({
error: 'Content blocked',
reason: result.matchedRules
});
}
if (result.decision === 'divert') {
// Queue for human review
await queueForReview(req.user.id, message);
return res.json({ status: 'pending_review' });
}
next();
} catch (error) {
console.error('Safety check failed:', error);
next(error);
}
});React Hook
typescript
import { useState, useCallback } from 'react';
import { CreedSpace } from '@creed-space/sdk';
const client = new CreedSpace({ apiKey: '...' });
function useSafetyCheck() {
const [loading, setLoading] = useState(false);
const [result, setResult] = useState(null);
const checkSafety = useCallback(async (text: string) => {
setLoading(true);
try {
const evaluation = await client.safety.evaluate(text);
setResult(evaluation);
return evaluation;
} finally {
setLoading(false);
}
}, []);
return { checkSafety, loading, result };
}
// Usage
function ChatInput() {
const { checkSafety, loading } = useSafetyCheck();
const handleSubmit = async (message: string) => {
const result = await checkSafety(message);
if (result.decision === 'permit') {
sendMessage(message);
} else {
showWarning('Message blocked');
}
};
}Next.js API Route
typescript
// app/api/moderate/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { CreedSpace } from '@creed-space/sdk';
const client = new CreedSpace({ apiKey: process.env.CREED_API_KEY! });
export async function POST(req: NextRequest) {
const { text } = await req.json();
const result = await client.safety.evaluate(text);
return NextResponse.json({
safe: result.decision === 'permit',
riskScore: result.riskScore,
decision: result.decision
});
}Browser Usage
For browser environments, use a server-side proxy to protect your API key:
typescript
// Server-side proxy
app.post('/api/safety-check', async (req, res) => {
const result = await client.safety.evaluate(req.body.text);
res.json(result);
});
// Client-side
const response = await fetch('/api/safety-check', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ text: userInput })
});
const result = await response.json();WARNING
Never expose your API key in client-side code. Always use a server-side proxy.