EN ▾

Uncensored text API for music pipelines

Get API key

Tiny LLM Model Python Example vs a Hosted API

A tiny llm model python example usually means loading a small open model on your own machine and calling it from a script. This page compares that route with a hosted OpenAI-compatible API, and gives code you can run in a minute.

Updated

A tiny glowing chip linked by a light beam to a tall server tower, comparing local and hosted LLMs

Two ways to get an LLM into a Python script

People who search for a small model to run from Python usually want one of two things. Either they want to learn how a language model runs, end to end, on their own computer, or they want a small piece of working code that returns generated text so they can build something around it. The first goal points to a local model. The second is often better served by a hosted API.

The local route works like this: you pick a small open-weight model from a public model hub, install a library that can run it, download the weights, and call a generate function. It teaches you a lot about tokens, sampling and memory. It also means you own the setup: Python versions, drivers, disk space and RAM or VRAM. Small models are fast to load, but their answers are limited, and the quality gap to a larger model shows quickly on anything beyond short, simple prompts.

The hosted route moves all of that elsewhere. Your script sends an HTTP request and reads the reply. The API here is OpenAI-compatible, so the code is the one you would write for any OpenAI-style service, with a different base URL and key. There is one model, with the ID uncensored, an open-weight model run by an independent provider. You trade ownership of the hardware for a per-token bill.

Local tiny model or hosted API: a quick comparison

QuestionLocal small modelHosted API
Setup timeInstall libraries, download weights, tune memorypip install openai, one key
HardwareYour CPU, RAM or GPU decides what runsNone needed on your side
Works offlineYesNo
Answer qualityDepends on the model size you can fitOne larger open-weight model
Context windowSet by the model and your memory100,000 tokens, prompt plus completion
CostHardware and electricity$0.15 per 1M input, $0.50 per 1M output
Tool calling and JSON modeDepends on the model and your wrapper codeBuilt into the API

Neither side wins everywhere. If you have no network, need strict control over where bytes go, or just want to learn how inference works, run a small model locally. If you want results that look like a production feature, streaming output, structured replies and tool calls, with no hardware work, call the API. Many people do both: they learn locally and ship against an endpoint.

Step 1: install the client and make a first call

You need Python 3.8 or newer and the official openai package. Get a key from the API key page. New users can claim a $0.50 trial credit there with one click and no card.

pip install openai
export UNCENSORED_API_KEY="YOUR_KEY"

Then the whole program is a few lines:

import os
from openai import OpenAI

client = OpenAI(
    base_url="https://api.musicgen.cc/v1",
    api_key=os.environ["UNCENSORED_API_KEY"],
)

resp = client.chat.completions.create(
    model="uncensored",
    messages=[
        {"role": "system", "content": "You answer in two short sentences."},
        {"role": "user", "content": "Explain what a token is in a language model."},
    ],
    temperature=0.4,
    max_tokens=120,
)

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

That is the whole change from a stock OpenAI example: the base_url and the key. No other library is needed. If you prefer not to install anything, curl does the same:

curl https://api.musicgen.cc/v1/chat/completions \
  -H "Authorization: Bearer $UNCENSORED_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"model":"uncensored","messages":[{"role":"user","content":"Say hello in five words."}]}'

You can also list models with GET /v1/models, which is a handy way to check that your key and URL are right before debugging anything else.

Step 2: stream tokens as they arrive

A local small model prints text as it generates it, and a good demo should too. Set stream=True and the API sends server-sent events. The openai package turns them into an iterator.

stream = client.chat.completions.create(
    model="uncensored",
    messages=[{"role": "user", "content": "Write a four-line poem about a router."}],
    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 chunk.usage:
        print("\n", chunk.usage)

Usage is reported at the end of the stream. One point to remember when you run many calls in parallel: a streamed request keeps its concurrency slot until the stream ends, so a loop that opens streams and never reads them to the end will block itself.

Step 3: get JSON back that your code can parse

Small local models often wander off format. A hosted call can ask for JSON mode with response_format. Mention JSON in the prompt too, as that helps any model produce the shape you want.

import json

resp = client.chat.completions.create(
    model="uncensored",
    response_format={"type": "json_object"},
    messages=[
        {"role": "system", "content": "Reply with a JSON object with keys title and tags (a list of 3 strings)."},
        {"role": "user", "content": "A tutorial on running a tiny language model in Python."},
    ],
)

data = json.loads(resp.choices[0].message.content)
print(data["title"], data["tags"])

Still wrap json.loads in a try block in anything you plan to keep. JSON mode makes broken output rare, but a cut-off reply from a low max_tokens can still leave a truncated object, and your code should handle that case, not crash.

Step 4: let the model call a Python function

Tool calling lets the model ask your code to run a function and then use the result. You pass a list of tools, check whether the reply contains tool_calls, run the function, and send the result back as a message with role: "tool".

import json

def get_time(city: str) -> str:
    return f"It is 14:30 in {city}."

tools = [{
    "type": "function",
    "function": {
        "name": "get_time",
        "description": "Get the local time for a city",
        "parameters": {
            "type": "object",
            "properties": {"city": {"type": "string"}},
            "required": ["city"],
        },
    },
}]

messages = [{"role": "user", "content": "What time is it in Lisbon?"}]
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)
        messages.append({
            "role": "tool",
            "tool_call_id": call.id,
            "content": get_time(**args),
        })
    final = client.chat.completions.create(
        model="uncensored", messages=messages, tools=tools
    )
    print(final.choices[0].message.content)
