Skip to content

fix: Ollama Cloud tool calls fail on second turn - #96474

Merged
hannesrudolph merged 1 commit into
openclaw:mainfrom
849261680:fix/96441-ollama-cloud-tool-args
Jun 29, 2026
Merged

hannesrudolph merged 1 commit into
openclaw:mainfrom
849261680:fix/96441-ollama-cloud-tool-args

Conversation

@849261680

@849261680 849261680 commented Jun 24, 2026 •

Copy link
Copy Markdown
Contributor

Closes #96441

What Problem This Solves

Fixes an issue where users running Ollama Cloud models through the OpenAI-compatible Chat Completions route would hit a 400 error on the second agent turn after a tool call. The failing replay sent previous tool_calls.function.arguments as a JSON object even though the OpenAI-compatible request contract expects JSON strings.

Why This Change Was Made

The Ollama native /api/chat route still needs object arguments, but the OpenAI-compatible /v1/chat/completions route must preserve string arguments already produced by the shared OpenAI Chat Completions converter. This change removes the extra compat payload mutation that was converting replayed function arguments back into objects while keeping native Ollama argument normalization covered.

User Impact

Ollama Cloud users can continue multi-turn tool-calling conversations instead of failing immediately when OpenClaw replays the previous assistant tool call. Native Ollama users keep the existing object-argument behavior for /api/chat.

Evidence

Dependency contract checked:

  • node_modules/openai/resources/chat/completions/completions.d.ts defines both legacy function_call.arguments and ChatCompletionMessageFunctionToolCall.Function.arguments as string JSON.

Captured after-fix request proof:

  • Real environment tested: current source checkout, actual streamOpenAICompletions OpenAI SDK HTTP path, Ollama compat wrapper, local OpenAI-compatible /v1/chat/completions endpoint capturing the wire request body.
  • Exact scenario: second-turn conversation history with a previous assistant toolCall, matching the reporter's failing replay shape.
  • Observed request path: /v1/chat/completions.
  • Observed tool_calls[0].function.arguments type: string.
  • Observed tool_calls[0].function.arguments value: {"action":"config.get","path":"gateway.port"}.
  • Observed options.num_ctx: 262144, proving the Ollama compat wrapper still patched the same request.
  • Native sibling check in the same proof: convertToOllamaMessages still returns object arguments for native Ollama replay: { "action": "config.get", "path": "gateway.port" }.

Captured proof output:

{
  "capturedRequests": 1,
  "requestUrl": "/v1/chat/completions",
  "compatToolArgumentsType": "string",
  "compatToolArgumentsValue": "{\"action\":\"config.get\",\"path\":\"gateway.port\"}",
  "compatOptionsNumCtx": 262144,
  "nativeToolArgumentsType": "object",
  "nativeToolArgumentsValue": {
    "action": "config.get",
    "path": "gateway.port"
  }
}

Commands run:

  • pnpm install --frozen-lockfile
  • node scripts/run-vitest.mjs extensions/ollama/src/stream-runtime.test.ts
  • node scripts/run-vitest.mjs extensions/ollama/index.test.ts
  • node scripts/run-vitest.mjs extensions/ollama/src/stream.test.ts extensions/ollama/src/stream-runtime.test.ts
  • pnpm exec oxfmt --write --threads=1 extensions/ollama/src/stream.ts extensions/ollama/src/stream-runtime.test.ts
  • pnpm exec oxfmt --check --threads=1 extensions/ollama/src/stream.ts extensions/ollama/src/stream-runtime.test.ts
  • pnpm exec oxlint --config .oxlintrc.json --quiet extensions/ollama/src/stream.ts extensions/ollama/src/stream-runtime.test.ts
  • pnpm exec tsx - with a stdin harness that starts a local OpenAI-compatible endpoint, calls streamOpenAICompletions through createConfiguredOllamaCompatStreamWrapper, captures the HTTP request body, and checks the native conversion sibling.
  • .agents/skills/autoreview/scripts/autoreview --mode local --prompt 'Review the narrow fix for issue #96441: Ollama OpenAI-compatible Chat Completions payloads must preserve tool call function.arguments as JSON strings, while native Ollama /api/chat replay keeps object arguments. Focus on changed files only and dependency contract fit.'

