EN ▾
Get API key

Gemma 3 Tool Calling Through an OpenAI-Compatible API

Gemma 3 tool calling is awkward to set up locally because runtimes and wrappers each handle function calls their own way. Here is how the same job looks against a hosted OpenAI-compatible endpoint, with code you can run.

Updated:

Isometric diagram of a central node sending requests to tool modules and receiving results

Key points

Why tool calling on Gemma 3 is fiddly locally

If you searched gemma 3 tool calling, you probably ran into one of two situations. Either you tried the model in a local runtime and found that function calls only work after you paste a special prompt template, or you used a community build and got malformed JSON about one time in ten. Both come from the same cause: there is no single tool-call convention shared by every local runtime, so wrapper libraries fill the gap with their own, usually by instructing the model in the prompt to emit JSON and then parsing it out.

That approach works, but it moves a lot of work onto you. You maintain the prompt template, you write the parser, and you handle the cases where the model wraps JSON in prose or invents a function name. A hosted OpenAI-compatible API moves that layer to the server. You pass a tools array, you get back structured tool_calls, and your agent framework keeps working because it already expects that shape.

Be clear about what this service is. It runs one open-weight model, uncensored, operated by an independent provider and tuned to answer without content refusals for lawful adult use. It is not a router across vendors and it is not Google's official Gemma API. The examples below are about the wire protocol, which is the same no matter which model sits behind it.

The request and response shape

A tool is a JSON schema describing a function. You send the list with your messages, and the model either answers in text or returns one or more calls. tool_choice controls this: "auto" lets the model decide, "none" forbids calls, and naming a function forces it.

curl https://api.gemmaabliterated.top/v1/chat/completions \
  -H "Authorization: Bearer YOUR_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "uncensored",
    "messages": [{"role": "user", "content": "What is the weather in Lisbon?"}],
    "tools": [{
      "type": "function",
      "function": {
        "name": "get_weather",
        "description": "Current weather for a city",
        "parameters": {
          "type": "object",
          "properties": {"city": {"type": "string"}},
          "required": ["city"]
        }
      }
    }],
    "tool_choice": "auto"
  }'

When the model decides to call the function, the assistant message has no text and carries a tool_calls list. Each entry has an id, the function name, and arguments, which is a JSON string rather than an object. That detail trips up many first attempts. Parse it with json.loads, do not index into it directly.

{
  "role": "assistant",
  "content": null,
  "tool_calls": [{
    "id": "call_abc123",
    "type": "function",
    "function": {"name": "get_weather", "arguments": "{\"city\": \"Lisbon\"}"}
  }]
}

A complete call loop in Python

The loop has four steps: send, check for calls, run them, send the results back. Repeat until the model answers in plain text. Cap the number of rounds so a confused model cannot loop forever.

import json
from openai import OpenAI

client = OpenAI(base_url="https://api.gemmaabliterated.top/v1", api_key="YOUR_KEY")

def get_weather(city: str) -> dict:
    return {"city": city, "temp_c": 21, "sky": "clear"}  # stub

REGISTRY = {"get_weather": get_weather}

tools = [{
    "type": "function",
    "function": {
        "name": "get_weather",
        "description": "Current weather for a city",
        "parameters": {
            "type": "object",
            "properties": {"city": {"type": "string"}},
            "required": ["city"],
        },
    },
}]

messages = [{"role": "user", "content": "Is it warm in Lisbon right now?"}]

for _ in range(5):
    resp = client.chat.completions.create(
        model="uncensored", messages=messages, tools=tools, tool_choice="auto"
    )
    msg = resp.choices[0].message
    if not msg.tool_calls:
        print(msg.content)
        break
    messages.append(msg)
    for call in msg.tool_calls:
        fn = REGISTRY.get(call.function.name)
        try:
            args = json.loads(call.function.arguments)
            result = fn(**args) if fn else {"error": "unknown function"}
        except Exception as exc:
            result = {"error": str(exc)}
        messages.append({
            "role": "tool",
            "tool_call_id": call.id,
            "content": json.dumps(result),
        })

Two habits in that code matter in production. Unknown function names and bad arguments are returned to the model as an error result rather than raising, so it gets a chance to correct itself on the next round. And every tool message carries the tool_call_id of the call it answers; mismatched ids are the most common cause of confusing replies.

Streaming tool calls

With stream: true, tool calls are delivered as deltas. The first fragment for a call has its id and function name; later fragments append pieces of the arguments string. You must join them by index and parse the JSON only after the stream ends.