else:
    print(msg.content)

This is the same loop you would use with any OpenAI-style API. For more options, the docs list every supported parameter.

Where a tiny local model still wins

It would be wrong to push every project toward an endpoint. A small local model is the better pick in several cases, and it is worth being plain about them.

  • No network. A device on a plane, in a lab with no outbound traffic, or in an embedded project cannot call any API.
  • Learning. If you want to see tokenization, sampling and memory use with your own eyes, running the weights yourself teaches more than any HTTP call.
  • Very high volume of trivial work. If you classify millions of short strings and a small model handles it well enough, local compute may be cheaper than per-token billing. Run the numbers for your own case before you decide.
  • Fixed behavior. A file of weights on your disk does not change under you. That suits research that must be repeatable.

The hosted route wins when you want a larger model than your machine can hold, when several people or services share one setup, or when you simply want to ship. A common path is to prototype against the endpoint, because the code is short, and then decide later whether any part of the workload deserves a local model.

Cost, limits and common pitfalls

Price is $0.15 per 1M input tokens and $0.50 per 1M output tokens. Take a small example call with 300 tokens in and 100 tokens out. Input is 300 × $0.15 / 1,000,000 = $0.000045. Output is 100 × $0.50 / 1,000,000 = $0.00005. The call costs $0.000095, which means $0.50 of trial credit covers about 5,263 such calls ($0.50 / $0.000095). The pricing page lists top-ups, which start at $20.

A trial key allows 2 concurrent requests and 60 requests per minute. A full key allows 8 and 300. If you cross a limit you get HTTP 429 with the code rate_limited or concurrency. The same status with a Retry-After: 5 header means temporary overload. The openai package retries some failures on its own, and you can raise that with max_retries:

client = OpenAI(
    base_url="https://api.musicgen.cc/v1",
    api_key=os.environ["UNCENSORED_API_KEY"],
    max_retries=4,
    timeout=60,
)

resp = client.chat.completions.create(
    model="uncensored",
    messages=[{"role": "user", "content": "ping"}],
    max_tokens=5,
)
print(resp.choices[0].message.content)

Failed or refused requests are not charged. Each response includes X-Request-Id and X-Balance-USD headers, so you can log the request id when you ask for help and see your balance without opening a dashboard. Prompts are not used for training.

The model is text only and tuned to answer without content refusals for lawful adult use, with a hard rule against sexual content involving minors. It is not a router across vendors and not any vendor's official API.

Pitfalls and quick fixes

  • 401 or an empty reply. Check that the key is in the environment variable you read, and that the base URL ends in /v1 with no extra slash or path.
  • Model not found. The model ID is uncensored. Call GET /v1/models to see what your key can use.
  • Cut-off text. If answers stop mid-sentence, you set max_tokens too low. It is optional, and the completion can use whatever is left of the 100,000-token window.
  • Threads stuck on 429. If you fan out with a thread pool, cap it at the number of concurrent requests your key allows, which is 2 on a trial key and 8 on a full key.
  • Big payloads. The maximum request body is 8 MB. Chunk long documents before sending them.

When something looks wrong, print resp.usage and the X-Request-Id header, as the first tells you what you sent and the second helps support find the call. The docs cover the rest.

Questions and answers

Do I need a GPU for this?

No. The model runs on the provider's side. Your Python script only sends HTTP requests, so a small laptop is enough.

Can I use the official openai package?

Yes. Set base_url to the API address and use your key. Any OpenAI SDK or client works with those two changes.

Is a tiny local model free?

The software and many small models are free to download, but you pay in hardware, power and setup time. The hosted route is pay per token.

Does it support streaming and function calls?

Yes. Streaming over SSE, tool calling and JSON mode are all supported on the chat completions endpoint.

Your key is one form away

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

Key points

  • Small local models are good for learning and offline toys, but quality, speed and memory depend on your hardware.
  • A hosted endpoint needs only a base URL change in the openai package and works the same from a laptop or a server.
  • The same client code supports streaming, tool calling and JSON mode with the model ID uncensored.
  • Trial credit of $0.50 covers a few thousand small test calls, and a typical 300-in, 100-out call costs $0.000095.