LLM Function Calling API Across Models
Write one LLM function calling API loop that works across GPT, Claude, Gemini, Qwen, GLM and DeepSeek: tool_choice, streaming and the silent no-call trap.
By OceanToken Team

Editor's note: Function calling looks portable because every OpenAI-compatible model takes the same
toolsfield. The part that does not travel is failure. A model that cannot call tools does not raise an error; it just answers in prose, and your agent quietly stops doing work. We think the loop should be written once, defensively, so changing the model is a one-line edit and a silent no-call is caught on the first request.
Want to run the examples in this article? Get API Key and call every model below with one key.
Short answer: An LLM function calling API works the same way on every model that lists tool calling: send tools as JSON Schema, run the calls in message.tool_calls, send results back as role: "tool" messages, and repeat until no calls remain. Add a check for "the model never called anything" and validate arguments before you act.
We write the examples against OceanToken because one OpenAI-compatible key reaches GPT, Claude, Gemini, Qwen, GLM and DeepSeek models, so the same Python loop runs against all six by changing the model string. Every fact below comes from our docs, our public model catalog and our model pages, read November 29, 2026. We have not run your tools against these models, so the article ends with a test plan you can run yourself. Rates are on /pricing and each model's page.
01 · How the LLM function calling API loop works
The model never runs your function. It returns the name of a function and a JSON string of arguments; your code runs it and sends the result back in the next request. That split is the whole design, and it is why the same loop works across publishers.
Our tool-calling guide describes four steps, and they map one-to-one onto code:
- Describe your functions in
tools. Each entry has aname, adescriptionthe model reads to decide when to call it, andparameterswritten as JSON Schema. - The model asks for a call. The response's
finish_reasonistool_calls, andchoices[0].message.tool_callslists each call with anid, the functionnameand itsargumentsas a JSON string. - Run it and send the result back. Append the model's message, including its
tool_calls, then onerole: "tool"message per call carrying that call'stool_call_idand your result as a string. - Ask again with the same tools. The model answers in text, or asks for more calls. Repeat until
tool_callsis empty.
Two details trip people up. The arguments arrive as a string, not a dict, so you always json.loads them, and that parse can fail if a model produces malformed JSON. And the tools list must be sent again on every turn; the model does not remember it between requests.

