Skip to content

fix: deserialize string tool-call arguments before sending to Ollama - #52253

Merged
steipete merged 1 commit into
openclaw:mainfrom
Adam-Researchh:fix/ollama-tool-call-arguments
Apr 3, 2026
Merged

steipete merged 1 commit into
openclaw:mainfrom
Adam-Researchh:fix/ollama-tool-call-arguments

Conversation

@Adam-Researchh

Copy link
Copy Markdown

Summary

When tool calls round-trip through OpenAI-format storage, arguments is serialized as a JSON string (OpenAI chat completions format). When this conversation history is later sent back to Ollama via convertToOllamaMessages(), extractToolCalls() passes arguments as-is (string). Ollama's native API expects an object and rejects it with:

Value looks like object, but can't find closing '}' symbol

Result: After a successful tool execution, the model returns empty content on the next turn — the user sees no response.

Changes

  • Add ensureArgsObject() helper in ollama-stream.ts that safely parses JSON string arguments back to objects
  • Apply it in extractToolCalls() for both toolCall and tool_use content blocks
  • Add two test cases covering the round-trip scenario (OpenAI format → Ollama, Anthropic format → Ollama)

Testing

  • Applied as a local patch on our gateway (v2026.3.13) — confirmed it resolves the empty response issue for Qwen 3.5 and DeepSeek V3.2 tool-calling sub-agents
  • Added unit tests in ollama-stream.test.ts

Fixes #50689

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: S labels Mar 22, 2026
@greptile-apps

greptile-apps Bot commented Mar 22, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR fixes a real-world bug where tool-call arguments (or input) are stored as a JSON string after an OpenAI-format round-trip, then sent as-is to Ollama's native API which only accepts an object — producing a cryptic parse error and an empty model response on the next turn.

Changes:

  • Adds ensureArgsObject() in ollama-stream.ts that idempotently coerces string or object arguments to a Record<string, unknown>, with a safe {} fallback on malformed JSON.
  • Applies the helper in extractToolCalls() for both toolCall (OpenAI format) and tool_use (Anthropic format) content blocks.
  • Adds two focused unit tests reproducing the round-trip scenario for both formats.

Minor note: When the input string is valid JSON but not an object (e.g. a bare string, array, or number), or when it is not valid JSON at all, the function falls back silently to {}. This avoids crashing Ollama but discards argument data without any log output, which could make unexpected argument-format issues harder to diagnose. A console.warn in the catch block would help surface these cases.

Confidence Score: 4/5

  • Safe to merge; fixes a confirmed production regression with no behaviour change for the happy path.
  • The fix is minimal, correctly scoped, and validated by new tests. The one remaining consideration is that invalid JSON strings fall back to {} silently, which could obscure misconfiguration — a warning log would be a cheap improvement. This is non-blocking, keeping the score at 4.
  • No files require special attention.
Prompt To Fix All With AI
This is a comment left during a code review.
Path: src/agents/ollama-stream.ts
Line: 265-267

Comment:
**Silent data loss on invalid JSON string**

When `value` is a non-empty string that fails `JSON.parse` (e.g. a plain word or a malformed object), the function silently discards it and returns `{}`. The tool call then arrives at Ollama with no arguments at all — which may be equally confusing to debug as the original error.

Consider at least emitting a warning so that misconfigurations are surfaced rather than silently swallowed:

```suggestion
    } catch {
      // not valid JSON — log and fall through to empty object
      console.warn("[ollama] ensureArgsObject: could not parse tool-call arguments as JSON, falling back to {}:", value);
    }
```

How can I resolve this? If you propose a fix, please make it concise.

Reviews (1): Last reviewed commit: "fix: deserialize string tool-call argume..." | Re-trigger Greptile

Comment thread src/agents/ollama-stream.ts Outdated
Comment on lines +265 to +267
} catch {
// not valid JSON — fall through to empty object
}

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.

P2 Silent data loss on invalid JSON string

When value is a non-empty string that fails JSON.parse (e.g. a plain word or a malformed object), the function silently discards it and returns {}. The tool call then arrives at Ollama with no arguments at all — which may be equally confusing to debug as the original error.

Consider at least emitting a warning so that misconfigurations are surfaced rather than silently swallowed:

Suggested change
} catch {
// not valid JSON — fall through to empty object
}
} catch {
// not valid JSON — log and fall through to empty object
console.warn("[ollama] ensureArgsObject: could not parse tool-call arguments as JSON, falling back to {}:", value);
}
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/agents/ollama-stream.ts
Line: 265-267

