A coding agent works for an afternoon against Ollama’s native /api/chat. Then someone points the OpenAI SDK at http://localhost:11434/v1 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:
- the executor calls
args["path"]and getsTypeError: string indices must be integers, not 'str', because the arguments arrived as a JSON string; - or the client stores the native assistant message, sends it back to
/v1/chat/completions, and getsHTTP 400before a single token is generated.
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 qwen3:0.6b, POST /api/chat returned function.arguments as a JSON object. POST /v1/chat/completions, same model, same prompt, same tools array, returned the same call with function.arguments as a JSON string. Replaying either assistant message into the other endpoint was rejected with 400, each with its own parse error.
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.
What each specification actually says
Neither encoding is an accident. Ollama’s own API specification types tool-call arguments as an object: the ToolCall.function schema in docs.ollama.com/openapi.yaml declares
arguments:
type: object
description: JSON object of arguments to pass to the function
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 OpenAI OpenAPI specification:
arguments:
type: string
description: The arguments to call the function with, as generated by the model
in JSON format.
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’s OpenAI-compatibility page is explicit that the /v1 layer is partial — “Ollama supports a subset of the OpenAI API” — which is consistent with what follows. The string return on /v1 matches the OpenAI schema; the object return on /api/chat matches Ollama’s. A library that assumes one shape is correct only on the surface it was written for.
This is also the specific place where our own guide to Ollama’s two API surfaces overstates parity. Its sentence “Both approaches produce identical inference results” 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 the history-corruption cases; those are server-side parser and renderer defects, and they are a different failure. If you want the mechanism behind function calling first, the tool-use explainer covers it, and the tool-definition token cost piece covers what the same request spends before generation starts.
The measurement: one host, one model, one prompt
One read_file tool (path: string, max_bytes: integer, both required), one user message — “Read the file src/app.py and report the first 2000 bytes.” — sent to both endpoints of the same local server, temperature 0, native request with think: false. Environment: Ollama 0.20.3, qwen3:0.6b digest 7df6b6e09427 (Q4_K_M), 2 vCPU / 11 GB, localhost only, no credentials and no external network. Measured 2026-11-15; the two specification excerpts above were reopened on 2026-11-25 and are dated separately from the probe.
POST /api/chat | POST /v1/chat/completions | |
|---|---|---|
| HTTP status | 200 | 200 |
| tool-call keys | id, function (index, name, arguments) | id, index, type, function |
function.arguments | object → Python dict | JSON string → Python str |
| argument value | {"path": "src/app.py", "max_bytes": 2000} | "{\"path\":\"src/app.py\",\"max_bytes\":2000}" |
| tool-call id | call_3nn9ernp | call_im2sam5h |
| assistant message keys | role, content, tool_calls | role, content, reasoning, tool_calls |
| stop field | done_reason: "stop" | finish_reason: "tool_calls" |
| token counts | prompt_eval_count 175, eval_count 32 | usage 169 / 134 / 303 |
| wall clock (includes load) | 36.9 s | 74.1 s |
The raw bodies are published: /api/chat request, /api/chat response, /v1 request, /v1 response.
Two details in that table matter more than they look. The native response reports done_reason: "stop" on a turn that contains a tool call, while the compatible response reports finish_reason: "tool_calls". A client that treats stop as “the model finished talking” and never inspects tool_calls will silently discard a perfectly good call on the native surface. And the /v1 message carries a reasoning field with the model’s thinking text, which the native message from this think: false request does not carry.
Wall-clock numbers are load-inclusive observations from one 2 vCPU host, not a benchmark; this article makes no throughput claim.
Two client bugs, one wire difference
The shapes fail differently in client code, which is why the same root cause produces unrelated-looking tracebacks.
Decoding an OpenAI-shaped call with json.loads works; decoding a native call that way raises TypeError: the JSON object must be str, bytes or bytearray, not dict. Consuming a native call with args["path"] works; consuming an OpenAI-shaped call that way raises TypeError: string indices must be integers, not 'str', quoted here from the interpreter rather than paraphrased — the string is indexed by "path", 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.
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 400 immediately — before generation, so 0.0 s wall:
native assistant turn -> POST /v1/chat/completions
400 {"error":{"message":"json: cannot unmarshal object into Go struct field .messages.tool_calls.function.arguments of type string","type":"invalid_request_error","param":null,"code":null}}
openai assistant turn -> POST /api/chat
400 {"error":"Value looks like object, but can't find closing '}' symbol"}
Transcripts: native history replayed into /v1 and OpenAI history replayed into /api/chat. Both files contain the exact request that was sent, so you can replay them against your own server.
Read those messages as version-scoped fingerprints rather than API contracts. The first is a Go encoding/json error naming .messages.tool_calls.function.arguments and the expected type string; the second is Ollama’s own message parser failing to read a string that looks like an object. The durable behaviour to test for is the 400 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.
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’s history, and do not pass the OpenAI-shaped one back to /api/chat. The tool-call id is no help either. Each response generated its own call, and the two ids (call_3nn9ernp natively, call_im2sam5h on /v1) are unrelated strings, so a proxy that rewrites ids across surfaces (the layer LiteLLM-style translation deals with) still has to fix the argument type.
A normaliser that survives both shapes
The adapter below is the minimum that handles what was actually observed: object arguments, string arguments, one nested wrapper (a model occasionally emits {"arguments": "{...}"}), 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.
def normalise_tool_call(message, schema):
calls = message.get("tool_calls") or []
if len(calls) != 1:
raise ToolCallShapeError("expected exactly 1 tool call, found %d" % len(calls))
fn = calls[0].get("function") or {}
args = fn.get("arguments")
if isinstance(args, str):
args = json.loads(args) # OpenAI-compatible surface
elif isinstance(args, dict):
args = dict(args) # native surface
else:
raise ToolCallShapeError("arguments is %s" % type(args).__name__)
if "arguments" in args and len(args) <= 2: # model-invented wrapper
args = json.loads(args["arguments"]) if isinstance(args["arguments"], str) else args["arguments"]
missing = [k for k in schema.get("required", []) if k not in args]
if missing:
raise ToolCallShapeError("missing required argument(s): %s" % ", ".join(missing))
return fn.get("name"), args
The listing above is a condensed variant of the published file, not a verbatim excerpt: the json import, the ToolCallShapeError class and the per-property type checks are omitted for space, and the full file is normalise_tool_call.py, with per-property type validation. Its --selftest 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 normalise_selftest_output.txt. That is a local fixture check of the adapter, not a model measurement: no model was called to produce it.
Streaming: 2 chunks versus 100, and why a correct client looks hung
Streaming was measured on the same prompt. The native surface produced 2 NDJSON chunks in 5.1 s, with the complete call inside the message object of the first chunk: tool_calls_per_chunk was [1, 0], no content and no thinking text.
The OpenAI-compatible surface produced 100 SSE chunks in 42.9 s. Of those, 98 carried delta.reasoning (394 characters in total), none carried delta.content, and exactly one carried the tool call — whole, with the arguments string not fragmented across deltas. The run’s usage block was absent from the stream. Raw chunk dumps: native and /v1.
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 content is empty and whose only payload is reasoning text, so its idle timer, its “first token” 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’s request rather than a claim about the endpoint: the native call here carried think: false, while the /v1/chat/completions request carried no thinking control at all and still came back with 394 reasoning characters in the stream and a reasoning 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’s compatibility page documents reasoning_effort and reasoning.effort as thinking control on that surface, with "none" requesting false 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.
Two cautions before copying the usual SSE advice. First, this run did not 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’s observations, not constants; only the argument type, the status codes and the error bodies were stable enough to treat as findings.
What this is not
- Not an Ollama bug. 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.
- Not a statement about hosted OpenAI. No request was sent to
api.openai.com; the OpenAI schema is cited only because the/v1layer imitates it. - Not generalisable beyond this setup. One version (0.20.3), one model (
qwen3:0.6b, digest7df6b6e09427), one prompt, one host. Another model may serialise differently or emit no call at all. - Not a performance result. Wall-clock times include model load and are reported as observations from a 2 vCPU machine.
Reproduce it against your own server
Everything needed to re-run the probe and diff your server version is published with this page. shape_probe.py is standard-library Python: it posts to /api/chat with think: false, posts the same messages and tools to /v1/chat/completions, streams both, replays each assistant turn into the opposite endpoint, and writes one JSON file per step. METHOD.md records the environment and the determinism caveats, and 00_summary.json is the machine-readable summary behind every table cell above.
Run it as python3 shape_probe.py <out_dir> against a local Ollama with qwen3:0.6b 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 /v1 reasoning tokens. If your run returns string arguments on both 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.
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 done_reason: "stop" as proof that nothing was called.
