Middlewares

NodeLLM’s middleware system allows you to intercept, monitor, and modify LLM interactions at the infrastructure level. This is essential for building production-grade systems that require observability, auditing, cost tracking, and safety.

  1. Why Middlewares?
  2. Basic Usage
  3. The Middleware Interface (v1.10.0+)
  4. Common Use Cases
    1. 1. PII Redaction (Security)
    2. 2. Cost & Performance Tracking
    3. Watching Fallbacks and Tool Search
  5. Middleware Execution Order (v1.10.0+)
    1. Example Lifecycle
  6. Lifecycle Directives (RETRY | REPLACE | STOP) v1.15.0+
  7. Standard Middleware Library v1.10.0+
    1. 1. PIIMaskMiddleware
    2. 2. CostGuardMiddleware
    3. 3. UsageLoggerMiddleware
    4. 4. OpenTelemetry v1.20.0+
  8. Global Middlewares v1.10.0+
  9. Integration with @node-llm/orm

Why Middlewares?

In a production environment, you rarely want to call an LLM directly without additional logic. Middlewares allow you to separate these cross-cutting concerns from your business logic:

  • Observability: Log requests, responses, and errors to external systems.
  • Cost Tracking: Calculate and record the token usage and cost of every request.
  • Security & Compliance: Redact PII (Personally Identifiable Information) before it segments to the LLM.
  • Auditing: Maintain a permanent audit trail of all AI interactions.
  • Performance: Track latency and success rates across different models.
  • Quality: Automatically verify the integrity of the response.

Basic Usage

Middlewares are passed when creating a chat instance. You can pass a single middleware or an array of middlewares.

import { NodeLLM, Middleware, ChatResponseString } from "@node-llm/core";

const myMiddleware: Middleware = {
  name: "MyMiddleware",
  onRequest: async (context) => {
    console.log(`[Request] Sending to ${context.model}`);
  },
  onResponse: async (context, result) => {
    // result is NodeLLMResponse (union of Chat, Image, Transcription, etc.)
    if (result instanceof ChatResponseString) {
      console.log(`[Response] Received ${result.usage.total_tokens} tokens`);
    }
  }
};

const chat = NodeLLM.chat("gpt-5", {
  middlewares: [myMiddleware]
});

await chat.ask("Hello world");

The Middleware Interface (v1.10.0+)

A middleware consists of a unique name and several optional hooks that cover the entire lifecycle of an LLM request, including tool execution.

 interface Middleware {
   name: string;
   onRequest?: (context: MiddlewareContext) => Promise<void>;
   onResponse?: (context: MiddlewareContext, result: NodeLLMResponse) => Promise<RequestDirective>;
   onError?: (context: MiddlewareContext, error: Error) => Promise<RequestDirective>;
   
   // Tool Execution Hooks
   onToolCallStart?: (context: MiddlewareContext, tool: ToolCall) => Promise<void>;
   onToolCallEnd?: (context: MiddlewareContext, tool: ToolCall, result: unknown) => Promise<void>;
   onToolCallError?: (context: MiddlewareContext, tool: ToolCall, error: Error) => Promise<ToolErrorDirective>;

   // Model fallbacks (v1.21.0+)
   onFallback?: (context: MiddlewareContext, event: FallbackEvent) => Promise<void>;
 }

Warning: Since v1.10.0, the onResponse hook receives a NodeLLMResponse union. You must use a type guard (like instanceof ChatResponseString) before accessing chat-specific properties like usage or content.

### MiddlewareContext The context object is persistent across the lifecycle of a single request and provides deep access to the execution state:

  • requestId: A unique UUID for tracing the request.
  • provider: The provider name (e.g., “openai”, “anthropic”).
  • model: The model identifier.
  • messages: The conversation history (mutable in onRequest).
  • options: The ChatOptions for the request (mutable in onRequest).
  • state: A record for sharing data between hooks in the same middleware (e.g., storing a timer).
  • metadata: Custom metadata passed to the request.
  • Operation Specifics: input (Embeddings), imageOptions (Paint), etc.

Common Use Cases

1. PII Redaction (Security)

Redact sensitive information before it reaches the provider.

