evalguardai-openai
Drop-in OpenAI SDK wrapper that adds real-time guardrails, trace logging, and cost tracking via EvalGuard.
Installation
npm install evalguardai-openai openai
Quick Start
import OpenAI from "openai";
import { wrapOpenAI } from "evalguardai-openai";
const openai = wrapOpenAI(new OpenAI(), {
apiKey: "eg_...",
projectId: "proj_...",
});
const response = await openai.chat.completions.create({
model: "gpt-4o",
messages: [{ role: "user", content: "Hello, how are you?" }],
});
console.log(response.choices[0].message.content);
Streaming
Streaming works transparently. The wrapper intercepts chunks to log the assembled response without affecting stream behavior.
const stream = await openai.chat.completions.create({
model: "gpt-4o",
messages: [{ role: "user", content: "Write a poem about AI safety" }],
stream: true,
});
for await (const chunk of stream) {
process.stdout.write(chunk.choices[0]?.delta?.content ?? "");
}
Configuration
const openai = wrapOpenAI(new OpenAI(), {
apiKey: "eg_...",
baseUrl: "https://your-evalguard-instance.com/api/v1",
blockOnViolation: true,
enableLogging: true,
projectId: "proj_...",
metadata: { environment: "production", service: "chatbot" },
onViolation: (result) => {
console.warn("Guardrail violation:", result.violations);
},
});
What It Does
| Pre-request | Sends the prompt to EvalGuard's firewall for prompt injection detection, PII scanning, and toxicity checks |
| LLM call | Passes through to the real OpenAI API unchanged |
| Post-response | Logs model, tokens, latency, cost, and guardrail results as a trace to EvalGuard |
Fail-Open Design
If EvalGuard is unreachable (network error, timeout, 5xx), the wrapper passes requests through to OpenAI directly. Your application never breaks because of EvalGuard downtime.
Error Handling
When blockOnViolation is true (default) and a guardrail check fails:
import { EvalGuardViolationError } from "evalguardai-openai";
try {
const response = await openai.chat.completions.create({
model: "gpt-4o",
messages: [{ role: "user", content: "malicious prompt..." }],
});
} catch (error) {
if (error instanceof EvalGuardViolationError) {
console.log("Blocked:", error.violations);
}
}
Set blockOnViolation: false to log violations without blocking:
const openai = wrapOpenAI(new OpenAI(), {
apiKey: "eg_...",
blockOnViolation: false,
onViolation: (result) => {
analytics.track("guardrail_violation", result);
},
});
License
MIT