calls = {}
stream = client.chat.completions.create(
    model="uncensored", messages=messages, tools=tools, stream=True
)
for chunk in stream:
    if not chunk.choices:
        continue
    delta = chunk.choices[0].delta
    for tc in delta.tool_calls or []:
        slot = calls.setdefault(tc.index, {"id": "", "name": "", "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
    if delta.content:
        print(delta.content, end="", flush=True)

for slot in calls.values():
    print(slot["name"], json.loads(slot["args"]))

Remember that a streamed request occupies a concurrency slot until the stream finishes. In an agent that fires several calls in parallel, that is the first limit you will meet: a full key allows 8 requests at once, a trial key 2.

Using it from LangChain and similar frameworks

Frameworks that talk to OpenAI-style endpoints need only the base URL, key and model name. In LangChain, the ChatOpenAI class from langchain-openai accepts all three, and bind_tools converts your Python functions or Pydantic models into the schema shown above.

from langchain_openai import ChatOpenAI
from langchain_core.tools import tool

@tool
def get_weather(city: str) -> str:
    """Current weather for a city."""
    return f"{city}: 21 C, clear"

llm = ChatOpenAI(
    base_url="https://api.gemmaabliterated.top/v1",
    api_key="YOUR_KEY",
    model="uncensored",
    temperature=0,
)
llm_tools = llm.bind_tools([get_weather])
ai = llm_tools.invoke("Is it warm in Lisbon right now?")
print(ai.tool_calls)

The same applies to LlamaIndex, CrewAI, AutoGen and the Vercel AI SDK: look for the setting that names an OpenAI-compatible provider, and enter the endpoint, key and uncensored. Check each framework's current documentation for the exact parameter names, since they change between releases.

In Node, the official openai package works the same way: new OpenAI({ baseURL: "https://api.gemmaabliterated.top/v1", apiKey }) and then client.chat.completions.create({ model: "uncensored", messages, tools }).

Debugging a tool call that misbehaves

When an agent does something odd, log the raw request and response before changing the prompt. The X-Request-Id header on every response identifies the call, which helps if you need to ask support about a specific failure. The X-Balance-USD header shows your remaining credit after each request, a handy way to watch what a runaway loop costs while you test.

Work through these symptoms in order.

  • The model answers in text and ignores the tool. The description probably does not match the user's wording. Rewrite it using the words people actually type, or force the call with tool_choice naming the function while you test.
  • Arguments fail to parse. Print the raw string. Truncated JSON usually means max_tokens was too low; stray text around the braces means the schema was too loose. Tighten the types and add an enum where a field has a fixed set of values.
  • The model calls the same tool forever. The tool result is not telling it that the job is done. Return a clear status field such as {"status": "done", "items": 3}, and keep the round cap in place.
  • The reply after a tool result ignores the data. Check that the assistant message with the tool_calls was appended to the history before the tool messages. Skipping it breaks the pairing between call and result.
  • A 429 appears mid-run. You are either past 300 requests per minute or running more than 8 requests at once. Add a small semaphore around your calls, and treat a Retry-After: 5 header as an instruction to wait five seconds.

A small semaphore is easy to add in Python, and it keeps a parallel agent inside the concurrency limit without any other change.

import asyncio
from openai import AsyncOpenAI

client = AsyncOpenAI(base_url="https://api.gemmaabliterated.top/v1", api_key="YOUR_KEY")
gate = asyncio.Semaphore(6)  # stay under 8 concurrent requests

async def ask(messages, tools):
    async with gate:
        return await client.chat.completions.create(
            model="uncensored", messages=messages, tools=tools
        )

Leaving two slots free gives room for a retry or a second agent sharing the same key.

Making calls reliable

Open-weight models can call tools less predictably than you may be used to, so write defensively. These practices cut failures noticeably.

  • Write sharp descriptions. The description is the only thing telling the model when to call a function. Say what it does and when not to use it.
  • Keep schemas small. Few parameters, plain types, enums for fixed choices. Mark only truly required fields as required.
  • Lower the temperature. A value between 0 and 0.3 makes argument generation steadier. Set seed while debugging to reproduce a failure.
  • Validate before executing. Treat arguments as untrusted input, especially for anything that writes files, sends messages or spends money.
  • Limit the tool list. Ten tools are harder to choose between than three. Pass only those relevant to the current step.
  • Use JSON mode for plain extraction. If you only need structured output, response_format: {"type":"json_object"} is simpler than a fake function. Mention JSON in the prompt as well.

When a call fails, return the error text as the tool result and let the model retry once. Add a hard cap on rounds so a bad run costs cents, not dollars.

What tool use costs, and where to go next

Tool schemas count as input tokens on every round, as does the growing message history. Take an agent that makes 3 rounds per task, with 1,500 input tokens and 150 output tokens each. Input is 4,500 tokens, which is 4,500 × $0.15 / 1,000,000 = $0.000675. Output is 450 tokens, which is 450 × $0.50 / 1,000,000 = $0.000225. One task costs $0.0009, so 1,000 tasks cost $0.90. Check the pricing page for top-up options and the docs for the full parameter list.

Context is 100,000 tokens including the reply, and the request body can be up to 8 MB. Failed or refused requests are not charged. Your prompts are not used for training. To try it, create a key on the API key page; new accounts can claim $0.50 of trial credit with one click, valid 7 days, no card needed.

If you want to compare with running a modified Gemma build yourself, our article on hosted versus local abliterated models lays out that choice.

Questions and answers

Does the API support parallel tool calls?

The model can return several entries in tool_calls in one message. Run each one and send back one role tool message per call, each with its own tool_call_id.

Why is arguments a string and not an object?

The OpenAI format delivers arguments as a JSON-encoded string. Parse it with json.loads or JSON.parse, and handle the case where it fails.

Can I force the model to call a specific function?

Yes. Set tool_choice to an object naming the function, or use none to forbid calls and auto to let the model decide.

I get HTTP 429 during an agent run. What now?

The code is rate_limited for requests per minute or concurrency for too many at once. Wait and retry, and reduce parallel calls. A Retry-After: 5 header means temporary overload.

Is this Google's Gemma API?

No. It is a single open-weight model, ID uncensored, run by an independent provider. It is not an official API of any model vendor.

Your key is one form away

Create an account, copy the key, change the base URL. That is the whole setup.

Get API keyRead the docs