Autoreview result:

  • autoreview clean: no accepted/actionable findings reported

Not tested:

  • Live Ollama Cloud credentialed request; the after-fix proof above captures the real OpenAI SDK HTTP request body against a local OpenAI-compatible endpoint without needing live credentials.

@849261680

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Jun 24, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

@clawsweeper

clawsweeper Bot commented Jun 24, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed June 24, 2026, 2:50 PM ET / 18:50 UTC.

Summary
This PR removes OpenAI-compatible Ollama tool-call argument object coercion from the num_ctx wrapper and adds regression tests for native object arguments versus Chat Completions string arguments.

PR surface: Source -41, Tests +81. Total +40 across 2 files.

Reproducibility: yes. The current-main source path shows Chat Completions arguments are stringified and then the Ollama compat wrapper converts them back to objects, matching the canonical issue's captured 400 response.

Review metrics: 2 noteworthy metrics.

  • Exported helper behavior: 1 behavior changed, 0 signatures changed. The PR changes a public Ollama helper side effect, so maintainers should acknowledge compatibility even though the change fixes the regression.
  • Open fix candidates: 2 open PRs reference the canonical issue. Maintainers should choose one landing path before merge to avoid duplicate fixes for the same regression.

Root-cause cluster
Relationship: fixed_by_candidate
Canonical: #96441
Summary: This PR is a candidate fix for the canonical Ollama Cloud/OpenAI-compatible second-turn tool-call argument encoding regression, with one other open duplicate candidate still present.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Merge readiness
Overall: 🐚 platinum hermit
Proof: 🐚 platinum hermit
Patch quality: 🦞 diamond lobster
Result: ready for maintainer review.

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

Rank-up moves:

Risk before merge

  • [P1] wrapOllamaCompatNumCtx is exported through Ollama API barrels; removing its previous tool-argument coercion side effect is correct for Ollama Cloud but should be explicitly accepted as a compatibility-sensitive behavior change.
  • [P1] Another open PR, fix(ollama): stop forcing tool_calls.arguments back to an object on the openai-completions path #96498, targets the same canonical regression, so maintainers should land one candidate and close or supersede the other.
  • [P1] The PR body includes strong captured HTTP-path proof against a local OpenAI-compatible endpoint, but not a credentialed Ollama Cloud success run.

Maintainer options:

  1. Accept the helper behavior change and land one candidate (recommended)
    A maintainer can accept that wrapOllamaCompatNumCtx now only injects num_ctx, choose this PR or the duplicate candidate, and close the other path after merge.
  2. Consolidate the duplicate first
    If maintainers want one review thread, ask the authors to fold any desired tests or proof from fix(ollama): stop forcing tool_calls.arguments back to an object on the openai-completions path #96498 into the chosen PR before merge.
  3. Wait for credentialed Ollama Cloud proof
    If live provider acceptance is required for this release, pause merge until a redacted second-turn Ollama Cloud run confirms the request succeeds against the real service.

Next step before merge

  • [P2] The remaining action is maintainer selection between duplicate fix PRs and explicit acceptance of the exported-helper behavior change, not an automation repair.

Security
Cleared: The diff only changes Ollama TypeScript runtime behavior and tests; it adds no dependency, workflow, secret, package, or code-execution surface.

Review details

Best possible solution:

Land one narrow candidate that keeps native Ollama object coercion separate from OpenAI-compatible string replay, then close the duplicate PR path.

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

Yes. The current-main source path shows Chat Completions arguments are stringified and then the Ollama compat wrapper converts them back to objects, matching the canonical issue's captured 400 response.

Is this the best way to solve the issue?

Yes for code shape. Removing only the compat wrapper's object coercion is the narrowest maintainable fix because native /api/chat conversion remains covered in the native conversion path.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against f2bc159b79c3.

Label changes