const piiMiddleware = {
  name: "PIIRedactor",
  onRequest: async (context) => {
    context.messages.forEach(msg => {
      msg.content = msg.content.replace(/\b\d{4}-\d{4}-\d{4}-\d{4}\b/g, "[REDACTED_CC]");
    });
  }
}

2. Cost & Performance Tracking

Use standard telemetry patterns to track your infrastructure.

const perfMiddleware = {
  name: "PerformanceTracker",
  onRequest: async (context) => {
    context.state.startTime = Date.now();
  },
  onResponse: async (context, result) => {
    const latency = Date.now() - (context.state.startTime as number);
    
    // Safety check for usage metrics
    if (result instanceof ChatResponseString) {
      const cost = calculateCost(context.model, result.usage);
      await db.metrics.create({ model: context.model, latency, cost });
    }
  }
}

  • onFallback runs when a chat request failed and is about to go to a fallback model (see Model Fallbacks). It gets the same context as the rest of the request and an event with error, from, to and attempt. The response that follows reports the model and provider that answered.
  • Tool search needs no hook of its own. Loading deferred tools is a call to the tool_search tool, so onToolCallStart and onToolCallEnd see it like any other tool. The result is JSON whose loaded field lists the tools it loaded.
const fallbackLogger: Middleware = {
  name: "FallbackLogger",
  onFallback: async (context, { from, to, error }) => {
    console.warn(`[${context.requestId}] ${from.model} failed (${(error as Error).message}), trying ${to.model}`);
  }
};

Middleware Execution Order (v1.10.0+)

Middlewares are executed as a stack (Onion model). This ensures that outer middlewares (like loggers) can correctly wrap and observe the transformations made by inner middlewares (like security maskers).

  • onRequest: Executed in order (first to last).
  • onToolCallStart: Executed in order (first to last).
  • onToolCallEnd: Executed in REVERSE order (last to first).
  • onToolCallError: Executed in REVERSE order (last to first).
  • onResponse: Executed in REVERSE order (last to first).
  • onError: Executed in REVERSE order (last to first).

Example Lifecycle

If you have two middlewares: [Logger, Security], the execution order for a successful tool-calling request is:

  1. Logger.onRequest
  2. Security.onRequest
  3. Logger.onToolCallStart
  4. Security.onToolCallStart
  5. … Tool Execution …
  6. Security.onToolCallEnd
  7. Logger.onToolCallEnd
  8. Security.onResponse
  9. Logger.onResponse

Lifecycle Directives (RETRY | REPLACE | STOP) v1.15.0+

onResponse and onError aren’t limited to observing — they can return a RequestDirective to control what happens next:

type RequestDirective =
  | { action: "RETRY"; message: string }   // Push `message` to history and ask the model again
  | { action: "REPLACE"; response: NodeLLMResponse } // Swap in a different response entirely
  | "CONTINUE" // Proceed normally (equivalent to returning nothing)
  | "STOP"     // Abort the request and throw
  | void;

This is what powers the Schema Self-Correction Middleware: when the response fails schema validation, its onResponse hook returns { action: "RETRY", message: "..." } with the Zod error, which appends that message to the conversation and re-asks the model — all without your application code needing a manual retry loop.

RETRY directives are bounded by the maxCorrections limit (default 5). If a middleware keeps returning RETRY past that limit, the request throws instead of looping — a safety net against a misbehaving middleware retrying (and billing) indefinitely. Raise or lower it per-request via chat.ask(prompt, { maxCorrections }) or globally in configuration.

const validatingMiddleware: Middleware = {
  name: "Validator",
  onResponse: async (context, result) => {
    if (result instanceof ChatResponseString && !result.isValid) {
      return {
        action: "RETRY",
        message: `Your last response was invalid: ${result.validationError?.message}. Please try again.`
      };
    }
    // Returning nothing (or "CONTINUE") proceeds normally.
  }
};

When multiple middlewares are registered, the first non-void directive wins (subsequent middlewares in the reverse-order chain still run, but their directive is ignored once one has already been captured).

onToolCallError uses a similar (smaller) directive type, ToolErrorDirective, covered in the Tool Calling docs.


Standard Middleware Library v1.10.0+

