Files
headroom/tests/gateway/test_native_shapes.py
d6df127d57 feat(compress): accept Gemini and Bedrock Converse bodies on the gateway turn (#4679)
## Description

`/v1/compress` in gateway mode (a request with a `gateway` block) now
accepts two more native request bodies:
- Gemini `generateContent`
- Bedrock Converse

It compresses their text slots and returns `body` in the same native
shape. This lets a gateway like LiteLLM compress native Gemini and
Bedrock passthrough traffic, which it couldn't before.

`config.mode: "ccr"` is rejected for these shapes with a 400. Every
other mode is marker-free for them.

(Was stacked on #4617, which has merged; the branch now carries current
`main`.)

## Type of Change

- [ ] Bug fix (non-breaking change that fixes an issue)
- [x] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [x] Documentation update
- [ ] Performance improvement
- [ ] Code refactoring (no functional changes)

## Changes Made

### How

This works the same way `gateway_responses` does for Codex: it builds a
view instead of translating the body.
- Every compressible text slot becomes one chat-shaped pseudo message.
- Compressed text is written back by its path in the body.
- Everything else stays byte-identical: `thoughtSignature`, thought
parts, `functionCall`, `inlineData`, `toolUse`, `cachePoint`,
`reasoningContent`, `tools`/`toolConfig`.
- Tool calls appear in the view, so tool-name rules still apply. `Read`
stays verbatim, for example.
- A JSON slot is only written back if it still parses to the same JSON
type.
- If the compressed list doesn't line up with the slots, the original
transcript is forwarded and a warning is logged.

### CCR on native bodies (review fix)

A native body can't carry `headroom_retrieve`. Its `tools`/`toolConfig`
are forwarded untouched, and `create_ccr_tool_definition` only builds
chat, Anthropic and Responses shapes. It also never gets a re-drive. So
a CCR marker in a native body points at content the model can never
fetch. Before this fix, `config.mode: "ccr"` on a Gemini or Converse
gateway turn did exactly that: log output came back as a marker with
`ccr_hashes: [<hash>]` and `obligations: []`.

- `handle_compress` now answers `ccr` on a native view with `400
invalid_request`. The message names the shape, explains why, and lists
the supported modes.
- The check runs where the mode is chosen, right after `attach_view` has
recorded the shape. That is before any compression, session work or CCR
store write.
- **The rejection does not depend on `gateway.can_redrive`.** Even a
gateway that can re-drive has no way to put the retrieval tool into a
native request, so there is no capability under which native `ccr`
works.
- **Without a `gateway` block nothing changes.** A Gemini body is
already a 400 (no `messages`). A Converse body goes through the plain
messages path, where its untyped blocks are opaque: 0 tokens saved, no
markers in any mode, `ccr` included (checked). So the rule is
consistent: reject `ccr` wherever Headroom reads a native shape.
- The bypass header still returns the body untouched with no
compression, in any mode.
- I checked every other mode on the same marker-producing input
(default, `lossless`, `lossy_inline`, `lossless_then_lossy`): no marker
and no hash in any of them. These modes build pipelines with
`ccr_inject_marker=False, ccr_enabled=False`. Stale-Read notices are
hashless in marker-free modes since #4678.
- **Second defect, same family:** with `HEADROOM_DEDUPE=1`, cross-turn
dedup wrote `[↑NL same as msg 4]` into a Converse tool result. That `4`
counts view messages (system blocks, tool calls, result slots), not the
caller's `messages`, so it named the wrong message. Native views now set
`cross_turn_dedup_recoverable=False`, as `lossless` mode already did.
- The `not self.native_shape` guards on CCR arming and re-drive in
`GatewayTurn.finish` stay as defence in depth.

### Caller contract

**Gemini**
- Send top-level `contents` as a list, with no `messages` or `input`.
- `systemInstruction`/`system_instruction`, `tools` and
`generationConfig` are optional and pass through.

**Converse**
- Send `messages` where every message has role `user` or `assistant`,
and every content block has no `type` key.
- At least one block must use a Converse key: `text`, `toolUse`,
`toolResult`, `cachePoint`, and so on.
- `system` is optional, as a list of blocks.

**Both shapes**
- `config.mode`: omit it (marker-free default), or use `lossless`,
`lossy_inline` or `lossless_then_lossy`. `ccr` is a 400.
- Only gateway turns get a view. Without a `gateway` block the endpoint
behaves exactly as before. A client-sent `_headroom_native_view` key is
dropped, and `BODY_CONTROL_KEYS` strips the real one before the body is
returned.
- `config.frozen_message_count` and `config.protect_recent` count native
messages: Gemini `contents` entries and Converse `messages`.
`session.frozen_message_count` comes back in native units. The
`/v1/usage` reply's `frozen_message_count` still counts view messages,
and the docs say so.
- No re-drive is ever armed, so `obligations` never contains `redrive`,
and request hooks run stream-safe-only. Tool compaction and output
steering are skipped.
- Relayed usage can be:
- Gemini `usageMetadata`, where `promptTokenCount` already includes
`cachedContentTokenCount`.
- Converse `usage`, where `inputTokens` excludes `cacheReadInputTokens`
and `cacheWriteInputTokens`.
  - The whole provider response that carries either.
- Every gateway answer, fail-open ones included, carries `wire_shape`:
`gemini`, `converse`, `openai_responses` or `messages`. A caller that
sent a native body and gets anything else, or no field at all, is
talking to an older Headroom and should forward its original body.
- Top-level `messages` in the answer is the Converse list for Converse
and the chat-shaped view for Gemini.

## Testing

- [x] Unit tests pass (`pytest`)
- [x] Linting passes (`ruff check .`)
- [x] Type checking passes (`mypy headroom`): no new errors; the 8
reported are in `ccr/mcp_server.py` and `cache/prefix_tracker.py` and
are identical on `main`
- [x] New tests added for new functionality
- [x] Manual testing performed (local replay, below)

New in `tests/gateway/test_native_shapes.py`:
- `test_ccr_mode_is_rejected_for_native_bodies[gemini|converse]`: 400,
`invalid_request`, message asserted.
- `test_other_modes_forward_native_bodies_without_ccr_markers`: 4 modes
x 2 shapes, on log output large enough to produce a marker. Checks no
hash, no marker, the shape echoed, non-message keys byte-identical and
the native list mapped back.
- `test_ccr_still_works_on_a_chat_gateway_turn`: the same log output in
a chat body with `ccr` still carries a marker. This proves the input
above is marker-producing, and that chat `ccr` didn't regress.
- `test_native_bodies_get_no_dedup_pointer_into_view_messages`.
- `test_native_turns_are_never_asked_to_redrive` now runs in the default
mode, because `ccr` is a 400.

### Test Output

```text
# before the fix (new tests only, rest of the file passing)
FAILED tests/gateway/test_native_shapes.py::test_ccr_mode_is_rejected_for_native_bodies[gemini]
FAILED tests/gateway/test_native_shapes.py::test_ccr_mode_is_rejected_for_native_bodies[converse]
FAILED tests/gateway/test_native_shapes.py::test_native_bodies_get_no_dedup_pointer_into_view_messages
3 failed, 25 passed

# after
tests/gateway/test_native_shapes.py: 28 passed

# tests/gateway tests/test_gateway_turn_unit.py tests/test_compress_api.py
# tests/test_proxy_compress_endpoint.py tests/test_compress_session_mode.py
# tests/test_compress_session_shared.py tests/test_compress_passthrough.py tests/test_compress_failure.py
1 failed, 507 passed, 4 skipped
# the one failure, test_lossy_inline_emits_no_ccr_markers[1-json_minifier], fails identically on main fda75de5

uvx ruff@0.17.3 check / format --check (changed files): All checks passed! / 3 files already formatted
```

## Real Behavior Proof

These are local synthetic replays. They are not provider qualification.

- Environment: macOS, Python venv, branch head `530c20aa`. Headroom runs
in-process via `create_app(ProxyConfig(optimize=True,
cache_enabled=False, rate_limit_enabled=False,
cost_tracking_enabled=False, log_requests=False, image_optimize=False))`
behind `fastapi.testclient.TestClient` from a loopback client. The
"provider" is an `httpx.MockTransport` that records each body it
receives and answers with a Gemini `generateContent` or Bedrock Converse
response, including usage. `LITELLM_LOCAL_MODEL_COST_MAP=True`. No real
provider calls.
- Exact command / steps: `LITELLM_LOCAL_MODEL_COST_MAP=True python -I -c
"import sys; sys.path.insert(0,'<worktree>');
exec(open('native_replay.py').read())"`. For each shape the script does
three things:
1. POSTs the native body plus `gateway: {can_redrive, session_affinity,
can_relay_response: true}` to `/v1/compress`.
2. Sends the returned `body` through the mock upstream at the real
Gemini or Bedrock URL.
3. POSTs the provider's whole response to `/v1/compress/response` with
the `turn_id`.

It then sends both native bodies again with `config.mode: "ccr"`. The
tool output is the 399-line grep listing used in the tests. The `ccr`
requests use 3000 log lines, which produce a marker in `ccr` mode.
- Observed result:

```text
[gemini] request half: wire_shape=gemini obligations=['relay_usage'] tokens 7246->3863 ccr_hashes=[] marker_in_body=False
[gemini] all 399 grep lines still readable in the forwarded body=True
[gemini] non-message keys unchanged=True first two contents unchanged=True
[gemini] provider got 16125 bytes (raw 29694), control keys forwarded=[], host=generativelanguage.googleapis.com
[gemini] response half: 200 {'action': 'done', ..., 'billed_usage': {'input_tokens': 900, 'output_tokens': 12, 'cache_read_input_tokens': 512}}
[converse] request half: wire_shape=converse obligations=['relay_usage'] tokens 8823->4843 ccr_hashes=[] marker_in_body=False
[converse] all 399 grep lines still readable in the forwarded body=True
[converse] non-message keys unchanged=True first two messages unchanged=True
[converse] provider got 16184 bytes (raw 29761), control keys forwarded=[], host=bedrock-runtime.us-west-2.amazonaws.com
[converse] response half: 200 {'action': 'done', ..., 'billed_usage': {'input_tokens': 300, 'output_tokens': 12, 'cache_read_input_tokens': 600, 'cache_creation_input_tokens': 0}}
[gemini ccr] 400 {'error': {'type': 'invalid_request', 'message': "config.mode='ccr' is not supported for gemini bodies: Headroom cannot add its retrieval tool to a native Gemini or Bedrock Converse request, so the model could not resolve a CCR marker. Use lossless, lossy_inline or lossless_then_lossy, or omit config.mode for the default marker-free mode."}}
[converse ccr] 400 {'error': {'type': 'invalid_request', 'message': "config.mode='ccr' is not supported for converse bodies: ..."}}
provider calls: 2
```

Before the fix, the same `ccr` requests returned 200 with `ccr_hashes`
of length 1, a `hash=` marker in the forwarded body, and `obligations:
[]`.
- Not tested:
- live Gemini (AI Studio or Vertex) and live Bedrock Converse: the
provider was mocked, so provider acceptance of the rewritten bodies is
unverified;
  - real Kong `ai-proxy` or a real LiteLLM gateway in front of Headroom;
- streaming callers (`streamGenerateContent`, `ConverseStream`): the
request half is identical, but no streamed response was relayed;
  - Gemini `thoughtsTokenCount` in output accounting;
  - session mode with a Redis store for native bodies;
- multimodal parts (`inlineData`, `image`, `document`) beyond their
byte-identical pass-through in unit tests.

## Runtime Rollout Safety

- Rollout-managed feature(s): none. Native shapes only activate for
gateway-mode `/v1/compress` callers that send a `gateway` block and a
native body.
- Minimum rollout channel: n/a
- Stable/default behavior changed: no for existing callers. Chat,
Anthropic and Responses bodies are unchanged. A Converse body without a
`gateway` block goes through the plain path as before. Before this PR, a
native body with a `gateway` block was misread as chat (Converse) or
rejected (Gemini).
- Kill switch / disable path: the gateway omits the `gateway` block, or
forwards its original body when `wire_shape` doesn't match.
- Unsafe override required: no
- Qualification impact: none for existing paths
- Rollback path: revert this PR

## Review Readiness

- [x] I have performed a self-review
- [x] This PR is ready for human review

## Checklist

- [x] My code follows the project's style guidelines
- [x] I have performed a self-review of my code
- [x] I have commented my code, particularly in hard-to-understand areas
- [x] I have made corresponding changes to the documentation
- [x] My changes generate no new warnings
- [x] I have added tests that prove my fix is effective or that my
feature works
- [x] New and existing unit tests pass locally with my changes
- [x] I did **not** edit `CHANGELOG.md`

## Additional Notes

Known follow-ups, not in this PR:
- A `functionResponse.response` with any string field never compresses
its nested dict values. The JSON slot is only used when there are no
string fields. This is a missed saving, not a correctness bug.
- `handlers/gemini.py` (the proxy path) and `gateway_native.py` map
Gemini parts with different rules, and their part-key lists are kept in
step by hand. They should share one constant.
- `protect_recent` translation and stream-safe hook gating for native
turns have no dedicated test.
- Gemini `thoughtsTokenCount` is not added to output tokens when usage
is relayed, so output savings attribution undercounts for thinking
models.
- This is not specific to native shapes: the marker-free default folds
very repetitive logs to a single line (for example `[3000 lines omitted:
3000 INFO]`) on chat bodies too, with no retrieval path.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: JD Davis <mxjerrett@gmail.com>
2026-11-15 01:52:50 +05:30

375 lines
13 KiB
Python

"""Gemini ``generateContent`` and Bedrock Converse bodies on ``/v1/compress``.
What matters is what must NOT change: every part the provider needs back
(``thoughtSignature``, ``functionCall``, ``toolUse``, ``cachePoint``) comes back
byte-identical, and the body comes back in the shape it arrived in.
"""
from __future__ import annotations
import copy
import json
from unittest.mock import AsyncMock
import pytest
from headroom.proxy.gateway_native import apply_view, attach_view, native_shape
from tests.gateway.samples import anthropic_tool_history
GREP = "\n".join(
f"headroom/proxy/handlers/openai.py:{i}: value_{i} = compute(value_{i})"
for i in range(1, 400)
)
SIGNATURE = "CtYBAdHtim9vDGb1wQ5opaque"
def _compress(client, body, gateway=None, **config):
sent = {
**copy.deepcopy(body),
"gateway": gateway or {},
"config": {"mode": "lossless", **config},
}
resp = client.post("/v1/compress", json=sent)
assert resp.status_code == 200, resp.text
return resp.json()
def gemini_body() -> dict:
return {
"model": "gemini-2.5-pro",
"systemInstruction": {"parts": [{"text": "You are a coding agent."}]},
"contents": [
{"role": "user", "parts": [{"text": "Find the values."}]},
{
"role": "model",
"parts": [
{
"functionCall": {"name": "grep", "args": {"pattern": "value_"}},
"thoughtSignature": SIGNATURE,
}
],
},
{
"role": "user",
"parts": [{"functionResponse": {"name": "grep", "response": {"output": GREP}}}],
},
],
"tools": [{"functionDeclarations": [{"name": "grep", "parameters": {"type": "object"}}]}],
"generationConfig": {"temperature": 0},
}
def converse_body() -> dict:
rows = [{"id": i, "name": f"item {i}", "status": "active"} for i in range(50)]
return {
"model": "bedrock/anthropic.claude-sonnet-4-5",
"system": [{"text": "You are a coding agent."}, {"cachePoint": {"type": "default"}}],
"messages": [
{"role": "user", "content": [{"text": "Find the values."}]},
{
"role": "assistant",
"content": [
{"toolUse": {"toolUseId": "tu_1", "name": "grep", "input": {"p": "value_"}}}
],
},
{
"role": "user",
"content": [
{
"toolResult": {
"toolUseId": "tu_1",
"content": [{"text": GREP}, {"json": {"rows": rows}}],
"status": "success",
}
},
{"cachePoint": {"type": "default"}},
],
},
],
"inferenceConfig": {"maxTokens": 1024},
"toolConfig": {"tools": [{"toolSpec": {"name": "grep", "inputSchema": {"json": {}}}}]},
}
def test_a_gemini_body_comes_back_as_gemini_with_its_tool_output_folded(headroom_client):
sent = gemini_body()
data = _compress(headroom_client, sent)
body = data["body"]
assert data["wire_shape"] == "gemini"
assert "messages" not in body
assert {k: v for k, v in body.items() if k != "contents"} == {
k: v for k, v in sent.items() if k != "contents"
}
assert body["contents"][:2] == sent["contents"][:2]
folded = body["contents"][2]["parts"][0]["functionResponse"]["response"]["output"]
assert len(folded) < len(GREP)
assert all(f"value_{i} = compute(value_{i})" in folded for i in range(1, 400))
def test_a_converse_body_comes_back_as_converse_with_its_tool_output_folded(headroom_client):
sent = converse_body()
data = _compress(headroom_client, sent)
body = data["body"]
assert data["wire_shape"] == "converse"
assert {k: v for k, v in body.items() if k != "messages"} == {
k: v for k, v in sent.items() if k != "messages"
}
assert body["messages"][:2] == sent["messages"][:2]
result_block, cache_point = body["messages"][2]["content"]
assert cache_point == {"cachePoint": {"type": "default"}}
result = result_block["toolResult"]
assert result["toolUseId"] == "tu_1" and result["status"] == "success"
folded, rows = result["content"]
assert len(folded["text"]) < len(GREP)
assert all(f"value_{i} = compute(value_{i})" in folded["text"] for i in range(1, 400))
assert isinstance(rows["json"], dict)
json.dumps(rows["json"])
assert data["obligations"] == []
@pytest.mark.parametrize(
"messages",
[
anthropic_tool_history(),
[{"role": "user", "content": [{"type": "text", "text": "hi"}]}],
# Untyped parts, but `system` is not a Converse role.
[
{"role": "system", "content": [{"text": "You are terse."}]},
{"role": "user", "content": [{"text": "hi"}]},
],
],
ids=["anthropic", "openai-typed", "openai-untyped-system"],
)
def test_a_messages_body_is_not_mistaken_for_converse(headroom_client, messages):
sent = {"model": "claude-sonnet-4-5", "messages": messages}
assert native_shape(sent) is None
data = _compress(headroom_client, sent)
assert data["wire_shape"] == "messages"
assert [m["role"] for m in data["body"]["messages"]] == [m["role"] for m in messages]
assert data["messages"] == data["body"]["messages"]
def test_a_client_supplied_view_marker_is_ignored(headroom_client):
sent = {
"model": "gpt-4o",
"messages": [{"role": "user", "content": "hi"}],
"_headroom_native_view": {"shape": "gemini"},
}
data = _compress(headroom_client, sent)
assert data["body"]["messages"] == sent["messages"]
def test_without_a_gateway_block_native_bodies_are_handled_as_before(headroom_client):
converse = converse_body()
resp = headroom_client.post("/v1/compress", json=converse)
assert resp.status_code == 200, resp.text
returned = resp.json()["messages"]
assert [m["role"] for m in returned] == ["user", "assistant", "user"]
assert returned[1] == converse["messages"][1]
resp = headroom_client.post("/v1/compress", json=gemini_body())
assert resp.status_code == 400
def test_counts_the_caller_sends_are_in_native_messages(headroom_client):
sent = converse_body()
sent["system"] = [{"text": f"Rule {i}."} for i in range(3)]
data = _compress(headroom_client, sent, session_id="native-frozen", frozen_message_count=3)
assert data["body"]["messages"] == sent["messages"]
assert data["session"]["frozen_message_count"] == 3
REDRIVE_GATEWAY = {"can_redrive": True, "session_affinity": True, "can_relay_response": True}
# Log output the CCR pipeline replaces with a retrieval marker (see
# `test_ccr_still_works_on_a_chat_gateway_turn`), so a mode that lets markers
# through would show one here.
LOGS = "\n".join(
f"2026-01-01T00:00:{i % 60:02d} INFO worker-{i % 5} processed batch {i} in {i % 13}ms"
for i in range(3000)
)
def gemini_logs_body() -> dict:
body = gemini_body()
body["contents"][2]["parts"][0]["functionResponse"]["response"]["output"] = LOGS
return body
def converse_logs_body() -> dict:
body = converse_body()
body["messages"][2]["content"][0]["toolResult"]["content"] = [{"text": LOGS}]
return body
def _carries_ccr_marker(data: dict) -> bool:
blob = json.dumps(data["body"])
return bool(data["ccr_hashes"]) or "hash=" in blob or "<<ccr:" in blob
def test_native_turns_are_never_asked_to_redrive(headroom_client):
data = _compress(headroom_client, converse_body(), gateway=REDRIVE_GATEWAY, mode=None)
assert "redrive" not in data["obligations"]
assert "relay_usage" in data["obligations"]
@pytest.mark.parametrize(
("make_body", "shape"),
[(gemini_logs_body, "gemini"), (converse_logs_body, "converse")],
ids=["gemini", "converse"],
)
def test_ccr_mode_is_rejected_for_native_bodies(headroom_client, make_body, shape):
sent = {**make_body(), "gateway": REDRIVE_GATEWAY, "config": {"mode": "ccr"}}
resp = headroom_client.post("/v1/compress", json=sent)
assert resp.status_code == 400, resp.text
error = resp.json()["error"]
assert error["type"] == "invalid_request"
assert f"config.mode='ccr' is not supported for {shape} bodies" in error["message"]
for supported in ("lossless", "lossy_inline", "lossless_then_lossy"):
assert supported in error["message"]
@pytest.mark.parametrize("mode", [None, "lossless", "lossy_inline", "lossless_then_lossy"])
@pytest.mark.parametrize(
("make_body", "native"),
[(gemini_logs_body, "contents"), (converse_logs_body, "messages")],
ids=["gemini", "converse"],
)
def test_other_modes_forward_native_bodies_without_ccr_markers(
headroom_client, make_body, native, mode
):
sent = make_body()
data = _compress(headroom_client, sent, gateway=REDRIVE_GATEWAY, mode=mode)
body = data["body"]
assert not _carries_ccr_marker(data)
assert data["wire_shape"] == ("gemini" if native == "contents" else "converse")
assert {k: v for k, v in body.items() if k != native} == {
k: v for k, v in sent.items() if k != native
}
assert body[native][:2] == sent[native][:2]
assert len(body[native]) == len(sent[native])
def test_ccr_still_works_on_a_chat_gateway_turn(headroom_client):
sent = {
"model": "gpt-4o",
"messages": [
{"role": "user", "content": "Run it."},
{
"role": "assistant",
"content": None,
"tool_calls": [
{
"id": "c1",
"type": "function",
"function": {"name": "bash", "arguments": "{}"},
}
],
},
{"role": "tool", "tool_call_id": "c1", "content": LOGS},
{"role": "user", "content": "Summarize."},
],
}
data = _compress(headroom_client, sent, gateway=REDRIVE_GATEWAY, mode="ccr")
assert data["wire_shape"] == "messages"
assert _carries_ccr_marker(data)
def test_native_bodies_get_no_dedup_pointer_into_view_messages(make_headroom_client, monkeypatch):
# `[↑NL same as msg M]` counts Headroom's view messages, which are not the
# caller's native messages.
monkeypatch.setenv("HEADROOM_DEDUPE", "1")
client = make_headroom_client()
output = "\n".join(f"2026-01-01 worker-{i} finished job {i}" for i in range(400))
messages = [{"role": "user", "content": [{"text": "Run it twice."}]}]
for n in (1, 2):
use = {"toolUseId": f"tu_{n}", "name": "Bash", "input": {}}
result = {"toolUseId": f"tu_{n}", "content": [{"text": output}], "status": "success"}
messages.append({"role": "assistant", "content": [{"toolUse": use}]})
messages.append({"role": "user", "content": [{"toolResult": result}]})
sent = {**converse_body(), "messages": messages}
data = _compress(client, sent, mode=None)
assert "same as msg" not in json.dumps(data["body"])
def test_a_converse_fail_open_answer_keeps_its_own_messages(headroom_client, monkeypatch):
proxy = headroom_client.app.state.proxy
monkeypatch.setattr(proxy, "_run_compression_in_executor", AsyncMock(side_effect=TimeoutError))
sent = converse_body()
data = _compress(headroom_client, sent)
assert data["body"]["messages"] == sent["messages"]
assert data["messages"] == sent["messages"]
def _view_of(body):
body = {**copy.deepcopy(body), "gateway": {}}
assert attach_view(body)
marker = body.pop("_headroom_native_view")
view = body.pop("messages")
body.pop("gateway")
return body, marker, view
@pytest.mark.parametrize("rewritten", ["not json", "[1, 2]"])
def test_a_json_slot_is_only_written_back_as_the_same_json_type(rewritten):
body, marker, view = _view_of(converse_body())
json_slot = next(
i for i, m in enumerate(view) if m["role"] == "tool" and m["content"].startswith("{")
)
view[json_slot] = {**view[json_slot], "content": rewritten}
out, aligned = apply_view(body, marker, view)
assert aligned
assert out["messages"] == converse_body()["messages"]
def test_a_view_that_does_not_line_up_forwards_the_original():
body, marker, view = _view_of(converse_body())
out, aligned = apply_view(body, marker, [*view, {"role": "user", "content": "extra"}])
assert not aligned
assert out["messages"] == converse_body()["messages"]
def _gemini_read(response_id=None):
body = gemini_body()
body["contents"][1]["parts"][0]["functionCall"]["name"] = "Read"
response = body["contents"][2]["parts"][0]["functionResponse"]
response["name"] = "Read"
if response_id:
response["id"] = response_id
return body
def _converse_read():
body = converse_body()
body["messages"][1]["content"][0]["toolUse"]["name"] = "Read"
return body
@pytest.mark.parametrize(
"sent",
[_gemini_read(), _gemini_read(response_id="resp_1"), _converse_read()],
ids=["gemini", "gemini-response-id-only", "converse"],
)
def test_a_read_result_keeps_its_bytes_because_the_tool_name_is_seen(headroom_client, sent):
data = _compress(headroom_client, sent)
native = "contents" if "contents" in sent else "messages"
assert data["body"][native] == sent[native]