EN ▾
Get API key

Gemma 4 Tool Calling With an OpenAI-Compatible API

If you want gemma 4 tool calling in an app you already wrote against the OpenAI SDK, you only need to change the base URL, the key and the model name. This guide shows the full loop with working code.

Updated

Isometric illustration of a request cube travelling through function modules and returning with a result

Key points

  • Send the standard tools array to POST /v1/chat/completions with model uncensored.
  • Run the function yourself, then send the result back as a role tool message.
  • Streamed tool_calls arrive in pieces; merge them by index before parsing.
  • A three-step tool loop with 2,000 prompt tokens per step costs about $0.0011.

Short answer: the same tools format you already know

This service is not Google's Gemma API, and it does not run a model called Gemma 4. It hosts one open-weight model, run by an independent provider, that is tuned to answer without content refusals for lawful adult use. What it shares with the setup most people search for is the interface: an OpenAI-compatible chat endpoint with tool calling. If your question behind gemma 4 tool calling is "can I pass function schemas and get structured calls back", the answer is yes, using the same fields the OpenAI SDK sends.

You need three things: the base URL https://api.gemmauncensored.cc/v1, an API key sent as Authorization: Bearer, and the model ID uncensored. The request fields are tools, tool_choice, and for results the tool role. Streaming works too, and tool calls come through as streamed tool_calls deltas. For the general pitch and specs, see the Gemma 4 API overview on this site.

How a tool call round trip works

The model never runs your code. It only decides that a function should be called and writes the arguments. Your program does the work, and the model then reads the result. The loop has four steps:

  1. You send messages plus a list of tool definitions.
  2. The model replies with an assistant message that has tool_calls instead of (or in addition to) text.
  3. You run each call, and append one message per call with role: "tool", the matching tool_call_id and the result as a string.
  4. You send the whole conversation again. The model answers in plain text, or asks for another tool.

It helps to keep the roles straight. The model proposes, your code decides. It never has network access or a shell of its own on this API, so a function exists only if you wrote it and registered it in the request. That also means every safety check, such as permission rules or input limits, belongs in your function, not in the prompt.

Each pass is a normal request, billed by the tokens in and out. That matters for cost, and it matters for limits, because every pass counts as a request toward your per-minute allowance.

A working loop in Python

Install the official SDK with pip install openai. The example defines one function, get_order_status, and loops until the model stops asking for tools.

import json
from openai import OpenAI

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

tools = [{
    "type": "function",
    "function": {
        "name": "get_order_status",
        "description": "Look up the status of an order by its numeric id.",
        "parameters": {
            "type": "object",
            "properties": {"order_id": {"type": "integer"}},
            "required": ["order_id"],
        },
    },
}]

def get_order_status(order_id):
    return {"order_id": order_id, "status": "shipped"}

messages = [{"role": "user", "content": "Where is order 4812?"}]

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:
        args = json.loads(call.function.arguments)
        result = get_order_status(**args)
        messages.append({
            "role": "tool",
            "tool_call_id": call.id,
            "content": json.dumps(result),
        })

Two details are easy to miss. First, append the assistant message exactly as it came back, so the tool call ids line up with your tool messages. Second, cap the loop (here at five passes). A model that keeps asking for the same tool should not be able to run up your bill.

Streaming tool calls

With stream: true the arguments of a call arrive in fragments. Each chunk has a tool_calls delta with an index; the first fragment carries the id and function name, the rest append to the arguments string. Merge by index and parse the JSON only when the stream ends.

from openai import OpenAI
client = OpenAI(base_url="https://api.gemmauncensored.cc/v1", api_key="YOUR_KEY")

stream = client.chat.completions.create(
    model="uncensored", messages=messages, tools=tools, stream=True
)
calls = {}
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="")

Usage is reported at the end of the stream, so you can log token counts per request. One limit to plan for: a streamed request holds its concurrency slot until the stream ends, and a full key allows 8 requests at once. Agent frameworks that fan out many streams can hit the concurrency error faster than the per-minute one.

Using it from LangChain, Cursor and similar tools

Most developer tools that speak to OpenAI can be pointed elsewhere, since they only need a base URL and a key. In LangChain for Python, the chat class takes both as arguments:

from langchain_openai import ChatOpenAI

llm = ChatOpenAI(model="uncensored", base_url="https://api.gemmauncensored.cc/v1", api_key="YOUR_KEY")
llm_with_tools = llm.bind_tools([get_order_status_tool])

