Llama API Example: Chat, JSON Mode and Tool Calling
Below is a llama api example for each feature you are likely to need: a plain chat call, streaming, JSON mode, tool calling and a multi-turn loop. Every snippet uses the base URL https://api.llamaapi.cc/v1 and the model ID uncensored.

On this page
- Setup shared by every example
- Example 1: a basic request in curl
- Example 2: streaming tokens as they arrive
- Example 3: JSON mode for structured output
- Example 4: tool calling
- Example 5: a multi-turn chat loop with a persona
- Example 6: list models and read the headers
- Common mistakes and how to fix them
- Choosing sampling settings for each kind of task
- What these examples cost
- More guides
Key points
- Each example is complete and uses the openai Python package or curl.
- JSON mode needs a prompt that names the keys you want.
- Tool calling is a two-step loop: the model asks, you run the function and reply with role tool.
- A typical short chat call costs a fraction of a cent.
Setup shared by every example
You need an API key and the openai package. Install it with pip install openai and export the key so no snippet contains a secret. If you have no key yet, get an API key first; new accounts can claim $0.50 of trial credit with one click.
export LLAMAAPI_KEY="your-key-here"
Every Python example below assumes this client at the top of the file:
import os
from openai import OpenAI
client = OpenAI(
base_url="https://api.llamaapi.cc/v1",
api_key=os.environ["LLAMAAPI_KEY"],
)
The model behind uncensored is one open-weight model run by an independent provider and tuned to answer without content refusals for lawful adult use. The two methods you will use are POST /v1/chat/completions and GET /v1/models.
Example 1: a basic request in curl
The raw HTTP call is the best way to see what the SDKs send. This request asks for a short product description with a lower temperature, so the wording stays focused.
curl https://api.llamaapi.cc/v1/chat/completions \
-H "Authorization: Bearer $LLAMAAPI_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "uncensored",
"messages": [
{"role": "system", "content": "You write short, plain product copy."},
{"role": "user", "content": "Describe a pocket-sized label printer in two sentences."}
],
"temperature": 0.4,
"max_tokens": 120
}'
The reply is JSON with choices[0].message.content and a usage block. The max_tokens field is optional. If you leave it out, the completion can use whatever is left of the 100,000-token window, so set it when you want a hard cap on length and cost. The response headers include X-Request-Id and X-Balance-USD, which are handy in logs.
Example 2: streaming tokens as they arrive
Streaming makes a chat interface feel immediate, because text shows up while the model is still writing. Set stream to true and iterate over the chunks.
stream = client.chat.completions.create(
model="uncensored",
messages=[{"role": "user", "content": "Tell a 120-word story about a lighthouse keeper."}],
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\ntokens:", chunk.usage.prompt_tokens, chunk.usage.completion_tokens)
Usage arrives at the end of the stream. Remember that a streamed request holds one of your concurrency slots until it finishes, so read it to the end or close it. A full key allows 8 at once, a trial key 2.
Example 3: JSON mode for structured output
When a program, not a person, reads the answer, ask for JSON. Pass response_format and describe the shape in the prompt. The model is more reliable when you name the exact keys.
import json
resp = client.chat.completions.create(
model="uncensored",
response_format={"type": "json_object"},
messages=[
{"role": "system", "content": "Reply only with JSON using the keys: title, genre, characters (array of strings)."},
{"role": "user", "content": "Invent a short sci-fi story premise."},
],
temperature=0.9,
)
data = json.loads(resp.choices[0].message.content)
print(data["title"], "-", data["genre"])
print(", ".join(data["characters"]))
Wrap json.loads in a try block in real code and retry once if parsing fails. For repeatable tests, add "seed": 42 to the request. The seed is passed through, which makes outputs more stable between runs, although you should not treat it as a guarantee of identical text.
Example 4: tool calling
Tool calling lets the model ask your code to do something, such as look up an order. The flow has two requests. First you send the tool definitions and the model replies with a call. Then you run the function and send the result back as a message with role: "tool".
import json
def get_order_status(order_id):
return {"order_id": order_id, "status": "shipped", "eta_days": 2}
tools = [{
"type": "function",
"function": {
"name": "get_order_status",
"description": "Look up the shipping status of an order",
"parameters": {
"type": "object",
"properties": {"order_id": {"type": "string"}},
"required": ["order_id"],
},
},
}]
messages = [{"role": "user", "content": "Where is order A-1042?"}]
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 = get_order_status(**args)
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)
else:
print(msg.content)
Two habits save debugging time. Always check that tool_calls exists before reading it, because the model may answer directly. And always parse arguments with json.loads, since it arrives as a string. Streamed tool calls come in as deltas that you concatenate by index before parsing.
Example 5: a multi-turn chat loop with a persona
The API is stateless, so a conversation is just a list you keep and resend. This loop stores every turn and keeps a character in place through the system message. It suits fiction and companion apps for adults, where the persona has to hold across many messages.
history = [{
"role": "system",
"content": "You are Mara, a dry-witted ship navigator in a space opera. Stay in character.",
}]
while True:
user = input("you> ")
if user.strip().lower() in {"quit", "exit"}:
break
history.append({"role": "user", "content": user})
resp = client.chat.completions.create(model="uncensored", messages=history, temperature=0.9, top_p=0.95)
reply = resp.choices[0].message.content
history.append({"role": "assistant", "content": reply})
print("mara>", reply)
The one rule that holds regardless of persona: no sexual content involving minors. Everything else is governed by the terms and your own product rules. Because the history grows with each turn, input cost grows too. Trim old messages or summarize them once the list nears a size you are comfortable paying for.
Example 6: list models and read the headers
Two small calls are useful in monitoring scripts. The first lists the models your key can see. The second reads the response headers, which expose your remaining balance and limits without a separate request.
models = client.models.list()
print([m.id for m in models.data])
raw = client.chat.completions.with_raw_response.create(
model="uncensored",
messages=[{"role": "user", "content": "Say hello in five words."}],
max_tokens=20,
)
print("request id:", raw.headers.get("X-Request-Id"))
print("balance usd:", raw.headers.get("X-Balance-USD"))
print("req per minute:", raw.headers.get("X-RateLimit-Limit-Requests"))
print("concurrency:", raw.headers.get("X-RateLimit-Limit-Concurrency"))
completion = raw.parse()
print(completion.choices[0].message.content)
The listing call is a good health check at startup: if it fails with a 401, the key is wrong, and if it succeeds but your chat call fails, the problem is in the request body. The limit headers show if the key is a trial key or a full one, since the two have different numbers. Log the request ID next to your own job ID, and you can trace any one call later.
Common mistakes and how to fix them
Most failures with a first integration come from a short list of causes. Check these before assuming something is wrong with the service.
- Missing /v1 in the base URL. The client appends
/chat/completionsto whatever you give it. Use the fullhttps://api.llamaapi.cc/v1, or you will get a 404. - Wrong model name. Names such as a vendor's model ID will not be recognised. The only model ID is
uncensored. - 429 on a trial key. The trial limits are 2 concurrent requests and 60 per minute. A loop that fires five requests at once will hit the concurrency limit. Run them one after another, or top up to get a full key.
- Stream never closes. If you break out of a streaming loop early, close the stream so the concurrency slot is released.
- Tool arguments treated as a dict. They arrive as a JSON string. Parse them first.
- Body too large. The limit is 8 MB. Long histories with pasted documents can pass that, so trim before you send.
If a call still fails after these checks, copy the X-Request-Id header from the failing response and send it to support along with the time of the call. That is much faster than describing the problem from memory.
Choosing sampling settings for each kind of task
The examples above use different temperature values on purpose. Sampling settings change the output more than most prompt tweaks do, so it helps to have a starting point for each job and then adjust from there.
For extraction, classification and JSON output, use a low temperature between 0 and 0.3. You want the same input to produce the same shape of answer. For product copy and summaries, 0.4 to 0.7 gives some variety while staying on topic. For fiction, roleplay and brainstorming, 0.8 to 1.0 with a top_p around 0.9 to 0.95 gives livelier language. If the model starts repeating phrases in a long scene, raise frequency_penalty slightly, for example to 0.3, and test again. Change one setting at a time, so you know what caused a difference.
A fixed seed is useful when you debug a prompt: with the other settings held constant, you can compare two versions of a system message with less noise from sampling. Turn it off in production if you want variety between users.
What these examples cost
Prices are $0.15 per 1M input tokens and $0.50 per 1M output tokens. Say the support lookup in example 4 sends 600 input tokens and receives 150 output tokens in each of its two requests. That is 1,200 input and 300 output tokens in total: 1,200 x $0.15 / 1,000,000 = $0.00018, plus 300 x $0.50 / 1,000,000 = $0.00015, so $0.00033 per lookup.
The chat loop grows differently. If turn 20 carries 8,000 tokens of history and the model writes 250 tokens back, that single turn costs 8,000 x $0.15 / 1,000,000 = $0.0012 for input and 250 x $0.50 / 1,000,000 = $0.000125 for output, a total of $0.001325. Failed or refused requests are not charged. The pricing page lists top-up amounts and bonuses, and the docs cover everything else about the request format.
More guides
Questions and answers
Which SDKs work with this API?
Any OpenAI-compatible SDK or client. Change the base URL to https://api.llamaapi.cc/v1, add your key and use the model uncensored.
Does JSON mode guarantee valid JSON?
It is designed to produce a JSON object, but you should still parse defensively and describe the expected keys in your prompt.
How do I send the tool result back?
Append a message with role tool, the matching tool_call_id and the result as a string, then call the API again.
Can I run these examples on the trial credit?
Yes. The $0.50 trial credit is enough for many short calls, within the trial limits of 2 concurrent and 60 requests per minute.
Your key is one form away
Create an account, copy the key, change the base URL. That is the whole setup.