EN ▾
Get API key

Open Source LLM for Python: Call It With the OpenAI SDK

If you want an open source LLM for Python without buying a GPU, a hosted open-weight model behind an OpenAI-compatible endpoint is the shortest path. You install one package and change one URL.

Isometric illustration of a terminal sending data to a floating open cube, a Python app calling an open model

Key points

  1. The openai Python package works as is: set base_url to https://api.nanbeige.top/v1 and model to uncensored.
  2. Chat, streaming, JSON mode and tool calling all use the standard OpenAI call shapes.
  3. Limits are 8 concurrent requests and 300 per minute on a full key, so cap your async fan-out at 8.
  4. Pricing is $0.15 per 1M input tokens and $0.50 per 1M output tokens, prepaid.

Local weights or a hosted endpoint

When Python developers search for an open source LLM for Python, they usually mean one of two things. Either they want to download weights and run them with a library on their own machine, or they want a model whose weights are public but that someone else runs for them. Both are legitimate, and the right pick depends on your hardware and your patience.

Running locally gives you full control and no per-token bill, but a useful model needs a lot of memory, setup takes real time, and your laptop will be busy while it generates. A hosted endpoint trades that for a few lines of code and a small usage fee. The model behind this site is a single open-weight model run by an independent provider. It is tuned to answer without content refusals for lawful adult use, and it is not the official API of any model vendor.

The practical advantage for Python code is that the endpoint speaks the OpenAI chat-completions protocol. Anything you have written against the openai package, or against a framework that wraps it, keeps working. You can prototype against the hosted model today and swap the base URL later if you decide to host your own server with a compatible interface.

Setup in four steps

  1. Create a key. Sign up with Google, or with email and password, and open the API key page. New accounts can claim $0.50 of trial credit with one click, valid for 7 days, no card needed.
  2. Create a virtual environment. Run python -m venv .venv and activate it.
  3. Install the SDK. Run pip install openai.
  4. Keep the key out of source code. Export it as an environment variable, for example export NANBEIGE_API_KEY=... in your shell.

Then verify the connection with a minimal script:

import os
from openai import OpenAI

client = OpenAI(
    base_url="https://api.nanbeige.top/v1",
    api_key=os.environ["NANBEIGE_API_KEY"],
)

resp = client.chat.completions.create(
    model="uncensored",
    messages=[{"role": "user", "content": "Explain list comprehensions in two sentences."}],
)

print(resp.choices[0].message.content)
print(resp.usage)

If this prints text and a usage object, you are done with setup. The docs page has the same call in other languages if you need them.

Streaming responses

For anything interactive, stream tokens as they are produced. Set stream=True and iterate. The server sends Server-Sent Events, and the SDK turns them into chunks.

stream = client.chat.completions.create(
    model="uncensored",
    messages=[{"role": "user", "content": "Write a short scene set in a rainy train station."}],
    stream=True,
)

for chunk in stream:
    if chunk.choices and chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="", flush=True)
    if chunk.usage:
        print("\n", chunk.usage)

Usage is reported at the end of the stream. One detail matters for concurrency: a streamed request holds its slot until the stream finishes. If you open a stream and stop reading it without closing the connection, that slot stays busy. Use a with block or call stream.close() when you break out early.

JSON mode and tool calling

Two features turn a chat model into something a Python program can depend on: structured output and function calls.

JSON mode

Pass response_format and tell the model in the prompt which keys you expect. Always parse defensively.

import json

resp = client.chat.completions.create(
    model="uncensored",
    response_format={"type": "json_object"},
    messages=[
        {"role": "system", "content": "Reply with JSON only: {\"title\": str, \"tags\": [str]}"},
        {"role": "user", "content": "Summarize: a lighthouse keeper finds a message in a bottle."},
    ],
)
data = json.loads(resp.choices[0].message.content)
print(data["title"], data["tags"])

Tool calling

Describe your Python functions as tools, let the model choose, run the function yourself, then send the result back as a role: "tool" message.

tools = [{
    "type": "function",
    "function": {
        "name": "word_count",
        "description": "Count the words in a text",
        "parameters": {
            "type": "object",
            "properties": {"text": {"type": "string"}},
            "required": ["text"],
        },
    },
}]

messages = [{"role": "user", "content": "How many words are in: the quick brown fox?"}]
first = client.chat.completions.create(
    model="uncensored", messages=messages, tools=tools, tool_choice="auto"
)
call = first.choices[0].message.tool_calls[0]
args = json.loads(call.function.arguments)
result = len(args["text"].split())

messages.append(first.choices[0].message)
messages.append({"role": "tool", "tool_call_id": call.id, "content": str(result)})
final = client.chat.completions.create(model="uncensored", messages=messages, tools=tools)
print(final.choices[0].message.content)

The model may answer directly without calling a tool, so check that tool_calls is not empty before indexing into it in real code.

Running many requests with asyncio

Batch jobs are where a hosted model beats a local one, as long as you respect the limits. A full key allows 8 concurrent requests and 300 requests per minute. A trial key allows 2 concurrent and 60 per minute. The simplest way to stay inside the concurrency cap is a semaphore.

import asyncio, os
from openai import AsyncOpenAI

client = AsyncOpenAI(
    base_url="https://api.nanbeige.top/v1",
    api_key=os.environ["NANBEIGE_API_KEY"],
)
sem = asyncio.Semaphore(8)

async def summarize(text: str) -> str:
    async with sem:
        r = await client.chat.completions.create(
            model="uncensored",
            messages=[{"role": "user", "content": f"Summarize in one line: {text}"}],
            max_tokens=80,
        )
        return r.choices[0].message.content

async def main(items):
    return await asyncio.gather(*(summarize(t) for t in items))

results = asyncio.run(main(["first text", "second text", "third text"]))
print(results)

The semaphore handles the concurrency limit but not the per-minute limit. If you push 300 or more requests inside one minute, you will see HTTP 429 with the code rate_limited. Too many at once returns the code concurrency. Temporary overload also returns 429, with a Retry-After: 5 header.

Retries, errors and the usual mistakes

Wrap calls in a small retry that honors 429. The SDK raises openai.RateLimitError for it.

import time
from openai import OpenAI, RateLimitError

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

def ask(prompt: str, tries: int = 4) -> str:
    for attempt in range(tries):
        try:
            r = client.chat.completions.create(
                model="uncensored",
                messages=[{"role": "user", "content": prompt}],
            )
            return r.choices[0].message.content
        except RateLimitError:
            time.sleep(5 * (attempt + 1))
    raise RuntimeError("still rate limited")

Most failures in a first integration are configuration problems, not model problems:

  • Missing /v1 in the base URL. The base must be https://api.nanbeige.top/v1. The SDK appends /chat/completions itself.
  • Wrong model ID. Use uncensored exactly.
  • Key sent in the wrong place. The server expects Authorization: Bearer <key>, which the SDK builds from api_key.
  • Oversized body. The maximum request body is 8 MB. Trim or chunk long inputs.
  • Context overflow. The window is 100,000 tokens, prompt plus completion. A very long history leaves less room for the answer.

There is a longer checklist in the troubleshooting article if the quick fixes above do not solve it. Response headers such as X-Request-Id and X-Balance-USD are worth logging, since the request ID is what you quote if you contact support.

What it costs in a Python project

You pay $0.15 per 1M input tokens and $0.50 per 1M output tokens from prepaid credit. There is no subscription, credit never expires, and failed or refused requests are not charged. Here is a realistic batch job: 10,000 documents, each 1,500 tokens in and 300 tokens out.

  • Input: 10,000 x 1,500 = 15M tokens x $0.15 = $2.25
  • Output: 10,000 x 300 = 3M tokens x $0.50 = $1.50
  • Total: $3.75

The minimum top-up is $20, and you can add any whole amount up to $500, with a bonus of 5% from $50, 10% from $100 and 15% from $200. Pay with crypto (USDT, USDC). Details are on the pricing page. Prompts are not used for training, which matters if your Python code feeds in private text.

Keeping conversation history under control

A chat model has no memory between calls. Every request must carry the whole conversation, which means your Python code owns the history. That is simple at first and expensive later, because each new turn re-sends everything before it and you pay for those input tokens again.

A small wrapper keeps this tidy. Store the system message separately, append each turn, and drop the oldest turns once the history grows past a budget you choose. A rough budget in characters works well enough for a first version; counting tokens exactly is optional.

from openai import OpenAI

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

class Chat:
    def __init__(self, system: str, max_chars: int = 24000):
        self.system = {"role": "system", "content": system}
        self.turns = []
        self.max_chars = max_chars

    def say(self, text: str) -> str:
        self.turns.append({"role": "user", "content": text})
        while sum(len(t["content"]) for t in self.turns) > self.max_chars and len(self.turns) > 2:
            self.turns.pop(0)
        r = client.chat.completions.create(
            model="uncensored",
            messages=[self.system] + self.turns,
        )
        reply = r.choices[0].message.content
        self.turns.append({"role": "assistant", "content": reply})
        return reply

bot = Chat("You are a patient Python tutor.")
print(bot.say("What is a generator?"))
print(bot.say("Show a short example."))

The window of 100,000 tokens is large, so most projects will not hit it in a normal chat. Long roleplay sessions and document analysis are the exceptions. When you do trim, prefer dropping whole old turns over cutting a message in half, and consider replacing a long stretch of old turns with a short summary that the model itself writes.

Structuring a small Python project around it

A few habits save time once the script grows past a single file. Put the client in one module and import it everywhere, so the base URL, the key and the model ID live in exactly one place. Read the key from an environment variable or a secrets manager, never from a committed file, and add your .env to .gitignore.

Log the request ID from the response headers when you use the raw client, because it is the handle for debugging a single odd answer. With the SDK, client.chat.completions.with_raw_response.create(...) gives you access to headers such as X-Request-Id and X-Balance-USD alongside the parsed result. Watching the balance header in a long batch job lets you stop cleanly before credit runs out instead of failing halfway.

For tests, do not call the live API from your unit tests. Wrap the call in one function, then replace that function with a stub that returns a fixed string. Keep a separate, small set of integration tests that hit the real endpoint, run them by hand or on a schedule, and give them a low max_tokens so they cost a fraction of a cent.

Finally, treat model output as untrusted text. If you pass it to a shell, a database or a web page, validate and escape it like any other user input. This holds for every language model, hosted or local.

Questions and answers

Can I run this model locally instead?

The model is open-weight, but this service is a hosted endpoint run by an independent provider. You call it over HTTPS and do not download anything.

Do I need a special Python library?

No. The standard openai package works. Set base_url to https://api.nanbeige.top/v1, pass your key, and use the model ID uncensored.

Does it support function calling from Python?

Yes. Pass tools and tool_choice, read tool_calls from the reply, and send results back as messages with role tool.

How do I avoid 429 errors in a loop?

Keep concurrency at 8 or below on a full key, stay under 300 requests per minute, and retry after a short wait when you get rate_limited or concurrency.

Is there a free way to test it?

New users can claim $0.50 of trial credit with one click on the key page. It needs no card and is valid for 7 days.

Your key is one form away

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

Get API key