Skip to content

fix(gateway): enforce OpenAI tool_choice required/function contracts - #88558

Merged
steipete merged 3 commits into
openclaw:mainfrom
Lellansin:dev/openai-http-tool-choice-compat
May 31, 2026
Merged

steipete merged 3 commits into
openclaw:mainfrom
Lellansin:dev/openai-http-tool-choice-compat

Conversation

@Lellansin

@Lellansin Lellansin commented May 31, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Accept OpenAI Chat Completions tool_choice: "required" and pinned function tool choice in /v1/chat/completions.
  • Enforce the same required and pinned-function tool-choice contract in /v1/responses, including the Responses API flat pinned shape { "type": "function", "name": "..." }.
  • Narrow the exposed client tool set for pinned function requests and validate unknown or missing tool selections at the gateway boundary.
  • Enforce the requested tool-choice contract on the response path: non-streaming requests fail if no matching structured tool call is produced, and streaming requests buffer assistant text until a matching tool call is confirmed.
  • Update OpenAI-compatible HTTP gateway docs for the supported tool_choice forms.

Refs #45049.

Verification

  • node scripts/run-vitest.mjs src/gateway/openai-http.test.ts -t "handles request validation and routing|streams SSE chunks" --reporter=verbose - passed; 4 focused Gateway HTTP e2e cases across gateway-server and gateway-client.
  • node scripts/run-vitest.mjs src/gateway/openai-http.test.ts - passed; 18/18 tests.
  • node scripts/run-vitest.mjs src/gateway/openresponses-http.test.ts src/gateway/openai-http.test.ts - passed; 43/43 tests covering Chat Completions plus Responses required/pinned tool-choice success and failure paths.
  • pnpm docs:list - passed; docs/gateway/openresponses-http-api.md was the relevant docs page.
  • git diff --check - passed.
  • .agents/skills/autoreview/scripts/autoreview --mode local --engine codex - clean; no accepted/actionable findings after addressing two review findings.

Real behavior proof

Behavior addressed: OpenAI-compatible Gateway HTTP requests now accept standard Chat Completions and Responses tool_choice: "required" and pinned function tool choice, return structured tool calls when the model complies, and reject invalid or unsatisfied tool-choice contracts instead of silently returning ordinary assistant text.

Real environment tested: Local Gateway HTTP server started from this checkout via startGatewayServer, loopback port 18812, auth: none, gateway.http.endpoints.chatCompletions.enabled=true, model deepseek/deepseek-chat, provider base URL https://api.deepseek.com, and a temporary DeepSeek API key supplied only through the process environment. Responses behavior was also tested through the repo Gateway HTTP e2e harness with the real /v1/responses HTTP handler and mocked agent results for deterministic required/pinned success and failure paths.

Exact steps or command run after this patch: Started the Gateway in-process from the current checkout, then posted four local requests to /v1/chat/completions: one tool_choice: "required" request with a get_weather function tool, one pinned function request for get_weather, one tool_choice: "required" request without tools, and one pinned function request for a missing tool. After adding /v1/responses enforcement, ran node scripts/run-vitest.mjs src/gateway/openresponses-http.test.ts src/gateway/openai-http.test.ts to exercise Responses non-streaming and streaming required/pinned tool-choice success and failure cases through the HTTP endpoint.

Evidence after fix:

{
  "ok": true,
  "modelRef": "deepseek/deepseek-chat",
  "chatCompletionsLiveResults": [
    {
      "label": "required",
      "httpStatus": 200,
      "finishReason": "tool_calls",
      "toolCallCount": 1,
      "toolNames": ["get_weather"],
      "contentPreview": ""
    },
    {
      "label": "pinned_function",
      "httpStatus": 200,
      "finishReason": "tool_calls",
      "toolCallCount": 1,
      "toolNames": ["get_weather"],
      "contentPreview": ""
    },
    {
      "label": "required_no_tools",
      "httpStatus": 400,
      "errorType": "invalid_request_error",
      "errorMessage": "Invalid tools/tool_choice: tool_choice=required but no tools were provided"
    },
    {
      "label": "missing_tool",
      "httpStatus": 400,
      "errorType": "invalid_request_error",
      "errorMessage": "Invalid tools/tool_choice: tool_choice requested unknown tool: missing_tool"
    }
  ],
  "responsesFocusedTests": {
    "command": "node scripts/run-vitest.mjs src/gateway/openresponses-http.test.ts src/gateway/openai-http.test.ts",
    "testFiles": 2,
    "tests": 43,
    "result": "passed"
  }
}

