|
| 1 | +/** |
| 2 | + * Guard Error Handling Example |
| 3 | + * ============================= |
| 4 | + * Demonstrates that real guard errors (network timeout, HTTP failure, code bug) |
| 5 | + * propagate as GuardExecutionError — they are NOT silently treated as logical |
| 6 | + * failures. This matches Python SDK behavior. |
| 7 | + * |
| 8 | + * Each example verifies: |
| 9 | + * - GuardExecutionError is thrown to the caller |
| 10 | + * - The guard span gets ERROR OTel status + error.type/error.message attributes |
| 11 | + * |
| 12 | + * Check the Traceloop UI after running — look for spans with red ERROR status. |
| 13 | + * |
| 14 | + * Run: |
| 15 | + * npm run build && node dist/src/guardrails/error_handling.js |
| 16 | + * |
| 17 | + * Environment: |
| 18 | + * TRACELOOP_API_KEY — your Traceloop API key |
| 19 | + * TRACELOOP_BASE_URL — https://api.traceloop.dev |
| 20 | + */ |
| 21 | + |
| 22 | +// ── Init — Traceloop FIRST ─────────────────────────────────────────────────── |
| 23 | +import * as traceloop from "@traceloop/node-server-sdk"; |
| 24 | + |
| 25 | +traceloop.initialize({ |
| 26 | + appName: "guardrails-error-handling-example", |
| 27 | + apiKey: process.env.TRACELOOP_API_KEY, |
| 28 | + baseUrl: process.env.TRACELOOP_BASE_URL, |
| 29 | + disableBatch: true, |
| 30 | + silenceInitializationMessage: true, |
| 31 | +}); |
| 32 | + |
| 33 | +import { |
| 34 | + Guardrails, |
| 35 | + validateContent, |
| 36 | + GuardExecutionError, |
| 37 | +} from "@traceloop/node-server-sdk"; |
| 38 | +import type { Guard } from "@traceloop/node-server-sdk"; |
| 39 | + |
| 40 | +// ── Helpers ─────────────────────────────────────────────────────────────────── |
| 41 | + |
| 42 | +function sep(title: string) { |
| 43 | + console.log(`\n${"─".repeat(60)}`); |
| 44 | + console.log(` ${title}`); |
| 45 | + console.log("─".repeat(60)); |
| 46 | +} |
| 47 | + |
| 48 | +// A guard that always throws a real error (simulates timeout / network failure) |
| 49 | +function makeErrorGuard(message: string): Guard { |
| 50 | + const g: Guard = async (_input) => { |
| 51 | + throw new Error(message); |
| 52 | + }; |
| 53 | + g.guardName = "error-guard"; |
| 54 | + return g; |
| 55 | +} |
| 56 | + |
| 57 | +// A guard that always passes — used alongside error guards in multi-guard cases |
| 58 | +const alwaysPass: Guard = Object.assign( |
| 59 | + async (_input: Record<string, unknown>) => true, |
| 60 | + { guardName: "always-pass" }, |
| 61 | +); |
| 62 | + |
| 63 | +// ── Example 1: validateContent() propagates GuardExecutionError ───────────────────── |
| 64 | + |
| 65 | +async function example1_validateThrows(): Promise<void> { |
| 66 | + sep("EXAMPLE 1 — validateContent() throws GuardExecutionError on real error"); |
| 67 | + |
| 68 | + console.log( |
| 69 | + " Running validateContent() with a guard that throws a network error...", |
| 70 | + ); |
| 71 | + |
| 72 | + try { |
| 73 | + await validateContent("some LLM output", [ |
| 74 | + makeErrorGuard("Simulated network timeout"), |
| 75 | + ]); |
| 76 | + console.log(" ❌ ERROR: validateContent() should have thrown but didn't"); |
| 77 | + } catch (err) { |
| 78 | + if (err instanceof GuardExecutionError) { |
| 79 | + console.log(" ✅ GuardExecutionError thrown as expected"); |
| 80 | + console.log(` .message: "${err.message}"`); |
| 81 | + console.log( |
| 82 | + ` .originalException: "${err.originalException.message}"`, |
| 83 | + ); |
| 84 | + console.log(` .guardIndex: ${err.guardIndex}`); |
| 85 | + console.log( |
| 86 | + " ℹ️ Check Traceloop UI: error-guard.guard span → ERROR status,", |
| 87 | + ); |
| 88 | + console.log(" gen_ai.guardrail.error.type = Error,"); |
| 89 | + console.log( |
| 90 | + " gen_ai.guardrail.error.message = Simulated network timeout", |
| 91 | + ); |
| 92 | + } else { |
| 93 | + console.log(" ❌ Wrong error type thrown:", err); |
| 94 | + } |
| 95 | + } |
| 96 | +} |
| 97 | + |
| 98 | +// ── Example 2: run() propagates GuardExecutionError ────────────────────────── |
| 99 | + |
| 100 | +async function example2_runThrows(): Promise<void> { |
| 101 | + sep("EXAMPLE 2 — run() throws GuardExecutionError on real error"); |
| 102 | + |
| 103 | + console.log( |
| 104 | + " Running Guardrails.run() with a guard that throws an HTTP error...", |
| 105 | + ); |
| 106 | + |
| 107 | + const g = new Guardrails([makeErrorGuard("HTTP 503: Service Unavailable")], { |
| 108 | + onFailure: "log", |
| 109 | + }); |
| 110 | + |
| 111 | + try { |
| 112 | + await g.run(async () => "LLM response text"); |
| 113 | + console.log(" ❌ ERROR: run() should have thrown but didn't"); |
| 114 | + } catch (err) { |
| 115 | + if (err instanceof GuardExecutionError) { |
| 116 | + console.log( |
| 117 | + " ✅ GuardExecutionError thrown — onFailure='log' was NOT called", |
| 118 | + ); |
| 119 | + console.log(` .message: "${err.message}"`); |
| 120 | + console.log( |
| 121 | + ` .originalException: "${err.originalException.message}"`, |
| 122 | + ); |
| 123 | + console.log( |
| 124 | + " ℹ️ Check Traceloop UI: error-guard.guard span → ERROR status", |
| 125 | + ); |
| 126 | + } else { |
| 127 | + console.log(" ❌ Wrong error type thrown:", err); |
| 128 | + } |
| 129 | + } |
| 130 | +} |
| 131 | + |
| 132 | +// ── Example 3: parallel().runAll() — one guard errors, one passes ───────────── |
| 133 | + |
| 134 | +async function example3_parallelRunAllThrows(): Promise<void> { |
| 135 | + sep( |
| 136 | + "EXAMPLE 3 — parallel().runAll() propagates error even when another guard passes", |
| 137 | + ); |
| 138 | + |
| 139 | + console.log( |
| 140 | + " Running 2 guards in parallel (runAll): alwaysPass + errorGuard...", |
| 141 | + ); |
| 142 | + |
| 143 | + const g = new Guardrails( |
| 144 | + [alwaysPass, makeErrorGuard("Evaluator API returned 500")], |
| 145 | + {}, |
| 146 | + ) |
| 147 | + .parallel() |
| 148 | + .runAll(); |
| 149 | + |
| 150 | + try { |
| 151 | + await g.run(async () => "LLM response text"); |
| 152 | + console.log(" ❌ ERROR: run() should have thrown but didn't"); |
| 153 | + } catch (err) { |
| 154 | + if (err instanceof GuardExecutionError) { |
| 155 | + console.log( |
| 156 | + " ✅ GuardExecutionError propagated from parallel().runAll()", |
| 157 | + ); |
| 158 | + console.log(` .message: "${err.message}"`); |
| 159 | + console.log( |
| 160 | + ` .originalException: "${err.originalException.message}"`, |
| 161 | + ); |
| 162 | + console.log(` .guardIndex: ${err.guardIndex}`); |
| 163 | + console.log(" ℹ️ Check Traceloop UI: always-pass.guard → PASSED,"); |
| 164 | + console.log(" error-guard.guard → ERROR with full exception event"); |
| 165 | + } else { |
| 166 | + console.log(" ❌ Wrong error type thrown:", err); |
| 167 | + } |
| 168 | + } |
| 169 | +} |
| 170 | + |
| 171 | +// ── Main ────────────────────────────────────────────────────────────────────── |
| 172 | + |
| 173 | +async function main(): Promise<void> { |
| 174 | + console.log(`\n${"═".repeat(60)}`); |
| 175 | + console.log(" GUARDRAILS ERROR HANDLING EXAMPLE"); |
| 176 | + console.log( |
| 177 | + ` Backend: ${process.env.TRACELOOP_BASE_URL ?? "https://api.traceloop.dev"}`, |
| 178 | + ); |
| 179 | + console.log(`${"═".repeat(60)}`); |
| 180 | + console.log( |
| 181 | + "\n Real guard errors throw GuardExecutionError — never silently", |
| 182 | + ); |
| 183 | + console.log(" treated as logical failures. Check spans for ERROR status.\n"); |
| 184 | + |
| 185 | + await traceloop.withWorkflow( |
| 186 | + { name: "guardrails-error-handling-workflow" }, |
| 187 | + async () => { |
| 188 | + await example1_validateThrows(); |
| 189 | + await example2_runThrows(); |
| 190 | + await example3_parallelRunAllThrows(); |
| 191 | + }, |
| 192 | + ); |
| 193 | + |
| 194 | + console.log(`\n${"═".repeat(60)}`); |
| 195 | + console.log(" ALL EXAMPLES COMPLETE"); |
| 196 | + console.log(`${"═".repeat(60)}\n`); |
| 197 | + |
| 198 | + await traceloop.forceFlush(); |
| 199 | +} |
| 200 | + |
| 201 | +main(); |
0 commit comments