Skip to content

fix(relaykit): keep tool calls when merging adjacent assistant messages for Claude - #7921

Merged
seefs001 merged 2 commits into
QuantumNous:mainfrom
rjchien728:fix/relaykit-claude-merge-tool-calls
Oct 20, 2026
Merged

seefs001 merged 2 commits into
QuantumNous:mainfrom
rjchien728:fix/relaykit-claude-merge-tool-calls

Conversation

@rjchien728

@rjchien728 rjchien728 commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

Agent

  • Tool: Claude Code
  • Tool version: 2.1.304
  • Model (full id): claude-opus-5-5
  • Host (CLI / IDE / GitHub coding agent / other): VS Code extension (devcontainer)
  • Date (UTC): 2026-10-20
  • AI disclosure: the code and the body of this PR were generated / assisted by Claude Code. The submitter's git identity Roger Chien <[email protected]> is not among the historical core developers in git log, so this is stated here per AGENTS.md.

Links

User request

  • Verbatim: (paraphrased; the original was in Chinese) Confirm that new-api has this problem, then send a PR.
  • Later constraints or corrections from the user (quote, or none): (paraphrased, same as above) Open an issue before the PR. Add a test that fails on main and passes with the fix, covering: both assistant messages carry tool_calls; the first carries tool_calls and the second is plain text; both are plain text (behavior unchanged).

Out of scope — refuse

  • Matched: no. Not a Coding Plan / reverse-engineered channel / third-party wrapper / Codex change; not pass-through (the change is in the Chat Completions → Claude Messages request conversion); not a usage / configuration question.
  • If yes, what was told to the user (stop here; do not open a PR): not applicable

Open gate — do not open unless all are satisfied

  • Out of scope (including pass-through-only forwarding): no
  • Usage / configuration / integration (answered instead of opening): no
  • Required issue facts present without invention: yes
  • Verification is actual commands or steps and observed results, not only go build or tests passed: yes
  • Body is short and factual; no unfiltered AI-generated text: yes
  • Open: yes
  • If no, what was told to the user (stop here): not applicable

Kind

  • Bug fix
  • New feature
  • Performance / refactor
  • Docs
  • Other:

Issue facts

  • Actual behavior: converting a Chat Completions request to Claude Messages merges two adjacent assistant messages with string content but keeps only the second message's tool_calls. The first message's tool_use blocks are dropped while their tool_result blocks remain.
  • Impact: Claude rejects a tool_result without a matching tool_use in the preceding assistant message (HTTP 400), so the conversation cannot continue.
  • Frequency: deterministic whenever a client sends one turn's tool calls as several adjacent assistant messages with string content (including ""). How often clients send this shape was not measured.
  • Evidence that the problem is in new-api rather than the client or upstream: calling only OpenAIChatRequestToClaudeMessages on the request in relaykit: Chat → Claude conversion drops tool_calls when merging adjacent assistant messages #7920 produces tool_result for call_a with no tool_use for call_a; the same conversation as one assistant message with both tool_calls converts correctly.
  • Applicable types and their fields (relay / billing / frontend / deployment; write "not applicable" otherwise): Relay: client POST /v1/chat/completions, RelayFormatOpenAI → RelayFormatClaude, Claude / AWS / Vertex Claude channels per the code, pass-through off; reproduced at the converter level, not against a server. Billing / Frontend / Deployment: not applicable.

Change

In OpenAIChatRequestToClaudeMessages, when two adjacent same-role messages with string content are merged and either has tool calls:

  • ToolCalls of the merged message = previous message's tool calls followed by the current message's (input order).
  • The merged text joins the non-empty texts with a space, skipping the previous message's "..." when that message has tool calls (that "..." is the placeholder the converter puts on an empty tool-call message, not client text). If the result is empty, the existing placeholder logic sets "..." as before.

Merging two messages without tool calls keeps the existing fmt.Sprintf("%s %s", ...) branch, so plain-text output is unchanged.

Research

Duplicate / prior art

Docs and code

  • https://docs.newapi.ai/ : /en/docs/api and /en/docs/api/ai-model/chat/openai/createchatcompletion have nothing on Chat → Claude conversion and no setting for it.
  • https://deepwiki.com/QuantumNous/new-api : could not be read (HTTP 429).
  • README / repo docs: nothing relevant.
  • Code paths and what they imply for this change:
    • relaykit/relayconvert/internal/oai_chat/to_claude_messages_req.go:157-165 (main) — fmtMessage carries only the current ToolCalls; the merge removes the previous message without carrying its ToolCalls.
    • Same file :166-168 — empty / null content becomes "...", so a tool-call-only assistant message always looks like string content to the next merge, and its "..." would otherwise end up in the merged text.
    • Same file :246 onward — a message with ToolCalls is emitted as text + tool_use blocks, so carrying the merged list in ToolCalls is enough for both tool calls to reach Claude.
    • Claude docs (Handle tool calls): tool_use_id is the id of the tool use request the result answers.