Observed result after fix: The valid Chat Completions required and pinned-function requests completed through the real local Gateway and live DeepSeek provider with finish_reason: "tool_calls" and a single get_weather structured tool call. Invalid Chat Completions tool-choice requests were rejected at the Gateway boundary with deterministic OpenAI-compatible 400 invalid_request_error responses. Responses HTTP e2e tests now prove non-streaming unsatisfied tool_choice returns a failed 502 api_error, streaming unsatisfied tool_choice emits response.failed without leaking buffered text, and satisfied required/pinned turns return or stream the matching function_call output.

What was not tested: Crabbox/Testbox and cross-OS proof were not run. The live provider proof used DeepSeek rather than OpenAI because the reported compatibility gap is OpenAI-compatible tool-choice protocol behavior and DeepSeek exposes an OpenAI-compatible Chat Completions API for this flow. /v1/responses was verified with deterministic local Gateway HTTP e2e tests rather than a live external Responses provider.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime size: M proof: supplied External PR includes structured after-fix real behavior proof. labels May 31, 2026
@clawsweeper

clawsweeper Bot commented May 31, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs real behavior proof before merge. Reviewed May 31, 2026, 9:52 AM ET / 13:52 UTC.

Summary
The PR adds required and pinned-function tool_choice handling for Gateway Chat Completions and Responses, updates Gateway docs/tests, and includes small unrelated docs/test cleanups.

PR surface: Source +215, Tests +450, Docs +7. Total +672 across 10 files.

Reproducibility: yes. Source inspection of the PR head shows both constrained streaming paths append deltas to unbounded strings until the run resolves, and current main still lacks the requested Chat enforcement.

Review metrics: 1 noteworthy metric.

  • Gateway API contract changed: 2 HTTP endpoints. The PR adds or tightens constrained tool_choice behavior for both Chat Completions and Responses, so compatibility and upgrade behavior need maintainer attention before merge.

Merge readiness
Overall: 🦪 silver shellfish
Proof: 🦪 silver shellfish
Patch quality: 🦪 silver shellfish
Result: blocked until stronger real behavior proof is added.

Overall follows the weaker of proof and patch quality, so missing proof can cap an otherwise strong patch.

Rank-up moves:

  • [P1] Add bounded buffering, truncation, or early failure for constrained streaming in both Gateway endpoints.
  • [P1] Add redacted live local /v1/responses HTTP proof for required and pinned success/failure behavior.
  • Refresh the dirty branch against current main and drop or explicitly retain unrelated cleanup commits.

Proof guidance:

  • [P1] Needs stronger real behavior proof before merge: Partial live output covers Chat Completions, but /v1/responses enforcement still needs redacted local HTTP output, terminal logs, live output, or screenshots; redact private data and update the PR body for re-review, or ask a maintainer to comment @clawsweeper re-review if it does not rerun.

Risk before merge

  • [P1] Constrained streaming currently buffers arbitrary assistant prose in memory until the run resolves; a provider that ignores tool_choice can grow memory per request before the Gateway fails the stream.
  • [P1] /v1/responses constrained tool_choice changes from best-effort text return to fail-closed 502 api_error or response.failed, so maintainers should explicitly accept that compatibility tradeoff.
  • [P1] Real behavior proof is still partial: Chat Completions has copied live local Gateway output, but /v1/responses enforcement is only backed by mocked-agent HTTP e2e proof.
  • [P1] The GitHub context reports a dirty, non-mergeable branch and the PR includes unrelated docs/test cleanup, so the branch likely needs refresh or splitting before landing.

Maintainer options:

  1. Bound constrained streaming first (recommended)
    Add a cap, truncation, or early-failure strategy for constrained streaming in both Gateway endpoints and cover the ignored-model long-prose path before merge.
  2. Accept fail-closed Responses behavior
    Maintainers can intentionally accept that constrained /v1/responses requests now return 502 api_error or response.failed when the agent does not produce the matching structured client tool call.
  3. Refresh or split the dirty branch
    Rebase onto current main and either keep the unrelated docs/test cleanup as an explicit maintainer choice or split it out before landing the Gateway change.

Next step before merge

  • [P1] The remaining blockers are contributor-supplied Responses proof, a bounded-buffer repair, maintainer acceptance of fail-closed behavior, and a dirty branch refresh, so this should stay human-reviewed rather than enter an automated repair lane.

Security
Cleared: No concrete security or supply-chain regression was found in the Gateway/docs/test diff; the remaining concerns are compatibility, availability, proof, and mergeability.