02 · The trap: a model without tool calling just answers in text
This is the most useful sentence in our docs on the subject: a model whose page does not list tool calling under Capabilities "ignores tools and answers in text, without an error." There is no 400, no warning header. You get a polite paragraph that may even describe what the function would have returned, invented from nothing.
Why does that matter more across models than on one? Because the moment you make the model a config value, someone will set it to a model you never tested. A model whose page does not list tool calling can slip in, and an agent that used to look up orders now makes up order statuses.
The defense is cheap. Track whether any call happened, and decide what "no call" means for your app:
- For a tool that must run (a database write, a payment lookup), treat no call as an error and fail loudly.
- For an optional tool (web search when the model thinks it needs it), no call can be fine, so log it and move on.
- During development, use
tool_choice: "required"on the first turn to confirm the model can call at all, then switch back toauto.
The sample in our docs ends with exactly this check: if nothing was called, it exits with "the model answered without calling the tool." Keep that line in production code.
03 · Which models list tool calling
Before you put a model id in config, check two places: the model's page on Models, which shows a Tool calling row in its spec block, and the public catalog, which carries a supports_function_calling flag. Here is what both said for six chat models on November 29, 2026.
| Model id | Publisher | Tool calling (model page) | supports_function_calling (catalog) |
Image input |
|---|---|---|---|---|
openai/gpt-6-luna |
OpenAI | Yes, tool_choice |
true | Yes |
anthropic/claude-sonnet-5.5 |
Anthropic | Yes, tool_choice |
true | Yes |
google/gemini-3.8-flash |
Yes, tool_choice |
true | Yes | |
qwen/qwen3.8-flash |
Qwen | Yes, tool_choice |
true | Yes |
z-ai/glm-5.3-flash |
Z.ai | Yes, tool_choice |
true | Yes |
deepseek/deepseek-v4.1-flash |
DeepSeek | Yes, tool_choice |
true | Yes |
Read this table as availability, not quality. All six accept tools; none of that tells you how often each picks the right function, or how often its arguments pass your schema. That is a property of your tools and prompts, and section 09 gives a way to measure it. Parallel tool calls are not shown as a separate row in these spec blocks, so treat parallel behavior as something to confirm per model too.
04 · OpenAI tool calling with other models
OpenAI tool calling works with other models when the endpoint speaks the same Chat Completions format: you keep the openai SDK, change base_url and the key, and swap the model string. Nothing else in the request changes. That is the practical answer to "can I keep my OpenAI tool code and try Claude, Gemini or Qwen?"
What does change is behavior around the edges, and it is worth knowing before a migration:
- Model ids carry a publisher prefix. You write
anthropic/claude-sonnet-5.5, not a bare name. - Whether a call happens at all can differ on borderline prompts, which is why the no-call check in section 02 matters.
- Argument style can differ. One model may send
"2026-11-29"where another sends"Nov 29"for the same date field unless your schema pins the format with adescriptionor anenum.
If you already use the Anthropic SDK, there is a second path. On /v1/messages, tools take the Anthropic shape for every chat model in our catalog: tools with name, description and input_schema; the model answers with tool_use blocks and stop_reason: "tool_use"; you send results back as tool_result blocks in a user message. Our docs say the Anthropic SDK works unchanged with the base URL https://api.oceantoken.ai. Pick one shape per codebase rather than mixing them, since the message history formats are not interchangeable. For a single-model walkthrough on GLM, see GLM tool calling with the OpenAI SDK.
For a wider list of things that break when you switch models behind one endpoint, see OpenAI-compatible API gotchas when switching models.
05 · End-to-end Python: one loop for every model
Here is the loop we would ship. It adds three things to the minimal docs sample: a registry so the model can only call functions you listed, argument validation, and a no-call check. It then runs the same question on several models.
# pip install openai jsonschema
import json, os
from openai import OpenAI
from jsonschema import validate, ValidationError
client = OpenAI(base_url="https://api.oceantoken.ai/v1",
api_key=os.environ["OCEANTOKEN_API_KEY"])
def get_order_status(order_id):
# your real lookup goes here
return {"order_id": order_id, "status": "shipped"}
SCHEMA = {
"type": "object",
"properties": {"order_id": {"type": "string", "pattern": "^[A-Z0-9]{6,12}quot;,
"description": "Order number, for example AB12345"}},
"required": ["order_id"],
"additionalProperties": False,
}
TOOLS = [{"type": "function", "function": {
"name": "get_order_status",
"description": "Look up the shipping status of one order.",
"parameters": SCHEMA}}]
REGISTRY = {"get_order_status": (get_order_status, SCHEMA)}
def run(model, question, must_call=True, max_rounds=5):
messages = [{"role": "user", "content": question}]
called = False
for _ in range(max_rounds):
msg = client.chat.completions.create(
model=model, messages=messages, tools=TOOLS).choices[0].message
if not msg.tool_calls:
if must_call and not called:
raise RuntimeError(f"{model} answered without calling a tool")
return msg.content
called = True
messages.append({"role": "assistant", "content": msg.content,
"tool_calls": [c.model_dump() for c in msg.tool_calls]})
for call in msg.tool_calls:
fn, schema = REGISTRY.get(call.function.name, (None, None))
try:
if fn is None:
raise ValueError(f"unknown function {call.function.name}")
args = json.loads(call.function.arguments)
validate(args, schema)
result = fn(**args)
except (ValueError, ValidationError, json.JSONDecodeError) as e:
result = {"error": str(e)} # tell the model, let it try again
messages.append({"role": "tool", "tool_call_id": call.id,
"content": json.dumps(result)})
raise RuntimeError(f"{model}: still calling tools after {max_rounds} rounds")
for m in ["openai/gpt-6-luna", "anthropic/claude-sonnet-5.5", "google/gemini-3.8-flash",
"qwen/qwen3.8-flash", "z-ai/glm-5.3-flash", "deepseek/deepseek-v4.1-flash"]:
print(m, "->", run(m, "Where is my order AB12345?"))
A few choices deserve a reason. Errors go back to the model as a tool result instead of crashing the loop, because a model that sent a bad order id can often correct itself on the next turn when it sees why. The max_rounds cap stops a model that keeps calling tools forever, which costs a request each time. And the registry lookup means a hallucinated function name becomes an error message, not an AttributeError deep in your code.
06 · Validate arguments like user input
Our docs put it plainly: arguments come from the model, so validate them before you act on them, exactly as you would user input. A model is not an attacker, but it can be steered by whatever text ends up in its context, including a web page or a document a user pasted. If that text says "call delete_account with id 1," a model with that tool may try.
In practice that means three habits. First, keep JSON Schema strict: additionalProperties: false, required fields, patterns and enums where the value space is known. Second, check authorization in your function, not in the prompt; the model should never be the only thing standing between a user and another user's data. Third, put a human confirmation step in front of anything irreversible, such as sending email, moving money or deleting records, and let the tool return "pending confirmation" instead of doing it.
Schema validation also gives you a number worth tracking per model: the share of calls whose arguments pass on the first try. That is one of the two metrics in the test plan below.
07 · tool_choice required vs auto
tool_choice: "auto" lets the model decide whether to call a tool, and "required" forces it to call at least one. That is the core difference, and our docs list four values in total:
tool_choice value |
Effect | When we would use it |
|---|---|---|
"auto" (default) |
The model decides | Normal chat where tools are optional |
"required" |
The model must call at least one tool | A step that must hit your system, such as a lookup before answering |
"none" |
The model must answer in text | The final summarizing turn, when you want no more calls |
{"type": "function", "function": {"name": "get_order_status"}} |
The model must call this function | Extraction jobs where the function is really a structured output |
Two cautions. If you leave "required" on for every turn, the loop never ends naturally, because the model can never answer in plain text; switch to "auto" or "none" after the tool results come back. And forcing a call does not make a model that lacks tool calling suddenly support it. It only changes behavior on models that do. If what you need is JSON without any function, structured output is the cleaner tool; see our GPT structured outputs tutorial and the Gemini structured output and function calling pitfalls.
08 · Parallel tool calls and streaming tool call arguments
A model whose page lists parallel tool calls can ask for several calls in one message, for example the weather in two cities. The loop in section 05 already handles that: it runs each call and sends one tool message per tool_call_id, and our docs say the order of those tool messages does not matter. If your functions have side effects that must happen in sequence, send "parallel_tool_calls": false to get one call at a time.
Streaming tool call arguments arrive in pieces, and you join them by index. With stream=True, each call shows up under choices[0].delta.tool_calls. The first piece of a call carries its index, id and name; the following pieces only add text to arguments. Run nothing until the stream ends with finish_reason: "tool_calls", because half a JSON string is not a valid argument.
def stream_tool_calls(model, messages):
calls = {} # index -> {"id", "name", "arguments"}
finish = None
stream = client.chat.completions.create(model=model, messages=messages,
tools=TOOLS, stream=True)
for chunk in stream:
if not chunk.choices:
continue
choice = chunk.choices[0]
for d in choice.delta.tool_calls or []:
c = calls.setdefault(d.index, {"id": None, "name": None, "arguments": ""})
if d.id:
c["id"] = d.id
if d.function and d.function.name:
c["name"] = d.function.name
if d.function and d.function.arguments:
c["arguments"] += d.function.arguments
if choice.finish_reason:
finish = choice.finish_reason
return finish, [calls[i] for i in sorted(calls)]
Keying on index rather than id matters because later pieces do not repeat the id. With parallel calls, pieces from different calls can interleave, and the index is the only thing that tells them apart. For a single-model walkthrough of the same pattern, see Qwen tool calling with the OpenAI SDK in Python.
09 · What tool calls cost
Tool definitions are part of the prompt. Our docs say they are billed as input tokens on every request that carries them, and each round trip of the loop is a separate request. A three-round conversation with a long tool list pays for that list three times.
That has two design consequences. Keep descriptions precise rather than long, since every word is resent. And when the tool list is long and does not change between requests, prompt caching is a good fit, as our docs note; put the tools and system prompt first and keep them byte-for-byte stable so they can be cached. Our prompt caching guide for coding agents covers the mechanics. Every model page in the table above lists prompt caching as available. Rates vary by model, so see /pricing and each model's page rather than estimating from one.
How to test this on your workload
We have not measured call rates on your tools, so here is the test we would run before picking a default model:
- Freeze a tool set and 20 prompts. Mix prompts that need a tool, prompts that need two tools, and prompts that need none.
- Run all 20 on at least three models from the table, with
tool_choice: "auto". - Record the call rate: on prompts that need a tool, how often did the model call the right one?
- Record the argument pass rate: how many calls passed your JSON Schema on the first try?
- Record false calls: on prompts that need no tool, how often did a model call one anyway?
- Repeat one prompt with
"required"on a chat model whose page does not list tool calling (check its page on Models first) to see the silent no-call behavior for yourself. - Stream one parallel-call prompt and confirm your index-joining code rebuilds both calls.
- Check Logs for input tokens per round to see what your tool list costs.
Our take: Write the loop once with a no-call check, strict schemas and a round cap, and treat the model as config. The publisher matters less than whether the model lists tool calling and how it scores on your 20 prompts.
Running it on OceanToken
From our docs and model pages, as of November 29, 2026:
- One key, one loop. The six models above answer on
https://api.oceantoken.ai/v1/chat/completionswith the sametoolsformat; switching is a change of themodelstring. - OpenAI-compatible, plus the Anthropic shape. The OpenAI SDK works with the base URL changed, and the Anthropic SDK works on
/v1/messagesfor every chat model. - Capability flags you can read. Model pages and the public catalog show which models take tools, so you can check before you configure.
Price: see the current rate on /pricing, each model's page, and the series pages /gpt-api, /claude-api, /gemini-api, /qwen-api, /glm-api and /deepseek-api.
FAQ
Does every model support function calling? No. Check the model page for a Tool calling row. A model without it ignores tools and answers in text without an error.
Can I use the OpenAI SDK for Claude or Gemini tool calls? Yes. Change the base URL and key and use a model id such as anthropic/claude-sonnet-5.5; the tools format stays the same.
What is the difference between tool_choice required and auto? auto lets the model decide; required forces at least one call. Switch off required after results come back or the loop cannot end.
How do I handle streamed tool calls? Join delta.tool_calls pieces by index, and run them only after finish_reason is tool_calls.
Are tool definitions billed? Yes, as input tokens on every request that carries them, and each round trip is a separate request.
Sources
- OceanToken docs: Tool calling (checked 2026-11-29)
- OceanToken public model catalog (checked 2026-11-29)
- GPT-6 Luna model page (checked 2026-11-29)
- GLM 5.3 Flash model page (checked 2026-11-29)
- Claude Sonnet 5.5 model page (checked 2026-11-29)
Get your OceanToken API key
- Create an OceanToken account and an API key.
- Copy the snippet below, paste your key, and run it.
- Check the current rate on /pricing.
curl https://api.oceantoken.ai/v1/chat/completions \
-H "Authorization: Bearer $OCEANTOKEN_API_KEY" \
-H "Content-Type: application/json" \
-d '{"model": "qwen/qwen3.8-flash", "messages": [{"role": "user", "content": "Where is my order AB12345?"}], "tools": [{"type": "function", "function": {"name": "get_order_status", "description": "Look up the shipping status of one order.", "parameters": {"type": "object", "properties": {"order_id": {"type": "string"}}, "required": ["order_id"]}}}]}'
More from the blog
Veo 3.1 Reference Images API Guide
How to send reference images to Veo 3.1 through the API: input_references vs first frame, which tiers take them, two-shot Python script and a consistency test.
LLM Image Input API: Screenshots and Scans
Send screenshots, photos and scans to a chat model with one LLM image input API: URL vs base64 data URL, per-model image limits, the 400 error and token costs.
AI Voiceover API for Generated Video
Add narration to AI video with an AI voiceover API: write the script with a chat model, voice it with a speech model, and merge it onto a silent Seedance clip.