[Bug] Accept arbitrary JSON metadata values in Chat and Responses decoders #5293
/assign
Hi @FAUST-BENCHOU
Please review this PR
Tick the box to add this pull request to the merge queue (same as @mergifyio queue). If it does not match the queue conditions yet, it enters the queue once it does.
Thanks for picking this up. One concern: when the request has to be re-encoded, which happens for every streamed Chat call because the Router adds include_usage, the backend gets "tags":"[\"agent\"]" and "turn":"1" instead of the values the client sent, and large integers lose precision. drivebyer suggested on the issue keeping metadata as JSON with its types and rejecting translations that can't carry it. Could you follow that, and add a test that re-encodes the request?
Good catch, thanks @subin9. You're completely right about the reencoding behavior on streaming calls.
I've updated the implementation following drivebyer's recommendation:
1. Chat and Responses wire structs now type metadata and client_metadata as map[string]json.RawMessage.
2. Added MetadataJSON map[string]json.RawMessage to llmprotocol.Request to preserve uncoerced raw JSON byte representations across routing, while keeping stringified values in Metadata so existing routing predicates and limits continue to function as expected.
3. Updated encodeChatBaseRequest and encodeResponsesRequestWire so reencoded requests serialize native JSON types directly rather than stringified values, preserving arrays, booleans, objects, and large integers beyond 2^53 without float64 precision loss.
4. Added an explicit check in alidateAnthropicEncodableRequest returning unsupported_metadata whenever a request carrying metadata is translated to Anthropic Messages, as Messages cannot represent request metadata.
5. Added unit tests covering forced reencoding type fidelity, large integer precision preservation, and cross protocol translation rejection.
<!-- semantic-router-ci-status:v1 -->
All required CI qualification passed
All selected and required checks have completed successfully for this revision.
Revision 34916d8b6426 · CI run, attempt 2
Thanks, this fixes the re-encoding. CI's lint flags this assertion; errors.As would pass it.
Updated the assertion in codec_openai_metadata_test.go to use errors.As(err, &protocolErr) in commit 34916d8b6 to satisfy errorlint, and verified go test ./pkg/protocolcodec/... ./pkg/llmprotocol/... passes locally. Thanks for catching that @subin9!
/ci run
Thanks, LGTM.
Approved these changes.
subin9
Paramveersingh-S
Closes #5252
Related #3983
Purpose
The Chat Completions and Responses request decoders previously typed
metadataasmap[string]string(chatRequestWireinprotocolcodec/codec_openai_chat.go,responsesRequestWireinprotocolcodec/codec_openai_responses.go) andclient_metadataasmap[string]stringon Responses. Consequently, any request containing non-string metadata values (such as list tags, turn numbers, boolean flags, or nested objects) faileddecodeWireduring strict validation and was rejected before routing with400 invalid_json: request JSON is invalid.LiteLLM-based clients conventions (such as Langfuse and spend-tracking) attach request metadata with list tags or scalar metrics (e.g.,
{"tags": ["agent"], "turn": 1, "active": true}), causing every call from such clients to fail at the Router.Changes
1. Flexible Wire Metadata: Changed
chatRequestWire.Metadata,responsesRequestWire.Metadata, andresponsesRequestWire.ClientMetadatafrommap[string]stringtomap[string]any.2. Metadata Value Coercion: Added
coerceWireMetadataandcoerceMetadataValueinpkg/protocolcodec/json_helpers.goto coerce arbitrary JSON values (strings, numbers, booleans, arrays, objects, nulls) into string values for the protocol-neutralllmprotocol.Request.Metadatacontract. This ensures downstream classifier signals (MetadataRule), routing predicates, masking, and request validation limits work without modification.3. Verbatim Replay Preservation: Same-format routes (Chat -> Chat, Responses -> Responses) continue to forward raw client request bytes via envelope caching (
envelope.CanReplay), preserving the native JSON types upstream.4. Wire Encoding: Added
encodeWireMetadatafor re-encoding requests when cross-format translation or modifications prevent envelope replay.5. Comprehensive Tests: Added
codec_openai_metadata_test.gocovering LiteLLM list tags, numbers, booleans, nested objects, compound metadata, round-trip encoding,client_metadataomission diagnostics, and rejection of non-object metadata types (e.g. strings or arrays).