NodeLLM includes a set of pre-built, production-ready middlewares that you can use out of the box.

1. PIIMaskMiddleware

Automatically redacts emails, phone numbers (US-style and international with a + country code), card numbers, US social security numbers and IBANs: in the conversation before it is sent to the LLM, and in each tool result before the model sees it. With redactOutput: true, it also masks the answer ask() returns; streamed text is sent as it arrives, so it isn’t masked.

import { NodeLLM, PIIMaskMiddleware } from "@node-llm/core";

const chat = NodeLLM.chat("gpt-5", {
  middlewares: [new PIIMaskMiddleware({ mask: "[SECRET]", redactOutput: true })]
});

It matches patterns, so it catches common formats, not names, addresses or data in images and files. Treat it as a safety net, not a guarantee. JSON tool results are masked in their string values only, so numbers such as timestamps stay intact. With redactOutput, the masked answer is also what the chat’s history keeps; onEndMessage handlers run before middlewares and see the answer as the model gave it. With @node-llm/orm, a chat or agent session that uses PIIMaskMiddleware also saves masked text.

A middleware’s onToolResult(ctx, toolCall, content, { isError }) may return { content } to change any tool result the model is sent, a tool’s error included, as this one does. onToolCallEnd may too, for successful calls.

2. CostGuardMiddleware

Monitors accumulated cost during a session (especially useful for multi-turn tool calling loops) and throws an error if a defined budget is exceeded.

import { NodeLLM, CostGuardMiddleware } from "@node-llm/core";

const chat = NodeLLM.chat("gpt-5", {
  middlewares: [
    new CostGuardMiddleware({ 
      maxCost: 0.05, // $0.05 budget
      onLimitExceeded: (ctx, cost) => console.log(`Budget blown for ${ctx.requestId}`)
    })
  ]
});

3. UsageLoggerMiddleware

Standardizes telemetry by logging token usage, request IDs, and calculated costs for every successful interaction.

import { NodeLLM, UsageLoggerMiddleware } from "@node-llm/core";

const chat = NodeLLM.chat("gpt-5", {
  middlewares: [new UsageLoggerMiddleware({ prefix: "MY-APP" })]
});

4. OpenTelemetry v1.20.0+

Sends a trace span for every model call and tool call to your OpenTelemetry setup (Jaeger, Honeycomb, Datadog, Grafana Tempo and so on). Pass the @opentelemetry/api module your app already uses; NodeLLM does not add it as a dependency.

import * as otel from "@opentelemetry/api";
import { createLLM, OpenTelemetry } from "@node-llm/core";

const llm = createLLM({ provider: "openai", middlewares: [OpenTelemetry(otel)] });
  • One span per call: chat <model>, embeddings <model>, generate_image <model> and so on. A chat span covers the whole ask() or stream(), including its tool loop.
  • Tool spans: execute_tool <name>, as children of the chat span.
  • Attributes: the GenAI semantic conventions, such as gen_ai.provider.name, gen_ai.request.model, gen_ai.response.model, gen_ai.usage.input_tokens and gen_ai.usage.output_tokens. Errors set the span status and error.type.
  • Fallbacks: when a chat falls back to another model, the span gets a node_llm.fallback event with the models and providers involved, and gen_ai.provider.name names the provider that answered.
  • Privacy: spans never include prompts, responses or tool arguments.

Spans go nowhere until your app registers an OpenTelemetry SDK and exporter.


Global Middlewares v1.10.0+

You can also register middlewares at the global level when creating the LLM instance. These will be applied to every chat, embedding, or image generation call made from that instance.

import { createLLM, UsageLoggerMiddleware } from "@node-llm/core";

const llm = createLLM({
  provider: "openai",
  middlewares: [new UsageLoggerMiddleware()]
});

// This chat will automatically use the global UsageLoggerMiddleware
const chat = llm.chat("gpt-5");

Integration with @node-llm/orm

When using the ORM, you can pass middlewares directly to the createChat call. They will be applied to the underlying chat instance but will NOT be persisted to the database.

import { createChat } from "@node-llm/orm/prisma";

const chat = await createChat(prisma, llm, {
  model: "gpt-5",
  middlewares: [new UsageLoggerMiddleware()]
});