Home/Guide
Llama API Python Setup for OpenAI-Compatible Endpoints
A llama api python setup is short, because most hosted Llama-style services speak the OpenAI format. Install the openai package, set a base URL and key, and call chat completions. The code below is the same for any compatible provider, and it is tested against this endpoint with model <code>uncensored</code>.
Updated


- Use the openai package with base_url=https://api.llamaapis.com/v1 and model uncensored.
- Streaming, tool calls and JSON mode use the standard OpenAI parameters.
- Retry on HTTP 429 and read the Retry-After header.
- The same script works on other compatible providers by changing three settings.
Install and make the first call
Python 3.9 or newer works. Install the SDK and store your key in an environment variable so it never lands in source control.
pip install openai
export LLM_API_KEY="YOUR_KEY"
# base URL: https://api.llamaapis.com/v1 model: uncensored
Then the first request:
import os
from openai import OpenAI
client = OpenAI(
base_url="https://api.llamaapis.com/v1",
api_key=os.environ["LLM_API_KEY"],
)
resp = client.chat.completions.create(
model="uncensored",
messages=[
{"role": "system", "content": "You are a concise assistant."},
{"role": "user", "content": "Explain what a token is in two sentences."},
],
)
print(resp.choices[0].message.content)
print(resp.usage)
Get a key from the API key page. New users can claim $0.50 of trial credit with one click, valid for 7 days and with no card. This service is a text-only, OpenAI-compatible endpoint for one open-weight model. It is not the official API of Meta or any other model vendor, so the model name is uncensored rather than a Llama version string.
Keep the conversation: roles and history
The API is stateless. To hold a conversation, send the full message list each time and append every reply.
import os
from openai import OpenAI
client = OpenAI(base_url="https://api.llamaapis.com/v1", api_key=os.environ["LLM_API_KEY"])
history = [{"role": "system", "content": "You are a patient writing coach."}]
def chat(user_text):
history.append({"role": "user", "content": user_text})
r = client.chat.completions.create(model="uncensored", messages=history, temperature=0.7)
reply = r.choices[0].message.content
history.append({"role": "assistant", "content": reply})
return reply
print(chat("Give me a prompt for a ghost story."))
print(chat("Make it set on a ferry."))
The context window is 100,000 tokens, prompt plus completion, which allows long histories. You still pay for every input token on every turn, so trim or summarize old messages once the list grows. The cost math is simple: input costs $0.15 per 1M tokens and output $0.50 per 1M.
Streaming in Python
Pass stream=True and iterate. Add stream_options to get token usage in the final chunk.
import os
from openai import OpenAI
client = OpenAI(base_url="https://api.llamaapis.com/v1", api_key=os.environ["LLM_API_KEY"])
stream = client.chat.completions.create(
model="uncensored",
messages=[{"role": "user", "content": "Write a short scene at a night market."}],
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)
The last chunk has an empty choices list, which is why the loop checks it first. Remember that a streamed request holds its concurrency slot until it ends, so close the stream if the user leaves.
Tools and JSON mode
For function calling, describe your function in tools, check message.tool_calls, run the function and return the output with role: "tool":
import json, os
from openai import OpenAI
client = OpenAI(base_url="https://api.llamaapis.com/v1", api_key=os.environ["LLM_API_KEY"])
tools = [{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get the weather for a city",
"parameters": {
"type": "object",
"properties": {"city": {"type": "string"}},
"required": ["city"],
},
},
}]
messages = [{"role": "user", "content": "What is the weather in Lisbon?"}]
first = client.chat.completions.create(model="uncensored", messages=messages, tools=tools)
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 = {"city": args["city"], "temp_c": 21} # 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)
For plain structured output, set response_format={"type": "json_object"} and say in the prompt that you want JSON. Parse the result with json.loads inside a try block, because any model can return broken JSON sometimes.
Retries and rate limits
A full key allows 8 concurrent requests and 300 requests per minute; a trial key allows 2 and 60. If you pass a limit, the API returns HTTP 429 with code rate_limited or concurrency. Under temporary overload it also returns 429 with Retry-After: 5. The SDK raises RateLimitError, so wrap calls like this:
import os, time
from openai import OpenAI, RateLimitError
client = OpenAI(base_url="https://api.llamaapis.com/v1", api_key=os.environ["LLM_API_KEY"], max_retries=0)
def call_with_retry(messages, tries=4):
for attempt in range(tries):
try:
return client.chat.completions.create(model="uncensored", messages=messages)
except RateLimitError as e:
if attempt == tries - 1:
raise
wait = int(e.response.headers.get("retry-after", 2 ** attempt))
time.sleep(wait)
Setting max_retries=0 turns off the SDK's own retries so that yours are the only ones. The usage limits article has more patterns, including a semaphore to cap parallel calls.
Async calls for many requests
For batch work use the async client and cap parallelism at your concurrency limit, so you are not answered with 429:
import asyncio, os
from openai import AsyncOpenAI
client = AsyncOpenAI(base_url="https://api.llamaapis.com/v1", api_key=os.environ["LLM_API_KEY"])
sem = asyncio.Semaphore(8) # use 2 on a trial key
async def one(prompt):
async with sem:
r = await client.chat.completions.create(
model="uncensored",
messages=[{"role": "user", "content": prompt}],
)
return r.choices[0].message.content
async def main():
prompts = [f"Give a name for fantasy town number {i}." for i in range(20)]
for text in await asyncio.gather(*(one(p) for p in prompts)):
print(text)
asyncio.run(main())Common mistakes and how to fix them
- Missing
/v1in the base URL. The SDK appends/chat/completions, so a base URL without/v1usually fails with a not-found error. - Using a vendor model name. Strings such as a Llama version are not valid here. Send
uncensored. - Reading
choices[0]on the last streaming chunk. That chunk can have no choices, so check the list first. - Forgetting the history. If the model seems to forget the last message, you probably did not append it to the list.
- Parsing tool arguments blindly. Wrap
json.loadsin a try block and send an error message back as the tool result if it fails, which often lets the model correct itself. - Blank replies. A very small
max_tokensor a stop sequence that fires early can end the output at once. Remove both while debugging.
When something odd happens, log the X-Request-Id response header. With the raw response from the SDK, client.chat.completions.with_raw_response.create(...) gives access to headers such as X-Balance-USD and the rate limit headers.
Checking balance from code
The endpoint GET /v1/balance returns your remaining credit, and an OpenAI-style route at /v1/dashboard/billing/credit_grants also exists. A small check before a large batch avoids a job that stops halfway because the balance ran out.
Same code, other providers, and cost
Because the format is shared, this code runs against any compatible service. Change base_url, the key and the model name, then test parameters that vary between providers. The article on OpenAI-compatible API servers explains where compatibility stops.
On this endpoint, a call with 1,500 input and 400 output tokens costs 1,500 x $0.15 / 1M + 400 x $0.50 / 1M = $0.000225 + $0.0002 = $0.000425. The trial credit of $0.50 covers about 1,176 of those. After that, top up from $20 to $500; the pricing page lists the bonuses. Prompts are not used for training, and failed or refused requests are not charged. The docs cover the rest.
More guides
Questions and answers
Which Python package do I need?
The official openai package. Create the client with base_url set to https://api.llamaapis.com/v1 and your key, and use the model ID uncensored.
Does the same code work with other Llama-style hosts?
Usually yes, if the host is OpenAI-compatible. Change the base URL, key and model name, and check which optional parameters it supports.
How do I stream tokens in Python?
Set stream=True and iterate over the chunks. Add stream_options with include_usage to get token counts at the end.
What should I do on a 429 error?
Wait for the Retry-After seconds if given, otherwise back off, then retry. If the code is concurrency, lower the number of parallel requests.
Your key is one form away
Create an account, copy the key, change the base URL. That is the whole setup.