scriptRun Beta

LLM Function Calling API: Running Tools Across OpenAI, Claude, and Gemini

James
November 23, 2026
Business
AI WorkflowsAutomation
LLM Function Calling API: Multi-Model Tool Calling Guide

Hooking one language model up to a database or internal REST service is straightforward. The headache starts when you add a second provider for failover or lower token spend, because every vendor formats tool schemas differently. OpenAI returns stringified JSON inside tool_calls, Anthropic sends tool_use blocks with input_schema, and Gemini works with functionCall and functionResponse objects.

Maintaining three separate parsers for the same business logic rarely makes sense. This guide shows how to run a unified function calling API across OpenAI, Claude, and Gemini through one OpenAI SDK client, validate arguments with JSON Schema, estimate hidden input-token overhead, and move long MCP chains into background workflows past the 60-second timeout.

How function calling works and where providers diverge

No matter which vendor you pick, function calling follows the same four-step loop between your backend and the model:

  1. Your server sends the conversation history (messages) along with a tools array listing function names, descriptions, and JSON Schema parameter rules.

  2. Instead of replying in plain text, the model emits one or more structured call requests containing a call ID, function name, and arguments.

  3. Your backend parses the arguments, validates them, and runs the local handler or external HTTP request. The model never executes code or touches your network directly.

  4. Your app appends the output back into the thread as a role: "tool" message matched to the original tool_call_id, then calls the model again. From there, the model either writes the final reply or requests another tool.

Once a codebase supports two or three vendors, native payloads diverge quickly, and even official OpenAI compatibility layers drop or alter specific options.

Provider

Native tool format

OpenAI compatibility quirks

OpenAI

tools with parameters; returns tool_calls carrying a JSON-encoded arguments string; strict: true enables constrained decoding.

Newer models like GPT-6 Astra use OpenAI's Responses API natively for tool calls. Models from GPT-5.4 onward restrict Chat Completions tool calls when reasoning_effort is set above "none".

Anthropic Claude

tools with input_schema; returns tool_use blocks with parsed JSON input objects; replies use tool_result blocks.

Anthropic's OpenAI SDK layer ignores strict: true on tool definitions, skips prompt caching, and moves all system messages to the top of the prompt.

Google Gemini

functionDeclarations using an OpenAPI schema subset; returns functionCall and expects functionResponse parts.

Google still keeps its OpenAI-compatible endpoint (/v1beta/openai/) in beta and puts Gemini-specific options like thinking config inside extra_body.

Running three native SDKs forces you to duplicate retry logic, error handling, and conversation state. Sending requests through an OpenAI-compatible unified API keeps one client, one key, and one request shape while letting you switch models in a single line. Protocol translation does not hide every model quirk underneath, so local validation on your backend still matters.

Running one function calling loop with the OpenAI SDK

ScriptRun exposes its OpenAI-compatible chat gateway at POST https://scriptrun.ai/v1/chat/completions. Point the standard OpenAI SDK at base_url="https://scriptrun.ai/v1" and pass your ScriptRun API key as a Bearer token (Authorization: Bearer <API_KEY>).

Pay attention to the path prefix and auth header. Platform management endpoints live under /api/v1/ and expect X-Api-Key. The chat gateway sits at the root /v1 with Bearer auth so official OpenAI clients can append /chat/completions automatically without custom adapters. For base proxy setup and streaming, see the OpenAI-compatible Chat Completions API guide.

Swapping between OpenAI, Claude, and Gemini comes down to changing the model string. Check your ScriptRun dashboard for exact active IDs, such as "gpt-4o", "claude-sonnet-4-6", or "gemini-3.8-flash".

Multi-turn tool loop in Python

When pushing the model's tool-call message (role: "assistant") back into messages, build a clean dictionary instead of forwarding the raw SDK object. Several third-party gateways return a 400 error when they encounter null fields like refusal or audio.

import json
import os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["SCRIPTRUN_API_KEY"],
    base_url="https://scriptrun.ai/v1",
)

TOOLS = [
    {
        "type": "function",
        "function": {
            "name": "get_order_status",
            "description": "Look up shipping status and item count by order ID.",
            "strict": True,
            "parameters": {
                "type": "object",
                "properties": {
                    "order_id": {"type": "string", "description": "Order code like ORD-4021"}
                },
                "required": ["order_id"],
                "additionalProperties": False,
            },
        },
    },
    {
        "type": "function",
        "function": {
            "name": "get_customer_tier",
            "description": "Return support tier and SLA hours for a customer email.",
            "strict": True,
            "parameters": {
                "type": "object",
                "properties": {
                    "email": {"type": "string"}
                },
                "required": ["email"],
                "additionalProperties": False,
            },
        },
    },
]


def execute_tool(name: str, args: dict) -> dict:
    if name == "get_order_status":
        return {"order_id": args["order_id"], "status": "in_transit", "items": 2}
    if name == "get_customer_tier":
        return {"email": args["email"], "tier": "enterprise", "sla_hours": 4}
    return {"error": f"Unknown tool: {name}"}


def run_tool_loop(user_prompt: str, model: str = "gpt-4o", max_steps: int = 5) -> str:
    messages = [
        {"role": "system", "content": "Use available tools to answer customer order questions accurately."},
        {"role": "user", "content": user_prompt},
    ]

    for _ in range(max_steps):
        response = client.chat.completions.create(
            model=model,
            messages=messages,
            tools=TOOLS,
            tool_choice="auto",
        )
        msg = response.choices[0].message

        if not msg.tool_calls:
            return msg.content or ""

        # Keep assistant payload minimal for cross-provider compatibility
        messages.append({
            "role": "assistant",
            "content": msg.content or "",
            "tool_calls": [
                {
                    "id": call.id,
                    "type": "function",
                    "function": {
                        "name": call.function.name,
                        "arguments": call.function.arguments,
                    },
                }
                for call in msg.tool_calls
            ],
        })

        for call in msg.tool_calls:
            parsed_args = json.loads(call.function.arguments)
            output = execute_tool(call.function.name, parsed_args)
            messages.append({
                "role": "tool",
                "tool_call_id": call.id,
                "content": json.dumps(output),
            })

    raise RuntimeError(f"Stopped after {max_steps} turns without a final answer.")

You can run run_tool_loop("Check order ORD-4021 for ada@acme.io", model="claude-sonnet-4-6") or pass "gemini-3.8-flash" without changing a single line of dispatch code.

Parallel tool calls in TypeScript

Models often request two or three independent lookups in one turn, and running them sequentially adds avoidable latency. In Node.js or TypeScript, resolve the tool_calls array concurrently with Promise.all and append one role: "tool" message per matching tool_call_id.

import OpenAI from "openai";

const client = new OpenAI({
  apiKey: process.env.SCRIPTRUN_API_KEY,
  baseURL: "https://scriptrun.ai/v1",
});

async function runParallelTurn(
  messages: OpenAI.Chat.ChatCompletionMessageParam[],
  tools: OpenAI.Chat.ChatCompletionTool[],
  model = "gemini-3.8-flash"
) {
  const response = await client.chat.completions.create({
    model,
    messages,
    tools,
    tool_choice: "required",
  });

  const msg = response.choices[0].message;
  if (!msg.tool_calls?.length) {
    return msg.content ?? "";
  }

  messages.push({
    role: "assistant",
    content: msg.content ?? "",
    tool_calls: msg.tool_calls,
  });

  const toolResults = await Promise.all(
    msg.tool_calls.map(async (call) => {
      if (call.type !== "function") {
        return { role: "tool" as const, tool_call_id: call.id, content: '{"error":"unsupported"}' };
      }
      const args = JSON.parse(call.function.arguments);
      // dispatchLocalTool - your local function handler
      const data = await dispatchLocalTool(call.function.name, args);
      return {
        role: "tool" as const,
        tool_call_id: call.id,
        content: JSON.stringify(data),
      };
    })
  );

  messages.push(...toolResults);
  const followUp = await client.chat.completions.create({ model, messages, tools });
  return followUp.choices[0].message.content ?? "";
}

Controlling tool selection with tool_choice

The tool_choice field controls whether the model picks an action on its own or follows a fixed path on the current turn:

  • "auto" (default): lets the model decide between calling tools or replying directly in text.

  • "required": forces at least one tool call - handy when fresh database records are mandatory before replying.

  • "none": keeps tool definitions in context so the model knows what exists, while blocking invocations.

  • Named function ({"type": "function", "function": {"name": "get_order_status"}}): locks the turn to one specific tool when your backend already knows the next step.

JSON Schema validation and backend security

JSON mode is often confused with strict tool schemas. Setting response_format: {"type": "json_object"} only enforces valid JSON syntax, not that the expected keys or data types are present. Anthropic's OpenAI compatibility layer also rejects json_object with a 400 error.

Adding strict: true inside a function definition enables constrained decoding on supported OpenAI models, binding token generation directly to your schema. To keep strict: true requests from throwing 400 errors in function calling, follow four schema rules:

  • set "additionalProperties": false on the root object and every nested object;

  • include every property key inside the required array;

  • model optional fields with nullable union types like $"string", "null"$ instead of omitting them from required;

  • skip recursive $ref links and complex oneOf branches that strict grammar compilers reject.

Never rely on provider-side strict mode alone. Anthropic's OpenAI layer ignores strict: true on tools, and models across vendors occasionally emit empty {} objects even for required fields. Validate every arguments string locally with Pydantic (Python) or Zod (TypeScript) before calling any internal service.

When validation fails, return the error details inside the role: "tool" message instead of throwing an unhandled exception. Most models read the schema error and send corrected arguments on the next turn.

import json
from typing import Optional
from pydantic import BaseModel, Field, ValidationError


class RefundInput(BaseModel):
    order_id: str = Field(pattern=r"^ORD-\d{4,8}$")
    amount_cents: int = Field(gt=0, le=500_000)
    reason: Optional[str] = None


def handle_refund_call(raw_arguments: str) -> str:
    try:
        payload = RefundInput.model_validate_json(raw_arguments)
    except ValidationError as exc:
        # Feed schema errors back to the model so it can self-correct
        return json.dumps({"status": "validation_error", "details": exc.errors()})

    # issue_refund - your local refund handler
    result = issue_refund(payload.order_id, payload.amount_cents, payload.reason)
    return json.dumps(result)

Treat every model-generated argument as untrusted user input. System prompts cannot enforce access control.

  • Keep authorization in backend code: verify inside your handler that the signed-in user actually owns order_id before reading or updating records.

  • Guard write actions with idempotency keys: attach a deterministic idempotency key to mutations like refunds, invoices, or outbound emails so network retries or duplicate parallel calls never run the same write twice.

  • Isolate budgets and keys by project: separate staging, production, and client integrations into distinct ScriptRun Projects so webhooks, provider keys, and total_spent counters stay partitioned.

Token overhead and loop limits in multi-turn function calling

Chat Completions requests are stateless. Every round trip resends your system prompt, prior messages, tool results, and the full tools JSON array.

That repeated input adds up quickly. One simple function definition takes roughly 80 to 150 tokens, while 10 tools with nested objects and detailed comments easily add 2,000 to 4,000 input tokens on every call.

Look at the math for a 4-turn loop carrying 3,000 tokens of tool schemas:

  • One user request: 3,000 schema tokens × 4 turns = 12,000 extra input tokens before counting chat history or tool outputs.

  • At 50,000 requests per month: 600 million input tokens spent strictly on resending static tool definitions.

Your choice of model decides whether that overhead costs pennies or drains a monthly budget. Below are per-1,000-token rates from the ScriptRun pricing catalog in prepaid SR credits (at base rates, 1 SR = $0.01, combining request and token charges):

Model

Provider

Rate per 1,000 tokens

Practical role in tool loops

GPT-5 nano

OpenAI

0.08 SR ($0.0008)

Fast parameter extraction and single-tool dispatch

Gemini 2.5 Flash-Lite

Google

0.08 SR ($0.0008)

High-volume classification and lightweight routing

GPT-5.4 mini

OpenAI

0.9 SR ($0.009)

Multi-tool loops balancing speed and accuracy

Gemini 3.8 Flash

Google

2 SR ($0.015)

Large tool outputs and wide context windows

Claude Sonnet 4.6

Anthropic

3 SR ($0.03)

Complex argument selection and document tools

Claude Opus 4.6

Anthropic

5 SR ($0.05)

Deep analytical summaries after data lookups

GPT-6 Astra

OpenAI