Comment:
**Silent data loss on invalid JSON string**

When `value` is a non-empty string that fails `JSON.parse` (e.g. a plain word or a malformed object), the function silently discards it and returns `{}`. The tool call then arrives at Ollama with no arguments at all — which may be equally confusing to debug as the original error.

Consider at least emitting a warning so that misconfigurations are surfaced rather than silently swallowed:

```suggestion
    } catch {
      // not valid JSON — log and fall through to empty object
      console.warn("[ollama] ensureArgsObject: could not parse tool-call arguments as JSON, falling back to {}:", value);
    }
```

How can I resolve this? If you propose a fix, please make it concise.

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 4b8fc03aa7

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread src/agents/ollama-stream.ts Outdated
function ensureArgsObject(value: unknown): Record<string, unknown> {
if (typeof value === "string") {
try {
const parsed = JSON.parse(value);

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.

P1 Badge Parse round-tripped tool args without losing large integers

ensureArgsObject decodes stringified tool arguments with raw JSON.parse, which rounds integers above Number.MAX_SAFE_INTEGER (for example 1234567890123456789 becomes 1234567890123456800). That silently corrupts replayed tool-call arguments before they are sent back to Ollama, so any tool relying on 64-bit numeric IDs can receive the wrong target/value. This file already preserves unsafe integers for streamed Ollama JSON via parseJsonPreservingUnsafeIntegers, so this new decode path should do the same to avoid data corruption.

Useful? React with 👍 / 👎.

@Adam-Researchh

Copy link
Copy Markdown
Author

Update — scope clarification: This fix applies to the local Ollama API path (ollama-stream.ts → extractToolCalls() → convertToOllamaMessages()). We've confirmed it resolves tool-call round-trip failures for locally-hosted Ollama models (tested with qwen3.5:122b-a10b on macOS arm64).

Ollama Cloud models (routed through the Ollama cloud API) appear to use a different code path and still exhibit tool-calling issues (500 errors when context is large + tool results are in the conversation history). That may be a separate bug or a server-side Ollama Cloud limitation — haven't traced it yet.

Wanted to be transparent about the scope so reviewers know exactly what this PR covers and what it doesn't.

@Adam-Researchh

Copy link
Copy Markdown
Author

Added cloud Ollama fix (commit 3b0a78e)

The cloud Ollama path routes through src/agents/pi-embedded-runner/run/attempt.ts via the OpenAI-compatible endpoint. Same root cause — string-serialized arguments in tool calls need to be parsed back to objects before sending to Ollama's API.

Changes:

  • Added ensureOllamaCompatArgsObject() and normalizeOllamaCompatMessageToolArgs() in attempt.ts
  • Hooked into wrapOllamaCompatNumCtx()'s onPayload callback so both num_ctx injection and argument deserialization happen in the same outbound payload hook
  • Covers both tool_calls[].function.arguments and legacy function_call.arguments
  • Added test coverage in attempt.test.ts

This PR now fixes both the local Ollama path (ollama-stream.ts) and the cloud Ollama path (attempt.ts).

@steipete
steipete force-pushed the fix/ollama-tool-call-arguments branch from 3b0a78e to 53f5103 Compare April 3, 2026 12:06
@steipete
steipete merged commit 87abcfd into openclaw:main Apr 3, 2026
3 checks passed
@steipete

steipete commented Apr 3, 2026

Copy link
Copy Markdown
Contributor

Landed via temp rebase onto main.

  • Gate: pre-commit pnpm check; pnpm build; pnpm test -- src/agents/pi-embedded-runner/run/attempt.test.ts; pnpm test -- src/agents/ollama-stream.test.ts -t "deserializes|handles tool_use|preserves unsafe integers"; live local Ollama smoke (400 for string args, 200 for fixed object args, unsafe integers preserved on native + compat paths)
  • Note: pnpm test -- src/agents/ollama-stream.test.ts -t "emits text_end as soon as Ollama switches from text to tool calls" still fails on pre-fix HEAD~1, so I treated that as unrelated base breakage, not a regression from this PR.
  • Land commit: 53f5103
  • Merge commit: 87abcfd

Thanks @Adam-Researchh!

lovewanwan pushed a commit to lovewanwan/openclaw that referenced this pull request Apr 28, 2026
ogt-redknie pushed a commit to ogt-redknie/OPENX that referenced this pull request May 2, 2026
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request May 24, 2026
Nachx639 pushed a commit to Nachx639/clawdbot that referenced this pull request Jun 17, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling size: L

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Ollama tool call arguments serialized as string instead of object — breaks tool loop

2 participants