How to Use Llama in Python With an OpenAI-Compatible API
The shortest path to a working Python script is the official openai package pointed at a compatible endpoint. Below are the install step, a first request, streaming, JSON, tools and error handling.
Updated

Key points
Install openai, set base_url and api_key, and call chat.completions.create.
Use model uncensored; streaming, JSON mode and tool calling are supported.
Back off on HTTP 429 and respect the Retry-After header.
The same code can point to a local Ollama server by changing two values.
Quick answer: ten lines of Python
If you want to know how to use Llama in Python without installing weights or a GPU stack, call a hosted endpoint with the OpenAI client. Install the package, point it at the base URL, and send messages.
pip install openai
export UNCENSORED_API_KEY="your-key-here"
import os
from openai import OpenAI
client = OpenAI(
base_url="https://api.uncensoredllama.top/v1",
api_key=os.environ["UNCENSORED_API_KEY"],
)
resp = client.chat.completions.create(
model="uncensored",
messages=[{"role": "user", "content": "Give me three names for a fantasy tavern."}],
)
print(resp.choices[0].message.content)
Get a key from the API key page. New accounts can claim $0.50 of trial credit with one click, which is plenty for everything on this page.
The model behind uncensored is one open-weight model run by an independent provider. It is not Meta's own API and the name does not promise a specific Llama release. If you instead want weights on your own machine, the last section shows the one-line change.
Python 3.8 or newer works with the current openai package. If you use a virtual environment, activate it before running pip install, so the package lands where your script will look for it. A quick way to confirm that everything is connected is to list models: client.models.list() returns the models the key can use, and it fails fast with a clear error if the key or the URL is wrong.
Messages, roles and a system prompt
The messages list is the whole conversation. Each item has a role: system for standing instructions, user for your input, assistant for earlier replies. The API is stateless, so you send the history each time and append the new reply yourself.
import os
from openai import OpenAI
client = OpenAI(
base_url="https://api.uncensoredllama.top/v1",
api_key=os.environ["UNCENSORED_API_KEY"],
)
history = [{"role": "system", "content": "You are a terse editor for fiction manuscripts."}]
def ask(text):
history.append({"role": "user", "content": text})
r = client.chat.completions.create(
model="uncensored",
messages=history,
temperature=0.7,
max_tokens=400,
)
answer = r.choices[0].message.content
history.append({"role": "assistant", "content": answer})
return answer
print(ask("Tighten this: She walked slowly down the long road."))
print(ask("Now make it more ominous."))
The context window is 100,000 tokens for prompt plus completion, so a long history fits, but each turn re-sends it and you pay for it as input. Parameters such as temperature, top_p, stop, seed and the penalties are passed through to the model. max_tokens is optional.
Reading the response object
A non-streaming call returns a ChatCompletion object. The fields you will use most are choices[0].message.content for the text, choices[0].finish_reason for why generation stopped, and usage for token counts.
The finish reason is worth checking. A value of stop means the model ended naturally or hit one of your stop strings. A value of length means it ran into max_tokens or the end of the context window, so the answer is cut off. If you see length on a task that should finish, raise max_tokens or trim the prompt.
The response headers carry X-Request-Id, which you should log. If something odd happens and you contact support, that id lets them find the exact request. Other headers report X-Balance-USD, your remaining credit, and the rate limit numbers for your key.
A practical tip on system prompts: keep them short and specific. A sentence that names the role, the tone and any hard format rule does more than a page of vague guidance, and it costs less on every call. For fiction and roleplay projects, put character and setting notes in the system message and keep the user turns for the story itself. If the history grows long, summarise the oldest turns into a short paragraph and drop the originals.
Streaming tokens as they arrive
For chat interfaces and long outputs, stream the reply so text appears while the model is still writing. Set stream=True and iterate.
import os
from openai import OpenAI
client = OpenAI(
base_url="https://api.uncensoredllama.top/v1",
api_key=os.environ["UNCENSORED_API_KEY"],
)
stream = client.chat.completions.create(
model="uncensored",
messages=[{"role": "user", "content": "Describe a rainy harbor town in 120 words."}],
stream=True,
)
for chunk in stream:
if chunk.choices and chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="", flush=True)
print()
Streaming uses server-sent events and the usage totals arrive at the end. One practical point: a streamed request holds its concurrency slot until the stream finishes, so if you forget to consume or close a stream, that slot stays busy.
Structured output with JSON mode
When another program reads the answer, ask for JSON mode and describe the shape in the prompt. The mode forces valid JSON syntax; it does not guarantee your exact keys, so validate after parsing.
import json, os
from openai import OpenAI
client = OpenAI(
base_url="https://api.uncensoredllama.top/v1",
api_key=os.environ["UNCENSORED_API_KEY"],
)
r = client.chat.completions.create(
model="uncensored",
response_format={"type": "json_object"},
messages=[
{"role": "system", "content": "Reply with JSON: {\"title\": string, \"tags\": [string]}"},
{"role": "user", "content": "A story about a lighthouse keeper who finds a locked door."},
],
)
data = json.loads(r.choices[0].message.content)
print(data["title"], data["tags"])Tool calling
Tool calling lets the model ask your code to run a function. You describe the function, the model returns a call with arguments, you run it and send the result back with the role tool.
import json, os
from openai import OpenAI
client = OpenAI(
base_url="https://api.uncensoredllama.top/v1",
api_key=os.environ["UNCENSORED_API_KEY"],
)
tools = [{
"type": "function",
"function": {
"name": "roll_dice",
"description": "Roll a die with the given number of sides",
"parameters": {
"type": "object",
"properties": {"sides": {"type": "integer"}},
"required": ["sides"],
},
},
}]
messages = [{"role": "user", "content": "Roll a 20-sided die for my character."}]
first = client.chat.completions.create(model="uncensored", messages=messages, tools=tools)
msg = first.choices[0].message
if msg.tool_calls:
call = msg.tool_calls[0]
sides = json.loads(call.function.arguments)["sides"]
messages.append(msg)
messages.append({"role": "tool", "tool_call_id": call.id, "content": "17"})
final = client.chat.completions.create(model="uncensored", messages=messages, tools=tools)
print(final.choices[0].message.content)
In real code, run your own function with the parsed arguments instead of the fixed result shown here. Also check tool_calls before using it, since the model may answer in plain text.
If the same prompts feed a report or a data pipeline, set a fixed seed and a low temperature so reruns give similar output. That makes it easier to compare two versions of a prompt, because differences come from your edit and not from sampling noise. Keep a small file of test prompts and run it after each change. It takes a minute and catches regressions before users do.
Handling errors and rate limits
A full key allows 8 concurrent requests and 300 requests per minute; a trial key allows 2 and 60. Going over returns HTTP 429. The error code is rate_limited for requests per minute and concurrency for too many at once. Temporary overload also returns 429 with a Retry-After: 5 header.
import os, time
from openai import OpenAI, RateLimitError
client = OpenAI(
base_url="https://api.uncensoredllama.top/v1",
api_key=os.environ["UNCENSORED_API_KEY"],
max_retries=0,
)
def chat(messages, tries=5):
for attempt in range(tries):
try:
return client.chat.completions.create(model="uncensored", messages=messages)
except RateLimitError as e:
wait = float(e.response.headers.get("Retry-After", 2 ** attempt))
time.sleep(wait)
raise RuntimeError("still rate limited after retries")
For batches, cap your worker pool at the concurrency limit, for example ThreadPoolExecutor(max_workers=8) on a full key. Failed or refused requests are not charged. Rates are on the pricing page: $0.15 per 1M input and $0.50 per 1M output tokens.
Whatever you build, the minors rule is a hard limit: the service does not allow sexual content involving minors, and requests of that kind are not something the model or the platform will support. Everything else in your own app is lawful adult use that you are responsible for configuring sensibly, for instance with age gates and clear user terms of your own.
Running the same script against local weights
If you prefer to run a model on your own computer, Ollama serves an OpenAI-style path at http://localhost:11434/v1. Use that as base_url, any non-empty string as the key, and the name of the model you pulled, such as llama3.2. The rest of your code stays the same. Local runs are free per token but limited by your memory and speed, and stock models may decline requests the hosted model answers.
The docs list the endpoints in full: POST /v1/chat/completions and GET /v1/models. It is text only, with no images, audio or embeddings.
Common mistakes and fixes
- Forgetting the
/v1suffix. The base URL ends in/v1. Without it, the client calls the wrong path and you get a 404. - Hard-coding the key. Keep it in an environment variable so it does not end up in a repository.
- Using the wrong model name. Pass
uncensored. A name likellama-3will not match. - Not appending replies to history. The API remembers nothing between calls. If the model seems to forget, you are probably sending only the latest message.
- Parallel calls above the limit. A loop that fires 50 requests at once on a trial key (2 concurrent) will mostly return 429. Use a small pool.
- Ignoring stream cleanup. Break out of a streaming loop without closing the stream and the slot stays occupied until it ends.
Most of these show up in the first hour and are quick to fix once you know the pattern.
Wrapping it in a small module
Once the basics work, put the client in one file so the rest of the project imports a single function. That keeps the base URL and model name in one place, which also makes it easy to switch to another endpoint during tests.
# llm.py
import os
from openai import OpenAI
_client = OpenAI(
base_url=os.environ.get("LLM_BASE_URL", "https://api.uncensoredllama.top/v1"),
api_key=os.environ["UNCENSORED_API_KEY"],
)
MODEL = os.environ.get("LLM_MODEL", "uncensored")
def complete(prompt, system=None, **kw):
messages = []
if system:
messages.append({"role": "system", "content": system})
messages.append({"role": "user", "content": prompt})
r = _client.chat.completions.create(model=MODEL, messages=messages, **kw)
return r.choices[0].message.content
With that, any script can call complete("Write a limerick about a debugger", temperature=0.9). Because the options pass through as keyword arguments, you can add seed for repeatable output or stop for custom cut-offs without changing the module.
More guides
Questions and answers
Do I need a GPU to use Llama in Python this way?
No. The model runs on the provider's servers, and your Python script only sends HTTP requests. Any computer that runs Python is enough.
Which Python package should I use?
The official openai package. Set base_url to the API address and use your key; no special client is needed.
Can I use async code?
Yes. The openai package has an AsyncOpenAI client with the same arguments. Keep concurrency within the 8-request limit of a full key.
What model name do I pass?
Use uncensored as the model value. You can also call GET /v1/models to list what the key can use.
Your key is one form away
Create an account, copy the key, change the base URL. That is the whole setup.