Review findings

  • [P1] Bound the Chat Completions tool-choice stream buffer — src/gateway/openai-http.ts:1210
  • [P1] Bound the Responses tool-choice stream buffer — src/gateway/openresponses-http.ts:1003
Review details

Best possible solution:

Land a refreshed, focused Gateway PR only after constrained streaming is bounded, /v1/responses has redacted live local HTTP proof, and maintainers accept the fail-closed compatibility behavior.

Do we have a high-confidence way to reproduce the issue?

Yes. Source inspection of the PR head shows both constrained streaming paths append deltas to unbounded strings until the run resolves, and current main still lacks the requested Chat enforcement.

Is this the best way to solve the issue?

No. The compatibility direction is sound, but the proposed implementation should bound constrained streaming and prove live /v1/responses behavior before maintainers accept the fail-closed contract.

Full review comments:

  • [P1] Bound the Chat Completions tool-choice stream buffer — src/gateway/openai-http.ts:1210
    When toolChoiceConstraint is active, every assistant delta is appended to bufferedAssistantContent until the run resolves. A provider that ignores the forced tool prompt can stream arbitrary prose and grow per-request memory before the Gateway emits the error, so this needs a cap, truncation, or early-fail path before merge.
    Confidence: 0.9
  • [P1] Bound the Responses tool-choice stream buffer — src/gateway/openresponses-http.ts:1003
    The Responses streaming path has the same unbounded accumulation while a constrained tool_choice is pending. If the agent keeps streaming text without a matching tool call, accumulatedText grows until completion, which makes the new fail-closed path an availability risk under ignored-tool providers.
    Confidence: 0.9

Overall correctness: patch is incorrect
Overall confidence: 0.88

AGENTS.md: found and applied where relevant.

Codex review notes: model gpt-5.5, reasoning high; reviewed against 0d17623f0090.

Label changes

Label justifications:

  • P2: This is a normal-priority Gateway compatibility fix with limited surface area, but it still has merge-blocking proof and availability concerns.
  • merge-risk: 🚨 compatibility: The Responses endpoint would fail closed for constrained tool_choice requests that current main can return as best-effort assistant text.
  • merge-risk: 🚨 availability: The constrained streaming paths can buffer unbounded assistant prose per request before failing when a provider ignores the tool-choice prompt.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🦪 silver shellfish.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask. Needs stronger real behavior proof before merge: Partial live output covers Chat Completions, but /v1/responses enforcement still needs redacted local HTTP output, terminal logs, live output, or screenshots; redact private data and update the PR body for re-review, or ask a maintainer to comment @clawsweeper re-review if it does not rerun.
Evidence reviewed

PR surface:

Source +215, Tests +450, Docs +7. Total +672 across 10 files.

View PR surface stats
Area Files Added Removed Net
Source 4 229 14 +215
Tests 3 461 11 +450
Docs 3 12 5 +7
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 10 702 30 +672

What I checked:

  • Current Chat Completions behavior: Current main still rejects tool_choice: "required" in the Chat Completions gateway path, so the central compatibility gap is not already implemented on main. (src/gateway/openai-http.ts:219, 0d17623f0090)
  • Current Responses behavior: Current main only converts Responses constrained tool_choice into prompt text and narrowed tools; it does not reject a text-only agent result when the required or pinned tool call is missing. (src/gateway/openresponses-http.ts:289, 0d17623f0090)
  • Dependency contract: OpenAI's Chat Completions API documents tool_choice as supporting none, auto, required, and named function tool choice; the Responses API also exposes tool_choice as string or object for selecting tools. (platform.openai.com)
  • Shared PR implementation: The PR adds a shared tool-choice constraint helper that treats required as any structured tool call and pinned function as a matching tool-name call, then rejects unsatisfied turns. (src/gateway/openai-tool-choice.ts:16, f87c4c6f2e3f)
  • Chat streaming availability risk: The PR buffers every assistant delta in bufferedAssistantContent while a Chat Completions tool-choice constraint is active, with no cap, truncation, or early-fail strategy. (src/gateway/openai-http.ts:1210, f87c4c6f2e3f)
  • Responses streaming availability risk: The PR buffers every assistant delta in accumulatedText while a Responses tool-choice constraint is active, with no cap, truncation, or early-fail strategy. (src/gateway/openresponses-http.ts:1003, f87c4c6f2e3f)

