Node.js Examples
Complete JavaScript and TypeScript examples for integrating AletheionGuard with Node.js, Express, Next.js, and modern frameworks.
Express.js Integration
Build an Express API with epistemic uncertainty auditing middleware.
Basic Setup
// server.js
const express = require("express")
const axios = require("axios")
const app = express()
app.use(express.json())
// AletheionGuard API client
const ALETHEION_API = "https://aletheionguard.onrender.com/v1"
const API_KEY = process.env.ALETHEION_API_KEY
const auditText = async (text, context = null) => {
const response = await axios.post(
`${ALETHEION_API}/audit`,
{ text, context },
{ headers: { "X-API-Key": API_KEY } }
)
return response.data
}
// Route with auditing
app.post("/ask", async (req, res) => {
const { question } = req.body
try {
// Generate answer (your logic here)
const answer = await generateAnswer(question)
// Audit the answer
const audit = await auditText(answer, question)
if (audit.verdict === "REFUSED") {
return res.status(503).json({
error: "Cannot provide confident answer",
audit
})
}
res.json({ answer, audit })
} catch (error) {
res.status(500).json({ error: error.message })
}
})
app.listen(3000, () => console.log("Server running on port 3000"))
Audit Middleware
// middleware/audit.js
const axios = require("axios")
const auditMiddleware = (options = {}) => {
const { minHeight = 0.6, field = "answer" } = options
return async (req, res, next) => {
// Intercept res.json to audit response
const originalJson = res.json
res.json = async function(data) {
if (data && data[field]) {
try {
const response = await axios.post(
"https://aletheionguard.onrender.com/v1/audit",
{ text: data[field] },
{ headers: { "X-API-Key": process.env.ALETHEION_API_KEY } }
)
const audit = response.data
data._audit = {
verdict: audit.verdict,
height: audit.height
}
if (audit.height < minHeight) {
data.warning = "Low confidence response"
}
} catch (error) {
console.error("Audit failed:", error)
}
}
return originalJson.call(this, data)
}
next()
}
}
module.exports = auditMiddleware
// Usage
app.use(auditMiddleware({ minHeight: 0.7 }))
TypeScript Integration
Type-safe integration with TypeScript for better developer experience.
// types/aletheion.ts
export interface AuditResult {
q1: number
q2: number
height: number
verdict: "ACCEPT" | "MAYBE" | "REFUSED"
ece: number
brier: number
}
export interface AuditRequest {
text: string
context?: string
model_source?: string
}
// services/aletheion.ts
import axios, { AxiosInstance } from "axios"
import { AuditResult, AuditRequest } from "../types/aletheion"
export class AletheionClient {
private client: AxiosInstance
constructor(apiKey: string, baseURL = "https://aletheionguard.onrender.com/v1") {
this.client = axios.create({
baseURL,
headers: { "X-API-Key": apiKey }
})
}
async audit(request: AuditRequest): Promise<AuditResult> {
const response = await this.client.post<AuditResult>("/audit", request)
return response.data
}
async batchAudit(texts: string[]): Promise<AuditResult[]> {
const response = await this.client.post<AuditResult[]>("/batch", {
texts,
batch_size: 32
})
return response.data
}
}
// Usage
const client = new AletheionClient(process.env.ALETHEION_API_KEY!)
const result = await client.audit({ text: "Paris is the capital" })
Next.js API Routes
Integrate AletheionGuard with Next.js API routes and Server Actions.
API Route Handler
// app/api/audit/route.ts
import { NextRequest, NextResponse } from "next/server"
export async function POST(request: NextRequest) {
try {
const { text, context } = await request.json()
// Call AletheionGuard API
const response = await fetch(
"https://aletheionguard.onrender.com/v1/audit",
{
method: "POST",
headers: {
"X-API-Key": process.env.ALETHEION_API_KEY!,
"Content-Type": "application/json"
},
body: JSON.stringify({ text, context })
}
)
const audit = await response.json()
return NextResponse.json(audit)
} catch (error) {
return NextResponse.json(
{ error: "Failed to audit text" },
{ status: 500 }
)
}
}
Server Action
// app/actions/audit.ts
"use server"
export async function auditText(text: string, context?: string) {
const response = await fetch(
"https://aletheionguard.onrender.com/v1/audit",
{
method: "POST",
headers: {
"X-API-Key": process.env.ALETHEION_API_KEY!,
"Content-Type": "application/json"
},
body: JSON.stringify({ text, context }),
cache: "no-store"
}
)
return response.json()
}
// app/components/AuditForm.tsx
"use client"
import { auditText } from "@/app/actions/audit"
export function AuditForm() {
const handleSubmit = async (formData: FormData) => {
const text = formData.get("text") as string
const result = await auditText(text)
console.log(result)
}
return <form action={handleSubmit}>...</form>
}
NestJS Integration
Enterprise-grade integration with NestJS using services and interceptors.
Audit Service
// audit/audit.service.ts
import { Injectable, HttpService } from "@nestjs/common"
import { ConfigService } from "@nestjs/config"
@Injectable()
export class AuditService {
private readonly apiKey: string
private readonly baseURL: string
constructor(
private httpService: HttpService,
private configService: ConfigService
) {
this.apiKey = configService.get("ALETHEION_API_KEY")
this.baseURL = "https://aletheionguard.onrender.com/v1"
}
async audit(text: string, context?: string) {
const response = await this.httpService
.post(`${this.baseURL}/audit`, { text, context }, {
headers: { "X-API-Key": this.apiKey }
})
.toPromise()
return response.data
}
}
Audit Interceptor
// audit/audit.interceptor.ts
import { Injectable, NestInterceptor, ExecutionContext, CallHandler }
from "@nestjs/common"
import { Observable } from "rxjs"
import { map } from "rxjs/operators"
import { AuditService } from "./audit.service"
@Injectable()
export class AuditInterceptor implements NestInterceptor {
constructor(private auditService: AuditService) {}
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
return next.handle().pipe(
map(async (data) => {
if (data?.answer) {
const audit = await this.auditService.audit(data.answer)
return { ...data, _audit: audit }
}
return data
})
)
}
}
// Usage in controller
@UseInterceptors(AuditInterceptor)
@Post("/ask")
async ask(@Body() dto: AskDto) {
return { answer: await this.generateAnswer(dto.question) }
}
Streaming with Real-time Audit
Stream LLM responses while auditing chunks in real-time.
// streaming-audit.ts
import { OpenAI } from "openai"
import axios from "axios"
const openai = new OpenAI()
async function streamWithAudit(question: string) {
let fullResponse = ""
// Stream from OpenAI
const stream = await openai.chat.completions.create({
model: "gpt-4",
messages: [{ role: "user", content: question }],
stream: true
})
for await (const chunk of stream) {
const content = chunk.choices[0]?.delta?.content || ""
fullResponse += content
// Yield chunk to client
process.stdout.write(content)
}
// Audit complete response
const auditResponse = await axios.post(
"https://aletheionguard.onrender.com/v1/audit",
{ text: fullResponse, context: question },
{ headers: { "X-API-Key": process.env.ALETHEION_API_KEY } }
)
return {
response: fullResponse,
audit: auditResponse.data
}
}
Rate Limiting and Caching
Implement intelligent caching and rate limiting for optimal performance.
// utils/audit-cache.ts
import { createHash } from "crypto"
import { Redis } from "ioredis"
import axios from "axios"
const redis = new Redis(process.env.REDIS_URL)
export async function auditWithCache(
text: string,
context?: string
) {
// Generate cache key
const hash = createHash("sha256")
.update(`${text}:${context || ''}`)
.digest("hex")
const cacheKey = `audit:${hash}`
// Check cache
const cached = await redis.get(cacheKey)
if (cached) {
return JSON.parse(cached)
}
// Audit via API
const response = await axios.post(
"https://aletheionguard.onrender.com/v1/audit",
{ text, context },
{ headers: { "X-API-Key": process.env.ALETHEION_API_KEY } }
)
// Cache for 1 hour
await redis.setex(cacheKey, 3600, JSON.stringify(response.data))
return response.data
}
Testing with Jest
Write tests for your AletheionGuard integration using Jest and mocks.
// __tests__/audit.test.ts
import axios from "axios"
import { auditText } from "../services/audit"
jest.mock("axios")
const mockedAxios = axios as jest.Mocked<typeof axios>
describe("AletheionGuard Audit", () => {
it("should return ACCEPT for confident text", async () => {
mockedAxios.post.mockResolvedValue({
data: {
verdict: "ACCEPT",
q1: 0.08,
q2: 0.05,
height: 0.90
}
})
const result = await auditText("Paris is the capital of France")
expect(result.verdict).toBe("ACCEPT")
expect(result.height).toBeGreaterThan(0.8)
})
it("should return REFUSED for uncertain text", async () => {
mockedAxios.post.mockResolvedValue({
data: {
verdict: "REFUSED",
q1: 0.25,
q2: 0.68,
height: 0.32
}
})
const result = await auditText("Bitcoin will hit $1M tomorrow")
expect(result.verdict).toBe("REFUSED")
})
})