ノート / 02

Streaming tool_calls on a non-OpenAI upstream

2026-11-17Modelry のノート

Function calling is the part of the OpenAI contract most likely to break when the model behind the endpoint is not OpenAI's, and the breakage is rarely a clean error. Arguments arrive as fragments, content is null on the turn that emits a call, finish_reason becomes tool_calls instead of stop, and JSON Schema mode may not exist at all. This article walks a complete, runnable tool loop, then the streaming variant that accumulates fragments by index. It covers the three failures that account for nearly every broken integration, plus what changes when the endpoint in front of the model is a gateway that bills tool schemas as input tokens on every turn.

The shape of a tool turn

The model never runs your function. It returns a message whose content is null and whose tool_calls array holds one or more calls, each with an id and a JSON-encoded arguments string, and it sets finish_reason to tool_calls. Your job is to append that assistant message verbatim, execute each call, append one tool message per call carrying the matching tool_call_id, and then call the API again with the extended history. The loop terminates when finish_reason is no longer tool_calls.

#!/usr/bin/env python3
"""tool_loop.py — one complete tool-calling turn against an OpenAI-compatible endpoint."""
import json, os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["MODELRY_API_KEY"],
    base_url=os.environ.get("BASE_URL", "https://api.tokenaimodels.com/v1"),
    timeout=120.0,
    max_retries=1,
)

TOOLS = [{
    "type": "function",
    "function": {
        "name": "get_weather",
        "description": "Current weather for a city.",
        "parameters": {
            "type": "object",
            "properties": {"city": {"type": "string", "description": "City name in English."}},
            "required": ["city"],
        },
    },
}]

def get_weather(city: str) -> dict:
    """Stand-in for your real integration."""
    return {"city": city, "temp_c": 14, "sky": "clear"}

def run(user_text: str, max_turns: int = 4) -> str:
    messages = [{"role": "user", "content": user_text}]
    for _ in range(max_turns):
        resp = client.chat.completions.create(
            model="deepseek-chat",
            messages=messages,
            tools=TOOLS,
            tool_choice="auto",
            max_tokens=800,
        )
        choice = resp.choices[0]
        msg = choice.message

        # Append the assistant turn exactly as received: content may be None.
        messages.append(msg.model_dump(exclude_none=False))

        if choice.finish_reason != "tool_calls":
            return msg.content or ""

        for call in msg.tool_calls or []:
            try:
                args = json.loads(call.function.arguments or "{}")
                payload = json.dumps(get_weather(**args))
            except Exception as exc:                      # model sent bad args
                payload = json.dumps({"error": str(exc)})
            messages.append({
                "role": "tool",
                "tool_call_id": call.id,
                "content": payload,
            })
    raise RuntimeError("tool loop did not converge in %d turns" % max_turns)

if __name__ == "__main__":
    print(run("What is the weather in Osaka right now? One sentence."))

The streaming variant, which is where integrations actually break

With stream=True the calls arrive as deltas, and function.arguments is a *string being typed one character at a time*. You cannot parse a fragment; you accumulate by index and parse once, after the stream ends.

import json
from openai import OpenAI

client = OpenAI(api_key=os.environ["MODELRY_API_KEY"],
                base_url="https://api.tokenaimodels.com/v1")

def collect_tool_calls(user_text: str) -> list[dict]:
    slots: dict[int, dict] = {}
    stream = client.chat.completions.create(
        model="deepseek-chat",
        messages=[{"role": "user", "content": user_text}],
        tools=TOOLS,
        stream=True,
        max_tokens=800,
    )
    for event in stream:
        if not event.choices:                 # usage-only event
            continue
        for tc in event.choices[0].delta.tool_calls or []:
            slot = slots.setdefault(tc.index, {"id": None, "name": None, "args": ""})
            if tc.id:
                slot["id"] = tc.id
            if tc.function and tc.function.name:
                slot["name"] = tc.function.name
            if tc.function and tc.function.arguments:
                slot["args"] += tc.function.arguments
    out = []
    for idx in sorted(slots):
        slot = slots[idx]
        out.append({"index": idx, "id": slot["id"], "name": slot["name"],
                    "arguments": json.loads(slot["args"] or "{}")})
    return out

