EN ▾

Uncensored Qwen API for developers

  1. qwenuncensored.top
  2. Qwen Agent Function Call on an OpenAI-Compatible API

Qwen Agent Function Call on an OpenAI-Compatible API

A qwen agent function call is a normal OpenAI-style tool call: you describe functions, the model asks for one, your code runs it and sends the result back. This article shows the full loop against our endpoint, plus the failure cases that bite in practice.

Updated

Isometric illustration of an agent loop passing data between a model and several tools

Key points

  • Tool calling uses the standard tools, tool_choice and role tool fields, so existing OpenAI-style agent code needs only a new base URL and key.
  • Your code executes the function. The model only proposes a name and JSON arguments, so validate them before you act.
  • Cap the number of loop steps, and handle HTTP 429 with a short backoff.
  • A five-step agent run with 3,000 input tokens per step costs about $0.003.

What a function call actually is

The phrase comes from the way people use Qwen-Agent, the open-source agent framework published by the Qwen team, and from the Qwen model cards that show tool use. Underneath, the mechanism is the one OpenAI popularised. You send a list of function definitions with the chat request. The model either answers in text or returns a message with a tool_calls array. Each entry holds a call ID, a function name and a string of JSON arguments. Nothing is executed on the server. Your program runs the function, appends the result as a message with role: "tool", and calls the API again so the model can use the result.

That design is why the same client code works on many back ends. Our endpoint follows it: POST /v1/chat/completions accepts tools and tool_choice, returns tool_calls in the response (or streamed in deltas), and expects results as role: "tool" messages. The model ID is uncensored. It is a single open-weight model run by an independent provider, so this is not the official Qwen API and not a router across vendors. If you read a tutorial that names a specific Qwen model, change the model string and nothing else.

Check how well the model picks tools on your own tasks before you commit to it. Tool selection quality depends on the model and on how clear your descriptions are, and no tutorial can promise it for you. The loop below gives you a cheap way to find out.

A minimal tool-calling loop in Python

Install the standard SDK with pip install openai. The client is created with our base URL and your key. The example gives the model one function, a currency formatter, which is deliberately boring: the interesting part is the loop, not the tool.

import json
from openai import OpenAI

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

def format_money(amount: float, currency: str) -> str:
    return f"{amount:,.2f} {currency.upper()}"

TOOLS = [{
    "type": "function",
    "function": {
        "name": "format_money",
        "description": "Format a number as a money string for an invoice line.",
        "parameters": {
            "type": "object",
            "properties": {
                "amount": {"type": "number"},
                "currency": {"type": "string", "description": "ISO code, e.g. EUR"},
            },
            "required": ["amount", "currency"],
        },
    },
}]
REGISTRY = {"format_money": format_money}

messages = [{"role": "user", "content": "Write the invoice line for 1234.5 euros."}]

for step in range(6):                      # hard cap on loop length
    resp = client.chat.completions.create(
        model="uncensored", messages=messages, tools=TOOLS, tool_choice="auto"
    )
    msg = resp.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)
            result = REGISTRY[call.function.name](**args)
        except Exception as exc:           # bad JSON, unknown tool, bad args
            result = f"error: {exc}"
        messages.append({
            "role": "tool",
            "tool_call_id": call.id,
            "content": str(result),
        })
else:
    print("stopped: step limit reached")

Three details matter here. First, the assistant message that contains tool_calls goes back into the history before the tool results, or the next request is malformed. Second, every result carries the tool_call_id of the call it answers. Third, errors are returned to the model as text instead of crashing the run. A model that sees error: missing required argument will often correct itself on the next step.

The same call from Node and curl

If your agent lives in a TypeScript service, the official openai package takes the same two settings.

import OpenAI from "openai";

const client = new OpenAI({ baseURL: "https://api.qwenuncensored.top/v1", apiKey: process.env.API_KEY });

