Llama 3.1 Tool Calling in an OpenAI-Style API
Tool use through an OpenAI-style API comes down to a loop: describe your functions, let the model ask for one, run it yourself, and send the result back. Here is that loop in the OpenAI format, with code you can copy and the mistakes that break it.
Updated

Key points
- Tool calling is a loop you run: model requests, your code executes, you return the result.
- The API uses the standard OpenAI fields: tools, tool_choice, tool_calls and role tool.
- Always parse arguments defensively; a model can return malformed or incomplete JSON.
- This is one open-weight model behind the ID uncensored, not Meta's official API.
How tool calling works
Search for llama 3.1 tool calling and you find two layers mixed together. The first is the model layer: Llama 3.1 was trained to emit a structured function request when it decides a tool would help, instead of answering in prose. The second is the API layer: a server that turns that raw output into a clean tool_calls field, so your code never parses model-specific tags. This article is about the API layer, because that is what you write against.
A short note on what you are connecting to. This service exposes one open-weight model, run by an independent provider and tuned to answer without content refusals for lawful adult use. It is addressed by the model ID uncensored. It is not the official API of Meta or any other vendor, and it is not a router across several models, so you should test tool behaviour on your own tasks rather than assume it matches any published description of another deployment. The Llama API integration guide covers the general connection side.
The model never runs your function. It only says which function it wants and with which arguments. Your program runs the function and reports back. That is why a mistake in tool calling is nearly always a mistake in one of three places: the schema you sent, the parsing of the arguments, or the message you return.
The request: declare tools
The endpoint is POST /v1/chat/completions with the usual body plus a tools array. Each tool has a name, a description the model reads, and a JSON Schema for the parameters. The description is where most of the quality comes from, so write it as an instruction: say when to use the tool and what each argument means.
import json, os
from openai import OpenAI
client = OpenAI(base_url="https://api.uncensoredllama.cc/v1", api_key=os.environ["API_KEY"])
tools = [{
"type": "function",
"function": {
"name": "get_order_status",
"description": "Look up the shipping status of an order. Use when the user asks where an order is.",
"parameters": {
"type": "object",
"properties": {
"order_id": {"type": "string", "description": "Order number, for example A1042"},
},
"required": ["order_id"],
},
},
}]
messages = [{"role": "user", "content": "Where is order A1042?"}]
resp = client.chat.completions.create(
model="uncensored",
messages=messages,
tools=tools,
tool_choice="auto",
)
msg = resp.choices[0].message
print(msg.tool_calls)
tool_choice controls the behaviour. "auto" lets the model decide, and is the right default. Passing a specific function forces that call, which suits extraction tasks where you always want structured output. Passing "none" turns tools off for a turn.
The loop: run the tool, return the result
When the model wants a tool, message.tool_calls is a list. Each entry has an id, a function name and an arguments string. Note that the arguments arrive as a string of JSON, not as an object. Parse it, run your function, then append two things to the conversation: the assistant message that contained the calls, and one role: "tool" message per call, each carrying the matching tool_call_id. Then call the API again.
def get_order_status(order_id):
return {"order_id": order_id, "status": "in transit", "eta_days": 2}
registry = {"get_order_status": get_order_status}
for _ in range(5): # hard cap on tool rounds
resp = client.chat.completions.create(
model="uncensored", messages=messages, tools=tools, tool_choice="auto"
)
msg = resp.choices[0].message
if not msg.tool_calls:
print(msg.content)
break
messages.append(msg.model_dump(exclude_none=True))
for call in msg.tool_calls:
try:
args = json.loads(call.function.arguments)
result = registry[call.function.name](**args)
except Exception as e:
result = {"error": str(e)}
messages.append({
"role": "tool",
"tool_call_id": call.id,
"content": json.dumps(result),
})
Three details in that loop save real trouble. The cap of five rounds stops a model that keeps requesting tools from burning tokens forever. The try block turns bad arguments or an unknown function name into an error message the model can read and recover from, instead of a crash. And the model may request several calls in one turn, so the inner loop answers every one of them before the next request.
Streaming tool calls
With stream: true the reply arrives over SSE, and tool calls arrive in pieces. Each chunk's delta.tool_calls holds an index and a fragment of the function name or the arguments string. You concatenate the fragments per index and parse only after the stream ends. Parsing half a JSON string mid-stream is the classic bug here.
import OpenAI from "openai";
const client = new OpenAI({
baseURL: "https://api.uncensoredllama.cc/v1",
apiKey: process.env.API_KEY,
});
const stream = await client.chat.completions.create({
model: "uncensored",
messages: [{ role: "user", content: "Where is order A1042?" }],
tools,
stream: true,
});
const calls = {};
for await (const chunk of stream) {
for (const tc of chunk.choices[0]?.delta?.tool_calls ?? []) {
const c = (calls[tc.index] ??= { id: "", name: "", args: "" });
if (tc.id) c.id = tc.id;
if (tc.function?.name) c.name += tc.function.name;
if (tc.function?.arguments) c.args += tc.function.arguments;
}
}
console.log(Object.values(calls).map((c) => ({ ...c, args: JSON.parse(c.args) })));
Here tools is the same array declared earlier. Usage figures arrive at the end of the stream. One more point from the limits: a streamed request holds its concurrency slot until the stream finishes, so an abandoned stream that you never read to the end can leave you short of slots and produce a concurrency 429.
Making calls reliable
Open-weight models are good at tool calling and not perfect at it. These practices cut failures without any special support from the server.
- Keep the tool list short. Five to eight well-described tools beat thirty vague ones. Send only the tools relevant to the current task.
- Use enums and required fields. A schema with
"enum": ["open", "closed"]gives the model a closed set to choose from. - Lower the temperature. Values around 0 to 0.3 make argument JSON steadier. The sampling parameters are passed through, so this works as expected.
- Validate before executing. Check types and ranges in your code. Never pass model-written strings straight into a shell command or a database query.
- Return errors as data. A tool message such as
{"error": "order not found"}lets the model ask the user a follow-up instead of guessing. - Use JSON mode for plain extraction. If you do not need an action,
response_format: {"type":"json_object"}is simpler than a tool.
If the model answers in prose when you expected a call, the description is usually too vague about when to use the tool, or the user message does not contain the needed value. Add a sentence to the description and test again with tool_choice set to the specific function to confirm the schema itself is accepted.
Writing tool descriptions the model understands
The schema is a prompt. The model never sees your code, only the name, the description and the parameter notes, so those words decide whether the right tool gets picked with the right values.
Name tools with a verb and an object, such as search_orders or cancel_booking, rather than a bare noun. In the description, state the trigger: "Use when the user asks about delivery". If two tools overlap, say how they differ in each description, for example that one returns a list and the other returns a single record. For every parameter, add a short example value in its description. Formats are where models slip most: dates, identifiers and units. "Date in YYYY-MM-DD format, for example 2025-03-14" removes a whole class of errors.
Avoid optional parameters unless you really need them. Each optional field is a decision the model can get wrong, and a default applied in your code is more dependable than one the model must remember. Keep nested objects shallow too. A flat list of simple fields is easier to fill correctly than an object that contains an array of objects.
Testing a tool set
Build a small table of test messages: some that should trigger each tool, some that should trigger none, and some with a missing value that should lead to a clarifying question. Run it after every change to a description. Count correct tool choices and valid argument objects over, say, thirty messages. A schema that works in three hand-picked examples can fail on one in ten real messages, and you only see that rate by measuring it. Set seed and a low temperature while comparing versions, so a change in the numbers comes from your edit and not from sampling noise.
Cost and limits for agent loops
Every round of the loop resends the conversation, tool definitions included, so input tokens grow with each turn. Pricing is $0.15 per 1M input tokens and $0.50 per 1M output tokens. Take a task that needs three rounds, with the tool schemas and history adding up to 1,200, 1,500 and 1,800 input tokens, and 60 output tokens per round.
- Input: 1,200 + 1,500 + 1,800 = 4,500 tokens, which at $0.15 per 1M is $0.000675.
- Output: 3 x 60 = 180 tokens, which at $0.50 per 1M is $0.00009.
- Total: $0.000765 for the whole task, so 1,000 such tasks cost $0.765.
The context window is 100,000 tokens for prompt plus completion, so long agent runs fit, but trim old tool results when they are no longer needed. A full key allows 8 concurrent requests and 300 per minute; a trial key allows 2 and 60. Failed or refused requests are not charged. Credit is prepaid, does not expire, and can be topped up from $20 to $500 by crypto (USDT on TRC20, USDC on Base). See the pricing page for bonus tiers, and create a key on the API key page; new users can claim $0.50 of trial credit there, valid for 7 days. The docs show the base request format.
More guides
Questions and answers
Is this the official Llama 3.1 API?
No. It is an OpenAI-compatible endpoint serving one open-weight model run by an independent provider, with the model ID uncensored. It is not Meta's API.
Does the API support parallel tool calls?
A reply can contain several entries in tool_calls. Answer each one with its own role tool message carrying the matching tool_call_id before the next request.
Why are the arguments a string?
The OpenAI format delivers function arguments as a JSON string. Parse it with json.loads in a try block, because a model can occasionally return invalid or truncated JSON.
Can I force the model to call a specific tool?
Yes. Set tool_choice to the function object for that tool. Use auto when the model should decide, and none to disable tools for a turn.
Your key is one form away
Create an account, copy the key, change the base URL. That is the whole setup.