EN ▾

Uncensored API. No refusals. Direct.

Qwen function_call: Tool Calling via OpenAI API

If you searched for qwen function_call, the short version is that this endpoint speaks the OpenAI tools format. You declare functions, the model returns tool calls, and you send the results back.

Updated

Isometric illustration of a terminal sending data cubes through gears and returning results along a rail

Key points

  • Use the tools and tool_choice parameters; results go back as messages with role tool.
  • Streamed tool calls arrive in pieces, so collect the argument fragments by index before parsing.
  • JSON mode (response_format json_object) covers cases where you want structured output without a function.
  • Always parse arguments defensively: the model can return malformed JSON, and a failed request is not charged.

The short answer: tools, not function_call

Older OpenAI code and many Qwen examples use a functions list together with a function_call parameter. That style has been replaced across the OpenAI SDKs by tools and tool_choice, and those are the names this API documents. If your project still uses the legacy parameter names, port them once and you are done. The shape of the data barely changes: each function description moves inside a {"type": "function", "function": {...}} wrapper.

The flow has four steps. You send messages plus a list of tools. The model either answers in plain text or returns one or more tool_calls. Your code runs the matching functions. You append the results as messages with role: "tool" and call the endpoint again so the model can write the final answer. Nothing here is specific to one SDK, so the same logic works in Python, Node or plain HTTP.

A few facts about the service apply to everything below. The base URL is https://api.qwennsfw.top/v1, the model ID is uncensored, and the key goes in an Authorization: Bearer header. The model is an open-weight model run by an independent provider. It is not the official API of any vendor. If you do not have a key yet, the API key page explains the steps, and the docs cover the basic request format.

Define a tool and send the first request

A tool is a name, a description and a JSON Schema for the arguments. The description matters more than people expect, because it is the only thing the model reads when it decides whether to call the function. Write it as an instruction to a colleague: what the function does, when to use it and what the arguments mean.

The example below uses a dice roller, which is a typical helper in tabletop and fiction tools where you want real randomness instead of numbers the model invents.

from openai import OpenAI

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

tools = [{
    "type": "function",
    "function": {
        "name": "roll_dice",
        "description": "Roll dice for a game scene and return each roll and the total. "
                       "Use it whenever the story needs a random outcome.",
        "parameters": {
            "type": "object",
            "properties": {
                "count": {"type": "integer", "description": "How many dice to roll"},
                "sides": {"type": "integer", "description": "Number of sides per die"}
            },
            "required": ["count", "sides"]
        }
    }
}]

messages = [{"role": "user", "content": "Roll three six-sided dice for the duel."}]

resp = client.chat.completions.create(
    model="uncensored",
    messages=messages,
    tools=tools,
)
print(resp.choices[0].message.tool_calls)

When the model decides to call the function, content may be empty and tool_calls holds a list. Each entry has an id, the function name and an arguments string. That string is JSON text, not a parsed object, so you have to call json.loads on it yourself.

Run the call and return the result

The second half of the exchange is where most first attempts go wrong. The assistant message that contains the tool calls has to stay in the history, and every result must carry the matching tool_call_id. If you drop the assistant message or mix up the ids, the next request either fails or the model loses track of what it asked for.

A small loop handles this and also copes with the model chaining several calls in a row. The cap of five rounds is a guard against a loop that never ends.

import json
import random
from openai import OpenAI

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

def roll_dice(count, sides):
    rolls = [random.randint(1, sides) for _ in range(count)]
    return {"rolls": rolls, "total": sum(rolls)}

registry = {"roll_dice": roll_dice}

def run(messages, tools):
    for _ in range(5):
        resp = client.chat.completions.create(
            model="uncensored", messages=messages, tools=tools
        )
        msg = resp.choices[0].message
        messages.append(msg)
        if not msg.tool_calls:
            return msg.content
        for call in msg.tool_calls:
            try:
                args = json.loads(call.function.arguments)
                result = registry[call.function.name](**args)
            except Exception as exc:
                result = {"error": str(exc)}
            messages.append({
                "role": "tool",
                "tool_call_id": call.id,
                "content": json.dumps(result),
            })
    return None

Notice that errors are sent back to the model as a tool result instead of raising. A model that sees {"error": "sides must be positive"} will often correct its own arguments on the next round, which is cheaper than failing the whole job. Requests that fail or are refused are not charged, so a retry costs nothing extra on the failed attempt.

Streaming tool calls