Label justifications:

  • P1: The PR targets a latest-release regression that breaks multi-turn tool use for Ollama Cloud users after the first tool call.
  • merge-risk: 🚨 compatibility: The diff changes behavior of an exported Ollama helper by removing the previous tool-argument coercion side effect.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🦞 diamond lobster.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): The PR body includes after-fix captured outgoing HTTP payload output through the OpenAI SDK path and Ollama compat wrapper, plus a native sibling check; no contributor proof action remains.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR body includes after-fix captured outgoing HTTP payload output through the OpenAI SDK path and Ollama compat wrapper, plus a native sibling check; no contributor proof action remains.
Evidence reviewed

PR surface:

Source -41, Tests +81. Total +40 across 2 files.

View PR surface stats
Area Files Added Removed Net
Source 1 0 41 -41
Tests 1 81 0 +81
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 81 41 +40

What I checked:

  • Current main has the failing compat mutation: wrapOllamaCompatNumCtx on current main injects options.num_ctx and then calls normalizeOllamaCompatMessageToolArgs, so the OpenAI-compatible payload is still mutated after the shared Chat Completions converter builds it. (extensions/ollama/src/stream.ts:242, f2bc159b79c3)
  • Current main coerces Chat Completions arguments back to objects: normalizeOllamaCompatMessageToolArgs walks legacy function_call.arguments and tool_calls[*].function.arguments, replacing present values with ensureArgsObject(...). (extensions/ollama/src/stream.ts:739, f2bc159b79c3)
  • Base OpenAI-compatible converter emits string arguments: The shared Chat Completions converter maps assistant tool calls with function.arguments: JSON.stringify(tc.arguments), so the object conversion happens after the correct base payload is built. (src/llm/providers/openai-completions.ts:1079, f2bc159b79c3)
  • Native Ollama path still owns object conversion: The native /api/chat message conversion path uses ensureArgsObject inside extractToolCalls, which is separate from the OpenAI-compatible wrapper this PR narrows. (extensions/ollama/src/stream.ts:886, f2bc159b79c3)
  • PR head removes only the compat argument mutation: At the PR head, wrapOllamaCompatNumCtx still injects num_ctx but no longer calls the compat message argument normalizer. (extensions/ollama/src/stream.ts:242, 2f95c1e54fdb)
  • PR head tests both sides of the split: The added tests assert native Ollama replay keeps object arguments and OpenAI-compatible replay preserves legacy and modern tool-call arguments as strings while retaining options.num_ctx. (extensions/ollama/src/stream-runtime.test.ts:119, 2f95c1e54fdb)

Likely related people:

  • steipete: The over-broad compat normalizer appears in the merged Ollama replay-hardening commit for fix: deserialize string tool-call arguments before sending to Ollama #52253, which was authored, committed, and merged by this contributor. (role: introduced behavior and area contributor; confidence: high; commits: 87abcfd6a6b8; files: extensions/ollama/src/stream.ts)
  • Adam-Researchh: The prior merged native Ollama replay PR was opened by this contributor, and its discussion explicitly scoped native and cloud/OpenAI-compatible argument normalization work. (role: original fix proposer; confidence: medium; commits: 87abcfd6a6b8; files: extensions/ollama/src/stream.ts)
  • vincentkoc: The latest release tag that still contains the affected wrapper behavior was created in the 2026.6.10 release closeout, so release routing may be relevant if maintainers want a patch release. (role: release carrier; confidence: medium; commits: aa69b12d0086; files: extensions/ollama/src/stream.ts, CHANGELOG.md)
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 rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. labels Jun 24, 2026
@849261680

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@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. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Jun 24, 2026
@harjothkhara

harjothkhara commented Jun 24, 2026 •

Copy link
Copy Markdown
Contributor

ClawSweeper marked this "the canonical fix" and superseded my equivalent #96473: identical production deletion, yours carries the captured HTTP-path proof and clean mergeability. It also suggested "consolidating any desired tests first," so here are the two regression tests from mine that this PR doesn't yet have, in case they're useful to fold into extensions/ollama/src/stream-runtime.test.ts. Both pass on this branch's fix; I verified the asymmetry test is red on main (compat half) and green with the fix, and the file typechecks (tsgo -p tsconfig.extensions.json), oxfmt, and oxlint clean.

