Qwen API Function Call: Tool Use Walkthrough With Code
A qwen api function call follows the OpenAI tools format: you describe your functions, the model replies with the one it wants and its arguments, and you send the result back. This walkthrough shows the full loop in Python, Node and curl against an OpenAI-compatible endpoint.
Updated

Key points
- Send a tools array, read tool_calls from the reply, run the function yourself, then return the output as a role tool message.
- Streaming works: tool_calls arrive as deltas that you stitch together by index.
- Arguments come back as a string. Parse and validate them before you act on them.
- A request that is being streamed holds its concurrency slot until the stream ends.
How the tool-use loop works
The model never runs your code. When you pass a list of tools, it can answer with a structured request instead of plain text: "call this function with these arguments." Your program runs the function, adds the output to the conversation, and asks again. The model then writes the final answer using that output. That is a qwen api function call in practice, and it is the same pattern as in the OpenAI Chat Completions API, so existing client code carries over.
The endpoint here is OpenAI-compatible. You change the base URL to https://api.qwenapi.cc/v1, use your key as a bearer token, and set the model to uncensored. The request goes to POST /v1/chat/completions. Tool calling is supported with tools, tool_choice, streamed tool_calls and results sent back as role: "tool" messages. This is an independent host running one open-weight model, not the vendor's own API, so test your prompts rather than assuming behavior from another service.
The loop has four steps:
- Send the user message together with the
toolsarray. - Check whether the reply has
tool_calls. If not, you already have the answer. - For each call, parse the arguments, run the matching function, and append a
toolmessage with the matchingtool_call_id. - Call the API again with the extended message list and read the final text.
Need a key first? The API key page has a one-click $0.50 trial for new users.
Define a tool and make the first request
A tool is a name, a plain-language description and a JSON Schema for its parameters. The description matters more than people expect, because it is the only thing the model reads when deciding whether to call the function. Say what the function does, when to use it, and what the arguments mean.
from openai import OpenAI
client = OpenAI(
base_url="https://api.qwenapi.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 ID. Use when the user asks where an order is.",
"parameters": {
"type": "object",
"properties": {
"order_id": {"type": "string", "description": "Order ID such as A-1042"}
},
"required": ["order_id"],
},
},
}]
messages = [{"role": "user", "content": "Where is order A-1042?"}]
resp = client.chat.completions.create(
model="uncensored",
messages=messages,
tools=tools,
tool_choice="auto",
)
msg = resp.choices[0].message
print(resp.choices[0].finish_reason)
print(msg.tool_calls)
When the model decides to use the tool, finish_reason is tool_calls and msg.tool_calls holds a list. Each item has an id, a function name and an arguments string such as {"order_id": "A-1042"}. If the model decides it can answer without the tool, tool_calls is empty and msg.content has text.
Run the function and send the result back
Now finish the loop. Append the assistant message exactly as it came back, including its tool calls, then one tool message per call. The tool_call_id links each result to its request.
import json
def get_order_status(order_id):
return {"order_id": order_id, "status": "shipped", "eta_days": 2}
registry = {"get_order_status": get_order_status}
if msg.tool_calls:
messages.append({
"role": "assistant",
"content": msg.content,
"tool_calls": [
{
"id": tc.id,
"type": "function",
"function": {"name": tc.function.name, "arguments": tc.function.arguments},
}
for tc in msg.tool_calls
],
})
for tc in msg.tool_calls:
try:
args = json.loads(tc.function.arguments)
result = registry[tc.function.name](**args)
except Exception as exc:
result = {"error": str(exc)}
messages.append({
"role": "tool",
"tool_call_id": tc.id,
"content": json.dumps(result),
})
final = client.chat.completions.create(
model="uncensored",
messages=messages,
tools=tools,
)
print(final.choices[0].message.content)
Two details deserve attention. First, the result goes back as a string, so serialize it with json.dumps. Second, the error branch returns a structured error instead of crashing. The model can read that message and either correct its arguments or explain the problem to the user, which beats a stack trace in your logs and a silent failure for the user.
Keep the tools array on the follow-up request too. Some apps need more than one round, for example a lookup followed by an update, and the model can only ask for another call if the tools are still listed. Put a hard cap on rounds, such as five, so a confused loop cannot run forever.
The same call in Node and curl
The request body is identical in every language, so use whichever client you already have. This is the Node version with the official openai package, using ES modules.
import OpenAI from "openai";
const client = new OpenAI({
baseURL: "https://api.qwenapi.cc/v1",
apiKey: process.env.API_KEY,
});
const tools = [{
type: "function",
function: {
name: "get_order_status",
description: "Look up the shipping status of an order by its ID.",
parameters: {
type: "object",
properties: { order_id: { type: "string" } },
required: ["order_id"],
},
},
}];
const resp = await client.chat.completions.create({
model: "uncensored",
messages: [{ role: "user", content: "Where is order A-1042?" }],
tools,
});
console.log(resp.choices[0].message.tool_calls);
And the raw HTTP request, handy for checking behavior without any SDK in the way:
curl https://api.qwenapi.cc/v1/chat/completions -H "Authorization: Bearer $API_KEY" -H "Content-Type: application/json" -d '{
"model": "uncensored",
"messages": [{"role": "user", "content": "Where is order A-1042?"}],
"tools": [{
"type": "function",
"function": {
"name": "get_order_status",
"description": "Look up the shipping status of an order by its ID.",
"parameters": {
"type": "object",
"properties": {"order_id": {"type": "string"}},
"required": ["order_id"]
}
}
}]
}'
The response headers include X-Request-Id, which you should log. If something odd happens, that ID is what you send to support so the request can be found.
Controlling when the model calls a tool
The tool_choice field sets the policy. With "auto" the model decides. With "none" it answers in text and ignores the tools, which is useful on the last round of a loop. To force a specific function, pass an object naming it:
{"tool_choice": {"type": "function", "function": {"name": "get_order_status"}}}
Forcing a call is a good way to extract structured data from free text. You define a function whose parameters match the shape you want, force it, and read the arguments as your result. You never run anything; the schema does the work. If you only need a JSON object and no function at all, JSON mode is lighter.
JSON mode instead of a tool
Set response_format to {"type": "json_object"} and ask for JSON in your instructions. The reply is a JSON string in message.content. Pick tools when the model should choose between several actions. Pick JSON mode when there is one output shape and no action to take. In both cases, parse the result inside a try block, because a model can still produce something that your own validation rejects.
A practical rule for schemas: keep them small. Three or four parameters with clear names and short descriptions give better results than a sprawling object with twenty optional fields. Use enums for fixed choices, mark only the truly required fields as required, and give every string a one-line hint with an example value. If you have a dozen tools, consider splitting them by task and sending only the ones relevant to the current screen or step, which also saves input tokens on every request.
Test with awkward inputs on purpose. Ask for an order that does not exist, leave out a required detail, or phrase the request in a way that suggests no tool is needed. How the model behaves in those cases tells you more about your tool descriptions than a clean happy-path demo does.
Streaming tool calls
With stream: true the reply arrives over server-sent events. Text comes in delta.content. Tool calls come in delta.tool_calls in small fragments: the first fragment for a call carries its id and function name, and later ones carry pieces of the arguments string. Each fragment has an index, and you join them by that index. Do not try to parse the arguments until the stream finishes, because half a JSON string is not JSON.
stream = client.chat.completions.create(
model="uncensored",
messages=messages,
tools=tools,
stream=True,
)
calls = {}
text = ""
for chunk in stream:
if not chunk.choices:
continue
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
for index in sorted(calls):
print(index, calls[index])
The final chunk carries usage, with an empty choices list, which is why the loop skips chunks that have no choices. Remember that a streaming request occupies one of your concurrency slots until the stream ends. A full key allows 8 at once, so a client that opens streams and forgets to close them will start getting concurrency errors.
Pitfalls and how to fix them
- Arguments are a string, not an object. Always run
json.loadsand handle failure. If parsing fails, return an error as the tool result so the model can retry. - Several calls in one reply. The model may request more than one function at once. Answer every
tool_call_id, or the next request will be malformed. - Vague descriptions. If the model calls the wrong function, rewrite the description with the exact situations in which it applies. Adding a second, sharply different function can also help.
- Randomness. For structured work, lower
temperature. Parameters such astemperature,top_p,stopandseedare passed through. - Rate limits. A full key allows 8 concurrent requests and 300 per minute. Over the limit you get HTTP 429 with
rate_limitedorconcurrencyas the error code. On temporary overload you also get 429 with aRetry-After: 5header. Wait that long and retry. - Growing context. Every tool result stays in the message list. Return only the fields the model needs, not a whole database row.
What it costs
A tool round trip is two requests. Say the first has 1,500 input tokens and 100 output tokens, and the second, which carries the tool result, has 1,700 input and 200 output. Total input is 3,200 tokens at $0.15 per 1M, which is $0.00048. Total output is 300 tokens at $0.50 per 1M, which is $0.00015. The round trip costs $0.00063. Failed or refused requests are not charged. The pricing page lists the rates and top-up bonuses, and the docs cover the rest of the API surface.
More guides
Questions and answers
Your key is one form away
Create an account, copy the key, change the base URL. That is the whole setup.
Does this API support parallel tool calls?
- The reply can contain several entries in tool_calls. Run each one and send back one tool message per tool_call_id before making the next request.
What model ID do I use?
- Set the model field to "uncensored" on every request. You can list it with GET /v1/models.
Can I stream a reply that includes tool calls?
- Yes. Set stream to true, collect the delta.tool_calls fragments by index, and parse the joined arguments after the stream ends.
Is tool calling the same as JSON mode?
- No. Tool calling lets the model pick a function and fill its arguments. JSON mode only forces the reply into a JSON object.
Is this the official Qwen API?
- No. It is an independent OpenAI-compatible host running one open-weight model, so you change only the base URL and key in your existing OpenAI client code.