EN ▾
geminiuncensored.ccUncensored API, OpenAI compatible, pay per token
Get API key

Function Calling in Gemini Style on an Uncensored API

If you built function calling in Gemini and want the same pattern on an uncensored model, the OpenAI-style tools format is what you use here. This article shows the full loop in Python, streaming, JSON mode, and the failure cases to plan for.

Updated

Illustration of a model core passing tool blocks along a conveyor, representing function calling

Key points

  1. Tools are declared with the OpenAI tools array; results go back as messages with role tool.
  2. Streaming sends tool_calls in pieces, so you must join the argument fragments before parsing.
  3. JSON mode via response_format guarantees a JSON object shape to aim for, but still validate it.
  4. This is not the Gemini API, so code written against Google's request format needs a small rewrite.

How tool calling differs from Gemini's format

Searching for function calling in gemini usually means one of two jobs: you want to understand the idea, or you have working Gemini code and need it to run against another model. The idea is the same everywhere. You describe functions to the model, the model answers with a request to call one of them with arguments, your code runs it, and you send the result back so the model can write the final answer.

What changes is the wire format. Google's own Gemini API has its own request shape for declaring functions. This service is not that API. It is an OpenAI-compatible endpoint for one open-weight, uncensored model, so you declare functions the way OpenAI clients do: a tools array, an optional tool_choice, and results returned as messages with role: "tool". Any OpenAI SDK works once you change the base URL to https://api.geminiuncensored.cc/v1 and use the model ID uncensored.

The model does not run your code. It only produces the name of a function and a JSON string of arguments. Execution, permissions and safety checks stay on your side, which is the right place for them.

Declaring a tool

A tool is a JSON object with a name, a description and a parameter schema written in JSON Schema. The description matters more than people expect, because it is the main thing the model reads when deciding whether to call the function.

from openai import OpenAI

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

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

Write descriptions as instructions to a new colleague. Say what the function does, what the arguments mean, and when not to use it. Keep the number of tools small. A handful of clearly different functions is easier for any model to pick between than twenty near-duplicates.

The full call loop in Python

Tool calling takes at least two requests. The first returns the call request. The second carries the result and gets the final text. The code below handles any number of rounds in a loop, with a cap so a confused model cannot run forever.

import json

def get_order_status(order_id: int) -> dict:
    return {"order_id": order_id, "status": "shipped", "eta_days": 2}

registry = {"get_order_status": get_order_status}

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

for _ in range(5):  # hard cap on rounds
    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)  # keep the assistant turn that asked for the calls
    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),
        })

Three details trip people up. The assistant message with the tool_calls must stay in the history, or the tool result has nothing to attach to. Each tool message needs the matching tool_call_id. And the arguments field is a string, not an object, so it needs json.loads. Returning errors to the model as data, as the code does, often lets it correct itself on the next round.

Controlling when tools get called

The tool_choice field sets the policy. With "auto" the model decides. With "none" it answers in text only. If you need a specific function every time, pass an object that names it, for example {"type": "function", "function": {"name": "get_order_status"}}. Forcing a call is useful for extraction jobs, where the function is just a way to get structured output.

The same curl request shows the raw shape, which helps when you debug without an SDK:

curl https://api.geminiuncensored.cc/v1/chat/completions \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "uncensored",
    "messages": [{"role": "user", "content": "Where is order 4812?"}],
    "tools": [{
      "type": "function",
      "function": {
        "name": "get_order_status",
        "description": "Look up the shipping status of an order by its numeric ID.",
        "parameters": {
          "type": "object",
          "properties": {"order_id": {"type": "integer"}},
          "required": ["order_id"]
        }
      }
    }],
    "tool_choice": "auto"
  }'

Streaming tool calls

With stream: true the reply arrives over server-sent events, and tool calls arrive in fragments. Each chunk carries a small piece of the function name or of the arguments string, tagged with an index. You have to glue the pieces together and only parse once 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="")

