Nanbeige API Python Setup With the OpenAI SDK
If you want a hosted chat API you can call from Python without learning a new client library, the OpenAI SDK already does the job. You change two settings and keep the rest of your code.
Updated

Key points
- Use the official openai package with base_url set to https://api.nanbeige.cc/v1 and model set to uncensored.
- Streaming, tool calling and JSON mode work through the normal SDK parameters.
- Handle 429 responses by reading the error code: rate_limited and concurrency need different fixes.
- This is not an official Nanbeige service, and it is text only.
The short version
For a nanbeige api python setup that talks to this service, you need the openai package, an API key and two values: the base URL https://api.nanbeige.cc/v1 and the model ID uncensored. Here is the whole thing in one block.
from openai import OpenAI
client = OpenAI(
base_url="https://api.nanbeige.cc/v1",
api_key="YOUR_API_KEY",
)
resp = client.chat.completions.create(
model="uncensored",
messages=[
{"role": "system", "content": "You are a direct, concise assistant."},
{"role": "user", "content": "Give me three names for a fantasy tavern."},
],
temperature=0.8,
)
print(resp.choices[0].message.content)
print(resp.usage)
A quick clarification before you copy it. This site is not the Nanbeige vendor's API and does not serve Nanbeige weights. It is an independent, OpenAI-compatible endpoint that runs one open-weight model tuned to answer without content refusals for lawful adult use. The code above works because the request and response shapes match the OpenAI format, not because of any tie to a particular model family.
Get a key and install the SDK
Sign up with Google, or with email and password, and open the API key page. New users can claim $0.50 of trial credit with one click there. It needs no card, is valid for 7 days and is limited to one per person. The page at get your API key shows the exact button.
Install the client with pip install openai. Any recent release of the SDK works, because the chat completions interface has been stable for a long time. A virtual environment keeps the dependency out of your system Python.
Do not hard-code the key. Read it from the environment so it never lands in version control:
import os
from openai import OpenAI
client = OpenAI(
base_url=os.environ.get("LLM_BASE_URL", "https://api.nanbeige.cc/v1"),
api_key=os.environ["LLM_API_KEY"],
)
MODEL = os.environ.get("LLM_MODEL", "uncensored")
Keeping the base URL and model in variables pays off later. If you ever point the same script at a local server or another provider, you change an environment variable instead of editing code.
Check the connection first
Before debugging your own logic, confirm the key and URL with a models call. This returns the list of available model IDs, which should include uncensored.
for m in client.models.list():
print(m.id) # base https://api.nanbeige.cc/v1, expect: uncensored
Streaming replies token by token
For chat interfaces and long outputs, stream the response so users see text as it is produced. The service sends server-sent events when you pass stream=True, and the SDK turns them into an iterator. If you also ask for usage, the final chunk reports token counts, which is handy for logging cost.
# client created as above, base_url https://api.nanbeige.cc/v1
stream = client.chat.completions.create(
model="uncensored",
messages=[{"role": "user", "content": "Write a short scene set on a night train."}],
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("\n", chunk.usage)
One detail matters for production code: a streamed request occupies its concurrency slot until the stream ends. If your code breaks out of the loop early, close the stream so the slot is released, either by exhausting it or by using it as a context manager (with stream:). Leaving half-read streams open is the classic way to hit the concurrency limit while sending very few requests.
Tool calling and JSON mode
Tool calling follows the OpenAI shape. You describe functions in tools, the model may answer with tool_calls, you run the function and return the result as a message with role: "tool". Here is a complete round trip.
# client created as above, base_url https://api.nanbeige.cc/v1
import json
tools = [{
"type": "function",
"function": {
"name": "get_order_status",
"description": "Look up an order by its numeric ID.",
"parameters": {
"type": "object",
"properties": {"order_id": {"type": "integer"}},
"required": ["order_id"],
},
},
}]
messages = [{"role": "user", "content": "Where is order 4417?"}]
first = client.chat.completions.create(
model="uncensored", messages=messages, tools=tools, tool_choice="auto"
)
msg = first.choices[0].message
if msg.tool_calls:
messages.append(msg)
for call in msg.tool_calls:
args = json.loads(call.function.arguments)
result = {"order_id": args["order_id"], "status": "shipped"} # your real lookup here
messages.append({
"role": "tool",
"tool_call_id": call.id,
"content": json.dumps(result),
})
final = client.chat.completions.create(model="uncensored", messages=messages, tools=tools)
print(final.choices[0].message.content)
Always parse arguments defensively. The model produces a JSON string, and like any model it can occasionally produce a malformed one, so wrap json.loads in a try block and send an error message back as the tool result if parsing fails.
JSON mode for structured output
When you need machine-readable output, set response_format to a JSON object and say in the prompt what shape you want. JSON mode asks for valid JSON; it does not enforce your schema, so validate the fields you depend on.
# client created as above, base_url https://api.nanbeige.cc/v1
resp = client.chat.completions.create(
model="uncensored",
messages=[
{"role": "system", "content": "Reply only with JSON: {\"title\": str, \"tags\": [str]}"},
{"role": "user", "content": "Describe a cozy detective novel set in a lighthouse."},
],
response_format={"type": "json_object"},
)
data = json.loads(resp.choices[0].message.content)
print(data["title"], data["tags"])
Sampling parameters and context size
The usual knobs are passed through: temperature, top_p, stop, seed and the frequency and presence penalties. For creative writing, a temperature around 0.8 to 1.0 with a modest top_p tends to give varied prose. For extraction or classification, drop the temperature close to zero and set a seed if you want repeatable runs.
The context window is 100,000 tokens, counted across prompt and completion together. max_tokens is optional; leave it out and the completion can use whatever room remains. Set it anyway when you know the answer should be short, because it protects you from a runaway response that costs more than expected. The request body is capped at 8 MB, which is rarely the binding limit but is worth knowing when you paste large documents.
The docs list every supported field. Only chat completions and the models listing exist, so code that calls image, audio or embeddings endpoints will fail here. Check for those calls if you are porting a larger project.
Handling 429 errors and concurrency
A full key allows 8 concurrent requests and 300 requests per minute. A trial key allows 2 concurrent and 60 per minute. Going over either gives HTTP 429, and the error code tells you which limit you hit: rate_limited means too many requests per minute, concurrency means too many at once. On temporary overload the API also returns 429 with a Retry-After: 5 header.
The OpenAI SDK retries a couple of times by default, but you should control the behavior yourself for batch jobs. This helper retries with the server's hint and caps parallelism with a semaphore so you stay under the concurrency limit in the first place.
import asyncio
from openai import AsyncOpenAI, RateLimitError
aclient = AsyncOpenAI(base_url="https://api.nanbeige.cc/v1", api_key="YOUR_API_KEY")
gate = asyncio.Semaphore(6) # stay under 8 concurrent
async def ask(prompt, tries=4):
async with gate:
for attempt in range(tries):
try:
r = await aclient.chat.completions.create(
model="uncensored",
messages=[{"role": "user", "content": prompt}],
)
return r.choices[0].message.content
except RateLimitError as e:
wait = 5 * (attempt + 1)
print("429, waiting", wait, "s:", e)
await asyncio.sleep(wait)
raise RuntimeError("gave up after retries")
async def main():
prompts = [f"Give one fun fact about the number {n}." for n in range(20)]
results = await asyncio.gather(*(ask(p) for p in prompts))
print(len(results), "done")
asyncio.run(main())
Setting the semaphore to 6 instead of 8 leaves headroom for retries and for anything else using the same key. Response headers help too: X-RateLimit-Limit-Requests and X-RateLimit-Limit-Concurrency show the limits for your key, X-Balance-USD shows remaining credit, and X-Request-Id identifies a call if you need to contact support.
Common mistakes and quick fixes
- 401 or an authentication error. The key is missing, has stray whitespace, or was copied with a trailing newline. Print its length and strip it.
- Model not found. The model ID must be exactly
uncensored. Names from other services will not work here. - Connection errors at the wrong host. The base URL ends in
/v1and has no trailing path. If you also set theOPENAI_BASE_URLenvironment variable, make sure it matches. - Empty or cut-off output. Check
finish_reason. A value oflengthmeans you hitmax_tokensor the context window. - Surprise cost. Print
resp.usageduring development. Input tokens cost $0.15 per 1M and output tokens $0.50 per 1M, so long outputs are the expensive part. The pricing page has the details.
Failed or refused requests are not charged, so a request that errors out costs nothing. Prompts are not used for training. If you run into behavior that looks wrong, save the request ID and the exact payload and send them to support; that gets a faster answer than a description from memory.
More guides
Questions and answers
Do I need a special Python library?
No. The official openai package works. Set base_url to https://api.nanbeige.cc/v1, pass your key, and use the model ID uncensored.
Is this the official Nanbeige API?
No. It is an independent OpenAI-compatible text API that runs a different open-weight model. It is not operated by Nanbeige or any other model vendor.
Does it support streaming and function calling from Python?
Yes. Pass stream=True for server-sent events with usage at the end, and use the tools and tool_choice parameters for tool calling. JSON mode is available through response_format.
What happens when I hit a rate limit?
You get HTTP 429 with the error code rate_limited or concurrency. Back off, and cap parallel requests at 8 for a full key or 2 for a trial key.
Can I call embeddings or image endpoints?
No. Only chat completions and the models listing exist. The service is text only.
Your key is one form away
Create an account, copy the key, change the base URL. That is the whole setup.