For Node projects the pattern is the same: create the client with baseURL set to the same address and pass your key. Any library built on the OpenAI client classes will accept those two settings, which is why moving an agent from one provider to another is often a two-line change. Keep the key in an environment variable instead of in the source file.

Editors and chat front ends usually have a field for a custom OpenAI-compatible endpoint. Paste the base URL, the key, and type uncensored as the model name. Whether a given editor feature (agent mode, inline edits) works depends on how the tool builds its requests, so test with a short prompt first. If a tool also expects embeddings or image input, note that this API is text only and has neither.

The documentation page lists the supported parameters, including temperature, top_p, stop, seed and the penalties. For function calling, a low temperature such as 0.2 keeps argument values closer to the schema.

Problems you will probably hit

Arguments that are not valid JSON

Models sometimes emit a trailing comma or a stray quote. Wrap json.loads in a try block. On failure, do not crash: return a tool message that says the arguments were invalid and show the parse error. The model usually corrects itself on the next pass.

The model answers in text when you wanted a call

Write the function description as an instruction ("Use this when the user asks about an order"), and keep the list of tools short. Ten overlapping tools confuse any model. You can also force a specific function with tool_choice set to that function's name.

Calls that repeat forever

If the same call with the same arguments appears twice in a row, your tool result probably did not answer the question, for instance because it returned an empty list with no explanation. Return something the model can act on, such as a message saying that no order was found for that id, and add a hard cap on passes as a backstop.

Hallucinated function names

Look the name up in a dictionary of your own functions. If it is missing, send back an error message. Never call eval or build a dynamic import from a model-supplied name.

Status 429

The API returns 429 with code rate_limited when you exceed 300 requests per minute, concurrency when more than 8 requests run at once, and 429 with a Retry-After: 5 header on temporary overload. Honour the header and retry with a short backoff. A trial key is stricter: 2 concurrent requests and 60 per minute.

What a tool loop costs

Pricing is $0.15 per 1M input tokens and $0.50 per 1M output tokens. Tool loops are input-heavy because each pass resends the conversation plus the schemas. Take a loop with three passes, each sending about 2,000 prompt tokens and generating 150 tokens:

  • Input: 3 x 2,000 = 6,000 tokens, which is 6,000 / 1,000,000 x $0.15 = $0.0009.
  • Output: 3 x 150 = 450 tokens, which is 450 / 1,000,000 x $0.50 = $0.000225.
  • Total: $0.001125 per run, or about $1.13 for 1,000 runs.

Failed or refused requests are not charged. The full price list and the top-up options are on the pricing page. To try the loop above, claim the one-click trial credit of $0.50 on the API key page after signing up. It needs no card and is valid for 7 days.

One last point on scope: prompts are not used for training, and the hard content limit is that nothing sexual involving minors is ever allowed. Everything else about lawful adult use is up to your application.

Frequently Asked Questions

Q: Is the Gemma 4 API compatible with OpenAI SDKs?
A: Yes, most uncensored Gemma APIs follow the OpenAI protocol, allowing you to use standard SDKs like the official OpenAI Python or Node.js libraries. You just need to update the base URL and API key.

Q: How do I get an API key?
A: You can sign up on the provider’s website, usually via Google or email. The API key is provided immediately after registration, ready for use in your applications.

Q: What happens if I exceed my token limit?
A: Your requests may be rate-limited or paused until your next billing cycle. Our prepaid model ensures you know your costs upfront, with no surprise charges.

Q: Can I run Gemma 4 locally?
A: Yes, since it’s an open-weight model, you can download the weights and run it on your own hardware, provided you have sufficient GPU memory. This offers full control over your data and inference.

Questions and answers

Is this the official Gemma 4 API?

No. It is a separate service that runs one open-weight model, tuned to answer without content refusals, behind an OpenAI-compatible endpoint. It is not run by Google.

Does tool calling work with streaming?

Yes. Set stream to true and merge the tool_calls deltas by index. Usage is sent at the end of the stream.

Can I force the model to call a specific function?

Yes. Pass tool_choice with the function name, or use auto to let the model decide.

Do tool calls cost extra?

No separate fee. You pay for input and output tokens at $0.15 and $0.50 per 1M, and the tool definitions count as input tokens.

Your key is one form away

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