Parsing half of an arguments string raises an error, so wait for the end of the stream. Token usage is reported at the end of a streamed response, which lets you log costs per request. Remember that a streamed request holds one of your concurrency slots until it finishes: 2 on a trial key, 8 on a full key.

JSON mode for structured output without tools

Sometimes you do not need a function at all. You only want the model to return data in a fixed shape, such as a list of entities from a paragraph. JSON mode handles that: set response_format to {"type": "json_object"} and say in the prompt what keys you expect.

resp = client.chat.completions.create(
    model="uncensored",
    messages=[
        {"role": "system", "content": "Reply only with a JSON object with keys name, mood, location."},
        {"role": "user", "content": "Mara stepped off the night train in Lisbon, tired but pleased."},
    ],
    response_format={"type": "json_object"},
    temperature=0,
)
data = json.loads(resp.choices[0].message.content)

The mode pushes the output toward valid JSON. It does not enforce your schema, so keys can still be missing or have the wrong type. Treat the result like any untrusted input: parse it inside a try block and check the fields before use. A low temperature, and a fixed seed if you want repeatable tests, both pass through to the model.

Moving existing Gemini code over

If you already have function calling working against Google's API, the port is mostly renaming. The concepts line up one to one, so you rarely need to change your application logic, only the thin layer that builds requests and reads responses.

In Google's APIOn this endpoint
Function declarations listtools array of type function
A function call part in the replyEntries in message.tool_calls
A function response part you send backA message with role: "tool" and the matching tool_call_id
Call mode settingtool_choice

Two habits from the old code need a second look. First, argument objects: here arguments arrives as a JSON string, so add a parse step. Second, the message history: the OpenAI format wants you to append the assistant turn that contained the calls before the tool results, and to keep ids matched. Everything else, such as your registry of Python functions, your validation and your retries, carries over unchanged.

Writing schemas the model can follow

Use enums when an argument has a closed set of values, and give every property a short description with an example value. Mark only the truly required fields as required. If two functions overlap, merge them or state in each description when the other one should be used instead. When a call goes wrong, read the raw arguments string before blaming the model. A vague schema is the usual cause of wrong arguments, and tightening the description fixes it faster than changing sampling settings.

The response can hold more than one entry in tool_calls, which is why the loop above walks the whole list and answers every id. Skipping one leaves the history inconsistent and the next request may fail or confuse the model.

Reliability tips and cost

  • Validate before executing. Check argument types and ranges. If a function deletes or sends something, ask for human confirmation first.
  • Retry on 429. Over the per-minute cap the API returns rate_limited; with too many parallel calls it returns concurrency. On temporary overload it adds a Retry-After: 5 header. Sleep and retry, and run tool calls in parallel only up to your concurrency limit.
  • Keep results short. Every tool result is input tokens on the next round. Trim large records to the fields the model needs.
  • Cap the loop. The five-round limit above stops runaway loops from spending credit.

As a worked example, an agent turn with three rounds, each carrying about 2,000 tokens of input and returning 150 tokens, uses 6,000 input tokens and 450 output tokens. That costs 0.006 x $0.15 = $0.0009 for input plus 0.00045 x $0.50 = $0.000225 for output, about $0.0011 in total. The pricing page has the rates and top-up bonuses, and the docs quickstart covers the basic request. To try the examples above, create a key and claim the $0.50 trial credit.

Questions and answers

Is this the same as Google's Gemini function calling?

No. The idea is the same, but this endpoint uses the OpenAI tools format and runs a different, open-weight model. Code written for Google's request shape needs small changes.

Can I use the OpenAI Python SDK?

Yes. Set base_url to https://api.geminiuncensored.cc/v1, pass your key, and use the model ID uncensored. Tools, tool_choice and role tool messages work as in the examples.

Does JSON mode guarantee my schema?

No. It pushes the model toward a valid JSON object, but fields can still be missing. Always parse inside a try block and validate the keys.

Do I pay for tool calls separately?

No separate fee. You pay the normal per-token price for the input and output of each request, and failed requests are not charged.

Your key is one form away

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