15 SR ($0.15)

Flagship reasoning when accuracy outweighs token cost

The gap between a lightweight model and a flagship model reaches nearly 188x (0.08 SR vs. 15 SR). Four habits keep multi-model function calling costs predictable:

  • Cap turns with max_steps: keep synchronous loops to 5 to 8 steps. If a model cannot resolve a request in 5 calls, giving it 15 more tries usually burns tokens on a broken upstream API or repeating arguments.

  • Attach tools selectively: pass only the 3 to 5 functions needed for the active screen instead of sending your full internal catalog on every prompt.

  • Keep schema descriptions short: long examples inside description fields are billed on every turn. Use concise parameter constraints instead.

  • Split routing from final writing: let GPT-5 nano or Gemini 2.5 Flash-Lite choose tools and pull data, then hand the structured results to Claude Sonnet 4.6 or GPT-5.4 only for the final answer. For caching and prompt budgeting tactics, see our LLM API cost optimization guide.

Handling the 60-second timeout with Workflow API and MCP

Synchronous chat completions fit interactive UIs where users wait a few seconds. On ScriptRun, POST /v1/chat/completions has a 60-second server-side timeout.

Two quick database lookups finish well under a minute, but chaining five LLM turns with slow external APIs or document parsing risks a timeout. Once a flow regularly hits 30 to 40 seconds, move it to asynchronous execution in ScriptRun Workflows, which removes the one-minute cap and supports Model Context Protocol (MCP) servers.

Developers often conflate function calling with MCP, even though they operate at different layers:

Dimension

Function calling

Model Context Protocol (MCP)

Role

Model-level contract for emitting structured JSON call requests.

Client-server protocol for discovering and calling external tools over SSE or Streamable HTTP.

Where schemas live

Sent inside your app's tools payload on every chat request.

Published dynamically by an MCP server and fetched when configuring a workflow node.

Where code runs

Your backend runs the function and sends back role: "tool".

The remote MCP server runs the tool and returns the output to the workflow runtime.

When to use it

Interactive loops under 60 seconds using local handlers.

Background agents, shared internal tool servers, and multi-minute chains.

Discovering MCP tools and launching a background run

Before adding an MCP node to a workflow (billed at 0.01 SR / $0.0001 per MCP node call on ScriptRun), query which tools the remote server exposes via POST /api/v1/workflows/mcp-tools/. Remember that all /api/v1/ routes authenticate via the X-Api-Key header.

import os
import requests

API_KEY = os.environ["SCRIPTRUN_API_KEY"]

mcp_resp = requests.post(
    "https://scriptrun.ai/api/v1/workflows/mcp-tools/",
    headers={"X-Api-Key": API_KEY, "Content-Type": "application/json"},
    json={
        "endpoint_url": "https://mcp.internal.example.com/sse",
        "transport": "auto",  # supports "auto", "sse", or "streamable_http"
        "headers": {"Authorization": "Bearer <MCP_SERVER_TOKEN>"},
        "timeout": 10.0,
    },
    timeout=15,
)
mcp_tools = mcp_resp.json()

Once your graph is ready, triggering and polling it from backend code requires four checks covered in full in the asynchronous AI workflow API guide:

  1. Send root-level JSON fields with X-Api-Key: place trigger fields directly at the root of the JSON body without wrapping them inside {"input_data": {...}} (that wrapper is only for browser JWT sessions). Plain text (text/plain) also works and maps to {{ input._raw_input_ }} inside nodes.

  2. Check inner response$"status"$, not HTTP 200: POST /api/v1/workflows/{id}/run/ returns HTTP 200 even when node validation fails. Read the JSON status field: 201 confirms the run was queued (store the UUID from data.id), while 422 flags a validation error with per-node details inside data.data.

  3. Wait for node outputs to populate after status changes: poll GET /api/v1/workflows/workflow_result/?id=<run_uuid> every 3 to 5 seconds until data.status becomes "succeed" or "failed". Right after launch, the endpoint can briefly return "not found" while the worker initializes the record, so treat that as transient. Once status flips to "succeed", verify data.data is non-empty (retry up to 3 times with a 2-second pause if empty), since node outputs can finish writing 1 to 2 seconds after the status updates.

  4. Strip Markdown fences before parsing result.content: data.data is a dictionary keyed by node UUID rather than an ordered array, so look up outputs by node UUID. Because LLM nodes occasionally wrap JSON inside ```json ... ``` fences, strip those fences with a regex before calling json.loads().

