What Does sanitizeChatRequestBody Do in OmniRoute? A Deep Dive into Request Sanitization

sanitizeChatRequestBody is a core utility in the OmniRoute proxy that normalizes incoming Chat completion payloads by mapping legacy token fields, stripping empty metadata, filtering malformed tools, and adapting request structures for compatibility with 350+ LLM providers.

The OmniRoute repository (diegosouzapw/OmniRoute) implements a universal routing layer for large language model APIs. Before any request reaches a provider, the system must ensure the payload conforms to the target API's expectations. The sanitizeChatRequestBody function serves as the critical preprocessing step that bridges format differences between OpenAI-style requests, the Responses API, and other provider specifications.

Core Responsibilities of sanitizeChatRequestBody

The implementation in open-sse/handlers/chatCore/sanitization.ts performs five distinct transformations to guarantee provider compatibility and prevent downstream errors.

Token Field Normalization

The sanitizer maps legacy token limit fields to their canonical equivalents based on the target format. When routing to standard Chat Completions endpoints, it converts max_output_tokens or max_completion_tokens to max_tokens. Conversely, when targeting the Responses API, it maps max_completion_tokens to max_output_tokens. This ensures providers receive the parameter names they expect, avoiding silent truncation or validation failures.

Metadata Cleaning and Tool Validation

Empty name removal prevents the propagation of empty string metadata that could break downstream parsers. The function strips the name field from message objects when the value is an empty string. Additionally, the sanitizer performs tool filtering by dropping any tool definitions that lack a name property or contain empty names. This maintains the tool-execution contract and prevents provider rejections due to malformed function definitions.

Format-Aware Request Adaptation

Beyond simple field mapping, the utility adapts the entire request shape based on source and target format identifiers. Located in the main handler at open-sse/handlers/chatCore.ts (line 35), this transformation allows the same routing logic to handle conversions between OpenAI-style requests, Responses API formats, and other provider-specific structures without requiring the caller to understand each endpoint's quirks.

Implementation Details and Source Code

The sanitization logic resides in [open-sse/handlers/chatCore/sanitization.ts](https://github.com/diegosouzapw/OmniRoute/blob/release/v3.8.50/open-sse/handlers/chatCore/sanitization.ts), where it exports the primary normalization function. The main chat handler imports and invokes this utility early in the request pipeline, specifically at line 35 of [open-sse/handlers/chatCore.ts](https://github.com/diegosouzapw/OmniRoute/blob/release/v3.8.50/open-sse/handlers/chatCore.ts#L35).

According to the source code, the function accepts three parameters: the raw request body, the source format identifier, and the target format identifier. It returns a clean, canonical representation that downstream translation and execution layers can process uniformly. This design reduces the attack surface for injection attacks and helps the guardrails layer enforce consistent policies across all supported providers.

Practical Usage Examples

The following TypeScript examples demonstrate how to invoke the sanitizer for common transformation scenarios:

// Example: Normalizing a legacy OpenAI-style request
import { sanitizeChatRequestBody } from "@/open-sse/handlers/chatCore/sanitization";
import { FORMATS } from "@/open-sse/handlers/chatCore/constants";

const legacyBody = {
  max_output_tokens: 256,
  messages: [{ role: "user", content: "Hello", name: "" }],
  tools: [{ type: "function", function: { name: "" } }]
};

const cleanBody = sanitizeChatRequestBody(
  legacyBody,
  FORMATS.OPENAI,          // source format
  FORMATS.OPENAI           // target format
);

// Result: max_tokens: 256, empty name removed, nameless tool omitted
console.log(cleanBody.max_tokens); // 256
console.log(cleanBody.messages[0].name); // undefined
console.log(cleanBody.tools.length); // 0
// Example: Converting Chat Completions to Responses API format
import { sanitizeChatRequestBody, FORMATS } from "@/open-sse/handlers/chatCore";

const chatBody = { max_tokens: 128, messages: [{ role: "user", content: "Hi" }] };
const responsesBody = sanitizeChatRequestBody(
  chatBody,
  FORMATS.OPENAI,
  FORMATS.OPENAI_RESPONSES
);

// Field mapped to Responses API convention
console.log(responsesBody.max_output_tokens); // 128
console.log(responsesBody.max_tokens); // undefined

Testing and Validation

The expected behavior is verified by comprehensive unit tests in [tests/unit/chatcore-extracted-modules-3821.test.ts](https://github.com/diegosouzapw/OmniRoute/blob/release/v3.8.50/tests/unit/chatcore-extracted-modules-3821.test.ts). These tests document the sanitizer's contract, including:

  • Token mapping for Chat Completions: Verifies that max_output_tokens maps to max_tokens for OpenAI-style targets (lines 21-27)
  • Token mapping for Responses API: Confirms that max_completion_tokens maps to max_output_tokens for Responses targets (lines 28-33)
  • Empty metadata handling: Validates that empty message names are stripped and nameless tools are filtered from the array (lines 46-48)

Additional integration tests in [tests/unit/codex-responses-to-chat-9161.test.ts](https://github.com/diegosouzapw/OmniRoute/blob/release/v3.8.50/tests/unit/codex-responses-to-chat-9161.test.ts) ensure the sanitizer works correctly across the "Responses → Chat" conversion path.

Summary

  • sanitizeChatRequestBody normalizes request payloads in open-sse/handlers/chatCore/sanitization.ts before they reach LLM providers.
  • The function handles token field mapping between max_tokens, max_output_tokens, and max_completion_tokens based on the target API format.
  • It performs defensive cleaning by removing empty string names from messages and filtering tools that lack valid name properties.
  • Invoked at line 35 of the main handler, the utility enables OmniRoute to support 350+ providers through format-aware request adaptation.
  • Comprehensive unit tests in chatcore-extracted-modules-3821.test.ts verify the transformation logic across different API standards.

Frequently Asked Questions

What is the difference between max_tokens and max_output_tokens in OmniRoute?

max_tokens is the legacy OpenAI Chat Completions parameter for limiting response length, while max_output_tokens is the canonical field used by the Responses API. The sanitizeChatRequestBody function automatically maps between these fields based on the target format identifier, ensuring providers receive the parameter name they recognize regardless of what the client originally sent.

How does sanitizeChatRequestBody handle malformed tool definitions?

The sanitizer inspects every object in the tools array and removes any tool where the name property is missing or contains an empty string. This prevents providers from receiving incomplete function definitions that would cause validation errors. The filtering occurs before the request leaves OmniRoute, maintaining a clean tool-execution contract between the client and the target LLM.

Where is sanitizeChatRequestBody invoked in the request pipeline?

The function is imported and called at line 35 of [open-sse/handlers/chatCore.ts](https://github.com/diegosouzapw/OmniRoute/blob/release/v3.8.50/open-sse/handlers/chatCore.ts#L35). This placement ensures sanitization happens immediately after request parsing but before format translation, routing, and stream processing, allowing all downstream components to operate on a validated, canonical representation of the user request.

Why is request sanitization necessary for LLM routing?

Without sanitization, differences in API specifications between providers would require callers to know the specific parameter names and schemas for each of the 350+ supported endpoints. Sanitization abstracts these differences, prevents injection attacks through malformed metadata, and ensures consistent guardrail enforcement. It allows OmniRoute to accept requests in various formats while guaranteeing that providers receive only well-formed, expected payloads.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →