Why the OpenAI SDK covers what you need
When people search for a qwen api sdk, they usually want a client library that handles auth, retries, streaming and typed responses. The OpenAI SDKs already do all of that, and this service implements the same HTTP interface: POST /v1/chat/completions, POST /v1/responses and GET /v1/models. Any client that lets you override the base URL can talk to it.
One clarification before you start. This is not the official API of Alibaba or of any other model vendor, and it is not a router that forwards your request elsewhere. It is one open-weight model, run by an independent provider and tuned to answer without content refusals for lawful adult use. The only model ID you pass is uncensored.
That makes migration simple. If your project already calls a hosted chat model through the OpenAI SDK, you change three values: the base URL, the API key and the model name. Nothing else in your code has to move.
Install and make the first call
Install the official package for Python or Node. There is nothing service-specific to add.
pip install openai
# Node: npm install openai
Create a key on the API key page, then export it so it never lands in your source code.
export API_KEY="paste-your-key-here"
Now the smallest useful Python script. The client reads the key from the environment and sends requests to the service instead of to OpenAI.
import os
from openai import OpenAI
client = OpenAI(
base_url="https://api.uncensoredqwen.com/v1",
api_key=os.environ["API_KEY"],
)
resp = client.chat.completions.create(
model="uncensored",
messages=[
{"role": "system", "content": "You are a concise technical assistant."},
{"role": "user", "content": "Explain what a context window is in two sentences."},
],
temperature=0.7,
)
print(resp.choices[0].message.content)
print(resp.usage)
If you prefer raw HTTP, the same request in curl looks like this:
curl https://api.uncensoredqwen.com/v1/chat/completions \
-H "Authorization: Bearer $API_KEY" \
-H "Content-Type: application/json" \
-d '{"model":"uncensored","messages":[{"role":"user","content":"Say hello."}]}'Streaming replies with the SDK
Set stream=True and iterate over the chunks. The service sends server-sent events and reports token usage at the end of the stream, so you can log cost without a second call.
import os
from openai import OpenAI
client = OpenAI(base_url="https://api.uncensoredqwen.com/v1",
api_key=os.environ["API_KEY"])
stream = client.chat.completions.create(
model="uncensored",
messages=[{"role": "user", "content": "Write a short product description for a desk lamp."}],
stream=True,
stream_options={"include_usage": True},
)
for chunk in stream:
if chunk.choices and chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="", flush=True)
if getattr(chunk, "usage", None):
print("\nTokens:", chunk.usage.prompt_tokens, chunk.usage.completion_tokens)
Keep one thing in mind: a streamed request holds its concurrency slot until the stream ends. If a consumer is slow or you forget to close the stream, you will hit the concurrency limit sooner than you expect.
The same pattern in Node:
import OpenAI from "openai";
const client = new OpenAI({
baseURL: "https://api.uncensoredqwen.com/v1",
apiKey: process.env.API_KEY,
});
const stream = await client.chat.completions.create({
model: "uncensored",
messages: [{ role: "user", content: "Name three uses of JSON mode." }],
stream: true,
});
for await (const chunk of stream) {
process.stdout.write(chunk.choices[0]?.delta?.content ?? "");
}Tool calling and JSON mode
The SDK parameters you already use for tools pass straight through: tools, tool_choice, streamed tool_calls, and results sent back as messages with role: "tool". A minimal round trip looks like this:
import os, json
from openai import OpenAI
client = OpenAI(base_url="https://api.uncensoredqwen.com/v1",
api_key=os.environ["API_KEY"])
tools = [{
"type": "function",
"function": {
"name": "get_order_status",
"description": "Look up an order by id",
"parameters": {
"type": "object",
"properties": {"order_id": {"type": "string"}},
"required": ["order_id"],
},
},
}]
messages = [{"role": "user", "content": "Where is order A-1042?"}]
first = client.chat.completions.create(model="uncensored", messages=messages, tools=tools)
call = first.choices[0].message.tool_calls[0]
messages.append(first.choices[0].message)
messages.append({
"role": "tool",
"tool_call_id": call.id,
"content": json.dumps({"status": "shipped"}),
})
final = client.chat.completions.create(model="uncensored", messages=messages, tools=tools)
print(final.choices[0].message.content)
For structured output, pass response_format={"type": "json_object"} and also say "reply in JSON" in the prompt. JSON mode asks the model for JSON output, but your code should still parse it and validate field names and types before using them.
Sampling settings such as temperature, top_p, stop, seed and the penalties are passed through, so existing tuning carries over.
Handle 429 errors and read the headers
The SDK raises a rate-limit exception on HTTP 429, and the response body tells you which limit you hit. A full key allows 8 concurrent requests and 300 requests per minute. A trial key allows 2 concurrent requests and 60 per minute.
| Error code | Meaning | What to do |
|---|---|---|
rate_limited | Too many requests per minute | Spread calls out or add a client-side limiter |
concurrency | Too many requests at once | Cap your worker pool at 8 (2 on a trial key) |
429 with Retry-After: 5 | Temporary overload | Wait 5 seconds and retry |
Every response carries X-Request-Id, X-Balance-USD, X-RateLimit-Limit-Requests and X-RateLimit-Limit-Concurrency. To read them with the Python SDK, use the raw-response wrapper:
import os
from openai import OpenAI
client = OpenAI(base_url="https://api.uncensoredqwen.com/v1",
api_key=os.environ["API_KEY"])
raw = client.chat.completions.with_raw_response.create(
model="uncensored",
messages=[{"role": "user", "content": "ping"}],
max_tokens=5,
)
print("Balance:", raw.headers.get("X-Balance-USD"))
print("Request id:", raw.headers.get("X-Request-Id"))
completion = raw.parse()
Failed or refused requests are not charged, so a retry after a 429 does not cost you twice. The existing article on common Qwen API mistakes covers more of the setup errors people hit.
What a call costs
Pricing is $0.15 per 1M input tokens and $0.50 per 1M output tokens, paid from prepaid credit. Take a request with 2,000 prompt tokens and 500 completion tokens:
- Input: 2,000 x $0.15 / 1,000,000 = $0.0003
- Output: 500 x $0.50 / 1,000,000 = $0.00025
- Total: $0.00055
The $0.50 trial credit covers about 900 requests of that size ($0.50 / $0.00055 is roughly 909). The trial is one click on the key page after sign-up, needs no card and lasts 7 days; the free tier article explains how it works. Paid top-ups start at $20, and the pricing page lists the bonus tiers and accepted payment methods.
Context is 100,000 tokens for prompt plus completion together, and max_tokens is optional. Setting it is still a good habit when you want a predictable upper bound on cost.
Moving an existing project over
Most readers arrive with code that already calls a chat model. A short checklist keeps the switch uneventful:
- Change
base_url(orbaseURLin Node) tohttps://api.uncensoredqwen.com/v1. Keep the/v1suffix and do not add/chat/completionsyourself, because the SDK appends the path. - Replace the key with the one from your account. Authentication is a standard
Authorization: Bearerheader, which the SDK builds for you. - Replace the model name with
uncensored. Requests with an unknown model name will fail, so search your codebase for hard-coded names. - Remove any request fields for features the service does not offer, such as image inputs or embeddings calls.
- Run a call to
GET /v1/modelsas a smoke test. If it lists the model, your URL and key are correct.
Frameworks that wrap the OpenAI client usually expose the same two settings under names like openai_api_base or OPENAI_BASE_URL. If your tool offers an environment variable for the base URL, you can switch a whole application without touching its source. Test with a trial key first, since its lower limits of 2 concurrent requests and 60 per minute will show quickly whether your app opens more parallel connections than you planned.
Context handling deserves a second look too. The window here is 100,000 tokens shared by prompt and completion. If your old setup trimmed history to a different size, you can relax or tighten that trimming to match, but keep an eye on the cost of resending a long history on every turn.
Practical tips for production code
- Keep the key out of the repo. Read it from an environment variable or a secret store, as in the examples above.
- Set a timeout. The SDK accepts a
timeoutargument on the client. Long generations with streaming need a generous read timeout. - Bound your workers. A thread pool or semaphore sized to your concurrency limit avoids most 429 errors before they happen.
- Log the request id. If you contact support, the value from
X-Request-Ididentifies the call. - Watch the balance. Read
X-Balance-USDfrom responses, or callGET /v1/balance, so a batch job stops before credit runs out.
The model is text only. There is no image, audio or video generation, no embeddings and no fine-tuning, so do not plan around those SDK methods. Full parameter details live in the documentation. Prompts are not used for training.