const res = await client.chat.completions.create({
  model: "uncensored",
  messages: [{ role: "user", content: "What is 17% of 2400? Use the tool." }],
  tools: [{
    type: "function",
    function: {
      name: "percent_of",
      description: "Compute a percentage of a number.",
      parameters: {
        type: "object",
        properties: { pct: { type: "number" }, base: { type: "number" } },
        required: ["pct", "base"],
      },
    },
  }],
  tool_choice: "auto",
});

console.log(JSON.stringify(res.choices[0].message.tool_calls, null, 2));

For a quick check from a shell, curl is enough. This is useful when you want to see the raw JSON that your framework is hiding.

curl https://api.qwenuncensored.top/v1/chat/completions \
  -H "Authorization: Bearer $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "uncensored",
    "messages": [{"role": "user", "content": "Convert 5 km to miles with the tool."}],
    "tools": [{"type": "function", "function": {
      "name": "convert_units",
      "description": "Convert a value between units.",
      "parameters": {"type": "object",
        "properties": {"value": {"type": "number"}, "from": {"type": "string"}, "to": {"type": "string"}},
        "required": ["value", "from", "to"]}}}]
  }' 

The response header X-Balance-USD shows your remaining credit after each call, which makes it easy to log what an agent run really cost.

Using Qwen-Agent itself

Qwen-Agent can talk to any server that speaks the OpenAI chat format, because its model config accepts a server URL and a key. The shape is a dictionary with the model name, model_server and api_key. Point model_server at https://api.qwenuncensored.top/v1, set the model to uncensored, and register your tools the way the framework documents. Check the project's current README for the exact class and field names, since they have changed between releases.

Two cautions apply. Frameworks sometimes add their own prompt templates for function calling, tuned to the model family they were written for. If tool calls look odd, try the raw loop above first. It removes one layer and tells you whether the problem is the model or the wrapper. Also, a framework may default to parallel tool calls or long reasoning prefixes that raise token use. Look at the usage numbers in a few real runs before you scale up.

Streaming tool calls

With stream: true the arguments arrive in pieces. Each chunk's delta.tool_calls entry has an index, and only the first chunk for an index carries the ID and function name. Later chunks add fragments of the arguments string. You must concatenate 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,
    stream_options={"include_usage": True},
)
for chunk in stream:
    if not chunk.choices:
        if chunk.usage:
            print("tokens:", chunk.usage.prompt_tokens, chunk.usage.completion_tokens)
        continue
    for tc in chunk.choices[0].delta.tool_calls or []:
        slot = calls.setdefault(tc.index, {"id": "", "name": "", "args": ""})
        slot["id"] = tc.id or slot["id"]
        if tc.function:
            slot["name"] = tc.function.name or slot["name"]
            slot["args"] += tc.function.arguments or ""

Streaming is optional for agents that run in the background, but it helps when a person watches the run. One rule affects capacity planning: a streamed request holds its concurrency slot until the stream ends. A full key allows 8 requests at once, so an agent that opens a stream and then waits on a slow tool before reading the end of it can starve its own siblings. Finish reading the stream first, then run the tool.

JSON mode for structured steps

Not every step needs a tool. When an agent step should produce a plan, a classification or a record, JSON mode is simpler: set response_format to {"type": "json_object"} and say in the prompt which keys you expect. The API passes the setting through, but it does not know your schema, so validate the result with your own code and retry once on failure.

resp = client.chat.completions.create(
    model="uncensored",
    response_format={"type": "json_object"},
    messages=[
        {"role": "system", "content": "Reply with JSON: {\"next_action\": str, \"reason\": str}"},
        {"role": "user", "content": "The build failed on a missing env var. What now?"},
    ],
    temperature=0.2,
)
plan = json.loads(resp.choices[0].message.content)

A reasonable pattern is a planner step in JSON mode followed by executor steps that use tools. Low temperature, between 0 and 0.3, keeps the planner steady. The seed parameter is passed through if you want repeatable test runs, though treat repeatability as a debugging aid and not as a guarantee.

Limits, retries and what a run costs