import json
import re
import time
import requests


def parse_node_content(content: str):
    cleaned = re.match(r"```(?:json)?\s*([\s\S]*?)\s*```", content.strip())
    raw = cleaned.group(1) if cleaned else content
    try:
        return json.loads(raw)
    except ValueError:
        return raw


def run_and_poll_workflow(workflow_id: int, payload: dict, api_key: str, timeout_s: int = 180) -> dict:
    headers = {"X-Api-Key": api_key, "Content-Type": "application/json"}
    start_resp = requests.post(
        f"https://scriptrun.ai/api/v1/workflows/{workflow_id}/run/",
        headers=headers,
        json=payload,
        timeout=30,
    ).json()

    if start_resp.get("status") == 422:
        details = start_resp.get("data", {}).get("data")
        raise ValueError(f"Node validation failed: {details}")
    if start_resp.get("status") != 201:
        raise RuntimeError(f"Unexpected launch status: {start_resp}")

    run_id = start_resp["data"]["id"]
    deadline = time.time() + timeout_s
    empty_terminal_retries = 0

    while time.time() < deadline:
        poll = requests.get(
            "https://scriptrun.ai/api/v1/workflows/workflow_result/",
            headers={"X-Api-Key": api_key},
            params={"id": run_id},
            timeout=15,
        ).json()

        exec_data = poll.get("data", {})
        status = exec_data.get("status")

        if status in {"succeed", "failed"}:
            node_outputs = exec_data.get("data") or {}
            if node_outputs or empty_terminal_retries >= 3:
                return exec_data
            empty_terminal_retries += 1
            time.sleep(2)
            continue

        time.sleep(3)

    raise TimeoutError(f"Workflow run {run_id} exceeded {timeout_s}s")

If a downstream API drops out mid-run, you don't need to rebuild the payload from scratch - replay the run with its original inputs (or pass a new root-level JSON body) via POST /api/v1/workflows/{id}/history/{run_id}/re-run/. For sensitive actions like sending client emails or updating billing records, Agent nodes can pause execution for human review until your backend resolves the request through POST /api/v1/workflows/workflow_run/{workflow_run_id}/agent-approval/{request_id}/approve/ or .../reject/.

Rate limits, retries, and per-node cost tracking

Default ScriptRun API keys allow 60 requests per minute (RPM); reach out to support@scriptrun.ai or @scriptrunai on Telegram to raise quotas for production traffic. Keep in mind how function calling multiplies request counts: a 4-turn loop across 15 concurrent users hits 60 RPM immediately.

Handle 429 Too Many Requests and transient 500 or 503 upstream errors with exponential backoff and randomized jitter rather than immediate retries, and confirm every write handler is idempotent first. For retry budgets and queue smoothing, see our guide on fixing OpenAI API 429 rate limit errors.

In production, per-step visibility prevents a verbose tool response from inflating your bill unnoticed. Synchronous /v1/chat/completions responses include standard usage counters (prompt_tokens, completion_tokens, and total_tokens). For background workflows, fetch the per-node ledger via GET /api/v1/billing-history/workflowrun/{run_id}/:

curl -X GET "https://scriptrun.ai/api/v1/billing-history/workflowrun/0781b175-2135-45ec-9063-ad3e0d929adc/?page=1&size=25" \
  -H "X-Api-Key: <Your API Key>"

Each entry in items records the node label (description), transaction status (failed nodes show "Error"), operation, and amount across USD and SR. Pair that with GET /api/v1/projects/{id}/ to track cumulative project spend in the total_spent object (for example, {"USD": "0.00038", "SR": "0.038"}).

Reliable multi-model tool calling rests on a clean split: the model proposes a call, and your backend validates and executes it. Stick to one OpenAI-compatible client for fast loops under 60 seconds, validate every argument locally with Pydantic or Zod, cap turn counts, and move longer MCP chains into background workflows where every node's status and cost remain transparent.


Helpful?
Share this article!

Build AI workflows in minutes

Create automations, connect APIs, and access 50+ AI models from a single platform.

Visual workflow builder
OpenAI-compatible API
Workflow marketplace & templates
Start free, plans from $5

FAQs about LLM function calling API

Can I run LLM function calling across OpenAI, Claude, and Gemini from one SDK?

Yes. Point the standard OpenAI SDK at base_url="https://scriptrun.ai/v1" with your ScriptRun API key as a Bearer token, then switch providers by changing the model parameter (for example, "gpt-4o", "claude-sonnet-4-6", or "gemini-3.8-flash"). Build a clean dictionary when appending tool_calls back into messages so null fields like refusal or audio do not trigger 400 errors on third-party compatibility layers.

Does strict: true JSON Schema guarantee valid arguments on every provider?

No. OpenAI enforces constrained decoding with strict: true when every object sets "additionalProperties": false and lists all keys inside required, while Anthropic's OpenAI compatibility layer ignores strict: true on tool definitions. Validate every arguments string locally with Pydantic or Zod and send validation errors back inside a role: "tool" message so the model can correct its next call.

How do parallel tool calls work in an OpenAI-compatible API?

When a model needs several independent lookups at once, it returns multiple items inside a single tool_calls array. Execute those handlers concurrently (for example, with Promise.all in TypeScript) and append one role: "tool" message per call, matching each response to its original tool_call_id.

How much token overhead do tools definitions add to each request?

Chat Completions requests are stateless, so your full tools array is resent and billed on every turn. One simple tool adds roughly 80 to 150 input tokens, and 10 detailed schemas typically add 2,000 to 4,000 tokens per call. Load only the 3 to 5 tools needed for the active route, keep descriptions terse, and cap synchronous loops with max_steps at 5 to 8 turns.

What is the difference between function calling and MCP tools?

Function calling is the model-level contract where an LLM emits a structured JSON call request and your backend runs the local code. Model Context Protocol (MCP) is a client-server protocol over SSE or Streamable HTTP for discovering and running tools hosted on a remote server. On ScriptRun, you can query a remote server's available tools via POST /api/v1/workflows/mcp-tools/ using the X-Api-Key header.

What happens if a multi-step tool calling loop exceeds 60 seconds?

ScriptRun's POST /v1/chat/completions endpoint enforces a hard 60-second server-side timeout. Shift long chains and MCP calls into asynchronous workflows via POST /api/v1/workflows/{id}/run/ with a flat JSON body. Inspect the inner response["status"] key (201 for queued, 422 for node validation errors) and poll GET /api/v1/workflows/workflow_result/ until data.data is populated.

Read more from our blog

Related posts

AI WorkflowsAutomation
Zapier Alternatives: 8 Tools Compared on Price (2026)
BusinessDecember 4, 2026

Zapier Alternatives: 8 Tools Compared on Price (2026)

Zapier alternatives compared: what each tool costs, how it counts usage, a 10,000-action cost example, and open-source and enterprise picks.

1746
AnnaAnna
AI WorkflowsAutomation
LLM Vision API: Images & PDFs in OpenAI, Claude, Gemini
BusinessDecember 4, 2026

LLM Vision API: Processing Images and PDFs Across OpenAI, Claude, and Gemini

Run images and PDFs through OpenAI, Claude, and Gemini from one OpenAI-compatible LLM vision API. Includes Python and TypeScript base64 examples, 2026 token math, pre-resizing, JSON extraction, and async Workflow API batch jobs.

1717
James
AI WorkflowsAutomation
What Is OpenRouter? How It Works, Pricing and Limits (2026)
BusinessDecember 3, 2026

What Is OpenRouter? How It Works, Pricing and Limits (2026)

What is OpenRouter and should you use it? How the gateway works, what it costs, free limits, Auto Router and Fusion, privacy and who owns it.

1558
AnnaAnna
AI WorkflowsAutomation
OpenAI API Alternative: 8 Providers Compared for 2026
BusinessDecember 2, 2026

OpenAI API Alternative: 8 Providers Compared for 2026

Eight OpenAI API alternatives compared on current prices, speed, context and what changes when you switch, with a checklist and a gateway option.

1588
AnnaAnna
© 2024-2026 PIXEL LORIS IT SERVICES L.L.C. All rights reserved.