1. Cross-path asymmetry guard — the same replayed tool call must become object args on the native /api/chat path but stay a JSON string on the OpenAI-compatible path. This catches the exact #96441 regression and locks the native↔compat split that the deletion relies on (so a future re-unification of the two normalization paths is caught):

it("replays the same tool call as object args natively but string args for OpenAI-compat", async () => {
  // #96441 invariant: identical replayed tool calls must diverge by API. Native
  // /api/chat expects object arguments; OpenAI-compatible Chat Completions requires
  // JSON-string arguments. This guards against re-unifying the two normalization paths.
  const stringArgs = '{"action":"config.get","path":"gateway.port"}';

  const nativeMessages = convertToOllamaMessages([
    {
      role: "assistant",
      content: [{ type: "toolCall", id: "call_gateway", name: "gateway", arguments: stringArgs }],
    },
  ]);
  expect(nativeMessages[0].tool_calls).toEqual([
    {
      id: "call_gateway",
      function: { name: "gateway", arguments: { action: "config.get", path: "gateway.port" } },
    },
  ]);

  let patchedPayload: Record<string, unknown> | undefined;
  const baseStreamFn = vi.fn((_model, _context, options) => {
    options?.onPayload?.({
      messages: [
        {
          role: "assistant",
          tool_calls: [
            { id: "call_gateway", type: "function", function: { name: "gateway", arguments: stringArgs } },
          ],
        },
      ],
    });
    return (async function* () {})();
  });
  const model = {
    api: "openai-completions",
    provider: "ollama",
    id: "glm-5.2:cloud",
    contextWindow: 131072,
    params: { num_ctx: 32768 },
  };

  const wrapped = createConfiguredOllamaCompatStreamWrapper({
    provider: "ollama",
    modelId: "glm-5.2:cloud",
    model,
    streamFn: baseStreamFn,
  } as never);

  await wrapped?.(
    model as never,
    { messages: [] } as never,
    {
      onPayload: (payload: unknown) => {
        patchedPayload = payload as Record<string, unknown>;
      },
    } as never,
  );

  const payload = requireRecord(patchedPayload, "patched payload");
  const compatToolCalls = (payload.messages as Array<Record<string, unknown>>)[0].tool_calls as Array<{
    function: { arguments: unknown };
  }>;
  expect(compatToolCalls[0].function.arguments).toBe(stringArgs);
});

2. Options-merge edge — num_ctx injection must not clobber pre-existing options keys:

it("injects num_ctx without clobbering existing OpenAI-compat options", async () => {
  let patchedPayload: Record<string, unknown> | undefined;
  const baseStreamFn = vi.fn((_model, _context, options) => {
    options?.onPayload?.({ options: { temperature: 0.5 } });
    return (async function* () {})();
  });
  const model = {
    api: "openai-completions",
    provider: "ollama",
    id: "glm-5.2:cloud",
    contextWindow: 131072,
    params: { num_ctx: 32768 },
  };

  const wrapped = createConfiguredOllamaCompatStreamWrapper({
    provider: "ollama",
    modelId: "glm-5.2:cloud",
    model,
    streamFn: baseStreamFn,
  } as never);

  await wrapped?.(
    model as never,
    { messages: [] } as never,
    {
      onPayload: (payload: unknown) => {
        patchedPayload = payload as Record<string, unknown>;
      },
    } as never,
  );

  const payload = requireRecord(patchedPayload, "patched payload");
  const options = requireRecord(payload.options, "patched options");
  expect(options.temperature).toBe(0.5);
  expect(options.num_ctx).toBe(32768);
});

You can use the tests or not. I am closing mine in favor of this one. Nice work on the proof.

@aketchel

aketchel commented Jun 29, 2026 •

Copy link
Copy Markdown

Confirmed and tested in the release/2026.6.11 branch with the extensions\ollama\src\stream.ts changes recommended in this PR and this resolved an issue that I had experienced since v2026.6.9 where local ollama model calls would fail after tool calls with "cannot unmarshal object into Go struct field .messages.tool_calls.function.arguments of type string". For me, it was happening on all ollama cloud models (glm-5.2, minimax-m3 and kimi-k2.7-code). All models responded

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Jun 30, 2026
@EugeneClaw