print(json.dumps(collect_tool_calls("Weather in Osaka and in Kyoto."), indent=2))

Failure 1: json.JSONDecodeError inside the loop

Because arguments stream in pieces, '{"ci' is a perfectly normal intermediate state. Parsing inside the event loop throws on the second delta of every call. The fix is structural, not defensive: keep raw strings in a dict keyed by index, concatenate, and json.loads exactly once after the stream closes — as above. Guard against an empty string too: some upstreams emit a call which genuinely has no arguments, and json.loads("") raises.

Failure 2: 400 invalid_request_error on the second request

The model produced a call, you executed it, and the follow-up is rejected. Three variants, all common. You dropped the assistant message that contained tool_calls (the history must contain the call *and* its result). You replaced content: null with content: "" while the upstream expects the key present with a null value — or the opposite, an upstream that rejects an explicit null. Or you sent a tool message whose tool_call_id does not match any call in the preceding assistant message, which happens as soon as you handle parallel calls with a single result. Send one tool message per call, in any order, each with its own id.

Failure 3: the schema that only works on one upstream

response_format: {"type": "json_object"} is widely supported; {"type": "json_schema", "json_schema": {...}} frequently is not, and platforms differ in whether they reject it or silently ignore it. Silent ignoring is the dangerous case: your strict schema becomes a suggestion and the parse fails one in fifty times, in production, on the request that matters. Validate with pydantic or zod, retry once on validation failure, and put the schema itself in the system prompt so the constraint is at least expressed to the model. Also trim description strings: tool schemas are billed as input tokens on every single turn, and a 4,000-token schema you send 20 times per conversation is 80,000 tokens of pure overhead.

What to watch when you speak to a gateway instead of OpenAI

Tool calling is the most token-expensive surface you have, so three gateway properties matter. Schema caching: keeping the tool definitions byte-identical across turns (same key order, same description text) is what allows the provider's prefix cache to hit on that block; regenerating your schema from a dict whose ordering varies silently destroys it. Failover semantics: where a second channel is configured, a request that fails before producing output can be retried on another channel for the same model, but a request that has begun emitting tool_calls fragments is committed — so a truncated arguments string means a broken turn, not a retryable one. Error normalisation: provider-specific rejections of a tool schema arrive wrapped in the OpenAI error envelope with the provider's message inside, so read error.message, not just error.code, when a call is refused.

A contract test worth keeping

Pin the loop in CI with three assertions, and tool calling stops being a "works on my machine" feature. Assert that the first response has finish_reason == "tool_calls"; assert that json.loads(call.function.arguments) yields a dict with the required keys; assert that the second request returns 200 and a non-empty content. Three assertions, roughly twenty lines, and they catch the entire class of history-shape bugs — a dropped assistant turn, a mismatched tool_call_id, a serialiser that turns None into "". Run it against a fixed model id, not a floating alias, so a provider-side model update shows up as a failing test rather than as a support ticket. When the test fails after an upstream change, diff the raw response body first: the shape of tool_calls is stable across providers, the optional fields are not, and the raw body is the only place the difference is visible.

Get a key at https://tokenaimodels.com and run the loop above against deepseek-chat — if the second turn returns a sentence instead of executing your function, the history shape is the bug, not the model.

Modelry は、1つの HTTP endpoint の背後で DeepSeek モデルを提供するプラットフォームを運営しています。前払いクレジットと税務は購入時に merchant of record が処理し、データ保持方針も文書で公開しています。$0.50 分のトライアルクレジットから始められます: キーを作成する。

すべてのノート

Streaming tool_calls on a non-OpenAI upstream — Modelry