With stream: true the endpoint sends server-sent events, and tool calls arrive as fragments. The first fragment for a call carries its id and function name. Later fragments carry slices of the arguments string. Each fragment has an index, which is how you tell parallel calls apart. You cannot parse the JSON until the stream ends, so buffer the pieces.

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 last chunk carries usage and no choices
    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": "", "arguments": ""})
        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["arguments"] += tc.function.arguments

Usage is reported at the end of the stream, which is why the loop skips chunks without choices. One operational detail: a streamed request holds its concurrency slot until the stream finishes. A full key allows 8 requests at once and a trial key allows 2, so if you start many streams and never read them to the end, you will see HTTP 429 responses with the error code concurrency.

Control when tools are used with tool_choice

By default the model decides. You can narrow that with tool_choice. The usual values are:

  • "auto": the model may answer directly or call a tool. This is the default when tools are present.
  • "none": the model answers in text only. Use it on the final round when you already have all the data.
  • A named function, written as {"type": "function", "function": {"name": "roll_dice"}}: the model is pushed to call that function. This is handy for extraction jobs where the function schema is really an output schema.

The named form turns function calling into a structured-output tool. You define a function called save_character with the fields you want, force it, and read the arguments. You never execute anything. For short, flat structures that works well, but if you only need a JSON object, the next section is simpler.

JSON mode when you do not need a function

JSON mode is the lighter option. Set response_format to {"type": "json_object"} and the reply is a JSON object. Still describe the keys in your prompt, because the setting guarantees syntax, not your particular schema.

curl https://api.qwennsfw.top/v1/chat/completions \
  -H "Authorization: Bearer YOUR_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "uncensored",
    "messages": [
      {"role": "system", "content": "Reply with a JSON object with keys name, mood and hook."},
      {"role": "user", "content": "Invent a tavern keeper for a fantasy roleplay."}
    ],
    "response_format": {"type": "json_object"}
  }'

Choose tools when the model must trigger outside actions or when several steps depend on each other. Choose JSON mode when you only want the model to fill a form. For a comparison of how the same request costs out per token, see the pricing page.

Pitfalls and how to fix them

Arguments that do not parse

Treat arguments as untrusted text. Wrap json.loads in a try block, return the error as the tool result, and let the model retry. Setting a lower temperature such as 0.2 makes the argument text more stable, and the seed parameter is passed through if you want repeatable tests.

Tools the model should not have called

Models sometimes call a function when a plain answer would do, especially when the description is vague. Tighten the wording in the description, add a sentence about when not to use the tool, or set tool_choice to "none" for turns where no action is needed.

Wrong or invented function names

Look the name up in a dictionary and handle a miss. Never call eval or build a function name from model output.

Parallel calls

The model may return several entries in one message. Answer all of them, each with its own tool_call_id, before the next request. Missing one is the most common cause of confusing follow-up behavior.

Context growth

Every round adds the tool schema, the assistant message and the results to the prompt. The window is 100,000 tokens for prompt plus completion, which is generous, but large tool outputs eat into it fast. Trim results before you append them. Input costs $0.15 per 1M tokens, so a 2,000-token tool result added to every round is cheap per call, but it adds up over thousands of runs.

Rate limits

Agent loops make bursts of calls. A full key allows 300 requests per minute and 8 at once, a trial key 60 and 2. Over the limit you get HTTP 429, and the error code tells you which one you hit: rate_limited or concurrency. On temporary overload a 429 comes with Retry-After: 5, so wait that long before retrying.

The model itself comes with the usual caveat for open-weight models: tool calling quality depends on clear schemas, so keep descriptions short and the argument list small. For background on what kind of model sits behind the endpoint, read the explainer on uncensored Qwen for developers.

Questions and answers

Does this API support the old function_call parameter?

The documented interface is tools and tool_choice, and the examples above use only those. If your code uses the legacy functions and function_call names, convert it to the tools format.

Can the model call several functions in one reply?

Yes, a reply can contain several entries in tool_calls. Run each one and send back one tool message per call, each with the matching tool_call_id.

Do I have to use tools to get JSON back?

No. Set response_format to {"type": "json_object"} and describe the keys in your prompt. Use tools when the model should trigger actions in your code.

Is a failed tool-calling request billed?

Failed or refused requests are not charged. Successful ones are billed at $0.15 per 1M input tokens and $0.50 per 1M output tokens.

Your key is one form away

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

Get API key