<?xml version="1.0" encoding="utf-8" standalone="yes"?><rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:content="http://purl.org/rss/1.0/modules/content/"><channel><title>Ollama Api Chat on RockB</title><link>https://baeseokjae.github.io/tags/ollama-api-chat/</link><description>Recent content in Ollama Api Chat on RockB</description><image><title>RockB</title><url>https://baeseokjae.github.io/images/og-default.png</url><link>https://baeseokjae.github.io/images/og-default.png</link></image><generator>Hugo</generator><language>en-us</language><lastBuildDate>Wed, 25 Nov 2026 14:55:56 +0000</lastBuildDate><atom:link href="https://baeseokjae.github.io/tags/ollama-api-chat/index.xml" rel="self" type="application/rss+xml"/><item><title>Ollama Tool Calls: Object vs String Arguments on Two API Surfaces</title><link>https://baeseokjae.github.io/posts/ollama-native-vs-openai-tool-call-shape-2026/</link><pubDate>Wed, 25 Nov 2026 12:55:00 +0000</pubDate><guid>https://baeseokjae.github.io/posts/ollama-native-vs-openai-tool-call-shape-2026/</guid><description>Same prompt, same qwen3:0.6b call: /api/chat returns arguments as an object, /v1/chat/completions as a JSON string, and replaying either history returns HTTP 400. The two error strings, a tested normaliser, and the streaming shape that looks hung.</description><content:encoded><![CDATA[<p>A coding agent works for an afternoon against Ollama&rsquo;s native <code>/api/chat</code>. Then someone points the OpenAI SDK at <code>http://localhost:11434/v1</code> to reuse an existing client, or a library switches endpoints underneath the agent. The first turn still works. The second turn is where the run dies, in one of two ways that look unrelated:</p>
<ul>
<li>the executor calls <code>args[&quot;path&quot;]</code> and gets <code>TypeError: string indices must be integers, not 'str'</code>, because the arguments arrived as a JSON string;</li>
<li>or the client stores the native assistant message, sends it back to <code>/v1/chat/completions</code>, and gets <code>HTTP 400</code> before a single token is generated.</li>
</ul>
<p>Both failures have the same cause: the two surfaces of the same server encode a tool call in incompatible ways. On Ollama 0.20.3, non-streaming, with <code>qwen3:0.6b</code>, <code>POST /api/chat</code> returned <code>function.arguments</code> as a JSON object. <code>POST /v1/chat/completions</code>, same model, same prompt, same <code>tools</code> array, returned the same call with <code>function.arguments</code> as a JSON string. Replaying either assistant message into the other endpoint was rejected with <code>400</code>, each with its own parse error.</p>
<p>That is the whole finding, and it is a client problem rather than a server defect: each endpoint returns a well-formed call in its own encoding. The rest of this article is the measured evidence, the two error strings to grep for, a normaliser that survives both shapes, and the streaming behaviour that makes a correct client look hung.</p>
<h2 id="what-each-specification-actually-says">What each specification actually says</h2>
<p>Neither encoding is an accident. Ollama&rsquo;s own API specification types tool-call arguments as an object: the <code>ToolCall.function</code> schema in <a href="https://docs.ollama.com/openapi.yaml">docs.ollama.com/openapi.yaml</a> declares</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-yaml" data-lang="yaml"><span style="display:flex;"><span><span style="color:#f92672">arguments</span>:
</span></span><span style="display:flex;"><span>  <span style="color:#f92672">type</span>: <span style="color:#ae81ff">object</span>
</span></span><span style="display:flex;"><span>  <span style="color:#f92672">description</span>: <span style="color:#ae81ff">JSON object of arguments to pass to the function</span>
</span></span></code></pre></div><p>The OpenAI chat-completions schema types the same field as a string, and warns that the string is not guaranteed to be valid JSON. In the <a href="https://raw.githubusercontent.com/openai/openai-openapi/master/openapi.yaml">OpenAI OpenAPI specification</a>:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-yaml" data-lang="yaml"><span style="display:flex;"><span><span style="color:#f92672">arguments</span>:
</span></span><span style="display:flex;"><span>  <span style="color:#f92672">type</span>: <span style="color:#ae81ff">string</span>
</span></span><span style="display:flex;"><span>  <span style="color:#f92672">description</span>: <span style="color:#ae81ff">The arguments to call the function with, as generated by the model</span>
</span></span><span style="display:flex;"><span>    <span style="color:#ae81ff">in JSON format.</span>
</span></span></code></pre></div><p>So a client that moves between the two surfaces is not decoding the same type twice; it is decoding an object on one side and a serialised object on the other. Ollama&rsquo;s <a href="https://docs.ollama.com/api/openai-compatibility.md">OpenAI-compatibility page</a> is explicit that the <code>/v1</code> layer is partial — &ldquo;Ollama supports a subset of the OpenAI API&rdquo; — which is consistent with what follows. The string return on <code>/v1</code> matches the OpenAI schema; the object return on <code>/api/chat</code> matches Ollama&rsquo;s. A library that assumes one shape is correct only on the surface it was written for.</p>
<p>This is also the specific place where our own <a href="https://baeseokjae.github.io/posts/ollama-api-local-llm-integration-developer-guide-2026/">guide to Ollama&rsquo;s two API surfaces</a> overstates parity. Its sentence &ldquo;Both approaches produce identical inference results&rdquo; holds for plain text and does not hold for tool calls, as the measurement below shows. For a vanished or retyped call rather than an encoding mismatch, see <a href="https://baeseokjae.github.io/posts/ollama-tool-call-history-corruption-2026/">the history-corruption cases</a>; those are server-side parser and renderer defects, and they are a different failure. If you want the mechanism behind function calling first, <a href="https://baeseokjae.github.io/posts/llm-function-calling-tool-use-guide-2026/">the tool-use explainer</a> covers it, and <a href="https://baeseokjae.github.io/posts/ollama-tool-definition-prompt-token-cost-2026/">the tool-definition token cost piece</a> covers what the same request spends before generation starts.</p>
<h2 id="the-measurement-one-host-one-model-one-prompt">The measurement: one host, one model, one prompt</h2>
<p>One <code>read_file</code> tool (<code>path: string</code>, <code>max_bytes: integer</code>, both required), one user message — &ldquo;Read the file src/app.py and report the first 2000 bytes.&rdquo; — sent to both endpoints of the same local server, <code>temperature 0</code>, native request with <code>think: false</code>. Environment: Ollama 0.20.3, <code>qwen3:0.6b</code> digest <code>7df6b6e09427</code> (Q4_K_M), 2 vCPU / 11 GB, localhost only, no credentials and no external network. Measured <strong>2026-11-15</strong>; the two specification excerpts above were reopened on 2026-11-25 and are dated separately from the probe.</p>
<table>
	<thead>
			<tr>
					<th></th>
					<th><code>POST /api/chat</code></th>
					<th><code>POST /v1/chat/completions</code></th>
			</tr>
	</thead>
	<tbody>
			<tr>
					<td>HTTP status</td>
					<td>200</td>
					<td>200</td>
			</tr>
			<tr>
					<td>tool-call keys</td>
					<td><code>id</code>, <code>function</code> (<code>index</code>, <code>name</code>, <code>arguments</code>)</td>
					<td><code>id</code>, <code>index</code>, <code>type</code>, <code>function</code></td>
			</tr>
			<tr>
					<td><code>function.arguments</code></td>
					<td>object → Python <code>dict</code></td>
					<td>JSON string → Python <code>str</code></td>
			</tr>
			<tr>
					<td>argument value</td>
					<td><code>{&quot;path&quot;: &quot;src/app.py&quot;, &quot;max_bytes&quot;: 2000}</code></td>
					<td><code>&quot;{\&quot;path\&quot;:\&quot;src/app.py\&quot;,\&quot;max_bytes\&quot;:2000}&quot;</code></td>
			</tr>
			<tr>
					<td>tool-call id</td>
					<td><code>call_3nn9ernp</code></td>
					<td><code>call_im2sam5h</code></td>
			</tr>
			<tr>
					<td>assistant message keys</td>
					<td><code>role</code>, <code>content</code>, <code>tool_calls</code></td>
					<td><code>role</code>, <code>content</code>, <code>reasoning</code>, <code>tool_calls</code></td>
			</tr>
			<tr>
					<td>stop field</td>
					<td><code>done_reason: &quot;stop&quot;</code></td>
					<td><code>finish_reason: &quot;tool_calls&quot;</code></td>
			</tr>
			<tr>
					<td>token counts</td>
					<td><code>prompt_eval_count</code> 175, <code>eval_count</code> 32</td>
					<td><code>usage</code> 169 / 134 / 303</td>
			</tr>
			<tr>
					<td>wall clock (includes load)</td>
					<td>36.9 s</td>
					<td>74.1 s</td>
			</tr>
	</tbody>
