EN ▾

Uncensored API. OpenAI compatible.

Get API key

LLM tool_calls: How Function Calling Works, With Code

In an OpenAI-style chat API, llm tool_calls is the field where the model asks your code to run a function and hands you the arguments. This article shows the full round trip with working code, then covers streaming, JSON mode and the mistakes that cost people an afternoon.

Updated

A robotic arm passing a glowing cube between a function block and a terminal, illustrating tool calling in an LLM API

No card needed. After sign-up, claim $0.50 of free test credit with one click (once per person).

Get API key

The round trip in five steps

Tool calling confuses people because the name suggests the model does something. It does not. It writes a request, and your program decides whether to honour it. The loop looks like this:

  1. You send the conversation plus a list of tools, each with a name, a description and a JSON Schema for its parameters.
  2. The model replies with an assistant message. If it wants a tool, the message has a tool_calls array instead of (or beside) normal text. Each entry has an id, a function name and an arguments string.
  3. Your code parses the arguments, runs the matching function and captures the result.
  4. You append the assistant message and one role: "tool" message per call, each carrying the matching tool_call_id.
  5. You call the API again. The model reads the results and either answers or asks for more tools.

That is all there is to it. The rest of this page is about doing each step without surprises. Everything below runs against the hosted API at https://api.nofilter.top/v1 with the model ID uncensored. Tool calling, streamed tool_calls and tool results are all supported, so existing OpenAI-style agent code needs only a new base URL and key.

Step 1: describe your tools

A tool definition is a contract. The model sees the name, the description and the parameter schema, and nothing else. It cannot see your code. If the description is vague, the model guesses, so write descriptions the way you would explain the function to a new colleague who cannot ask follow-up questions.

from openai import OpenAI
import json

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

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

def get_order_status(order_id):
    # Replace with a real lookup.
    return {"order_id": order_id, "status": "shipped", "carrier": "post"}

registry = {"get_order_status": get_order_status}
MODEL = "uncensored"

Keep the schema tight. Use enum for fields with a fixed set of values, mark required fields as required, and give each property a short description. Fewer, clearer tools beat a long menu. Past a handful of tools the model starts to pick the wrong one more often, so group related operations into one tool with an action enum when it makes sense.

Step 2: run the loop

Here is a complete loop. It stops when the model returns a message with no tool calls, and it caps the number of rounds so a confused model cannot burn credit forever.

messages = [
    {"role": "user", "content": "Where is order 4812? Answer in one sentence."}
]

for _ in range(5):  # hard cap on rounds
    response = client.chat.completions.create(
        model="uncensored",
        messages=messages,
        tools=tools,
        tool_choice="auto",
        temperature=0.2,
    )
    msg = response.choices[0].message
    messages.append(msg)

    if not msg.tool_calls:
        print(msg.content)
        break

    for call in msg.tool_calls:
        try:
            args = json.loads(call.function.arguments)
            fn = registry[call.function.name]
            result = fn(**args)
        except Exception as exc:
            result = {"error": str(exc)}
        messages.append({
            "role": "tool",
            "tool_call_id": call.id,
            "content": json.dumps(result),
        })

Two details matter here. First, temperature=0.2: argument generation benefits from low randomness, and you rarely want creative variation in an order ID. Second, errors go back to the model as tool results instead of crashing the program. A model that sees {"error": "unknown tool"} will often correct itself on the next round.

The tool_choice field controls the behaviour. "auto" lets the model decide, "none" forbids tools for that call, and passing an object that names a function forces that specific call. Forcing a tool is a handy way to get structured extraction without writing a prompt that begs for it.

What the raw response looks like

When you log the assistant message, you will see something like this. Note that arguments is a string containing JSON, not an object. That trips up people who read the field and index into it directly.

{
  "model": "uncensored",
  "choices": [
    {
      "index": 0,
      "finish_reason": "tool_calls",
      "message": {
        "role": "assistant",
        "content": null,
        "tool_calls": [
          {
            "id": "call_01",
            "type": "function",
            "function": {
              "name": "get_order_status",
              "arguments": "{\"order_id\": 4812}"
            }
          }
        ]
      }
    }
  ]
}

The model may return several entries in one message when the calls are independent, for example looking up three orders at once. Run all of them, add one tool message per id, and only then call the API again. If you skip an id, the next request is malformed and the model loses track of what happened.

Streaming tool_calls

With stream: true, tool calls arrive in pieces. The first chunk for a call carries the index, the id and the function name. Later chunks carry slices of the arguments string. You cannot parse anything until the stream ends, because a half-finished JSON string is not JSON. Collect the pieces by index:

stream = client.chat.completions.create(
    model="uncensored",
    messages=messages,
    tools=tools,
    stream=True,
)