Copy link
Copy Markdown

Verified the merge is on main, but the published [email protected] npm package does not contain this fix.

Evidence (live test against ollama/glm-5.2:cloud):

Source-level confirmation:
/opt/homebrew/lib/node_modules/openclaw/dist/stream-D4CByBVL.js line 237 still calls normalizeOllamaCompatMessageToolArgs(payloadRecord); in wrapOllamaCompatNumCtx — the exact line this PR removes. The function definition is still at line 476.

Branch state:

  • release/2026.6.11 branch (commit da7f620c7ec7, updated 2026-06-30 19:20 UTC) does not contain fix commit 8ee6fe3 — same line 250 in extensions/ollama/src/stream.ts still has the buggy call.
  • Main has the fix.

Suggestion:
Cherry-pick this fix into the release/2026.6.11 branch and re-tag 2026.6.11 (or cut 2026.6.12 with the fix), so npm-installing users actually receive the regression fix that the closed issue #96441 promised. Otherwise the next user who runs npm install -g openclaw@latest will still hit the 400 on their second tool-call turn.

@aketchel — your confirmation comment says you tested in the release/2026.6.11 branch, but I want to flag that this can read ambiguously: did you apply the stream.ts changes from this PR on top of the release branch, or did the release branch already have them? My check shows the branch does not have them, so the npm package released as 2026.6.11 is still broken.

@aketchel

Copy link
Copy Markdown

Verified the merge is on main, but the published [email protected] npm package does not contain this fix.

Evidence (live test against ollama/glm-5.2:cloud):

Source-level confirmation: /opt/homebrew/lib/node_modules/openclaw/dist/stream-D4CByBVL.js line 237 still calls normalizeOllamaCompatMessageToolArgs(payloadRecord); in wrapOllamaCompatNumCtx — the exact line this PR removes. The function definition is still at line 476.

Branch state:

  • release/2026.6.11 branch (commit da7f620c7ec7, updated 2026-06-30 19:20 UTC) does not contain fix commit 8ee6fe3 — same line 250 in extensions/ollama/src/stream.ts still has the buggy call.
  • Main has the fix.

Suggestion: Cherry-pick this fix into the release/2026.6.11 branch and re-tag 2026.6.11 (or cut 2026.6.12 with the fix), so npm-installing users actually receive the regression fix that the closed issue #96441 promised. Otherwise the next user who runs npm install -g openclaw@latest will still hit the 400 on their second tool-call turn.

@aketchel — your confirmation comment says you tested in the release/2026.6.11 branch, but I want to flag that this can read ambiguously: did you apply the stream.ts changes from this PR on top of the release branch, or did the release branch already have them? My check shows the branch does not have them, so the npm package released as 2026.6.11 is still broken.

I applied the PR changes on top of the 2026.6.11 branch and confirmed compatability and issue resolution: the changes were not yet in the branch as the release branch was cut before the changes were validated. The PR has since been merged to main and will be released when the next release branch is created, unless it is cherry picked into 2026.6.11 as suggested.

@EugeneClaw

Copy link
Copy Markdown

Thanks for confirming, @aketchel — that matches what I found. Just to close the loop publicly for anyone landing here from the issue:

  • I locally applied the same one-line removal (normalizeOllamaCompatMessageToolArgs(payloadRecord); in wrapOllamaCompatNumCtx) to my installed [email protected] and can confirm: multi-turn tool calls on ollama/glm-5.2:cloud now succeed on the second turn with no 400, including config.get and exec ls paths.

  • For anyone waiting on the official fix: it's on main (commit 8ee6fe3) and will reach npm when the next release branch is cut or via cherry-pick into release/2026.6.11. The patch above is a safe interim if you need it now.

Thanks @ly-wang19 for the fix and @849261680 for the PR with proof-positive evidence. And @aketchel for the real-world confirmation.

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

Labels

extensions: ollama merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: S status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Ollama Cloud tool_calls fail on 2nd turn — arguments sent as JSON object instead of string (400 from Go server) — regression in 2026.6.9

5 participants