Likely related people:

  • steipete: Current-main blame for the existing gateway tool-choice code points to Peter Steinberger's recent gateway refactor, and the latest PR commits are also by Peter. (role: recent area contributor and current branch committer; confidence: high; commits: 242eab9d20f7, fde9fb05dfcf, aabdc63d20cb; files: src/gateway/openai-http.ts, src/gateway/openresponses-http.ts, docs/gateway/openai-http-api.md)
  • Lellansin: Lellansin authored the first two PR commits and has prior merged OpenAI-compatible gateway fixes in current history, including usage normalization and disconnect handling. (role: prior gateway contributor and current PR author; confidence: high; commits: c5095bb388ce, 18eea7fcefb7, 2ccd1839f212; files: src/gateway/openai-http.ts, src/gateway/openresponses-http.ts, src/gateway/openai-http.test.ts)
  • vincentkoc: Gateway OpenAI compatibility and streaming surfaces have several recent commits by Vincent Koc in the central file history. (role: gateway feature-history contributor; confidence: medium; commits: d10669629d73, eaad4ad1be38, 9dab1545190c; files: src/gateway/openai-http.ts, src/gateway/openresponses-http.ts, src/gateway/openai-http.test.ts)
What the crustacean ranks mean
  • 🦀 challenger crab: rare, exceptional readiness with strong proof, clean implementation, and convincing validation.
  • 🦞 diamond lobster: very strong readiness with only minor maintainer review expected.
  • 🐚 platinum hermit: good normal PR, likely mergeable with ordinary maintainer review.
  • 🦐 gold shrimp: useful signal, but proof or patch confidence is still limited.
  • 🦪 silver shellfish: thin signal; proof, validation, or implementation needs work.
  • 🧂 unranked krab: not merge-ready because proof is missing/unusable or there are serious correctness or safety concerns.
  • 🌊 off-meta tidepool: rating does not apply to this item.

Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

How this review workflow works
  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. P2 Normal backlog priority with limited blast radius. labels May 31, 2026
@openclaw-barnacle openclaw-barnacle Bot added size: L and removed size: M proof: sufficient ClawSweeper judged the real behavior proof convincing. labels May 31, 2026
@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. labels May 31, 2026
@Lellansin
Lellansin marked this pull request as ready for review May 31, 2026 09:33
@steipete steipete self-assigned this May 31, 2026
@steipete
steipete force-pushed the dev/openai-http-tool-choice-compat branch from f8a3570 to aa2e519 Compare May 31, 2026 12:59
@openclaw-barnacle openclaw-barnacle Bot removed the proof: sufficient ClawSweeper judged the real behavior proof convincing. label May 31, 2026
@byungskers

Copy link
Copy Markdown

The post-run enforcement makes sense, and buffering assistant prose until the structured tool call is confirmed is the right direction for API compatibility. One follow-up question: should the buffered commentary have a size cap on the streaming path? If an upstream model ignores the tool-choice prompt and emits a lot of prose before ending, bufferedAssistantContent / accumulatedText could grow quite a bit just to be discarded on failure.

@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels May 31, 2026
@steipete
steipete force-pushed the dev/openai-http-tool-choice-compat branch from 1165a66 to aabdc63 Compare May 31, 2026 13:35
@clawsweeper clawsweeper Bot added rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. labels May 31, 2026
@steipete
steipete force-pushed the dev/openai-http-tool-choice-compat branch from f87c4c6 to 79fa094 Compare May 31, 2026 13:57
@steipete

Copy link
Copy Markdown
Contributor

Proof for final head 79fa0947360d307cf4ecffe713489cdf5db61093:

  • Local: node scripts/run-vitest.mjs src/gateway/openai-http.test.ts src/gateway/openresponses-http.test.ts -> 2 files, 44 tests passed.
  • Local: pnpm format:docs:check -> docs formatting clean.
  • Local: git diff --check -> clean.
  • Local: .agents/skills/autoreview/scripts/autoreview --mode branch --base origin/main -> clean, no accepted/actionable findings.
  • GitHub CI: run 26714604449 passed, including build-artifacts, check-docs, check-lint, check-prod-types, check-test-types, gateway/core shards, and CI timing summary.
  • GitHub proof/security: real behavior proof run 26714603817 passed, OpenGrep PR diff run 26714604447 passed, CodeQL/security shards run 26714604448 passed.

Known gap: no live external OpenAI/Gemini provider call was run; coverage is repo HTTP compatibility/unit regression coverage plus full exact-head CI.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

docs Improvements or additions to documentation gateway Gateway runtime merge-risk: 🚨 availability 🚨 May cause crashes, hangs, restart loops, stalls, or process outages. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. proof: supplied External PR includes structured after-fix real behavior proof. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. size: L status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants