Proposed Proposal #00484ai
Anthropic Messages API Filters
Add Anthropic Messages API support to Praxis as composable filters, mirroring the pattern established by the OpenAI Responses API filters in #354.
What?
Add Anthropic Messages API support to Praxis as
composable filters, mirroring the pattern established
by the OpenAI Responses API filters in #354. This
enables Praxis to classify, route, and transform
requests between the Anthropic Messages API
(/v1/messages) and OpenAI Chat Completions
(/v1/chat/completions).
The OpenAI Responses API (/v1/responses) is a
fundamentally different protocol with stateful
semantics and is out of scope for format
transformation. Responses API support is covered
separately.
The scope covers five capabilities:
Classification and routing: detect
AnthropicMessages API requests by body structure and promote routing facts to headers for downstream routing and cluster selection. The classifier extends the sharedAiRequestFormatenum (atai/classifier/) with anAnthropicMessagesvariant, keeping a single classifier for all formats. It must distinguishAnthropicMessages fromOpenAIChat Completions even though both use amessagesfield, using discriminating signals: top-levelsystemparameter, requiredmax_tokens,anthropic-versionheader, and typed content blocks. Mid-conversation system messages ("role": "system"inside the messages array) are supported on newerAnthropicmodels per the mid-conversation system messages docs. Theanthropic-versionheader is the strongest signal. The promoted header name isx-praxis-ai-format(matching the existingopenai_responses_formatfilter convention).Request validation: validate only request properties the gateway or filters must act on locally. All other fields are forwarded to the inference backend unmodified; the backend handles Anthropic API requirements such as required fields, parameter types and ranges, model availability, role ordering, and content-level validation. Unknown fields are expected and must be preserved. Unlike the Responses API,
AnthropicMessages does not require persistence or stateful orchestration, so the validation filter is lighter: no shared state struct, no store initialization.Format transformation: bidirectional conversion between
AnthropicMessages andOpenAIChat Completions so that clients speaking one dialect can reach backends speaking the other. This filter is only needed when the backend does not natively support/v1/messages(e.g. OpenAI-only backends). Backends with native Messages support use the passthrough path instead. This is validated by existing production implementations in OGX (the open-source agentic API server) which performs the same translation in Python. The known mapping rules are:Request (
AnthropictoOpenAI):system(top-level string or text block array) to prependedOpenAImessage withrole: "system"- Content blocks flattened:
type: "text"to string contenttype: "tool_use"toOpenAItool_callswithfunction.arguments = JSON-serialized inputtype: "tool_result"to separateOpenAImessage withrole: "tool"(images in tool results promoted to follow-up user messages sinceOpenAItool messages are text-only);is_error: trueis represented in the tool message text because Chat Completions has no equivalent tool-result error flagtype: "search_result"to backend-visible text context containing available quoted metadata and nested text blockstype: "document"to backend-visible text context when the document source contains text; unresolved URL, file, and base64 sources are represented as quoted stable source references rather than silently disappearing
max_tokenstomax_tokens(direct mapping)stop_sequencestostoptool_choice:"any"to"required","none"to"none", default to"auto",{"type": "tool", "name": "X"}to{"type": "function", "function": {"name": "X"}}- Tool definitions: custom tools convert
(
input_schematoparameters); server-side tools (web_search, bash, text_editor) are dropped with a log warning top_k: no standardOpenAIequivalent, passed as extra body parameter for backends that support it (e.g. vLLM)temperature,top_p: forwarded as-is. Model-specific stripping (e.g. for Opus 4.7+ which rejects non-default values) is deferred to future workthinkingblocks: dropped (noOpenAIequivalent)- Image blocks:
Anthropicusestype: "image"withsource.type: "base64"|"url"|"file";OpenAIusestype: "image_url"withimage_url.url. Forsource.type: "base64"and"url", structural mapping is applied. Forsource.type: "file", the file reference must be resolved to a data URL before transformation (requires a separate file resolver; deferred to future work)
Response (
OpenAItoAnthropic):message.contentstring to content block withtype: "text"tool_callsto content block per call withtype: "tool_use"andinput = JSON-parsed arguments- Finish reason mapping:
"stop"to"end_turn","tool_calls"to"tool_use","length"to"max_tokens","content_filter"to"end_turn"(note: this is a lossy mapping; the originalfinish_reasonis preserved in filter metadata asopenai.finish_reasonso downstream filters can distinguish safety-filtered responses from natural completions) - Usage:
prompt_tokenstoinput_tokens,completion_tokenstooutput_tokens,cached_tokenstocache_read_input_tokens - Set
idto an Anthropic-stylemsg_ID, derived from upstream ID when present
Streaming SSE transformation: a separate filter (following the
stream_eventspattern in #354) that transforms OpenAI Chat Completions SSE chunks into Anthropic Messages SSE events. Decoupled from request body transformation so operators can use SSE event handling independently (e.g. for logging or guardrails on passthrough streams).Event mapping (
OpenAIchunks toAnthropicSSE):- Emit
MessageStartEventwith empty content - Per text delta:
ContentBlockStartEvent+ContentBlockDeltaEvent(text_delta) - Per tool call delta:
ContentBlockStartEventwith emptyToolUseBlock, thenContentBlockDeltaEvent(input_json_delta) ContentBlockStopEventto close each blockMessageDeltaEventwith finalstop_reasonand usageMessageStopEvent
- Emit
Anthropic-native features: proxy and preserveAnthropic-specific capabilities that have noOpenAIequivalent when routing toAnthropicbackends in pass-through mode:- Prompt caching (
cache_controlblocks withephemeraltype; 5-minute TTL is standard, 1-hour TTL requires theextended-cache-ttlbeta header) - Extended thinking (
thinkingparameter withbudget_tokens) - Citations in responses
AnthropicSSE streaming event protocolanthropic-versionheader preservation- Rate-limit header forwarding
(
x-ratelimit-limit-tokens, etc.) — deferred to future work
- Prompt caching (
Each capability is a separate filter implementing
HttpFilter, composable in YAML pipelines. Operators
deploy only what they need.
Goals
- Validate proxy-needed fields in
AnthropicMessages requests (messagesnon-empty,max_tokens> 0,modelpresent) and reject malformed requests with consistent error responses before they reach the backend. - Classify
AnthropicMessages API requests and promotex-praxis-ai-format: anthropic_messagesto headers for routing, extending the existingAiRequestFormatenum alongsideResponsesandChatCompletionsvariants (openai_responsesandopenai_chat_completionsas string values). - Transform requests bidirectionally between
AnthropicMessages andOpenAIChat Completions using the mapping rules documented above, validated against OGX’s production implementation. - Transform OpenAI Chat Completions SSE chunks
(
chat.completion.chunk) into Anthropic Messages SSE events (message_start,content_block_start,content_block_delta,content_block_stop,message_delta,message_stop). - Gracefully degrade when transforming
Anthropicrequests forOpenAIbackends: drop unsupported features (thinking, server-side tools,cache_control) with structured log warnings rather than rejecting the request. - Preserve
Anthropic-specific headers and request features end-to-end when routing to backends that natively support/v1/messages(e.g. vLLM,AnthropicAPI). - Provide a pass-through fast path for backends
that natively support
/v1/messageswith sub-millisecond proxy overhead. - Support credential injection for
Anthropicbackends using the existingcredential_injectionfilter forx-api-keyandanthropic_messages_protocolfor gateway-managedanthropic-versiondefaults. - Enable unified gateway configurations where a
single Praxis instance routes to vLLM (
OpenAI), llm-d (OpenAIvia vLLM), KServe/MaaS backends, andAnthropicAPI simultaneously, with format detection at request time and operator-configured filter chains for passthrough or transformation. Runtime backend capability detection is out of scope.
Why?
Motivation
Production AI platforms increasingly need to support
multiple inference backends and API formats
simultaneously. The Anthropic Messages API is a
first-class inference protocol alongside OpenAI’s
Chat Completions and Responses APIs, with
significant adoption in enterprise deployments.
Today, Praxis classifies requests as either
Responses (OpenAI Responses API) or
ChatCompletions (OpenAI Chat Completions) in the
AiRequestFormat enum. Anthropic Messages requests
arrive with messages (like Chat Completions) but
are structurally different: system is a top-level
parameter, max_tokens is required, content uses
typed blocks (text, image, tool_use,
tool_result), and streaming uses a distinct SSE
event protocol. The current classifier would
misidentify these as chat_completions, leading to
incorrect routing or transformation failures.
The format transformation filters are needed because real deployments mix backends:
- vLLM and llm-d expose
OpenAI-compatible endpoints (/v1/chat/completions) and also support/v1/messagesnatively, but not all deployments enableAnthropiccompatibility. vLLM’s/v1/messagesendpoint supports coreAnthropicfeatures (system, tools, tool_choice, thinking blocks, streaming SSE) but does not supportcache_controlorbudget_tokens(these are accepted but ignored). llm-d is a Kubernetes-native orchestration layer that routes to vLLM workers using the Gateway API Inference Extension with prefix-cache-aware scheduling and prefill/decode disaggregation. - KServe and MaaS (Models as a Service) provide
model discovery and API key management. MaaS
returns model URLs that clients call directly;
the model endpoints may implement either format.
MaaS uses
OpenAI-compatible API keys (sk-oai-*) and/v1/modelsfor discovery. AnthropicAPI is the canonical backend for Claude models and uses a distinct wire format with features that have noOpenAIequivalent: prompt caching withcache_controlblocks (5-minute TTL standard; 1-hour TTL requires theextended-cache-ttlbeta header), extended thinking withbudget_tokens, typed content blocks, and a block-based SSE streaming protocol.Anthropicalso provides anOpenAIcompatibility endpoint at/v1/chat/completions, but it lacks prompt caching, extended thinking details, and strict tool use, making native/v1/messagesrouting necessary for full feature access.
The bidirectional format transformation is a
validated pattern. OGX (the open-source agentic API
server) implements the same Anthropic to OpenAI
mapping in production, with a native-passthrough
fast path when backends support /v1/messages
directly. The mapping rules documented in this
proposal are derived from that implementation and
cover the known edge cases: tool result image
promotion, server-side tool filtering, thinking
block handling, and streaming event sequencing.
Without format transformation, operators must either standardize all clients on one format (impractical) or run separate gateway instances per format (operationally expensive). Praxis should handle this at the filter pipeline level.
Anthropic-native features (prompt caching, extended
thinking) represent capabilities that cannot be
expressed in OpenAI format. When routing to
Anthropic backends, these must be preserved
end-to-end. When routing Anthropic requests to
OpenAI-compatible backends, the filters must
gracefully degrade: strip unsupported fields, map
what can be mapped, and log what was dropped.
User Stories
- As a platform engineer, I want to route
/v1/messagesrequests to vLLM backends that only support/v1/chat/completionsso that clients using theAnthropicSDK can reach any backend in my fleet. - As an AI gateway operator, I want a single Praxis
instance to serve clients speaking
OpenAIChat Completions andAnthropicMessages formats, routing each to the appropriate backend with automatic format detection. - As a developer, I want to send
Anthropic-format requests with prompt caching to a Claude backend through Praxis without losing thecache_controlblocks oranthropic-versionheader. - As an SRE, I want to use Praxis credential
injection to manage
x-api-keyheaders forAnthropicbackends the same way I manageAuthorization: Bearerheaders forOpenAIbackends. - As a platform engineer using MaaS for model
discovery, I want to configure Praxis filter
chains per backend format so that clients
speaking
Anthropiccan reach any endpoint regardless of its native API format.
Translation Decision
The classifier detects the request format (always
anthropic_messages for Anthropic requests) but
does not determine whether the backend needs
translation. This follows the existing Praxis
classify → route pattern: the classifier promotes
facts to internal headers. The operator chooses
the pipeline at deployment time (via listener and
filter chain config); routes select clusters
within that pipeline at runtime.
The operator deploys separate configs (or separate
listeners) for native Messages vs transformation. The
native Messages config includes anthropic_messages_protocol
in the pipeline for protocol header normalization; the transformation config includes
anthropic_to_openai. In Praxis, listeners flatten
filter chains at startup and the router selects
clusters, not chains — so the translation decision
is a deployment-time config choice, not a runtime
routing decision.
This is the same pattern used by openai_responses_format
for Responses API vs Chat Completions routing. See
examples/configs/ai/openai/responses/format-routing.yaml
for the canonical example.
How?
Filter Summary
Five composable filters, each implementing HttpFilter.
Operators deploy only what they need for their use case.
flowchart TD
Client["Anthropic /v1/messages"]
Classify["anthropic_messages_format"]
Validate["anthropic_validate"]
Client --> Classify --> Validate
subgraph "Native Messages config"
Pass["anthropic_messages_protocol"]
Native["/v1/messages backend"]
Pass --> Native
end
subgraph "Transform config"
Transform["anthropic_to_openai"]
Rewrite["path_rewrite"]
OpenAI["/v1/chat/completions backend"]
Transform --> Rewrite --> OpenAI
end
Validate --> Pass
Validate --> Transform| Filter | Purpose |
|---|---|
anthropic_messages_format | Classify requests as Anthropic Messages and promote routing facts to headers, metadata, and filter results |
anthropic_validate | Validate proxy-needed fields (messages, max_tokens, model) and reject malformed requests with 400 |
anthropic_messages_protocol | Supply a gateway-managed anthropic-version default for native /v1/messages backends |
anthropic_to_openai | Transform Anthropic request body to OpenAI Chat Completions and non-streaming response back |
anthropic_stream_events | Transform OpenAI Chat Completions SSE chunks into Anthropic Messages SSE events per-chunk |
Source Material
AnthropicMessages API docs: https://platform.claude.com/docs/en/api/messages- OGX
transformation reference at
ogx/src/ogx/providers/inline/messages/impl.py - Target:
filter/src/builtins/http/ai/anthropic/in praxis
Architecture
Five filters, each implementing HttpFilter.
Filters communicate via HttpFilterContext:
filter_metadata: durable key-value state persisting across lifecycle phasesfilter_results: ephemeral key-value pairs consumed by branch conditionsextra_request_headers: headers injected into upstream requests- Request/response body access via
on_request_body/on_response_body
The classifier extends the existing
AiRequestFormat enum (moved to
filter/src/builtins/http/ai/classifier/mod.rs as
a shared module) with an AnthropicMessages
variant. The operator configures routes and filter
chains for passthrough vs transformation using the
existing classify → route pattern (see Translation
Decision above).
Filter 0: anthropic_messages_format
Purpose: Classify requests as Anthropic Messages
API and promote routing facts to headers, metadata,
and filter results. Mirrors the pattern of
openai_responses_format but detects /v1/messages
requests.
Praxis trait methods:
on_request_body: parse JSON body, classify format, write metadata and headersrequest_body_mode→StreamBuffer(read-only)
Classification logic (decision tree):
The pure classifier (classify_request_body) uses
body structure only. The filter layer applies
header and path overrides after classification.
Body classification precedence:
inputfield present →Responsesmessages+max_tokens+ Anthropic signals →AnthropicMessagesmessageswithout the above →ChatCompletions- Neither
inputnormessages→UnknownJson
Anthropic signals (required beyond max_tokens):
- Top-level
systemfield, OR - Typed content blocks in
messages(arrays of objects with atypekey)
Filter-layer overrides (checked in the filter, not the pure classifier):
anthropic-versionrequest header present → override toAnthropicMessages- Request path is
/v1/messages→ override toAnthropicMessages
This prevents false positives when OpenAI Chat
Completions requests include the optional
max_tokens field.
Classification result:
- Extends
AiRequestFormatwithAnthropicMessagesvariant as_str()returns"anthropic_messages"
Promoted facts:
x-praxis-ai-format: anthropic_messagesx-praxis-ai-model: <model>(extracted from body)x-praxis-ai-stream: true|falsefilter_metadata:anthropic_format.format,anthropic_format.model,anthropic_format.stream,anthropic_format.max_tokensfilter_results(under keyanthropic_messages_format):format,model,stream
Config:
filter: anthropic_messages_format
on_invalid: continue # continue | reject
max_body_bytes: 1048576 # 1 MiB
headers:
format: x-praxis-ai-format
model: x-praxis-ai-model
stream: x-praxis-ai-stream
Filter 1: anthropic_validate
Purpose: Validate proxy-needed fields in
Anthropic Messages requests before forwarding.
Unlike #354’s request_validate, this filter does
not create shared orchestrator state or initialize
persistence: Anthropic Messages has no stateful
orchestration.
Praxis trait methods:
on_request_body: parse JSON body, validate fields, reject with 400 if invalidrequest_body_mode→StreamBuffer(read-only)
Validation checks:
messagesarray exists and is non-emptymax_tokensis present and > 0modelis present and non-empty
Validation principle: Only validate what the proxy needs for its own operation. Let the inference server handle parameter ranges, model availability, and content-level validation. Forward unknown fields as-is.
Config:
filter: anthropic_validate
max_body_bytes: 1048576 # 1 MiB
Filter 2: anthropic_to_openai
Purpose: Transform an Anthropic Messages API
request body into an OpenAI Chat Completions request
body. Runs on the request path. Enables Anthropic
SDK clients to reach OpenAI-compatible backends
(vLLM, llm-d, KServe).
Praxis trait methods:
on_request_body: rewrite JSON bodyrequest_body_mode→StreamBuffer(read-write)response_body_mode→Stream(static default)on_response: upgrade toStreamBufferviactx.set_response_body_mode()for transformable non-streaming successes and every upstream 4xx/5xxon_response_body: transform compatible non-streaming success bodies from OpenAI format back to Anthropic format, and normalize pre-stream error bodies for both request modes
Streaming coexistence: by declaring Stream
statically and upgrading to StreamBuffer per-request,
both anthropic_to_openai and
anthropic_stream_events can coexist in a single
pipeline. Non-streaming requests get full response
buffering for compatible successful transformations.
Successful streaming responses pass through to
anthropic_stream_events for per-chunk SSE conversion.
Pre-stream 4xx/5xx responses are buffered and normalized
even when the original request enabled streaming.
When a body is replaced, the filter preserves the status,
copies request-id (falling back to x-request-id) into
the Anthropic body and canonical response header, sets the
content type to JSON, and clears stale Content-Length,
Content-Encoding, Content-Range, and ETag headers.
The request-side filter removes Accept-Encoding; encoded
or partial successful responses are passed through if an
upstream still returns them.
Request transformation (Anthropic → OpenAI):
- Hoist
system→ prepend OpenAI message withrole: "system". Handles both string and text block array forms. - Flatten content blocks in each message:
type: "text"→ string content or OpenAI text content parttype: "image"withsource.type: "base64"→ OpenAItype: "image_url"with data URLtype: "image"withsource.type: "url"→ OpenAItype: "image_url"with URLtype: "tool_use"→ OpenAItool_callsentry withfunction.arguments = serde_json::to_string(input)type: "tool_result"→ separate OpenAI message withrole: "tool",tool_call_id, and string content. Images in tool results promoted to follow-up user messages.is_error: trueis marked in the tool message content because Chat Completions has no equivalent flag.type: "search_result"→ text context with quoted title/source metadata and nested text blocks when present.type: "document"→ text context for text/content sources, or a quoted stable source reference for URL, file, and base64 sources.type: "thinking"→ dropped (logged)type: "redacted_thinking"→ dropped (logged)
- Map parameters:
max_tokens→max_tokensstop_sequences→stoptemperature→temperature(forwarded as-is)top_p→top_p(forwarded as-is)top_k→ extra body parameter
- Map
tool_choice:"any"→"required""none"→"none""auto"→"auto"{"type": "tool", "name": "X"}→{"type": "function", "function": {"name": "X"}}
- Map
tools:- Custom tools:
input_schema→parameters,name→function.name,description→function.description - Server-side tools (
web_search_*,bash_*,text_editor_*): dropped withtracing::warn!
- Custom tools:
- Rewrite
Content-TypeandContent-Lengthheaders - Strip
anthropic-versionandx-api-keyheaders (credential injection handles upstream auth)
Response transformation (OpenAI → Anthropic):
Non-streaming:
choices[0].message.content→ content block withtype: "text"choices[0].message.tool_calls→ content blocks withtype: "tool_use",id,name,input = serde_json::from_str(args)finish_reason→stop_reason:"stop"→"end_turn","tool_calls"→"tool_use","length"→"max_tokens","content_filter"→"end_turn"(lossy; original preserved in filter metadata)usage.prompt_tokens→input_tokens,usage.completion_tokens→output_tokens,usage.prompt_tokens_details.cached_tokens→cache_read_input_tokens- Set
idtomsg_prefix + upstream ID when present, settype: "message",role: "assistant"
Config:
filter: anthropic_to_openai
max_body_bytes: 1048576 # 1 MiB
Filter 3: anthropic_stream_events
Purpose: Transform OpenAI Chat Completions SSE chunks into Anthropic Messages SSE events. Separated from request transformation so operators can use SSE event handling independently: e.g. for logging, metrics, or guardrails on passthrough streams without transforming the request body.
Praxis trait methods:
on_response_body: process each TCP chunk as it arrives, transform complete SSE events immediately, buffer only partial lines across chunk boundariesresponse_body_mode→Stream(notStreamBuffer; no full-response buffering)
Per-chunk processing:
Each on_response_body call:
- Combines leftover partial data from the previous chunk with new bytes
- Splits on
\n\nSSE event boundaries - Transforms each complete
data:line immediately - Stores any trailing partial data in filter metadata
- Forwards transformed events to the client
This conforms to the Inference Proxy Conformance Guidelines Sections 4.2 (no streaming-to-non-streaming conversion) and 4.3 (no full-response buffering).
State machine (per-request, stored in filter metadata):
- Track: current block index, block type, open blocks, finish reason, output tokens
- First chunk →
message_startwith empty message envelope - Text delta →
content_block_start(first), thencontent_block_delta(text_delta) - Tool call delta →
content_block_startwith emptytool_useblock (first per tool), thencontent_block_delta(input_json_delta) - Block end →
content_block_stop [DONE]→message_deltawithstop_reasonandusage, thenmessage_stop
Config:
filter: anthropic_stream_events
Filter 4: anthropic_messages_protocol
Purpose: Normalize Anthropic Messages protocol
headers when routing to backends that natively
support /v1/messages (Anthropic API, vLLM with
Anthropic endpoint). No body transformation: only
gateway-managed anthropic-version defaulting and
credential injection coordination.
Praxis trait methods:
on_request: injectanthropic-versionheader if absent
Behavior:
Request:
- Inject
anthropic-versionheader with configured default if an internal or non-SDK client did not send one - Preserve caller-provided
anthropic-versionheaders - Preserve
cache_controlblocks in body as-is - Preserve
thinkingparameter as-is - Coordinate with
credential_injectionfilter forx-api-keyheader injection
Response:
- Pass through unchanged (no body or header transformation)
Future: Rate-limit header forwarding
(x-ratelimit-*) and request-id passthrough
are deferred to a follow-up.
Config:
filter: anthropic_messages_protocol
default_version: "2023-06-01"
Filter Chain Configuration
Internal or Anthropic client → native backend:
listeners:
- name: anthropic-gateway
address: "127.0.0.1:8080"
filter_chains: [anthropic-native]
filter_chains:
- name: anthropic-native
filters:
- filter: anthropic_messages_format
on_invalid: continue
- filter: anthropic_messages_protocol
default_version: "2023-06-01"
- filter: router
routes:
- path_prefix: "/"
cluster: "anthropic-backend"
- filter: load_balancer
clusters:
- name: "anthropic-backend"
endpoints:
- "127.0.0.1:3001"
Anthropic client → OpenAI backend (transform):
listeners:
- name: anthropic-gateway
address: "127.0.0.1:8080"
filter_chains: [anthropic-transform]
filter_chains:
- name: anthropic-transform
filters:
- filter: anthropic_messages_format
on_invalid: continue
- filter: anthropic_to_openai
max_body_bytes: 1048576
- filter: path_rewrite
replace:
pattern: "^/v1/messages$"
replacement: "/v1/chat/completions"
conditions:
- when:
path_prefix: "/v1/messages"
- filter: router
routes:
- path_prefix: "/"
cluster: "openai-backend"
- filter: load_balancer
clusters:
- name: "openai-backend"
endpoints:
- "127.0.0.1:3001"
Unified gateway (route by format):
Uses a single filter chain with both classifiers;
the router selects clusters by path. Note: branch
chains cannot be
used for transformation because body hooks
(on_request_body, on_response_body) are not
executed for filters inside branch chains.
listeners:
- name: unified-gateway
address: "127.0.0.1:8080"
filter_chains: [unified-routing]
filter_chains:
- name: unified-routing
filters:
- filter: anthropic_messages_format
on_invalid: continue
headers:
format: x-praxis-ai-format
model: x-praxis-ai-model
stream: x-praxis-ai-stream
- filter: openai_responses_format
on_invalid: continue
- filter: router
routes:
- path: "/v1/messages"
cluster: "anthropic-backend"
- path: "/v1/chat/completions"
cluster: "openai-backend"
- path: "/v1/responses"
cluster: "responses-backend"
- path_prefix: "/"
cluster: "default-backend"
- filter: load_balancer
clusters:
- name: "anthropic-backend"
endpoints:
- "127.0.0.1:3001"
- name: "openai-backend"
endpoints:
- "127.0.0.1:3002"
- name: "responses-backend"
endpoints:
- "127.0.0.1:3003"
- name: "default-backend"
endpoints:
- "127.0.0.1:3004"
Implementation Tiers
Build order; each tier produces a working system:
| Tier | Filter | What works after |
|---|---|---|
| 0 | anthropic_messages_format | Classification and routing. Anthropic requests detected and promoted to headers/metadata for downstream routing. |
| 1 | anthropic_validate | Request validation. Malformed requests rejected at the proxy with consistent error format. |
| 2 | anthropic_messages_protocol | Native Anthropic backend routing. Clients reach Anthropic API through Praxis with centralized anthropic-version defaults. |
| 3 | anthropic_to_openai (request + non-streaming response) | Anthropic SDK clients can reach vLLM/llm-d backends. Non-streaming responses translated back. |
| 4 | anthropic_stream_events | Per-chunk SSE streaming. OpenAI chunks translated to Anthropic events incrementally as they arrive. Conformant with Inference Proxy Conformance Guidelines. |
File Structure in Praxis
filter/src/builtins/http/ai/
classifier/
mod.rs # shared AiRequestFormat enum
anthropic/
mod.rs # module exports
messages_format/
mod.rs # classifier filter
config.rs # YAML config
validate/
mod.rs # validation filter
config.rs # YAML config
to_openai/
mod.rs # transformation filter
config.rs # YAML config
request.rs # Anthropic → OpenAI request
response.rs # OpenAI → Anthropic response
stream_events/
mod.rs # per-chunk SSE transformation
config.rs # YAML config
protocol/
mod.rs # protocol filter
config.rs # YAML config
examples/configs/ai/anthropic/
messages-protocol.yaml # protocol header config
messages-to-openai.yaml # transformation config
unified-gateway.yaml # multi-format routing
tests/integration/tests/suite/examples/
anthropic_messages.rs # functional integration tests
tests/integration/tests/suite/
anthropic_messages.rs # ported OGX conformance tests
Test Strategy
The integration tests are ported from
OGX’s Messages
test suite (test_messages.py), rewritten in Rust
to avoid Python dependencies in the repo. Each Rust
test maps 1:1 to its OGX Python counterpart by name.
Tests use Backend::fixed() with hardcoded
Anthropic Messages response fixtures. Each test
starts a mock backend, configures Praxis with the
protocol filter chain, sends an Anthropic
/v1/messages request, and validates the response
structure. No live backends or recording replay
servers are needed — fixtures are embedded in the
test file.
Test coverage:
| Rust test | OGX counterpart |
|---|---|
non_streaming_basic | test_messages_non_streaming_basic |
non_streaming_with_system | test_messages_non_streaming_with_system |
non_streaming_multi_turn | test_messages_non_streaming_multi_turn |
streaming_basic | test_messages_streaming_basic |
streaming_collects_full_text | test_messages_streaming_collects_full_text |
non_streaming_with_temperature | test_messages_non_streaming_with_temperature |
non_streaming_with_stop_sequences | test_messages_non_streaming_with_stop_sequences |
with_tool_definitions | test_messages_with_tool_definitions |
tool_use_round_trip | test_messages_tool_use_round_trip |
error_missing_model | test_messages_error_missing_model |
error_empty_messages | test_messages_error_empty_messages |
response_headers | test_messages_response_headers |
content_block_array | test_messages_content_block_array |
Limitations
- Token counting. Transformed responses report
the backend’s token accounting in Anthropic field
names (
prompt_tokens→input_tokens,completion_tokens→output_tokens). These reflect the OpenAI backend’s counts, not what Anthropic’s tokenizer would produce. Synthesizing “true Anthropic” counts would require owning tokenizer fidelity, which is out of scope.
Out of Scope (Future Proposals)
Batches API.
/v1/messages/batchesinvolves async job lifecycle, storage, polling, result retrieval, and cancellation — not just body transformation. If supported, it should be a separate proposal and filter family. Native passthrough can route batch requests to backends that support them./v1/messages/count_tokens. For native backends, passthrough works. For transformed backends, local implementation would require model-specific tokenizer config. Better addressed as a separate capability/filter if needed.