Guardrails
Guardrails let you validate, sanitize, or block data before it reaches the model or before results are returned to the user.
Interface
interface Guardrail {
name: string;
validateInput?(input: string): Promise<GuardrailResult> | GuardrailResult;
validateOutput?(message: Message): Promise<GuardrailResult> | GuardrailResult;
}
interface GuardrailResult {
valid: boolean;
message?: string; // Shown in error/event if invalid
}
Input Guardrail
Blocks dangerous or unwanted input before it reaches the LLM:
import { Guardrail } from 'gravity-sdk';
const profanityGuard: Guardrail = {
name: 'ProfanityFilter',
validateInput: (input) => {
const blocked = ['spam', 'hack', 'exploit'];
const found = blocked.find(w => input.toLowerCase().includes(w));
if (found) return { valid: false, message: `Blocked keyword: "${found}"` };
return { valid: true };
},
};
Output Guardrail
Validates or sanitizes the model's response before returning it:
const lengthGuard: Guardrail = {
name: 'ResponseLengthGuard',
validateOutput: (message) => {
if (message.content.length > 5000) {
return { valid: false, message: 'Response too long' };
}
return { valid: true };
},
};
Attaching Guardrails
const agent = new Agent({
name: 'SafeBot',
instructions: 'You are a helpful assistant.',
model: new DeepSeekProvider(),
memory: new InMemoryProvider(),
guardrails: [profanityGuard, lengthGuard],
});
Guardrail Events
When a guardrail rejects input or output, the guardrail_triggered event fires:
emitter.on('guardrail_triggered', (e) => {
if (e.type === 'guardrail_triggered') {
console.warn(`[Guardrail] ${e.message}`);
}
});
If a guardrail returns valid: false, the agent run throws an error immediately — no LLM call is made.