Login
Back to Blog
EnglishTutorial

Function Calling Across AI Providers in 2026: A Safe, Portable Implementation

Build portable function calling across GPT, Claude, Gemini, Qwen, and GLM with normalized schemas, validation, approval gates, retries, and Python and Node.js examples.

C
Crazyrouter Team
July 22, 2026 / 296 views
Share:
Function Calling Across AI Providers in 2026: A Safe, Portable Implementation

Function Calling Across AI Providers in 2026: A Safe, Portable Implementation#

Function calling lets a model request an application-defined operation such as searching a database, checking inventory, or creating a draft. The model does not execute the function by itself; it emits a structured request that your server validates and decides whether to run. This distinction is the foundation of a safe agent architecture.

What Is This Topic?#

Function calling lets a model request an application-defined operation such as searching a database, checking inventory, or creating a draft. The model does not execute the function by itself; it emits a structured request that your server validates and decides whether to run. This distinction is the foundation of a safe agent architecture. In practical engineering terms, the important unit is not the model name but the capability contract: accepted inputs, maximum context, output format, latency, rate limits, and data handling. Before integrating, check the provider’s current model catalog and run a small evaluation set using the exact prompts your product will send.

Function Calling Across AI Providers in 2026 vs Alternatives#

Provider-native tool formats differ in field names, parallel call behavior, streaming events, and strictness. Writing directly to each API can lock your business logic to one provider. A normalized internal schema is safer: represent every tool as name, description, JSON Schema parameters, risk level, timeout, and whether human approval is required. Then write thin adapters at the boundary.

A useful comparison matrix is:

Decision factorDirect providerMulti-model gatewaySelf-hosted/open model
Setup speedFast for one providerFast for many modelsSlowest
Model choiceLimited to providerBroadDepends on deployment
BillingSeparate accountsConsolidated usageInfrastructure cost
PortabilityLowerHigherDepends on API layer
OperationsProvider-managedShared boundaryTeam-managed

Do not compare only headline benchmark scores. Measure successful task rate, p95 latency, output validity, refusal behavior, and cost per successful task. A model that is 20% cheaper but requires frequent repair calls may be more expensive in production.

How to Use It with an API#

Never execute arbitrary tool arguments without validation. The following pattern keeps tool execution on your server and requires a known tool name:

Python#

python
from openai import OpenAI
import json

client = OpenAI(api_key="CRAZYROUTER_API_KEY", base_url="https://crazyrouter.com/v1")
tools = [{"type":"function","function": {"name":"lookup_order", "description":"Read order status", "parameters": {"type":"object", "properties":{"order_id":{"type":"string"}}, "required":["order_id"], "additionalProperties":False}}}]
r = client.chat.completions.create(model="gpt-5.2", messages=[{"role":"user","content":"Where is order A-102?"}], tools=tools)
call = r.choices[0].message.tool_calls[0]
args = json.loads(call.function.arguments)
if call.function.name != "lookup_order" or not args["order_id"].startswith("A-"):
    raise ValueError("Rejected tool call")
print("Run validated lookup", args)

Node.js#

javascript
const tools = [{ type: "function", function: { name: "lookup_order", description: "Read order status", parameters: { type: "object", properties: { order_id: { type: "string" } }, required: ["order_id"], additionalProperties: false } } }];
const r = await fetch("https://crazyrouter.com/v1/chat/completions", { method: "POST", headers: { Authorization: `Bearer ${process.env.CRAZYROUTER_API_KEY}`, "Content-Type": "application/json" }, body: JSON.stringify({ model: "gpt-5.2", messages: [{ role: "user", content: "Where is order A-102?" }], tools }) });
const data = await r.json();
const call = data.choices?.[0]?.message?.tool_calls?.[0];
if (call?.function?.name !== "lookup_order") throw new Error("Unknown tool");
console.log(JSON.parse(call.function.arguments));

cURL#

bash
curl https://crazyrouter.com/v1/chat/completions \
  -H "Authorization: Bearer $CRAZYROUTER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"model":"function-calling-across-providers-2026-schema-safety","messages":[{"role":"user","content":"Give a concise developer example."}]}'

For production, add timeouts, request IDs, structured logs, schema validation, and a clear policy for transient errors. Never put an API key in browser code. Keep provider-specific model IDs in configuration, not scattered through business logic. If media inputs are involved, validate MIME type, size, duration, and user authorization before forwarding them.

Pricing Breakdown#

Tool calling costs are mostly model-token costs plus your own tool execution. The same schema repeated in every request increases input tokens, so keep descriptions concise and cache stable instructions where supported. A gateway can help compare tool-call success and cost across models. Crazyrouter is useful when you want to route read-only tools to an economical model while reserving a stronger model for ambiguous or high-risk actions.

Cost componentWhat to measurePractical control
Input tokensPrompt and context sizeTrim, summarize, cache
Output tokensCompletion lengthSet limits and concise formats
MediaImages, audio, or video volumeResize, sample, batch
RetriesTransient and repair callsBackoff and retry budgets
OperationsLogs, queues, storage, GPUsRetention and autoscaling policy

For current rates, compare the official provider price with the live Crazyrouter pricing page. A gateway is most valuable when it reduces integration and switching costs, not when a static comparison table hides changing vendor rates. Start with a small test budget and record actual usage before committing to a monthly forecast.

Production Checklist#

  • Pin a tested model ID or configuration alias.
  • Validate outputs before storing or executing them.
  • Add rate limits per user, team, and route.
  • Redact secrets and personal data from logs.
  • Track cost per successful task, not just request count.
  • Keep a tested fallback for provider or model failures.
  • Evaluate updates before changing the default route.
  • Add human approval for destructive or external actions.

Frequently Asked Questions#

Can a model execute a function directly?#

No. It can request a function call; your trusted application must validate and execute it.

How do I make tool calls portable?#

Use an internal tool registry and adapters that translate it to each provider’s request and response format.

Should write operations require approval?#

Yes, especially payments, deletions, external messages, and permission changes.

How do I test tool calling?#

Test invalid arguments, unknown tool names, duplicate calls, timeouts, partial failures, and prompt-injection attempts.

Summary#

The fastest path from an AI model experiment to a dependable feature is a narrow contract, representative evaluation data, bounded cost, and observable failure handling. Start with one use case, compare at least two alternatives, and keep the provider boundary replaceable. If you want one API surface for evaluating multiple models, compare live rates and start building with Crazyrouter.

Implementation Guides

Topics

Tutorial

Related Posts

OpenAI Realtime API Complete Guide: Build Voice AI Apps in 2026Tutorial

OpenAI Realtime API Complete Guide: Build Voice AI Apps in 2026

"Learn how to use OpenAI's Realtime API for building voice AI applications with WebSocket streaming, audio input/output, and function calling. Complete tutorial with code examples."

Mar 2
Crazyrouter Codex CLI: Use Codex with One API Key and an OpenAI-Compatible GatewayTutorial

Crazyrouter Codex CLI: Use Codex with One API Key and an OpenAI-Compatible Gateway

Set up OpenAI Codex CLI through Crazyrouter with one command on Windows, macOS, and Linux. Use an OpenAI-compatible base URL, one API key, and model routing for GPT, Claude, Gemini, DeepSeek, and Qwen-style workflows.

Jun 4
MCP (Model Context Protocol) Complete Guide: The New Standard for AI Tool IntegrationTutorial

MCP (Model Context Protocol) Complete Guide: The New Standard for AI Tool Integration

Everything developers need to know about MCP (Model Context Protocol). Covers what it is, how it works, how to build MCP servers, and why it matters for AI application development.

Feb 23
AI Palm Reading with GPT-image-2 — Generate Professional Palmistry Analysis from a Single PhotoTutorial

AI Palm Reading with GPT-image-2 — Generate Professional Palmistry Analysis from a Single Photo

Use GPT-image-2 via Crazyrouter API to generate stunning palm reading infographics. Complete code in Python, curl, and Node.js.

May 1
Codex CLI Installation Guide 2026: macOS, Linux, Windows, and Proxy EnvironmentsTutorial

Codex CLI Installation Guide 2026: macOS, Linux, Windows, and Proxy Environments

A developer-first Codex CLI installation guide with setup steps for macOS, Linux, Windows, and teams working behind proxies or enterprise firewalls.

Mar 19
One API Key for GPT, Claude and Gemini: A Practical Setup for Central Asia DevelopersTutorial

One API Key for GPT, Claude and Gemini: A Practical Setup for Central Asia Developers

A practical tutorial for developers in Central Asia who want to call GPT, Claude and Gemini from one OpenAI-compatible API gateway.

May 22