Skip to content

gateway: repair and normalize damaged tool-call arguments - #598

Open
guyu233 wants to merge 3 commits into
caigee-cmd:mainfrom
guyu233:upstream/toolargs
Open

guyu233 wants to merge 3 commits into
caigee-cmd:mainfrom
guyu233:upstream/toolargs

Conversation

@guyu233

@guyu233 guyu233 commented Nov 27, 2026

Copy link
Copy Markdown
Contributor

Problem

An upstream stream can deliver a tool call whose arguments text is damaged: a bare quote inside a value, a trailing comma, prose appended after the object, a string cut mid-value by the output limit, or a second same-name call that reuses index: 0. Before this change the gateway either failed the whole round (arguments is invalid JSON) or merged two calls into one.

Change

  • internal/translate/toolargs.go: repair formatting damage first (trailing commas, bare quotes, appended prose), then drop the trailing incomplete member so only fields the model finished writing remain, and use {} as the last resort. The repair never pads a value cut mid-string, so rm -rf /tmp/fo cannot turn into rm -rf /tmp/foo.
  • internal/gateway/compat_stream.go / openai_stream.go / anthropic.go: keep same-tool calls separate when the upstream reuses index: 0, and stream only normalized, complete argument fragments instead of raw damaged deltas.
  • internal/gateway/openai_tool_normalizer.go: shared normalizer used by the OpenAI, Anthropic and Responses paths.

Well-formed calls are byte-identical to before.

Trade-off to review

A truncated call is emitted with the fields that were complete (possibly {}), so the client may invoke a tool the model did not finish writing. Dropping the unfinished field was chosen over inventing it, but this is a behavior change and worth a separate decision: an opt-out that fails the round instead is possible if maintainers prefer the old hard failure.

Tests

  • go test ./internal/gateway ./internal/translate passes.
  • New tests cover trailing commas, bare quotes, prose suffixes, mid-string truncation, index-0 reuse and normalized streaming (toolargs_stream_test.go, toolargs_test.go, toolargs_normalize_test.go).

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.

1 participant