ai newsMi., 25. Nov.
EilmeldungYale’s Sonnenfeld: Nvidia is a ‘detriment’ to U.S. industrial might — not a champion

Streaming tool_calls: Warum Function Calling bei nicht-OpenAI-Modellen oft scheitert

Function Calling ist der Teil des OpenAI-Vertrags, der am häufigsten bricht, wenn hinter dem Endpunkt kein OpenAI-Modell steckt. Statt sauberer Fehlermeldungen kommen fragmentierte Argumente, null-Inhalte und ein abweichendes finish_reason.

dev.toDienstag 06:32 · 24.11.DE7 Min. Lesezeit
Bild: dev.to

Veröffentlicht am 24. Nov • Ursprünglich veröffentlicht auf tokenaimodels.com

Function calling ist der Teil des OpenAI-Kontrakts, der am ehesten bricht, wenn das Modell hinter dem Endpoint nicht von OpenAI stammt, und der Bruch äußert sich selten als sauberer Fehler. Argumente kommen in Fragmenten an, content ist null in dem Zug, der einen Call ausgibt, finish_reason wird zu tool_calls statt stop, und JSON-Schema-Modus existiert möglicherweise gar nicht. Dieser Artikel durchläuft eine vollständige, ausführbare Tool-Schleife und danach die Streaming-Variante, die Fragmente nach Index akkumuliert. Er behandelt die drei Fehler, die für nahezu jede kaputte Integration verantwortlich sind, sowie das, was sich ändert, wenn der Endpoint vor dem Modell ein Gateway ist, das Tool-Schemas bei jedem Zug als Input-Tokens abrechnet.

Das Modell führt Ihre Funktion niemals selbst aus. Es gibt eine Nachricht zurück, deren content null ist und deren tool_calls-Array einen oder mehrere Calls enthält, jeder mit einer id und einem JSON-kodierten Argument-String, und es setzt finish_reason auf tool_calls. Ihre Aufgabe ist es, diese Assistant-Nachricht wortgetreu anzuhängen, jeden Call auszuführen, pro Call eine Tool-Nachricht mit der passenden tool_call_id anzuhängen und dann die API erneut mit der erweiterten Historie aufzurufen. Die Schleife endet, wenn finish_reason nicht mehr tool_calls ist.

#!/usr/bin/env python3 """tool_loop.py — ein vollständiger Tool-Calling-Zug gegen einen OpenAI-kompatiblen 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: """Platzhalter für Ihre echte 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 # Den Assistant-Zug exakt wie empfangen anhängen: content darf None sein. 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: # Modell hat ungültige Argumente gesendet 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." ) ) Vollbildmodus öffnen Vollbildmodus verlassen Die Streaming-Variante, in der Integrationen tatsächlich brechen Mit stream=True kommen die Calls als Deltas an, und function.arguments ist ein String, der Zeichen für Zeichen getippt wird. Ein Fragment können Sie nicht parsen; Sie akkumulieren nach Index und parsen genau einmal, nachdem der Stream beendet ist.

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: # nur Nutzungs-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 ) ) Vollbildmodus öffnen Vollbildmodus verlassen Fehler 1: json.JSONDecodeError innerhalb der Schleife Weil Argumente stückweise streamen, ist '{"ci' ein völlig normaler Zwischenzustand. Ein Parsen innerhalb der Event-Schleife wirft beim zweiten Delta jedes Calls eine Exception. Die Lösung ist strukturell, nicht defensiv: Rohstrings in einem nach Index verschlüsselten Dict behalten, konkatenieren und json.loads genau einmal nach Stream-Ende ausführen, wie oben.

Sichern Sie auch einen leeren String ab: Manche Upstreams senden einen Call, der tatsächlich keine Argumente hat, und json.loads("") wirft eine Exception.

Das Modell hat einen Call erzeugt, Sie haben ihn ausgeführt, und die Nachfolge-Anfrage wird abgelehnt. Drei Varianten, alle häufig. Sie haben die Assistant-Nachricht verworfen, die tool_calls enthielt (die Historie muss den Call und sein Ergebnis enthalten). Sie haben content: null durch content: "" ersetzt, während der Upstream den Schlüssel mit einem null-Wert erwartet, oder umgekehrt, ein Upstream, der ein explizites null ablehnt. Oder Sie haben eine Tool-Nachricht gesendet, deren tool_call_id zu keinem Call in der vorhergehenden Assistant-Nachricht passt, was schon passiert, sobald Sie parallele Calls mit einem einzigen Ergebnis behandeln. Senden Sie eine Tool-Nachricht pro Call, in beliebiger Reihenfolge, jede mit ihrer eigenen id.

response_format: {"type": "json_object"} wird breit unterstützt; {"type": "json_schema", "json_schema": {...}} häufig nicht, und Plattformen unterscheiden sich darin, ob sie es ablehnen oder stillschweigend ignorieren. Stilles Ignorieren ist der gefährliche Fall: Ihr strenges Schema wird zu einem Vorschlag, und das Parsen schlägt einmal unter fünfzig Mal fehl, in Produktion, bei der Anfrage, auf die es ankommt. Validieren Sie mit pydantic oder zod, wiederholen Sie einmal bei Validierungsfehler, und legen Sie das Schema selbst in den System-Prompt, damit die Einschränkung dem Modell wenigstens ausgedrückt wird.

Kürzen Sie außerdem die Description-Strings: Tool-Schemas werden bei jedem einzelnen Zug als Input-Tokens abgerechnet, und ein Schema mit 4.000 Tokens, das Sie zwanzig Mal pro Konversation senden, sind 80.000 Tokens reiner Overhead.

Tool calling ist die token-teuerste Oberfläche, die Sie haben, deshalb zählen drei Gateway-Eigenschaften. Schema-Caching: Die Tool-Definitionen über Züge hinweg byte-identisch zu halten (gleiche Schlüsselreihenfolge, gleicher Description-Text) ist es, was dem Prefix-Cache des Providers erlaubt, diesen Block zu treffen; ein erneutes Generieren Ihres Schemas aus einem Dict mit unbemerkt schwankender Reihenfolge zerstört ihn. Failover-Semantik: Wenn ein zweiter Kanal konfiguriert ist, kann eine Anfrage, die vor der Ausgabe scheitert, für dasselbe Modell auf einem anderen Kanal wiederholt werden, aber eine Anfrage, die bereits tool_calls-Fragmente ausgibt, ist festgelegt; ein abgeschnittener Argument-String bedeutet also einen kaputten Zug, keinen wiederholbaren.

Fehler-Normalisierung: Providerspezifische Ablehnungen eines Tool-Schemas kommen im OpenAI-Fehler-Umschlag an, mit der Meldung des Providers darin; lesen Sie also error.message, nicht nur error.code, wenn ein Call abgelehnt wird.

Verankern Sie die Schleife in CI mit drei Assertions, und Tool calling hört auf, ein "works on my machine"-Feature zu sein. Stellen Sie fest, dass die erste Antwort finish_reason == "tool_calls" hat; stellen Sie fest, dass json.loads(call.function.arguments) ein Dict mit den erforderlichen Schlüsseln liefert; stellen Sie fest, dass die zweite Anfrage 200 und einen nicht leeren content zurückgibt. Drei Assertions, rund zwanzig Zeilen, und sie fangen die gesamte Klasse von Historie-Form-Bugs ab: einen verworfenen Assistant-Zug, eine nicht passende tool_call_id, einen Serialisierer, der None in "" verwandelt.

Führen Sie es gegen eine feste Modell-ID aus, nicht gegen einen beweglichen Alias, damit ein providerseitiges Modell-Update als fehlschlagender Test auftaucht und nicht als Support-Ticket. Wenn der Test nach einer Upstream-Änderung fehlschlägt, diffen Sie zuerst den rohen Antwort-Body: Die Form von tool_calls ist über Provider hinweg stabil, die optionalen Felder nicht, und der rohe Body ist der einzige Ort, an dem der Unterschied sichtbar wird.

Holen Sie sich einen Schlüssel unter https://tokenaimodels.com und führen Sie die Schleife oben gegen deepseek-chat aus. Wenn der zweite Zug einen Satz zurückgibt, statt Ihre Funktion auszuführen, ist die Historie-Form der Bug, nicht das Modell.

Modelry ist ein unabhängiger Plattform-Betreiber, der einen vorausbezahlten, vermessen Endpoint für die DeepSeek-Modelle betreibt: keine Karte zur Registrierung und ein Ausgabenlimit auf jedem Schlüssel: https://tokenaimodels.com/signup?utm_source=devto&utm_medium=post&utm_campaign=tool_calls_on

Automatisch übersetzt. Das Original auf Englisch ist unten aufklappbar.

Original (Englisch) anzeigen

Posted on Nov 24 • Originally published at tokenaimodels.com

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 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." ) ) Enter fullscreen mode Exit fullscreen mode 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 ) ) Enter fullscreen mode Exit fullscreen mode 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.

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.

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.

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.

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 is an independent platform operator running a prepaid, metered endpoint for the DeepSeek models — no card to sign up, and a spend cap on every key: https://tokenaimodels.com/signup?utm_source=devto&utm_medium=post&utm_campaign=tool_calls_on

Originaltitel: Streaming tool_calls on a non-OpenAI upstreamQuelle: dev.to (dev.to). Original öffnen