Alternatives considered

  • Option A: stop merging adjacent assistant messages that have tool calls and emit them as consecutive assistant messages. The converter already emits that shape when the second content is null, but whether every Claude provider (Anthropic, Bedrock, Vertex) accepts it was not verified, and it changes output for requests that work today.
  • Option B: carry the tool calls in the existing merge. The output matches what the converter already produces when the client sends one assistant message with all tool calls.
  • Why this approach: Option B keeps the current merge rules and changes output only for merges that involve tool calls.

Files

Path Why
relaykit/relayconvert/internal/oai_chat/to_claude_messages_req.go keep both messages' tool calls when merging adjacent messages; skip the "..." placeholder of a tool-call message in the merged text
relaykit/relayconvert/internal/oai_chat/to_claude_messages_req_test.go adds TestOpenAIChatRequestToClaudeMessagesMergesAdjacentAssistantToolCalls (3 table cases) to the existing test file

Behavior

  • Before (split call_a / call_b, content ""): {"role":"assistant","content":[{"type":"text","text":"... "},{"type":"tool_use","id":"call_b",...}]}
  • After: {"role":"assistant","content":[{"type":"text","text":"..."},{"type":"tool_use","id":"call_a",...},{"type":"tool_use","id":"call_b",...}]}, identical to the output for one assistant message with both tool_calls.
  • Before (call_a with content null, then plain text "Checking a."): assistant text "... Checking a.", no tool_use. After: text "Checking a." plus tool_use call_a.
  • Two plain-text assistant messages: "First. Second." before and after.
  • Explicit non-goals / leftover work: adjacent assistant messages with array content, or with a null second content, are still not merged (they are sent as consecutive assistant messages and no tool calls are lost). Not changed here.

Verification

  • Commands and results:
    1. cd relaykit && GOWORK=off go test ./relayconvert/internal/oai_chat/ -run TestOpenAIChatRequestToClaudeMessagesMergesAdjacentAssistantToolCalls -count=1 -v: on upstream main 603a5ceb5 with only the test added, FAIL in 2 of 3 cases. both_assistants_have_tool_calls: tool uses [call_b] (expected [call_a call_b]), text "... ". tool_calls_followed_by_plain_text: tool uses nil (expected [call_a]), text "... Checking a.". both_assistants_are_plain_text: PASS. On this branch: all 3 PASS.
    2. cd relaykit && GOWORK=off go build ./... succeeds; GOWORK=off go vet ./relayconvert/internal/oai_chat/ clean; GOWORK=off go test ./dto/... ./relayconvert/... -count=1 all ok.
    3. Root module: go test ./relay/channel/claude/ ./relay/channel/aws/ ./relay/channel/vertex/ -count=1 all ok.
    4. gofmt -l relaykit/relayconvert/ prints nothing.
  • Manual steps and observed result: a throwaway test in the same package (not committed) converted the request from relaykit: Chat → Claude conversion drops tool_calls when merging adjacent assistant messages #7920 and printed json.Marshal(result.Messages). Upstream main: assistant has only tool_use call_b. This branch: tool_use call_a, call_b, byte-for-byte the same messages as converting one assistant message with both tool_calls. With a null second content, output is identical on main and this branch (two consecutive assistant messages).
  • UI: screenshot or recording (or why none): not applicable, no frontend change.
  • Tests added or updated, or why none: one table test added to the existing to_claude_messages_req_test.go; no new test file.
  • Databases / providers / platforms exercised: converter only, no database, no provider call from this branch; Go 1.27.0 linux/arm64.
  • Not verified: no new-api server deployed; the Claude API, Bedrock and Vertex were not called with this branch; array-content assistant messages (not merged, unchanged).

Risks

  • Failure modes: only merges where at least one message has tool calls produce different output: the merged message now has more tool_use blocks, and its text no longer contains the "..." placeholder of the tool-call message. Merges without tool calls take the unchanged branch.
  • Billing / quota / auth impact: none. Only the converted request's message content changes.
  • Follow-ups: none.

Scope check

  • Single focused change: yes
  • Secrets included: no
  • Out of scope (Coding Plan / reverse-engineered channel / third-party wrapper / Codex / pass-through-only forwarding): no

Summary by CodeRabbit

  • Bug Fixes

    • Preserved tool calls when consecutive assistant messages are combined.
    • Maintained associated text and tool-call details during OpenAI-to-Claude message conversion.
  • Tests

    • Added coverage for adjacent assistant messages containing multiple tool calls, text, and standard responses.

Adjacent assistant messages with string content were merged keeping only
the second message's tool calls, so tool results for the first message's
calls had no matching tool_use and Claude rejected the request.

- concatenate both messages' tool calls in input order
- skip the "..." placeholder of a tool-call message in the merged text
@coderabbitai

coderabbitai Bot commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Note

Currently processing new changes in this PR. This may take a few minutes, please wait...

⚙️ Run configuration
  • Configuration used: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 135b89f2-efd6-435d-830c-8f545f1e1bd1
📥 Commits

Reviewing files that changed from the base of the PR and between fae198f and fafee1b.

📒 Files selected for processing: 2
  • relaykit/relayconvert/internal/oai_chat/to_claude_messages_req.go
  • relaykit/relayconvert/internal/oai_chat/to_claude_messages_req_test.go
+---------------------------------------------------------+
| Eliminate bugs. Ship early. Sleep well. Pick all three. |
+---------------------------------------------------------+
  \
   \     /)/)
        ( '')
        /  |
      o(___)

Walkthrough

The Claude Messages converter now preserves tool calls when it merges adjacent assistant messages with string content. It joins non-placeholder text with spaces in that case and retains the existing text-merging behavior when neither message contains tool calls. Tests cover both cases.

Changes

Assistant message merging

Layer / File(s) Summary
Merge assistant content and verify conversion
relaykit/relayconvert/internal/oai_chat/to_claude_messages_req.go, relaykit/relayconvert/internal/oai_chat/to_claude_messages_req_test.go
The converter concatenates tool-call lists from adjacent assistant messages and joins their non-placeholder text with spaces. Messages without tool calls keep the previous text-merging behavior. Tests cover tool-call IDs, text handling, and plain-text merging.

Priority: ➖ Normal

Estimated code review effort: 2 (Simple) | ~10 minutes

Change: Bug fix · Severity of issue fixed: Medium

Suggested reviewers: calcium-ion

Merge Risk: ⚪ Minimal · up to fae19

No actionable merge-blocking issue was established. The change is mergeable after normal checks.

Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 3 functions across 2 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed
Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title clearly describes the primary change: preserving tool calls when merging adjacent assistant messages for Claude.
Linked Issues check Passed Issue #7920 requires preservation of all tool calls during adjacent assistant-message merging, omission of the artificial "..." text, unchanged plain-text merging, and regression tests. The implementa…
Out of Scope Changes check Passed The pull request changes only the Claude message converter and its focused regression test. Both changes directly support issue #7920. No unrelated source, provider, deployment, billing, frontend, or …
Full details: Linked Issues check

Explanation

Issue #7920 requires preservation of all tool calls during adjacent assistant-message merging, omission of the artificial "..." text, unchanged plain-text merging, and regression tests. The implementation concatenates previous and current tool calls in input order, omits the previous "..." placeholder when that message has tool calls, and retains the existing plain-text branch. The added table test covers both tool-call messages, tool calls followed by text, and two plain-text messages.

Full details: Out of Scope Changes check

Explanation

The pull request changes only the Claude message converter and its focused regression test. Both changes directly support issue #7920. No unrelated source, provider, deployment, billing, frontend, or documentation changes are present in the reviewed diff.

  • Fix all pre-merge checks with AI
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

A rabbit checks the messages in a row,
Tool calls stay together as they go.
The placeholder hops away,
Plain text keeps its usual way.
Tests confirm each call is in the flow.

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔇 Additional comments: 2
relaykit/relayconvert/internal/oai_chat/to_claude_messages_req_test.go: 1

82-177: LGTM!

relaykit/relayconvert/internal/oai_chat/to_claude_messages_req.go: 1

171-171: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

⚠️ Unverified finding
Verification ran but could not confirm this finding. It is shown for review, not as a verified issue.

Apply De Morgan's law to the placeholder check.

staticcheck reports QF1001 on this line. The negated compound condition is hard to read. Move the placeholder test into a named variable.

♻️ Proposed refactor
-					if previousText := lastMessage.StringContent(); previousText != "" && !(previousText == "..." && len(previousToolCalls) > 0) {
-						texts = append(texts, previousText)
-					}
+					previousText := lastMessage.StringContent()
+					isPlaceholder := previousText == "..." && len(previousToolCalls) > 0
+					if previousText != "" && !isPlaceholder {
+						texts = append(texts, previousText)
+					}

Source: Linters/SAST tools


ℹ️ Review info
⚙️ Run configuration
  • Configuration used: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: fb993c8b-3b00-4915-8d2a-4c4b92802097
📥 Commits

Reviewing files that changed from the base of the PR and between 603a5ce and fae198f.

📒 Files selected for processing: 2
  • relaykit/relayconvert/internal/oai_chat/to_claude_messages_req.go
  • relaykit/relayconvert/internal/oai_chat/to_claude_messages_req_test.go

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.

@seefs001
seefs001 merged commit 7837356 into QuantumNous:main Oct 20, 2026
2 of 3 checks passed
cicioln pushed a commit to cicioln/new-api that referenced this pull request Oct 25, 2026
…es for Claude (QuantumNous#7921)

* fix(relaykit): keep tool calls when merging adjacent assistant messages

Adjacent assistant messages with string content were merged keeping only
the second message's tool calls, so tool results for the first message's
calls had no matching tool_use and Claude rejected the request.

- concatenate both messages' tool calls in input order
- skip the "..." placeholder of a tool-call message in the merged text

* fix(relaykit): preserve literal ellipses in assistant message merges

---------

Co-authored-by: seefs001 <[email protected]>
(cherry picked from commit 7837356)
lizhongyi1209 pushed a commit to lizhongyi1209/new-api that referenced this pull request Oct 28, 2026
…es for Claude (QuantumNous#7921)

* fix(relaykit): keep tool calls when merging adjacent assistant messages

Adjacent assistant messages with string content were merged keeping only
the second message's tool calls, so tool results for the first message's
calls had no matching tool_use and Claude rejected the request.

- concatenate both messages' tool calls in input order
- skip the "..." placeholder of a tool-call message in the merged text

* fix(relaykit): preserve literal ellipses in assistant message merges

---------

Co-authored-by: seefs001 <[email protected]>
(cherry picked from commit 7837356)
cheryl-chun pushed a commit to maas-aitoken/new-api that referenced this pull request Oct 29, 2026
…es for Claude (QuantumNous#7921)

* fix(relaykit): keep tool calls when merging adjacent assistant messages

Adjacent assistant messages with string content were merged keeping only
the second message's tool calls, so tool results for the first message's
calls had no matching tool_use and Claude rejected the request.

- concatenate both messages' tool calls in input order
- skip the "..." placeholder of a tool-call message in the merged text

* fix(relaykit): preserve literal ellipses in assistant message merges

---------

Co-authored-by: seefs001 <[email protected]>
kyuhwi-choi pushed a commit to attodev/new-api that referenced this pull request Oct 30, 2026
…es for Claude (QuantumNous#7921)

* fix(relaykit): keep tool calls when merging adjacent assistant messages

Adjacent assistant messages with string content were merged keeping only
the second message's tool calls, so tool results for the first message's
calls had no matching tool_use and Claude rejected the request.

- concatenate both messages' tool calls in input order
- skip the "..." placeholder of a tool-call message in the merged text

* fix(relaykit): preserve literal ellipses in assistant message merges

---------

Co-authored-by: seefs001 <[email protected]>
(cherry picked from commit 7837356)
woncc added a commit to 86669666/new-api that referenced this pull request Nov 1, 2026
…es for Claude (QuantumNous#7921) (#128)

* fix(relaykit): keep tool calls when merging adjacent assistant messages

Adjacent assistant messages with string content were merged keeping only
the second message's tool calls, so tool results for the first message's
calls had no matching tool_use and Claude rejected the request.

- concatenate both messages' tool calls in input order
- skip the "..." placeholder of a tool-call message in the merged text

* fix(relaykit): preserve literal ellipses in assistant message merges

---------

Co-authored-by: Roger Chien <[email protected]>
Co-authored-by: seefs001 <[email protected]>
timwenx pushed a commit to timwenx/new-api that referenced this pull request Nov 18, 2026
…es for Claude (QuantumNous#7921)

* fix(relaykit): keep tool calls when merging adjacent assistant messages

Adjacent assistant messages with string content were merged keeping only
the second message's tool calls, so tool results for the first message's
calls had no matching tool_use and Claude rejected the request.

- concatenate both messages' tool calls in input order
- skip the "..." placeholder of a tool-call message in the merged text

* fix(relaykit): preserve literal ellipses in assistant message merges

---------

Co-authored-by: seefs001 <[email protected]>
xiaolanawaqaq pushed a commit to xiaolanawaqaq/new-apiaaa that referenced this pull request Nov 26, 2026
…es for Claude (QuantumNous#7921)

* fix(relaykit): keep tool calls when merging adjacent assistant messages

Adjacent assistant messages with string content were merged keeping only
the second message's tool calls, so tool results for the first message's
calls had no matching tool_use and Claude rejected the request.

- concatenate both messages' tool calls in input order
- skip the "..." placeholder of a tool-call message in the merged text

* fix(relaykit): preserve literal ellipses in assistant message merges

---------

Co-authored-by: seefs001 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

relaykit: Chat → Claude conversion drops tool_calls when merging adjacent assistant messages

2 participants