calls = {}
text = ""

for chunk in stream:
    if not chunk.choices:
        continue  # the final chunk may carry only usage
    delta = chunk.choices[0].delta
    if delta.content:
        text += delta.content
    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

for index, slot in sorted(calls.items()):
    args = json.loads(slot["args"])
    print(slot["name"], args)

Usage numbers are reported at the end of the stream, so a careful client tolerates a last chunk with an empty choices list, as the code above does. One more operational point: a streamed request occupies its concurrency slot until the stream ends. A full key allows 8 concurrent requests, a trial key 2. If a tool takes a long time to run between rounds, that does not hold a slot, because each round is its own request, but ten parallel users each streaming will hit the concurrency error code and an HTTP 429 quickly.

JSON mode versus tools

Tools and JSON mode solve different problems. Use tools when the model should choose between actions, or when a program must react to the choice. Use JSON mode when you only want the answer in a fixed shape, such as extracting fields from a paragraph. JSON mode is switched on with response_format:

curl https://api.nofilter.top/v1/chat/completions \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "uncensored",
    "response_format": {"type": "json_object"},
    "messages": [
      {"role": "system", "content": "Reply with a JSON object with keys title, mood and word_count_estimate."},
      {"role": "user", "content": "Summarise: a lighthouse keeper finds a message in a bottle."}
    ]
  }'

Describe the keys you want in the prompt, even in JSON mode. The flag makes the output valid JSON; it does not tell the model which fields you expect. Validate the result against your own schema anyway, since valid JSON can still miss a key.

For a single-shot extraction, forcing one tool with tool_choice and using JSON mode are close cousins. Pick whichever fits your code. Forced tools give you a schema in the request, which is easier to keep in sync with a typed function on your side.

Pitfalls and how to fix them

SymptomLikely causeFix
JSONDecodeError on argumentsThe model produced a stray comma or an unquoted key, or you parsed a partial stream.Join all fragments first, wrap parsing in try/except, return the error as a tool result so the model retries.
Model calls a tool that does not existName drift, or a vague tool list.Look the name up in a registry, return an error for unknown names, tighten descriptions.
400 error on the second requestA tool call id has no matching tool message, or the assistant message was not appended.Append the assistant message first, then exactly one tool message per call id.
Endless loopThe model keeps asking for the same data.Cap the rounds, return a clear "no results" message instead of an empty one.
HTTP 429 with Retry-After: 5Temporary overload.Wait the number of seconds in the header, then retry with a short backoff.
HTTP 429 with code concurrencyMore simultaneous requests than your key allows.Queue requests so no more than 8 run at once (2 on a trial key).

Two more habits save time. Log the X-Request-Id response header with every call, so you can point to a specific request if something looks off. And keep tool results short. Everything you return goes back into the prompt on the next round, and the context window is 100,000 tokens for prompt and completion together. Truncate big payloads and return only the fields the model needs.

Safety around tools, and a cost check

Treat every argument as untrusted input. The model decides what to pass, and a model with no content refusals will not second-guess a risky request on your behalf. If a tool can delete rows, send mail or spend money, put the permission check in your function, not in the prompt. Validate IDs against what the current user may access, and require a human confirmation step for anything irreversible.

The cost of tool loops is easy to estimate. Say a request has 3,000 tokens of input and the model answers with a 100-token tool call, then you send back 3,400 tokens including the result and get a 200-token answer. Input is 3,000 plus 3,400, which is 6,400 tokens, costing $0.00096. Output is 300 tokens, costing $0.00015. The whole exchange is $0.00111. The pricing page lists the rates: $0.15 per 1M input tokens and $0.50 per 1M output tokens, and failed requests are not charged.

To try the code, create a key on the API key page. New accounts can claim $0.50 of trial credit with one click, with no card. The documentation has the base URL, headers and rate limits in one place, and the page on uncensored models explains what kind of model sits behind the endpoint.

Questions and answers

What is the difference between tool_calls and function_call?

function_call is the older field from the first version of function calling. tool_calls is the current form: an array, so one reply can request several calls, each with its own id. Use tools and tool_calls in new code.

Why is arguments a string and not an object?

The model generates text, so the arguments come back as a JSON string. Parse it with json.loads or JSON.parse and handle the case where it is invalid.

Can I use streaming and tool calling together?

Yes. Collect the fragments of each call by index until the stream ends, join the arguments strings, then parse them. Only then run the function.

Does a failed tool call cost money?

Failed or refused requests are not charged. A successful request that returns a tool call is billed like any other, by input and output tokens.

Which model ID do I use?

Use uncensored as the model value with the base URL https://api.nofilter.top/v1. You can list it with GET /v1/models.

Your key is one form away

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

Get API key