A full key allows 8 concurrent requests and 300 requests per minute. A trial key allows 2 concurrent and 60 per minute. When you exceed the per-minute cap the API returns HTTP 429 with the error code rate_limited. Too many simultaneous calls give a 429 with concurrency. Temporary overload also returns 429, with a Retry-After: 5 header. The handling is the same in every case: wait, then retry, and give up after a few attempts.

import time
from openai import RateLimitError

def call(**kw):
    for attempt in range(4):
        try:
            return client.chat.completions.create(**kw)
        except RateLimitError as exc:
            wait = 5 if attempt == 0 else 2 ** attempt
            retry_after = getattr(exc.response, "headers", {}).get("Retry-After")
            time.sleep(int(retry_after) if retry_after else wait)
    raise RuntimeError("still rate limited after 4 tries")

Now the money. Pricing is $0.15 per 1M input tokens and $0.50 per 1M output tokens. Say an agent run takes five steps, and because the history is re-sent each time, each step has about 3,000 input tokens and 300 output tokens. Input is 15,000 tokens, which costs 15,000 / 1,000,000 x $0.15 = $0.00225. Output is 1,500 tokens, which costs 1,500 / 1,000,000 x $0.50 = $0.00075. The run costs $0.003. A thousand such runs cost $3.00. Failed or refused requests are not charged, and the credit never expires. The full table is on the pricing page.

Context is generous at 100,000 tokens, prompt plus completion, with a request body limit of 8 MB. That is enough for long tool outputs, but pasting a whole log file into every step is how a $0.003 run becomes a $0.05 run. Truncate tool results to what the model needs.

Pitfalls that cost an afternoon

  • Unbounded loops. Always cap steps, as the range(6) above does. A model that keeps calling the same tool with the same arguments will otherwise run until your balance says stop.
  • Trusting arguments. The arguments are model output. Validate types and ranges, and never pass them to a shell or a SQL string without checks.
  • Vague descriptions. Two tools with similar descriptions confuse selection. Name the difference in the description text, and state units and formats.
  • Too many tools. Start with three or four. Add more only when a test case fails for lack of one.
  • Dropping history. If you trim messages to save tokens, keep each tool call paired with its result. An orphaned result is rejected or ignored by many servers.

The API docs list the supported parameters, and the Qwen 3 API page explains how this endpoint relates to the model family. To try the loop, take a key from the API key page. New accounts can claim $0.50 of trial credit with one click, valid for 7 days and with no card needed, which is enough for roughly 160 runs of the size computed above.

FAQs

Is this the official Qwen API?

No, we are an independent service. We host an open-weight variant of the model optimized for uncensored use. We are not affiliated with the original Qwen team or any other vendor. Check the official Qwen documentation for their specific models and pricing.

What is the max output length?

There is no separate output cap. If you do not set the max_tokens parameter, the response can run to the end of the window. The total context window, including the prompt, is 100,000 tokens.

How do I top up my account?

We accept top-ups by crypto (USDT on TRC20, USDC on Base). Minimum top-up is $20, maximum is $500. Bonuses apply at $50 (+5%), $100 (+10%), and $200 (+15%).

Are prompts used for training?

No. Your prompts are processed by our servers but are not used to train the model. Your data privacy is maintained, requiring only an email for account creation.

Questions and answers

Does the model run my function?

No. It returns the function name and JSON arguments. Your code runs the function and sends the result back as a message with role tool.

Can I force the model to call a specific tool?

Set tool_choice to an object naming the function, in the standard OpenAI format. Use "auto" to let the model decide, and test the forced form on your own prompts.

Does it work with the OpenAI Python and Node SDKs?

Yes. Set the base URL to https://api.qwenuncensored.top/v1, use your key, and set the model to uncensored.

What happens when I hit the rate limit?

You get HTTP 429 with the code rate_limited or concurrency. Wait a few seconds, honour Retry-After if present, and retry.

Your key is one form away

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

Get API key