</table>
<p>The raw bodies are published: <a href="https://raw.githubusercontent.com/baeseokjae/baeseokjae.github.io/main/research/evidence/ollama-native-vs-openai-tool-call-shape-2026/01_native_request.json">/api/chat request</a>, <a href="https://raw.githubusercontent.com/baeseokjae/baeseokjae.github.io/main/research/evidence/ollama-native-vs-openai-tool-call-shape-2026/01_native_response.json">/api/chat response</a>, <a href="https://raw.githubusercontent.com/baeseokjae/baeseokjae.github.io/main/research/evidence/ollama-native-vs-openai-tool-call-shape-2026/02_openai_request.json">/v1 request</a>, <a href="https://raw.githubusercontent.com/baeseokjae/baeseokjae.github.io/main/research/evidence/ollama-native-vs-openai-tool-call-shape-2026/02_openai_response.json">/v1 response</a>.</p>
<p>Two details in that table matter more than they look. The native response reports <code>done_reason: &quot;stop&quot;</code> on a turn that contains a tool call, while the compatible response reports <code>finish_reason: &quot;tool_calls&quot;</code>. A client that treats <code>stop</code> as &ldquo;the model finished talking&rdquo; and never inspects <code>tool_calls</code> will silently discard a perfectly good call on the native surface. And the <code>/v1</code> message carries a <code>reasoning</code> field with the model&rsquo;s thinking text, which the native message from this <code>think: false</code> request does not carry.</p>
<p>Wall-clock numbers are load-inclusive observations from one 2 vCPU host, not a benchmark; this article makes no throughput claim.</p>
<h2 id="two-client-bugs-one-wire-difference">Two client bugs, one wire difference</h2>
<p>The shapes fail differently in client code, which is why the same root cause produces unrelated-looking tracebacks.</p>
<p>Decoding an OpenAI-shaped call with <code>json.loads</code> works; decoding a native call that way raises <code>TypeError: the JSON object must be str, bytes or bytearray, not dict</code>. Consuming a native call with <code>args[&quot;path&quot;]</code> works; consuming an OpenAI-shaped call that way raises <code>TypeError: string indices must be integers, not 'str'</code>, quoted here from the interpreter rather than paraphrased — the string is indexed by <code>&quot;path&quot;</code>, which Python rejects because string indices must be integers. Libraries that parse arguments in exactly one place get one of these, and libraries that parse in two places get the other on the second turn.</p>
<p>The history side is worse, because it is the server rejecting the request rather than the client misreading a value. Both directions were measured, and both returned <code>400</code> immediately — before generation, so 0.0 s wall:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-text" data-lang="text"><span style="display:flex;"><span>native assistant turn -&gt; POST /v1/chat/completions
</span></span><span style="display:flex;"><span>400 {&#34;error&#34;:{&#34;message&#34;:&#34;json: cannot unmarshal object into Go struct field .messages.tool_calls.function.arguments of type string&#34;,&#34;type&#34;:&#34;invalid_request_error&#34;,&#34;param&#34;:null,&#34;code&#34;:null}}
</span></span><span style="display:flex;"><span>
</span></span><span style="display:flex;"><span>openai assistant turn -&gt; POST /api/chat
</span></span><span style="display:flex;"><span>400 {&#34;error&#34;:&#34;Value looks like object, but can&#39;t find closing &#39;}&#39; symbol&#34;}
</span></span></code></pre></div><p>Transcripts: <a href="https://raw.githubusercontent.com/baeseokjae/baeseokjae.github.io/main/research/evidence/ollama-native-vs-openai-tool-call-shape-2026/05_replay_native_into_openai.json">native history replayed into /v1</a> and <a href="https://raw.githubusercontent.com/baeseokjae/baeseokjae.github.io/main/research/evidence/ollama-native-vs-openai-tool-call-shape-2026/06_replay_openai_into_native.json">OpenAI history replayed into /api/chat</a>. Both files contain the exact request that was sent, so you can replay them against your own server.</p>
<p>Read those messages as version-scoped fingerprints rather than API contracts. The first is a Go <code>encoding/json</code> error naming <code>.messages.tool_calls.function.arguments</code> and the expected type <code>string</code>; the second is Ollama&rsquo;s own message parser failing to read a string that looks like an object. The durable behaviour to test for is the <code>400</code> on cross-endpoint replay; the exact strings may change between releases. If a future version coerces the type instead of rejecting it, the failure disappears and this section becomes historical.</p>
<p>The practical consequence is a rule about what to store between turns. Keep tool calls in the encoding of the endpoint you are about to call, or keep a neutral representation and serialise at the edge. Do not pass the native assistant message straight into an OpenAI-compatible client&rsquo;s history, and do not pass the OpenAI-shaped one back to <code>/api/chat</code>. The tool-call <code>id</code> is no help either. Each response generated its own call, and the two ids (<code>call_3nn9ernp</code> natively, <code>call_im2sam5h</code> on <code>/v1</code>) are unrelated strings, so a proxy that rewrites ids across surfaces (the layer <a href="https://baeseokjae.github.io/posts/litellm-tool-call-id-translation-2026/">LiteLLM-style translation</a> deals with) still has to fix the argument type.</p>
<h2 id="a-normaliser-that-survives-both-shapes">A normaliser that survives both shapes</h2>
<p>The adapter below is the minimum that handles what was actually observed: object arguments, string arguments, one nested wrapper (a model occasionally emits <code>{&quot;arguments&quot;: &quot;{...}&quot;}</code>), and the empty case where the turn carries no call at all. It validates the decoded mapping against the schema that was sent, so a string that decodes to a list or a missing required key fails loudly instead of reaching the executor.</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-python" data-lang="python"><span style="display:flex;"><span><span style="color:#66d9ef">def</span> <span style="color:#a6e22e">normalise_tool_call</span>(message, schema):
</span></span><span style="display:flex;"><span>    calls <span style="color:#f92672">=</span> message<span style="color:#f92672">.</span>get(<span style="color:#e6db74">&#34;tool_calls&#34;</span>) <span style="color:#f92672">or</span> []
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">if</span> len(calls) <span style="color:#f92672">!=</span> <span style="color:#ae81ff">1</span>:
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">raise</span> ToolCallShapeError(<span style="color:#e6db74">&#34;expected exactly 1 tool call, found </span><span style="color:#e6db74">%d</span><span style="color:#e6db74">&#34;</span> <span style="color:#f92672">%</span> len(calls))
</span></span><span style="display:flex;"><span>    fn <span style="color:#f92672">=</span> calls[<span style="color:#ae81ff">0</span>]<span style="color:#f92672">.</span>get(<span style="color:#e6db74">&#34;function&#34;</span>) <span style="color:#f92672">or</span> {}
</span></span><span style="display:flex;"><span>    args <span style="color:#f92672">=</span> fn<span style="color:#f92672">.</span>get(<span style="color:#e6db74">&#34;arguments&#34;</span>)
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">if</span> isinstance(args, str):
</span></span><span style="display:flex;"><span>        args <span style="color:#f92672">=</span> json<span style="color:#f92672">.</span>loads(args)          <span style="color:#75715e"># OpenAI-compatible surface</span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">elif</span> isinstance(args, dict):
</span></span><span style="display:flex;"><span>        args <span style="color:#f92672">=</span> dict(args)                <span style="color:#75715e"># native surface</span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">else</span>:
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">raise</span> ToolCallShapeError(<span style="color:#e6db74">&#34;arguments is </span><span style="color:#e6db74">%s</span><span style="color:#e6db74">&#34;</span> <span style="color:#f92672">%</span> type(args)<span style="color:#f92672">.</span>__name__)
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">if</span> <span style="color:#e6db74">&#34;arguments&#34;</span> <span style="color:#f92672">in</span> args <span style="color:#f92672">and</span> len(args) <span style="color:#f92672">&lt;=</span> <span style="color:#ae81ff">2</span>:   <span style="color:#75715e"># model-invented wrapper</span>
</span></span><span style="display:flex;"><span>        args <span style="color:#f92672">=</span> json<span style="color:#f92672">.</span>loads(args[<span style="color:#e6db74">&#34;arguments&#34;</span>]) <span style="color:#66d9ef">if</span> isinstance(args[<span style="color:#e6db74">&#34;arguments&#34;</span>], str) <span style="color:#66d9ef">else</span> args[<span style="color:#e6db74">&#34;arguments&#34;</span>]
</span></span><span style="display:flex;"><span>    missing <span style="color:#f92672">=</span> [k <span style="color:#66d9ef">for</span> k <span style="color:#f92672">in</span> schema<span style="color:#f92672">.</span>get(<span style="color:#e6db74">&#34;required&#34;</span>, []) <span style="color:#66d9ef">if</span> k <span style="color:#f92672">not</span> <span style="color:#f92672">in</span> args]
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">if</span> missing:
</span></span><span style="display:flex;"><span>        <span style="color:#66d9ef">raise</span> ToolCallShapeError(<span style="color:#e6db74">&#34;missing required argument(s): </span><span style="color:#e6db74">%s</span><span style="color:#e6db74">&#34;</span> <span style="color:#f92672">%</span> <span style="color:#e6db74">&#34;, &#34;</span><span style="color:#f92672">.</span>join(missing))
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">return</span> fn<span style="color:#f92672">.</span>get(<span style="color:#e6db74">&#34;name&#34;</span>), args
</span></span></code></pre></div><p>The listing above is a condensed variant of the published file, not a verbatim excerpt: the <code>json</code> import, the <code>ToolCallShapeError</code> class and the per-property type checks are omitted for space, and the full file is <a href="https://raw.githubusercontent.com/baeseokjae/baeseokjae.github.io/main/research/evidence/ollama-native-vs-openai-tool-call-shape-2026/normalise_tool_call.py">normalise_tool_call.py</a>, with per-property type validation. Its <code>--selftest</code> runs four cases — the two measured shapes plus the nested wrapper and the empty turn — using the exact argument objects returned by this run. Those four checks passed on Python 3.12.3 at 2026-11-25T12:54:29Z; the captured run is <a href="https://raw.githubusercontent.com/baeseokjae/baeseokjae.github.io/main/research/evidence/ollama-native-vs-openai-tool-call-shape-2026/normalise_selftest_output.txt">normalise_selftest_output.txt</a>. That is a local fixture check of the adapter, not a model measurement: no model was called to produce it.</p>
<h2 id="streaming-2-chunks-versus-100-and-why-a-correct-client-looks-hung">Streaming: 2 chunks versus 100, and why a correct client looks hung</h2>
<p>Streaming was measured on the same prompt. The native surface produced <strong>2 NDJSON chunks in 5.1 s</strong>, with the complete call inside the <code>message</code> object of the first chunk: <code>tool_calls_per_chunk</code> was <code>[1, 0]</code>, no content and no thinking text.</p>
<p>The OpenAI-compatible surface produced <strong>100 SSE chunks in 42.9 s</strong>. Of those, 98 carried <code>delta.reasoning</code> (394 characters in total), none carried <code>delta.content</code>, and exactly one carried the tool call — whole, with the arguments string not fragmented across deltas. The run&rsquo;s usage block was absent from the stream. Raw chunk dumps: <a href="https://raw.githubusercontent.com/baeseokjae/baeseokjae.github.io/main/research/evidence/ollama-native-vs-openai-tool-call-shape-2026/03_native_stream_chunks.json">native</a> and <a href="https://raw.githubusercontent.com/baeseokjae/baeseokjae.github.io/main/research/evidence/ollama-native-vs-openai-tool-call-shape-2026/04_openai_stream_chunks.json">/v1</a>.</p>
<p>A client written against the native stream expects the first chunk to be the answer. On the compatible stream it receives dozens of chunks whose <code>content</code> is empty and whose only payload is reasoning text, so its idle timer, its &ldquo;first token&rdquo; log line and its progress bar all behave as though the server were stuck — while the server is generating normally. The extra time is a property of this probe&rsquo;s request rather than a claim about the endpoint: the native call here carried <code>think: false</code>, while the <code>/v1/chat/completions</code> request carried no thinking control at all and still came back with 394 reasoning characters in the stream and a <code>reasoning</code> field in the non-streamed message, which is why the same call took 42.9 s streamed and 74.1 s non-streamed against 5.1 s and 36.9 s natively. Ollama&rsquo;s <a href="https://docs.ollama.com/api/openai-compatibility.md">compatibility page</a> documents <code>reasoning_effort</code> and <code>reasoning.effort</code> as thinking control on that surface, with <code>&quot;none&quot;</code> requesting <code>false</code> for boolean-only models; this run sent neither field, so it tested neither and says nothing about whether they would suppress the reasoning text on 0.20.3.</p>
<p>Two cautions before copying the usual SSE advice. First, this run did <strong>not</strong> observe fragmented arguments: the whole call arrived in one delta, so the article does not claim fragmentation happens on this model. A robust client should still assemble fragments, because that is the documented OpenAI behaviour, but this measurement is not evidence that it occurs here. Second, chunk counts, reasoning volume and wall times are this run&rsquo;s observations, not constants; only the argument type, the status codes and the error bodies were stable enough to treat as findings.</p>
<h2 id="what-this-is-not">What this is not</h2>
<ul>
<li><strong>Not an Ollama bug.</strong> Both endpoints returned a correct, self-consistent call, and the compatibility layer is documented as a subset. The mismatch lives in clients that assume one encoding.</li>
<li><strong>Not a statement about hosted OpenAI.</strong> No request was sent to <code>api.openai.com</code>; the OpenAI schema is cited only because the <code>/v1</code> layer imitates it.</li>
<li><strong>Not generalisable beyond this setup.</strong> One version (0.20.3), one model (<code>qwen3:0.6b</code>, digest <code>7df6b6e09427</code>), one prompt, one host. Another model may serialise differently or emit no call at all.</li>
<li><strong>Not a performance result.</strong> Wall-clock times include model load and are reported as observations from a 2 vCPU machine.</li>
</ul>
<h2 id="reproduce-it-against-your-own-server">Reproduce it against your own server</h2>
<p>Everything needed to re-run the probe and diff your server version is published with this page. <a href="https://raw.githubusercontent.com/baeseokjae/baeseokjae.github.io/main/research/evidence/ollama-native-vs-openai-tool-call-shape-2026/shape_probe.py">shape_probe.py</a> is standard-library Python: it posts to <code>/api/chat</code> with <code>think: false</code>, posts the same messages and tools to <code>/v1/chat/completions</code>, streams both, replays each assistant turn into the opposite endpoint, and writes one JSON file per step. <a href="https://raw.githubusercontent.com/baeseokjae/baeseokjae.github.io/main/research/evidence/ollama-native-vs-openai-tool-call-shape-2026/METHOD.md">METHOD.md</a> records the environment and the determinism caveats, and <a href="https://raw.githubusercontent.com/baeseokjae/baeseokjae.github.io/main/research/evidence/ollama-native-vs-openai-tool-call-shape-2026/00_summary.json">00_summary.json</a> is the machine-readable summary behind every table cell above.</p>
<p>Run it as <code>python3 shape_probe.py &lt;out_dir&gt;</code> against a local Ollama with <code>qwen3:0.6b</code> pulled. It contacts localhost only — no credentials, no paid API, no external network — and takes roughly two to three minutes on 2 vCPU, most of it in the <code>/v1</code> reasoning tokens. If your run returns string arguments on <strong>both</strong> endpoints, or accepts cross-endpoint replay, that is a real result too: name your version and model, because the behaviour is version-scoped and your negative result supersedes this one for your deployment.</p>
<p>The fix in your own code is small and does not need a server change: normalise the arguments at the boundary, keep history in the encoding of the endpoint you will call next, and do not read <code>done_reason: &quot;stop&quot;</code> as proof that nothing was called.</p>
]]></content:encoded></item><item><title>Ollama Returns an Empty Response? Check the Token Limit</title><link>https://baeseokjae.github.io/posts/ollama-empty-tool-call-token-cap-2026/</link><pubDate>Sun, 08 Nov 2026 22:05:00 +0000</pubDate><guid>https://baeseokjae.github.io/posts/ollama-empty-tool-call-token-cap-2026/</guid><description>A tool-calling turn can return HTTP 200 with empty content and no tool_calls: the token cap fired mid-call. Read done_reason=length, and why raising the cap did not help here.</description><content:encoded><![CDATA[<p>An agent sends a request with a <code>tools</code> array and a modest output cap. The server answers HTTP 200, the body parses, and the assistant message is empty: <code>content</code> is <code>&quot;&quot;</code>, <code>tool_calls</code> is absent, and no error field explains it. The loop logs &ldquo;model returned no content&rdquo;, retries the identical request, and the next turn is empty in the same way. The operator starts suspecting the model, the quantisation or the chat template, because nothing in the client raised an exception.</p>
<p>The response already contains the diagnosis. Read the stop reason and the token count before anything else: <code>done_reason</code> is <code>&quot;length&quot;</code> on the native <code>/api/chat</code> surface, <code>finish_reason</code> is <code>&quot;length&quot;</code> through <code>/v1/chat/completions</code>, and <code>eval_count</code> (native) or <code>usage.completion_tokens</code> (compatible surface) equals the cap that was set. The cap fired while the model was still emitting its tool-call preamble. In the chat handler a parsed call is emitted when the parser closes it: it is attached to the streaming chunk that completed it, or to the aggregated non-streaming response once generation is over. A call still incomplete when generation ends is never emitted at all, because the final chunk carries only whatever text the parser was holding outside the call. So the partial call is dropped rather than returned, and the response looks like an ordinary completed turn with nothing in it.</p>
<p>That is the whole diagnostic, and it fits in one response. The rest of this article is the fixture that produced it, the server code path behind it, and a negative result that matters for the obvious fix: on this fixture, raising the cap from 8 to 64 tokens did not restore the call.</p>
<h2 id="the-fields-that-separate-a-truncated-call-from-a-finished-turn">The fields that separate a truncated call from a finished turn</h2>
<p>Both surfaces expose the same state with different names. The native handler returns <code>done_reason</code> and <code>eval_count</code>; the OpenAI-compatible handler maps <code>max_tokens</code> onto the same internal cap and returns <code>finish_reason</code> plus <code>usage</code>. The tools documentation for <a href="https://raw.githubusercontent.com/ollama/ollama/v0.20.3/docs/api.md">Ollama v0.20.3</a> shows the normal shapes of a streamed and a final <code>/api/chat</code> response, and the <a href="https://raw.githubusercontent.com/ollama/ollama/v0.20.3/docs/api/openai-compatibility.mdx">OpenAI-compatibility page</a> lists <code>max_tokens</code> and <code>tools</code> as supported parameters.</p>
<table>
	<thead>
			<tr>
					<th>What to read</th>
					<th>Native <code>POST /api/chat</code></th>
					<th><code>POST /v1/chat/completions</code></th>
			</tr>
	</thead>
	<tbody>
			<tr>
					<td>why generation stopped</td>
					<td><code>done_reason</code></td>
					<td><code>choices[0].finish_reason</code></td>
			</tr>
			<tr>
					<td>tokens actually generated</td>
					<td><code>eval_count</code></td>
					<td><code>usage.completion_tokens</code></td>
			</tr>
			<tr>
					<td>call present</td>
					<td><code>message.tool_calls</code></td>
					<td><code>message.tool_calls</code></td>
			</tr>
			<tr>
					<td>the limit you set</td>
					<td><code>options.num_predict</code></td>
					<td><code>max_tokens</code></td>
			</tr>
	</tbody>
</table>
<p>Three combinations are worth memorising, because they lead to different actions:</p>
<ul>
<li><code>length</code> plus a token count equal to your cap: the cap fired. Any partial call was dropped. This is the case measured here.</li>
<li><code>stop</code> with a non-empty <code>content</code> and no <code>tool_calls</code>: the model answered in prose instead of calling a tool. Raising the cap will not change that.</li>
<li><code>tool_calls</code> present: a call was parsed and returned. Whatever goes wrong after this is argument or client-side validation, not truncation.</li>
</ul>
<p>The <code>num_predict</code> option is documented in the <a href="https://raw.githubusercontent.com/ollama/ollama/v0.20.3/docs/modelfile.mdx">v0.20.3 Modelfile reference</a> as the maximum number of tokens to predict, defaulting to <code>-1</code> for unbounded generation. The cap in a failing request is therefore the caller&rsquo;s own number, not a hidden model limit.</p>
<h2 id="what-the-measured-run-shows">What the measured run shows</h2>
<p>The fixture is deliberately small and boring: <code>qwen2.5:0.5b</code> (Q4_K_M, 397 MB, 4096-token context) on Ollama 0.20.3, one <code>create_ticket</code> tool schema with three required fields (<code>title</code>, <code>priority</code> as an enum, <code>summary</code>), temperature 0, seed 7. Two prompt variants were used: A with a long operator preamble and a detailed customer message, B with a one-sentence preamble and a short request. Caps of 8, 16, 24, 32, 40 and 48 tokens were requested on both variants and both API surfaces, five repetitions per cell, with one extra repetition in the native variant-A cell at cap 24 and one further cell at 64 on the native surface. The run recorded 129 requests in total. The table below counts every request per cap, so its rows already include the two native streaming cells at caps 16 and 48; the remaining 127 requests are the graded cells.</p>
<table>
	<thead>
			<tr>
					<th>Cap</th>
					<th>Requests</th>
					<th>Empty content, no <code>tool_calls</code></th>
					<th>Complete calls</th>
					<th>Stop reason</th>
			</tr>
	</thead>
	<tbody>
			<tr>
					<td>8</td>
					<td>20</td>
					<td>20</td>
					<td>0</td>
					<td><code>length</code></td>
			</tr>
			<tr>
					<td>16</td>
					<td>21</td>
					<td>21</td>
					<td>0</td>
					<td><code>length</code></td>
			</tr>
			<tr>
					<td>24</td>
					<td>21</td>
					<td>21</td>
					<td>0</td>
					<td><code>length</code></td>
			</tr>
			<tr>
					<td>32</td>
					<td>20</td>
					<td>20</td>
					<td>0</td>
					<td><code>length</code></td>
			</tr>
			<tr>
					<td>40</td>
					<td>20</td>
					<td>20</td>
					<td>0</td>
					<td><code>length</code></td>
			</tr>
			<tr>
					<td>48</td>
					<td>21</td>
					<td>21</td>
					<td>0</td>
					<td><code>length</code></td>
			</tr>
			<tr>
					<td>64</td>
					<td>5</td>
					<td>5</td>
					<td>0</td>
					<td><code>length</code></td>
			</tr>
			<tr>
					<td>96</td>
					<td>1</td>
					<td>0</td>
					<td>1</td>
					<td><code>stop</code></td>
			</tr>
	</tbody>
</table>
<p>Every request at caps 8 through 64 returned HTTP 200 with <code>content</code> of length zero, no <code>tool_calls</code>, and a stop reason of <code>length</code>. On the native surface <code>eval_count</code> equalled the cap in every one of those requests; on the compatible surface <code>usage.completion_tokens</code> equalled <code>max_tokens</code> in all 60 compatible requests. The empty message is not a client serialisation artefact: the same state appears in the raw JSON body, on both surfaces, with the token accounting that proves generation happened.</p>
<p>The single exception in the log is one request at 96 tokens on the native surface with variant A: a complete <code>create_ticket</code> call, <code>done_reason</code> <code>&quot;stop&quot;</code>, <code>eval_count</code> 95. It is one observation, not a boundary. No repetition was made at 96, variant B was not tested there, and the compatible surface never reached a complete call inside the tested range. Treat it as evidence that the fixture can complete at a larger cap, not as a value to copy.</p>
<h2 id="why-the-content-is-empty-rather-than-truncated">Why the content is empty rather than truncated</h2>
<p>The intuitive model of a token cap is &ldquo;the answer gets cut off&rdquo;, and for plain text that is what happens: you receive a partial sentence. With a <code>tools</code> array the observable is different, because a partial tool call has nowhere to go in the response schema.</p>
<p>In the chat handler of <a href="https://raw.githubusercontent.com/ollama/ollama/v0.20.3/server/routes.go"><code>server/routes.go</code> at v0.20.3</a>, the branch that runs when the request carries a <code>tools</code> array hands each chunk to the tool parser (<code>toolCalls, content := toolParser.Add(res.Message.Content)</code>, line 2493). When the parser closes a call, that branch attaches the calls to the chunk that completed them and empties the content (<code>res.Message.ToolCalls = toolCalls; res.Message.Content = &quot;&quot;</code>, lines 2496-2501). When it has not closed one, the final chunk carries whatever text the parser is still holding and nothing else - <code>if r.Done { res.Message.Content = toolParser.Content(); ch &lt;- res }</code>, lines 2513-2515 - and a non-streaming call then attaches the collected calls only when at least one closed call was parsed: <code>if len(toolCalls) &gt; 0 { resp.Message.ToolCalls = toolCalls }</code>, lines 2608-2610. A generation stopped at the cap still reports done, but an unterminated call never becomes an entry in that slice, so the attachment is skipped and the message goes out with empty content. (The older <code>/api/generate</code> path applies the same rule in <code>GenerateHandler</code> with a different field, <code>if cr.Done &amp;&amp; len(toolCalls) &gt; 0 { res.ToolCalls = toolCalls }</code> at lines 584-585; every measurement in this article is on the chat path, where <code>/api/chat</code> and the <code>/v1/chat/completions</code> wrapper are both served by <code>ChatHandler</code>.) The response that reaches the client is a normal completion carrying an empty <code>content</code> string and no <code>tool_calls</code>. Nothing in that payload is marked as an error, because from the server&rsquo;s point of view nothing failed: the client&rsquo;s limit was honoured exactly.</p>
<p>The compatible layer inherits the same shape. In <a href="https://raw.githubusercontent.com/ollama/ollama/v0.20.3/openai/openai.go"><code>openai/openai.go</code> at v0.20.3</a>, <code>max_tokens</code> is copied into the internal <code>num_predict</code> option, and for a non-streaming response the finish reason is rewritten to <code>tool_calls</code> only when the response actually carries tool calls; otherwise the underlying <code>done_reason</code> string is returned unchanged. Streaming applies the same rule in <code>toChunk</code>, which reports <code>tool_calls</code> when the chunk itself carries calls or when an earlier chunk already sent one (<code>toolCallSent</code>), so the rewrite tracks calls having been emitted rather than calls present in the final message alone. A dropped partial call therefore keeps <code>finish_reason: &quot;length&quot;</code> instead of being rewritten into something a client might notice.</p>
<p>This is why the failure is so quiet in an agent loop. A text-generation client that checks only for empty content can treat the turn as a no-op; a tool-calling client that checks only for <code>tool_calls</code> sees &ldquo;no call&rdquo; and often assumes the model chose not to act. The stop reason is the field that separates those cases, and it is present in every response.</p>
<h2 id="the-negative-result-raising-the-cap-did-not-fix-it-on-this-fixture">The negative result: raising the cap did not fix it on this fixture</h2>
<p>The obvious remedy is to raise the limit. On this fixture it did not work over an eightfold range. Twenty graded runs at 48 tokens - five per cell across the two prompt variants and the two surfaces - plus the one streaming request at that cap produced zero complete calls, and five runs at 64 on the native surface also produced zero. The first and only complete call in the log came at 96 tokens, in a single run.</p>
<p>Two readings of that result are tempting and both are wrong. The first is that 96 is the required cap; with n=1 and one variant it supports no such constant, and the same schema on another model or template will spend a different number of tokens before the call closes. The second is that the cap value is irrelevant, which over-reads a single model. What the run does establish is narrower and still useful: the empty state is stable from 8 to 64 tokens, so a retry loop that bumps the cap by a small increment will keep producing identical empty turns while burning time, and a diagnostic that relies on &ldquo;it will work with a bigger number&rdquo; has no measured basis here.</p>
<p>The practical consequence is to stop treating the cap as the variable to tune and treat the empty response as the signal to inspect. If the stop reason is <code>length</code>, the request needs a different shape - a shorter preamble, a smaller schema, or a generation budget sized to the template - not the same request submitted again with a larger number.</p>
<h2 id="a-check-you-can-run-on-one-response">A check you can run on one response</h2>
<p>The detection step needs no server logs and no framework instrumentation. Take the response object your client already has, pass in the cap you sent, and check the three fields together:</p>
<div class="highlight"><pre tabindex="0" style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4;-webkit-text-size-adjust:none;"><code class="language-python" data-lang="python"><span style="display:flex;"><span><span style="color:#66d9ef">def</span> <span style="color:#a6e22e">capped_without_call</span>(resp, cap, native<span style="color:#f92672">=</span><span style="color:#66d9ef">True</span>):
</span></span><span style="display:flex;"><span>    <span style="color:#e6db74">&#34;&#34;&#34;cap is the limit you sent, not a field the server echoes back.&#34;&#34;&#34;</span>
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">if</span> native:
</span></span><span style="display:flex;"><span>        reason, tokens <span style="color:#f92672">=</span> resp<span style="color:#f92672">.</span>get(<span style="color:#e6db74">&#34;done_reason&#34;</span>), resp<span style="color:#f92672">.</span>get(<span style="color:#e6db74">&#34;eval_count&#34;</span>)
</span></span><span style="display:flex;"><span>        message <span style="color:#f92672">=</span> resp<span style="color:#f92672">.</span>get(<span style="color:#e6db74">&#34;message&#34;</span>) <span style="color:#f92672">or</span> {}
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">else</span>:
</span></span><span style="display:flex;"><span>        choice <span style="color:#f92672">=</span> (resp<span style="color:#f92672">.</span>get(<span style="color:#e6db74">&#34;choices&#34;</span>) <span style="color:#f92672">or</span> [{}])[<span style="color:#ae81ff">0</span>]
</span></span><span style="display:flex;"><span>        reason, tokens <span style="color:#f92672">=</span> choice<span style="color:#f92672">.</span>get(<span style="color:#e6db74">&#34;finish_reason&#34;</span>), (resp<span style="color:#f92672">.</span>get(<span style="color:#e6db74">&#34;usage&#34;</span>) <span style="color:#f92672">or</span> {})<span style="color:#f92672">.</span>get(<span style="color:#e6db74">&#34;completion_tokens&#34;</span>)
</span></span><span style="display:flex;"><span>        message <span style="color:#f92672">=</span> choice<span style="color:#f92672">.</span>get(<span style="color:#e6db74">&#34;message&#34;</span>) <span style="color:#f92672">or</span> {}
</span></span><span style="display:flex;"><span>    <span style="color:#66d9ef">return</span> (reason <span style="color:#f92672">==</span> <span style="color:#e6db74">&#34;length&#34;</span>
</span></span><span style="display:flex;"><span>            <span style="color:#f92672">and</span> <span style="color:#f92672">not</span> message<span style="color:#f92672">.</span>get(<span style="color:#e6db74">&#34;content&#34;</span>)
</span></span><span style="display:flex;"><span>            <span style="color:#f92672">and</span> <span style="color:#f92672">not</span> message<span style="color:#f92672">.</span>get(<span style="color:#e6db74">&#34;tool_calls&#34;</span>)
</span></span><span style="display:flex;"><span>            <span style="color:#f92672">and</span> cap <span style="color:#f92672">is</span> <span style="color:#f92672">not</span> <span style="color:#66d9ef">None</span> <span style="color:#f92672">and</span> tokens <span style="color:#f92672">==</span> cap)
</span></span></code></pre></div><p><code>cap</code> is an argument because the response does not carry it. In <a href="https://raw.githubusercontent.com/ollama/ollama/v0.20.3/api/types.go"><code>api/types.go</code> at v0.20.3</a>, <code>ChatResponse</code> (line 534 onward) has no <code>options</code> field - <code>Options</code> is declared on <code>ChatRequest</code> (line 168) - and the compatible body exposes <code>usage.completion_tokens</code> but never <code>max_tokens</code>, so the limit has to come from the request you sent and be compared against the token count the server reports. Pass the <code>num_predict</code> value you set, or the <code>max_tokens</code> you passed to the wrapper; the two are the same number after the mapping described above.</p>
<p>The predicate is a reading aid, not a fix: it tells you that the cap fired and the call was dropped. Log <code>done_reason</code>, <code>eval_count</code> and the configured cap on every turn, not only on errors, so the state is visible the first time it happens rather than after a retry storm. When the predicate is true, do not resubmit the identical request; change the prompt or the budget first, or surface the state to the operator.</p>
<p>Two neighbours are worth reading alongside this one. The <a href="https://baeseokjae.github.io/posts/ollama-api-local-llm-integration-developer-guide-2026/">Ollama API integration guide</a> covers the request and response fields this article relies on, and the <a href="https://baeseokjae.github.io/posts/llm-function-calling-tool-use-guide-2026/">function-calling guide</a> explains <code>finish_reason</code> as the signal for detecting a call; this piece is the case where that signal reads <code>length</code> instead. For the prompt-side failure that looks similar but is not the same, the <a href="https://baeseokjae.github.io/posts/ollama-silent-context-truncation-2026/">context-truncation diagnosis</a> covers a prompt that is cut before generation starts, and the <a href="https://baeseokjae.github.io/posts/local-llm-concurrent-agent-sessions-2026/">concurrent-session logging checklist</a> already names <code>length</code> plus <code>num_predict</code> as the stop signal for text turns, though not for a discarded tool call. Readers running the same loop against a different engine can compare the parser behaviour in the <a href="https://baeseokjae.github.io/posts/vllm-streaming-tool-call-parser-corruption-2026/">vLLM streaming tool-call case</a>, and the <a href="https://baeseokjae.github.io/posts/local-ai-agents-guide-2026/">local agent guide</a> covers the retry structure in which one empty turn becomes a stall.</p>
<h2 id="fixture-reproduction-and-limits">Fixture, reproduction and limits</h2>
<p>The run used two stdlib <code>urllib</code> scripts against the local daemon at <code>127.0.0.1:11434</code>, no SDK. Each request recorded the HTTP status, wall time, content length, presence of <code>tool_calls</code>, JSON-parseability of the arguments and whether every required key was present, plus <code>done_reason</code>/<code>finish_reason</code> and <code>eval_count</code>/<code>usage.completion_tokens</code>. The graded table, the raw request log, the environment capture and the method note are kept with the draft as a private local author verification; they are not offered here as a downloadable dataset or a reusable harness, so no reader-access promise is made for those files. The fixture is described completely enough to rebuild: one model tag, one tool schema, two prompts, one sampling setting, and the caps listed above.</p>
<p>The limits are the honest part of this result. It is one host (2 vCPU, recorded load average 4.64 before the sweep and 3.47 and 2.73 at two in-run checkpoints), one model, one quantisation, one tool schema, two prompt variants, and 129 requests. Requests went to a shared local daemon rather than a dedicated server instance, so wall times are provenance only and no throughput or latency claim is drawn from them. The single 96-token completion is one run on one variant, and no boundary is asserted across variants or surfaces. Nothing here measures how often this happens across models, and no prevalence figure is implied. What is supported is the diagnostic: a <code>length</code> stop with a token count equal to the cap and an empty message is the signature of a capped generation whose partial tool call was discarded, and on this fixture raising the cap across an eightfold range did not restore the call.</p>
]]></content:encoded></item></channel></rss>