Skip to content

[Bug]: Anthropic request codec drops provider-native tool history #501

Closed

Description

@afourniernv

Affected area

  • Rust core runtime
  • Python binding
  • Middleware or guardrails

Current behavior

AnthropicMessagesCodec can corrupt a valid provider request during a no-op managed LLM call.

The request decoder attempts to deserialize the complete Anthropic messages array into Relay's normalized Vec<Message>. Anthropic-native blocks such as tool_use and tool_result are not representable by the current normalized content types. The failed deserialization is silently converted to an empty vector:

// Extract messages (default to empty vec if absent).
let mut messages: Vec<Message> = obj
.get("messages")
.map(|v| serde_json::from_value(v.clone()).unwrap_or_default())
.unwrap_or_default();

The encoder then overlays the normalized values onto the original request. This replaces the original tool history with messages: [] and rewrites a block-form system value as a string, dropping block metadata such as cache_control:

fn encode(&self, annotated: &AnnotatedLlmRequest, original: &LlmRequest) -> Result<LlmRequest> {
let mut content = original.content.clone();
let obj = content
.as_object_mut()
.ok_or_else(|| FlowError::Internal("original content is not an object".into()))?;
let (system_text, non_system_messages) = split_system_and_messages(&annotated.messages);
if let Some(text) = system_text {
obj.insert("system".into(), Json::String(text));
}
// Overlay messages (non-system only).
insert_serialized(obj, "messages", &non_system_messages, "messages")?;

This occurs even when no request interceptor modifies the request because the managed execution path decodes and re-encodes whenever a request codec is supplied.

Given this input:

{
  "model": "claude-sonnet-4-20250514",
  "max_tokens": 128,
  "system": [
    {
      "type": "text",
      "text": "Be terse",
      "cache_control": {"type": "ephemeral"}
    }
  ],
  "messages": [
    {"role": "user", "content": "Check the weather"},
    {
      "role": "assistant",
      "content": [
        {
          "type": "tool_use",
          "id": "toolu_1",
          "name": "weather",
          "input": {"city": "Phoenix"}
        }
      ]
    },
    {
      "role": "user",
      "content": [
        {
          "type": "tool_result",
          "tool_use_id": "toolu_1",
          "content": "sunny"
        }
      ]
    }
  ]
}

the provider callback receives:

{
  "model": "claude-sonnet-4-20250514",
  "max_tokens": 128,
  "system": "Be terse",
  "messages": []
}

Expected behavior

A no-op decode()/encode() round trip must preserve a valid provider request, including Anthropic-native message blocks and block metadata.

Unsupported provider content must never be silently replaced or discarded. Relay should either preserve unmodeled content when merging normalized changes or return an explicit error before invoking the provider callback when a requested normalized rewrite cannot be applied safely.

This report does not prescribe whether the implementation should use codec-local opaque preservation or expand the normalized request types. Full normalized mutation support for every Anthropic block can be handled separately from preventing request corruption.

Steps to reproduce

import asyncio
import copy

import nemo_relay
from nemo_relay.codecs import AnthropicMessagesCodec


content = {
    "model": "claude-sonnet-4-20250514",
    "max_tokens": 128,
    "system": [
        {
            "type": "text",
            "text": "Be terse",
            "cache_control": {"type": "ephemeral"},
        }
    ],
    "messages": [
        {"role": "user", "content": "Check the weather"},
        {
            "role": "assistant",
            "content": [
                {
                    "type": "tool_use",
                    "id": "toolu_1",
                    "name": "weather",
                    "input": {"city": "Phoenix"},
                }
            ],
        },
        {
            "role": "user",
            "content": [
                {
                    "type": "tool_result",
                    "tool_use_id": "toolu_1",
                    "content": "sunny",
                }
            ],
        },
    ],
}


async def main():
    received = []

    async def provider(request):
        received.append(copy.deepcopy(request.content))
        return {"content": [{"type": "text", "text": "Sunny."}]}

    await nemo_relay.llm.execute(
        "anthropic",
        nemo_relay.LLMRequest({}, copy.deepcopy(content)),
        provider,
        codec=AnthropicMessagesCodec(),
        response_codec=None,
    )

    print(received[0])
    assert received[0] == content


asyncio.run(main())

The final assertion fails. The same failure was reproduced with a focused Rust regression test against current main by asserting that codec.encode(codec.decode(original), original) == original.

Environment

  • NeMo Relay: published Python package 0.5.0
  • NeMo Relay current main: f8a9e96d2d644a38e741fdd4809ac2d7bad5c2db
  • OS and architecture: macOS arm64
  • Python: 3.11
  • Rust: 1.96.1

Impact

Anthropic tool-using conversations can lose their complete tool-call and tool-result history before the provider is invoked. This can produce invalid requests, incorrect model behavior, or loss of conversational context. Flattening the system field also removes prompt-cache metadata and can affect latency and cost.

Plain-text-only requests may not expose the failure, so the first model call can succeed while a later call after tool execution is corrupted.

The current workaround is to omit the Anthropic request codec while retaining AnthropicMessagesCodec as the response codec. This preserves the provider request and keeps Relay scopes, lifecycle events, raw request intercepts, execution intercepts, guardrails, streaming, and response observability. The limitation is that normalized Anthropic request interceptors receive no AnnotatedLLMRequest until the request codec is fixed.

Activity

  1. self-assigned this
    on Jul 20, 2026
  2. added theissue type on Jul 20, 2026
  3. added
    Bug
    on Jul 20, 2026
  4. added this to the 0.6 milestone on Jul 20, 2026
  5. added a commit that references this issue on Jul 21, 2026
    c561b29
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

Bug

Type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions