Skip to content
Source
Sign inSign up
TanStack/ai

fix(openai-base): keep length when a tool call is cut off #1874

Mergedtombeckenhammerged 1 commit intomain fromrefs/pull/1874/headmerged by AlemTuzlak View on GitHub

tombeckenhamcommented

A Chat Completions tool call that the token limit cuts off now finishes with finishReason: "length". chat() does not send that unfinished call to the model again.

Fixes #1853.

🎯 Changes

OpenAIBaseChatCompletionsTextAdapter mapped every stream that emitted TOOL_CALL_END to finishReason: "tool_calls". That mapping hid finish_reason: "length". The core then treated the partial JSON as a parse error and called the model again, up to five times.

length now wins over that tool-call flag. The core already stops a run on length and does not execute the cut call.

No docs page describes this path, so docs/ is unchanged. A patch changeset is on the branch for @tanstack/openai-base.

✅ Checklist

  • I have followed the steps in the Contributing guide.
  • I have tested code changes locally with pnpm run test:pr, or these tests do not apply to this pull request.
  • I fully understand the code in this pull request, including any code generated with AI assistance.
  • Docs: I updated docs/ for this change, or this change is not user-facing.
  • Changeset: I added a changeset (pnpm changeset), or this PR does not change a published package.

🚀 Release Impact

  • This change affects published code, and I have generated a changeset.
  • This change is docs/CI/dev-only (no release).

Root cause

Issue. A caller of chat() with the Chat Completions adapter gets finishReason: "tool_calls" when max_tokens cuts a tool call. The same chat() call then sends the partial arguments again. One run made five requests.

Cause. In processStreamChunks, emittedAnyToolCallEnd replaces the pending length finish reason with tool_calls.

Fix. If the pending finish reason is length, the adapter keeps length. The core stop-on-length path then ends the run.

Possible alternatives

  • Stop in chat() on any bad tool JSON. A real malformed tool call must still go back to the model. This PR does not do that.
  • Apply the same mapping in @tanstack/ai-openrouter. That adapter has the same flag. Issue #1853 is only openai-base, so this PR does not change OpenRouter.

Testing

Commands run. On clean main (3e84606af), an agent-written Vitest in a detached worktree failed: expected "vi.fn()" to be called 1 times, but got 5 times. After this change, vitest run tests/repro-1853-length-tool-call.test.ts in packages/ai-openai passed (1 test). packages/openai-base tests chat-completions-empty-choices and chat-completions-text passed (42 tests). pnpm test:pr was not run.

Manual test.

  1. On main, stream a tool call whose arguments are cut, then a chunk with finish_reason: "length". The run finishes as tool_calls and the mock create runs five times.
  2. On this branch, run the same stream. create runs once. RUN_FINISHED metadata is finishReason: "length". The result text is not Failed to parse tool arguments as JSON.

How this PR makes testing easy. packages/ai-openai/tests/repro-1853-length-tool-call.test.ts

Risk / rollback

Low risk. A complete tool call that finishes with tool_calls is unchanged. Revert this PR to restore the old mapping.

Public API change

Before

// token limit cut the tool arguments
// event.metadata.tanstack.finishReason === "tool_calls"

After

// token limit cut the tool arguments
// event.metadata.tanstack.finishReason === "length"

Summary by CodeRabbit

  • Bug Fixes
    • When a response ends because it reaches the length limit during a tool call, the run now reports the length finish reason instead of indicating that the tool call completed.
    • Incomplete tool-call arguments are no longer sent back for processing, preventing JSON parsing errors and unnecessary follow-up API calls.
    1. 🦋 Changeset detected

      Latest commit: be46f2145617c1e06e92aa1e3542be3a60f7ad5f

      The changes in this PR will be included in the next version bump.

      This PR includes changesets to release 1 package
      NameType
      @tanstack/openai-basePatch

      Not sure what this means? Click here to learn what changesets are.

      Click here if you're a maintainer who wants to add another changeset to this PR

    2. coderabbitai[bot](GitHub profile, opens in a new tab)commented
      Review in Change Stack →

      No actionable comments were generated in the recent review. 🎉

      ℹ️ Recent review info
      ⚙️ Run configuration
      • Source mode: Auto
      • Repository: TanStack/ai
      • Branch: main
      • File: .coderabbit.yaml
      • Commit: d980ce1
      • Layers: Repository YAML
      • Review profile: CHILL
      • Plan: Advanced
      • Run ID: f62aace3-dcdc-4ded-8a8b-769880b60906
      📥 Commits

      Reviewing files that changed from the base of the PR and between d980ce153371404d71b6d4ceac37b0c8293df1d8 and be46f2145617c1e06e92aa1e3542be3a60f7ad5f.

      📒 Files selected for processing: 3
      • .changeset/openai-base-length-tool-call.md
      • packages/ai-openai/tests/repro-1853-length-tool-call.test.ts
      • packages/openai-base/src/adapters/chat-completions-text.ts

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

      📝 Walkthrough

      The Chat Completions adapter now preserves upstream length when a tool-call end was emitted. A regression test covers truncated streamed arguments and checks for one request, a RUN_FINISHED event with finish reason length, and no JSON-parse-failure tool result.

      Changes: Truncated tool-call finish reason

      Layer / File(s)Summary
      Finish-reason mapping and regression coverage
      packages/openai-base/src/adapters/chat-completions-text.ts, packages/ai-openai/tests/repro-1853-length-tool-call.test.ts, .changeset/openai-base-length-tool-call.md
      The adapter maps upstream length to length even when a tool-call end was emitted. The regression test checks that the run finishes with length, makes one request, and produces no JSON-parse-failure tool result. The changeset records a patch for @tanstack/openai-base.

      Priority: ➖ Normal

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

      Change: Bug fix · Severity of issue fixed: Medium

      Merge Risk: ⚪ Minimal · up to be46f

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

      Pre-merge checks: Passed 4 · Failed 1
      Failed Failed checks: 1 warning
      Check nameStatusExplanationResolution
      Docstring CoverageWarningDocstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 1 functions across 2 files. (1 skipped: 1 …Write docstrings for the functions missing them to satisfy the coverage threshold.
      Passed Passed checks: 4 passed
      Check nameStatusExplanation
      Title checkPassedThe title clearly and concisely describes the primary fix: preserving the length finish reason when an OpenAI tool call is truncated.
      Description checkPassedThe description includes the required Changes, Checklist, Release Impact, testing, root cause, risk, and public API sections. It explains the skipped full test command and unchanged documentation.
      Linked Issues checkPassedIssue #1853 requires finishReason: "length" when a Chat Completions tool call is cut off, and no retry of the incomplete call. In packages/openai-base/src/adapters/chat-completions-text.ts, `pendi…
      Out of Scope Changes checkPassedThe changes stay within issue #1853. The adapter change implements the required finish-reason precedence. The test covers the regression. The changeset documents the published-package fix. No unrelate…
      Full details: Linked Issues check

      Explanation

      Issue #1853 requires finishReason: "length" when a Chat Completions tool call is cut off, and no retry of the incomplete call. In packages/openai-base/src/adapters/chat-completions-text.ts, pendingFinishReason === 'length' now takes precedence over emittedAnyToolCallEnd. The regression test verifies one API call, RUN_FINISHED with length, and no JSON-argument parse failure result.

      Full details: Out of Scope Changes check

      Explanation

      The changes stay within issue #1853. The adapter change implements the required finish-reason precedence. The test covers the regression. The changeset documents the published-package fix. No unrelated adapter, documentation, or product behavior changes appear in the reviewed diff.

      Full details: Docstring Coverage

      Explanation

      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 1 functions across 2 files. (1 skipped: 1 unsupported.)

      Resolution

      Write docstrings for the functions missing them to satisfy the coverage threshold.

      ✨ Finishing Touches: 💡 1
      📝 Generate docstrings: 💡
      • Commit to this branch
      • Create a new PR
      🧪 Generate unit tests (beta)
      • Commit to this branch
      • 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
      Comment `@coderabbitai help` to get the list of available commands.
    3. nx-cloud[bot](GitHub profile, opens in a new tab)commented

      View your CI Pipeline Execution ↗ for commit be46f2145617c1e06e92aa1e3542be3a60f7ad5f

      CommandStatusDurationResult
      nx affected --targets=test:sherif,test:knip,tes...✅ Succeeded4m 21sView ↗
      nx run-many --targets=test:coverage --projects=...✅ Succeeded1sView ↗
      nx run-many --targets=build --exclude=examples/...✅ Succeeded1sView ↗

      ☁️ Nx Cloud last updated this comment at 2026-10-22 08:35:27 UTC

    4. Coverage

      ✅ Coverage held across 11 compared package(s).

      Each package is measured twice in this job — on this PR and on its merge-base with main — and compared. A metric fails only when it is at or above 60% on the merge-base and under 60% on this PR. Other drops are listed but do not fail. Packages your PR doesn't affect are not measured and not listed.

      packagestatementsbranchesfunctionslines
      ai-bedrock90.05% (0.00)82.59% (0.00)94.20% (0.00)91.27% (0.00)ok
      ai-byteplus97.05% (0.00)91.62% (0.00)98.27% (0.00)98.48% (0.00)ok
      ai-cloudflare85.55% (0.00)76.44% (0.00)85.48% (0.00)86.79% (0.00)ok
      ai-code-mode-snippets87.13% (0.00)75.67% (0.00)91.11% (0.00)88.39% (0.00)ok
      ai-grok48.80% (0.00)53.49% (0.00)56.46% (0.00)49.63% (0.00)ok
      ai-groq51.30% (0.00)47.73% (0.00)67.39% (0.00)53.42% (0.00)ok
      ai-llmgateway97.77% (0.00)100.00% (0.00)88.88% (0.00)97.77% (0.00)ok
      ai-lovable73.21% (0.00)55.63% (0.00)85.07% (0.00)73.96% (0.00)ok
      ai-openai65.12% (0.00)65.66% (+0.12)66.99% (0.00)65.56% (0.00)ok
      ai-vercel-gateway75.97% (0.00)55.63% (0.00)85.41% (0.00)79.38% (0.00)ok
      openai-base90.88% (0.00)79.77% (-0.02)97.77% (0.00)93.02% (0.00)ok
    5. Open in StackBlitz

      @tanstack/ai

      npm i https://pkg.pr.new/@tanstack/ai@1874

      @tanstack/ai-acp

      npm i https://pkg.pr.new/@tanstack/ai-acp@1874

      @tanstack/ai-angular

      npm i https://pkg.pr.new/@tanstack/ai-angular@1874

      @tanstack/ai-anthropic

      npm i https://pkg.pr.new/@tanstack/ai-anthropic@1874

      @tanstack/ai-bedrock

      npm i https://pkg.pr.new/@tanstack/ai-bedrock@1874

      @tanstack/ai-byteplus

      npm i https://pkg.pr.new/@tanstack/ai-byteplus@1874

      @tanstack/ai-claude-code

      npm i https://pkg.pr.new/@tanstack/ai-claude-code@1874

      @tanstack/ai-client

      npm i https://pkg.pr.new/@tanstack/ai-client@1874

      @tanstack/ai-cloudflare

      npm i https://pkg.pr.new/@tanstack/ai-cloudflare@1874

      @tanstack/ai-code-mode

      npm i https://pkg.pr.new/@tanstack/ai-code-mode@1874

      @tanstack/ai-code-mode-snippets

      npm i https://pkg.pr.new/@tanstack/ai-code-mode-snippets@1874

      @tanstack/ai-codex

      npm i https://pkg.pr.new/@tanstack/ai-codex@1874

      @tanstack/ai-cohere

      npm i https://pkg.pr.new/@tanstack/ai-cohere@1874

      @tanstack/ai-compaction

      npm i https://pkg.pr.new/@tanstack/ai-compaction@1874

      @tanstack/ai-computer-local

      npm i https://pkg.pr.new/@tanstack/ai-computer-local@1874

      @tanstack/ai-computer-playwright

      npm i https://pkg.pr.new/@tanstack/ai-computer-playwright@1874

      @tanstack/ai-computer-sandbox

      npm i https://pkg.pr.new/@tanstack/ai-computer-sandbox@1874

      @tanstack/ai-computer-use

      npm i https://pkg.pr.new/@tanstack/ai-computer-use@1874

      @tanstack/ai-devtools-core

      npm i https://pkg.pr.new/@tanstack/ai-devtools-core@1874

      @tanstack/ai-durable-stream

      npm i https://pkg.pr.new/@tanstack/ai-durable-stream@1874

      @tanstack/ai-elevenlabs

      npm i https://pkg.pr.new/@tanstack/ai-elevenlabs@1874

      @tanstack/ai-event-client

      npm i https://pkg.pr.new/@tanstack/ai-event-client@1874

      @tanstack/ai-fal

      npm i https://pkg.pr.new/@tanstack/ai-fal@1874

      @tanstack/ai-gemini

      npm i https://pkg.pr.new/@tanstack/ai-gemini@1874

      @tanstack/ai-grok

      npm i https://pkg.pr.new/@tanstack/ai-grok@1874

      @tanstack/ai-grok-build

      npm i https://pkg.pr.new/@tanstack/ai-grok-build@1874

      @tanstack/ai-groq

      npm i https://pkg.pr.new/@tanstack/ai-groq@1874

      @tanstack/ai-isolate-cloudflare

      npm i https://pkg.pr.new/@tanstack/ai-isolate-cloudflare@1874

      @tanstack/ai-isolate-daytona

      npm i https://pkg.pr.new/@tanstack/ai-isolate-daytona@1874

      @tanstack/ai-isolate-e2b

      npm i https://pkg.pr.new/@tanstack/ai-isolate-e2b@1874

      @tanstack/ai-isolate-node

      npm i https://pkg.pr.new/@tanstack/ai-isolate-node@1874

      @tanstack/ai-isolate-quickjs

      npm i https://pkg.pr.new/@tanstack/ai-isolate-quickjs@1874

      @tanstack/ai-isolate-quickjs-bun

      npm i https://pkg.pr.new/@tanstack/ai-isolate-quickjs-bun@1874

      @tanstack/ai-llmgateway

      npm i https://pkg.pr.new/@tanstack/ai-llmgateway@1874

      @tanstack/ai-lovable

      npm i https://pkg.pr.new/@tanstack/ai-lovable@1874

      @tanstack/ai-mcp

      npm i https://pkg.pr.new/@tanstack/ai-mcp@1874

      @tanstack/ai-memory

      npm i https://pkg.pr.new/@tanstack/ai-memory@1874

      @tanstack/ai-mistral

      npm i https://pkg.pr.new/@tanstack/ai-mistral@1874

      @tanstack/ai-octane

      npm i https://pkg.pr.new/@tanstack/ai-octane@1874

      @tanstack/ai-ollama

      npm i https://pkg.pr.new/@tanstack/ai-ollama@1874

      @tanstack/ai-ollaya

      npm i https://pkg.pr.new/@tanstack/ai-ollaya@1874

      @tanstack/ai-openai

      npm i https://pkg.pr.new/@tanstack/ai-openai@1874

      @tanstack/ai-opencode

      npm i https://pkg.pr.new/@tanstack/ai-opencode@1874

      @tanstack/ai-openrouter

      npm i https://pkg.pr.new/@tanstack/ai-openrouter@1874

      @tanstack/ai-perplexity

      npm i https://pkg.pr.new/@tanstack/ai-perplexity@1874

      @tanstack/ai-persistence

      npm i https://pkg.pr.new/@tanstack/ai-persistence@1874

      @tanstack/ai-preact

      npm i https://pkg.pr.new/@tanstack/ai-preact@1874

      @tanstack/ai-react

      npm i https://pkg.pr.new/@tanstack/ai-react@1874

      @tanstack/ai-reactor

      npm i https://pkg.pr.new/@tanstack/ai-reactor@1874

      @tanstack/ai-remix

      npm i https://pkg.pr.new/@tanstack/ai-remix@1874

      @tanstack/ai-sandbox

      npm i https://pkg.pr.new/@tanstack/ai-sandbox@1874

      @tanstack/ai-sandbox-blaxel

      npm i https://pkg.pr.new/@tanstack/ai-sandbox-blaxel@1874

      @tanstack/ai-sandbox-boxd

      npm i https://pkg.pr.new/@tanstack/ai-sandbox-boxd@1874

      @tanstack/ai-sandbox-cloudflare

      npm i https://pkg.pr.new/@tanstack/ai-sandbox-cloudflare@1874

      @tanstack/ai-sandbox-daytona

      npm i https://pkg.pr.new/@tanstack/ai-sandbox-daytona@1874

      @tanstack/ai-sandbox-docker

      npm i https://pkg.pr.new/@tanstack/ai-sandbox-docker@1874

      @tanstack/ai-sandbox-e2b

      npm i https://pkg.pr.new/@tanstack/ai-sandbox-e2b@1874

      @tanstack/ai-sandbox-local-process

      npm i https://pkg.pr.new/@tanstack/ai-sandbox-local-process@1874

      @tanstack/ai-sandbox-railway

      npm i https://pkg.pr.new/@tanstack/ai-sandbox-railway@1874

      @tanstack/ai-sandbox-sprites

      npm i https://pkg.pr.new/@tanstack/ai-sandbox-sprites@1874

      @tanstack/ai-sandbox-upstash-box

      npm i https://pkg.pr.new/@tanstack/ai-sandbox-upstash-box@1874

      @tanstack/ai-sandbox-vercel

      npm i https://pkg.pr.new/@tanstack/ai-sandbox-vercel@1874

      @tanstack/ai-skills

      npm i https://pkg.pr.new/@tanstack/ai-skills@1874

      @tanstack/ai-solid

      npm i https://pkg.pr.new/@tanstack/ai-solid@1874

      @tanstack/ai-svelte

      npm i https://pkg.pr.new/@tanstack/ai-svelte@1874

      @tanstack/ai-typesafe

      npm i https://pkg.pr.new/@tanstack/ai-typesafe@1874

      @tanstack/ai-utils

      npm i https://pkg.pr.new/@tanstack/ai-utils@1874

      @tanstack/ai-vercel-gateway

      npm i https://pkg.pr.new/@tanstack/ai-vercel-gateway@1874

      @tanstack/ai-vertex

      npm i https://pkg.pr.new/@tanstack/ai-vertex@1874

      @tanstack/ai-vue

      npm i https://pkg.pr.new/@tanstack/ai-vue@1874

      @tanstack/ai-worldlabs

      npm i https://pkg.pr.new/@tanstack/ai-worldlabs@1874

      @tanstack/openai-base

      npm i https://pkg.pr.new/@tanstack/openai-base@1874

      @tanstack/preact-ai-devtools

      npm i https://pkg.pr.new/@tanstack/preact-ai-devtools@1874

      @tanstack/react-ai-devtools

      npm i https://pkg.pr.new/@tanstack/react-ai-devtools@1874

      @tanstack/solid-ai-devtools

      npm i https://pkg.pr.new/@tanstack/solid-ai-devtools@1874

      @tanstack/svelte-ai-devtools

      npm i https://pkg.pr.new/@tanstack/svelte-ai-devtools@1874

      commit: be46f21

    6. AlemTuzlak merged this028f30f

    7. AlemTuzlak closed this

Sign in to join this conversation.