Repository navigation
fix(sdk): normalize blank Chat Completions content across roles - #4981
Conversation
Co-authored-by: openhands <openhands@all-hands.dev>
|
📁 PR Artifacts Notice This PR contains a |
|
Thank you for the contribution @BORAN002 ! My agent seems to have found a risk of regression, do you think you could look into it? AGENT: P2 regression: skipping blank text blocks can discard the Anthropic prompt-cache breakpoint. The SDK automatically marks the last user/tool content block for caching. If a tool result ends with a blank block, this new continue skips the code that preserves its cache marker. I reproduced this through SDK serialization and LiteLLM’s Anthropic request conversion: base retains cache_control; PR loses it. That can reduce cache reuse and increase cost/latency. Preserve the tool-level marker before filtering, and cover this case. Otherwise, the intended fix checks out:
This changes LLM message serialization, so benchmark runs can encounter it regardless of which tools are registered. The repository’s review guide calls for lightweight evals and human review for this scope; I’d address the cache regression first. |
Co-authored-by: openhands <openhands@all-hands.dev>
Retain tool-level cache markers before filtering and carry trailing blank block markers onto preceding content for other roles. Cover automatic SDK caching through Anthropic request conversion and loopback HTTP. Co-authored-by: openhands <openhands@all-hands.dev>
|
Hi enyst, thanks for catching this — you're right.
The regression is fixed in [86199bd](86199bd). Tool-level cache markers are now preserved before filtering blank blocks, including when the tool result is entirely blank. Regression tests cover both mixed and entirely blank tool results.
Validation at this revision passed all 1,037 LLM tests, full pre-commit, the four original HTTP cases, and six Anthropic-compatible loopback HTTP cases. The reproduction scripts and logs are linked in the PR description.
These checks validate request serialization; no live-provider or benchmark validation had been performed at this stage.
|
all-hands-bot
left a comment
There was a problem hiding this comment.
This review was posted by an AI agent (OpenHands).
Reviewed detached checkout of head 86199bdf. Scope: this change belongs here — OpenHands/software-agent-sdk owns LLM message serialization, and issue #4965 was explicitly moved into this repo for the upstream fix.
What I verified on this head
to_chat_dictnow normalizescontent == []→""for every role (previously assistant-only), and_list_serializerdrops blank/whitespace-onlyTextContentblocks for every role. This matches the issue's acceptance criteria (no blank text block and no emptycontentarray reaches the wire).- Cache-breakpoint preservation:
role_tool_with_prompt_cachingis now computed from the unfiltered content, so a wholly blank tool result keeps its message-level marker; for other roles a trailing blank block's marker is moved onto the preceding block. I reproduced both shapes through SDK →LLM.format_messages_for_llm→ LiteLLMAnthropicConfig.transform_requestand confirmedcache_control: {"type": "ephemeral"}survives on the resulting Anthropic payload. - Tests:
uv run pytest tests/sdk/llm/test_message_serialization.py tests/sdk/llm/test_prompt_caching_cross_conversation.py -q→ 50 passed. Fulltests/sdk/llm→ 1034 passed, 3 failed; those 3 (test_get_credentials_dir_default,test_get_credentials_dir_xdg,test_reasoning_effort_support[openrouter/moonshotai/kimi-k2.5]) are sandbox/baseline-dependent (HOME path resolution and an unrelated litellm model-feature entry) and do not touch message serialization.
Why this is COMMENT rather than APPROVE
Per .agents/skills/custom-codereview-guide.md, changes to LLM message serialization are in the eval-risk category — they shape every request regardless of which tools are registered — and require either benchmark evidence (an eval-monitor link plus a maintainer confirming the results) or a human maintainer decision. The PR description states that no real provider or benchmark run was performed and that maintainer-triggered lightweight evals and human review are still outstanding, and there is no eval-monitor link or maintainer confirmation in the discussion. In addition, the fork CI checks on this head — including Run tests — are currently action_required, so there is no CI test evidence for 86199bdf yet. A maintainer should approve CI and run the lightweight eval before merge. This is a validation-evidence gate, not a code defect.
Non-blocking observation
When the last user/tool message consists solely of blank content there is no preceding block to receive the moved breakpoint, so the user-role breakpoint is dropped (serializes as content: "" with no marker). Wholly blank tool results are unaffected because the message-level marker is preserved. This shape is unusual for a real last user turn, so I do not consider it blocking.
🔄 CHANGES REQUESTED
|
Thanks for rechecking the serialization and prompt-cache fix. I have now merged current main in The current review guide, updated in #5176, distinguishes required evaluations from optional ones. Could a maintainer take another look and clarify whether any additional evaluation is required? The reproduction uses the real SDK/LiteLLM transport against a strict loopback HTTP endpoint on macOS. It does not establish behavior on Windows/TokenRouter, real provider cache hits, or benchmark performance. I do not have a working model API available, so any required live-provider run would need the maintainer environment. The repository supports |
Revalidate the serialization and prompt-cache fixes against current main: 1090 LLM tests, four HTTP cases, six cache-marker cases, and all pre-commit checks pass. Co-authored-by: openhands <openhands@all-hands.dev>
all-hands-bot
left a comment
There was a problem hiding this comment.
This review was posted by an AI agent (OpenHands).
Fresh review of head 86f87ccf. State re-read this pass: PR open, non-draft, head matches, no labels, no review requests, no unresolved review threads; linked issue #4965 is OPEN with labels bug, llm, priority:medium, sdk, ready-for-dev.
Scope: in-repo. OpenHands/software-agent-sdk owns LLM message serialization, and #4965 was moved here for the upstream fix.
Findings on this head
to_chat_dictnow normalizescontent == []→""for every role (the removed_normalize_empty_assistant_contentcovered assistant only), and_list_serializerdrops blank/whitespace-onlyTextContentblocks for every role. This satisfies the issue's acceptance criteria.- The earlier prompt-cache regression is addressed:
role_tool_with_prompt_cachingis computed from unfiltered content before blank filtering (so a wholly blank tool result keeps its message-level marker), and for other roles a removed trailing blank block's marker is moved onto the preceding retained block. I reproduced SDK →LLM.format_messages_for_llm→ LiteLLMAnthropicConfig.transform_requestlocally: trailing-blank user, wholly blank tool, and mixed tool results all keepcache_control: {"type": "ephemeral"}on the emitted Anthropic payload, and input messages are unchanged. - No public signature, persisted-schema, settings-default, or dependency changes;
.pr/artifacts are workflow-owned.
Verification I ran on this head
uv run pytest tests/sdk/llm -q: 1088 passed, 2 failed. Both failures (test_get_credentials_dir_default,test_get_credentials_dir_xdg) are sandbox artifacts — this environment'sHOMEis/var/openhands/.openhands, so the expected.openhands/authpath assertion cannot hold. They are unrelated to message serialization.- Focused
tests/sdk/llm/test_message_serialization.py+tests/sdk/llm/test_prompt_caching_cross_conversation.py: 50 passed. - Current-head CI is fully green, including
sdk-tests,integration-test,pre-commit,windows-tests, and build/test on the new head.
Eval risk (for the human maintainer)
This changes LLM request serialization, so it can plausibly affect benchmark behavior regardless of registered tools. Per the current review guide's "Agent behavior and evaluation" section, missing optional eval evidence is not by itself a code defect and does not justify withholding approval, so I am approving and flagging the risk here rather than blocking. The reproduction is loopback-only: it does not establish real-provider cache hits, cost, latency, or benchmark performance, and the author notes no live model API is available. The maintainer should choose the appropriate lightweight evaluation (the PR suggests run-eval-1 as the smallest configured benchmark) after merge or before, as they prefer.
✅ APPROVED
neubig
left a comment
There was a problem hiding this comment.
Which provider did you test this with? Can you provide a program that can reproduce the error?
Record matching base and PR requests accepted by DeepSeek without claiming reproduction of the TokenRouter rejection. Co-authored-by: openhands <openhands@all-hands.dev>
|
Thanks @neubig. My earlier validation used a local HTTP test server, not a live model provider. The original report (#4965) used TokenRouter ( I have now tested the official DeepSeek API ( The DeepSeek program and both request/response logs are now included. It sends For a runnable reproduction of the reported rejection rule, the local SDK/LiteLLM program is available without an API key. After .venv/bin/python .pr/repro_chat_content.pyCopy the same script into |
all-hands-bot
left a comment
There was a problem hiding this comment.
This review was posted by an AI agent (OpenHands).
Fresh review of head 8e398742. State re-read this pass: PR open, non-draft, head matches, no labels, no review requests, no unresolved review threads, reviewDecision APPROVED; linked issue #4965 is OPEN with labels bug, llm, priority:medium, sdk, ready-for-dev. Since the previous review at 86f87ccf, @neubig asked which provider was tested and for a reproducing program, and the author replied with a DeepSeek live comparison.
Scope: in-repo. OpenHands/software-agent-sdk owns LLM message serialization, and #4965 was moved here for the upstream fix.
What changed at this head
git diff 86f87ccf..8e398742 touches only .pr/ artifacts: deepseek-live-validation.md, repro_chat_content_deepseek.py, deepseek-base.jsonl, deepseek-head.jsonl, and a validation.md refresh. openhands-sdk/openhands/sdk/llm/message.py and both test files are byte-identical to the revision I approved at 86f87ccf, so the code findings there carry over unchanged.
Findings on this head
- The serialization fix is unchanged:
to_chat_dictnormalizescontent == []→""for every role, and_list_serializerdrops blank/whitespace-onlyTextContentblocks for every role, satisfying #4965's acceptance criteria. - The earlier prompt-cache regression remains fixed: the tool-level cache flag is computed from unfiltered content, so a wholly blank tool result keeps its message-level marker, and for other roles a removed trailing blank block's marker moves to the preceding retained block. I re-ran my SDK →
LLM.format_messages_for_llm→ LiteLLMAnthropicConfig.transform_requestcheck on this head and confirmedcache_control: {"type": "ephemeral"}survives for trailing-blank user, wholly blank tool, and mixed tool results, with input messages unchanged. - No public signature, persisted-schema, settings-default, dependency, or production-code change at this head; the
.pr/additions are workflow-owned review evidence and contain no credentials (the only key literals are the deliberatelocal-test-only-not-a-real-keyplaceholders).
Verification I ran on this head
uv run pytest tests/sdk/llm -q: 1088 passed, 2 failed. Both failures (test_get_credentials_dir_default,test_get_credentials_dir_xdg) are sandbox artifacts — this environment'sHOMEis/var/openhands/.openhands, so the expected.openhands/authpath assertion cannot hold. They are unrelated to message serialization and also fail on base.- Focused
tests/sdk/llm/test_message_serialization.py+tests/sdk/llm/test_prompt_caching_cross_conversation.py: 50 passed. - Current-head CI: all 41 check runs on
8e398742aresuccessorskipped, includingsdk-tests,integration-test,pre-commit,windows-tests, and the macOS/Ubuntu/Windows binary builds.
Eval risk (for the human maintainer)
This changes LLM request serialization, so it can plausibly affect benchmark behavior regardless of registered tools. The new DeepSeek evidence is compatibility-only: the author explicitly states DeepSeek accepted both the base and PR payloads and did not reproduce the original TokenRouter rejection, and that no Agent benchmark was run. Per the current review guide's "Agent behavior and evaluation" section, missing optional eval evidence is not by itself a code defect and does not justify withholding approval, so I am approving and flagging the risk here rather than blocking. The maintainer should choose any additional lightweight evaluation (the PR suggests run-eval-1) as they see fit; independent TokenRouter validation remains outstanding and is the author's to arrange.
✅ APPROVED
juanmichelini
left a comment
There was a problem hiding this comment.
Thanks for the PR! Could you test this yourself to confirm it works?
A short video or screenshots showing it works would be helpful
|
Thanks @juanmichelini. I ran this myself on macOS today; the screenshot below is from my terminal. This run uses the public
All four calls ended with Both versions succeeded, so this is live SDK/DeepSeek compatibility evidence; it did not reproduce the original TokenRouter rejection. It is also separate from a full Agent task, benchmark, or live Anthropic cache-hit test. The local strict-server reproduction and cache-marker checks remain the evidence for those serialization cases. I have attached the exact test script, the terminal wrapper, both JSONL logs, and rerun instructions so the result can be inspected beyond the screenshot. Only local SDK source paths in the shared logs are replaced with checkout labels. Command used: .venv/bin/python .pr/demo_deepseek_sdk.py --live
|
This comment was marked as outdated.
This comment was marked as outdated.
|
Preview verification failed: #4981 comes from the fork This comment was posted by an AI agent (OpenHands) on behalf of the user. |

HUMAN:
I want conversations containing empty text blocks to work reliably without losing prompt-cache markers. This PR addresses the serialization issue in #4965 and the cache regression identified during review.
AGENT:
Why
The SDK can serialize empty content arrays or whitespace-only text blocks into Chat Completions requests. Strict endpoints can reject these payloads with HTTP 400, as reported in #4965.
Summary
"".Issue Number
Fixes #4965.
How to Test
Local reproduction and regression tests
After syncing main at a350dc7, validation on PR revision 86f87cc recorded:
.venv/bin/python .pr/repro_chat_content.py: 4/4 passed through SDK → LiteLLM → a strict loopback HTTP server. The baseline returned HTTP 400 for all four cases; the fixed version returned HTTP 200..venv/bin/python .pr/repro_prompt_cache.py: 6/6 cache markers retained in Anthropic-compatible HTTP requests, covering mixed and wholly blank tool results and mixed user content.uv run pytest tests/sdk/llm -q: 1,090 passed.uv run pre-commit run --all-files --show-diff-on-failure: passed.The production fix and regression tests are unchanged at head 8e39874. Reproduction instructions and logs.
Live SDK validation — October 7
On macOS, the public
LLM.completion()path was tested through LiteLLM's native DeepSeek adapter against the officialdeepseek-flashAPI. Base a350dc7 and head 8e39874 used the same script and dependency versions, with each checkout importing its own SDK.Both the normal control and a whitespace-only assistant message completed on both revisions: four calls total, all with
finish_reason=stop.Command:
.venv/bin/python .pr/demo_deepseek_sdk.py --live.The script, wrapper, JSONL logs, rerun instructions, and terminal screenshot are attached in the October 7 validation comment.
An earlier September 28 comparison sent
Message.to_chat_dict()output directly over HTTP. Its control and four edge cases succeeded on both revisions; that run did not use the LiteLLM transport path.Video/Screenshots
Terminal screenshot and runnable SDK validation.
Design Doc
Reproduction details are linked above.
Type
Notes
DeepSeek accepted both the base and fixed payloads, so the live runs establish compatibility, not reproduction of the original TokenRouter rejection. The strict-server comparison is local evidence only. TokenRouter, live Anthropic cache hits, and full Agent benchmarks remain unverified. No public API or persisted-schema change.
The October 30 preview attempt timed out waiting for the Agent Server image for this head. The Docker build/publish jobs were skipped in the workflow; preview validation remains pending.