LLM With Function Calling: How It Works, With Code
An LLM with function calling does not run your code. It returns a structured request naming a function and its arguments, and your program decides what to do. This guide shows the full loop with working code against an OpenAI-compatible endpoint.
Updated
Key points
- The model proposes a call; your code executes it and sends the result back as a role: tool message.
- Tool definitions use JSON Schema, so descriptions and parameter types decide how well calls come out.
- Always validate arguments and cap the number of loop iterations.
- Streamed responses deliver tool_calls in pieces that you must assemble.

What function calling actually is
Function calling, also called tool calling, is a protocol between your program and a language model. You describe functions in a JSON structure. The model reads the user message and either answers in plain text or replies with a tool_calls list: function name plus a JSON string of arguments. Nothing runs on the model side. Your code runs the function, then sends the output back so the model can write the final answer.
That small loop is what turns a chat model into something that can look up an order, query a database, check a calendar or call an internal API. It is also the base of most agent frameworks. If you can write the loop below by hand, you can debug any framework built on it.
This API follows the OpenAI chat completions format and supports tools, tool_choice, streamed tool_calls and results returned as role: "tool". The base URL is https://api.abliteratedllm.cc/v1 and the model ID is uncensored.
The request: describing a tool
A tool is a name, a description and a parameter schema. The description is not decoration. The model chooses between tools by reading it, so write it like a one-line spec: what the function does, when to use it, what it returns.
{
"model": "uncensored",
"messages": [
{"role": "user", "content": "Is order 48213 shipped yet?"}
],
"tools": [
{
"type": "function",
"function": {
"name": "get_order_status",
"description": "Look up the shipping status of an order by its numeric ID.",
"parameters": {
"type": "object",
"properties": {
"order_id": {"type": "integer", "description": "The order number"}
},
"required": ["order_id"]
}
}
}
],
"tool_choice": "auto"
}
tool_choice controls behavior. With auto the model decides. You can also force a specific function when you always want structured output from a step. If you only need clean JSON and no external call, response_format: {"type": "json_object"} is simpler.
A complete loop in Python
The loop has four moves: send messages and tools, check for tool_calls, run each one, append the results and call again. Stop when the model answers without a tool call.
import json, os
from openai import OpenAI
client = OpenAI(
base_url="https://api.abliteratedllm.cc/v1",
api_key=os.environ["LLM_API_KEY"],
)
def get_order_status(order_id: int) -> dict:
# replace with a real lookup
return {"order_id": order_id, "status": "shipped", "carrier": "post"}
REGISTRY = {"get_order_status": get_order_status}
tools = [{
"type": "function",
"function": {
"name": "get_order_status",
"description": "Look up the shipping status of an order by its numeric ID.",
"parameters": {
"type": "object",
"properties": {"order_id": {"type": "integer"}},
"required": ["order_id"],
},
},
}]
messages = [{"role": "user", "content": "Is order 48213 shipped yet?"}]
for _ in range(5): # hard cap on iterations
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) # keep the assistant turn that holds tool_calls
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 cause most first-time bugs. The assistant message containing tool_calls must stay in the history. Every tool message needs the matching tool_call_id. And content of a tool message is a string, so serialize your dict.
Try it from the command line
You can see the raw shape with curl before touching an SDK. Send the request from the previous section and look at the reply.
curl https://api.abliteratedllm.cc/v1/chat/completions \
-H "Authorization: Bearer $LLM_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "uncensored",
"messages": [{"role": "user", "content": "Is order 48213 shipped yet?"}],
"tools": [{"type": "function", "function": {
"name": "get_order_status",
"description": "Look up the shipping status of an order by its numeric ID.",
"parameters": {"type": "object",
"properties": {"order_id": {"type": "integer"}},
"required": ["order_id"]}}}]
}'
In the response you are looking for choices[0].message.tool_calls[0].function.arguments. It is a string containing JSON, such as {"order_id": 48213}, not an object. That is why the Python code calls json.loads.
Streaming tool calls
With stream: true, tool calls arrive as fragments. The first chunk for a call carries its id and function name, and later chunks append pieces of the arguments string. You must concatenate the pieces by index and parse only when the stream ends.
calls = {}
stream = client.chat.completions.create(
model="uncensored", messages=messages, tools=tools, stream=True
)
for chunk in stream:
if not chunk.choices:
continue
for tc in chunk.choices[0].delta.tool_calls or []:
slot = calls.setdefault(tc.index, {"id": "", "name": "", "args": ""})
if tc.id:
slot["id"] = tc.id
if tc.function and tc.function.name:
slot["name"] = tc.function.name
if tc.function and tc.function.arguments:
slot["args"] += tc.function.arguments
# after the loop: json.loads(slot["args"]) for each entry
One operational point: a streamed request keeps its concurrency slot until the stream ends. A full key allows 8 at once, a trial key 2. If your agent fans out several tool-using conversations in parallel, count the streams, or you will see 429 responses with the code concurrency.
The same call in Node
The shape is identical in JavaScript. Here is the first round, with the tool call read from the response and the argument string parsed.
import OpenAI from "openai";
const client = new OpenAI({
baseURL: "https://api.abliteratedllm.cc/v1",
apiKey: process.env.LLM_API_KEY,
});
const tools = [{
type: "function",
function: {
name: "get_order_status",
description: "Look up the shipping status of an order by its numeric ID.",
parameters: {
type: "object",
properties: { order_id: { type: "integer" } },
required: ["order_id"],
},
},
}];
const messages = [{ role: "user", content: "Is order 48213 shipped yet?" }];
const resp = await client.chat.completions.create({
model: "uncensored", messages, tools, tool_choice: "auto",
});
const msg = resp.choices[0].message;
if (msg.tool_calls) {
const args = JSON.parse(msg.tool_calls[0].function.arguments);
console.log("model wants order", args.order_id);
}
When JSON mode is the better choice
Not every structured task needs tools. If you want the model to extract fields from text, such as a name, a date and an amount from an email, there is nothing to call. Ask for a JSON object with response_format set to json_object, describe the keys in the prompt and parse the reply. Use tool calling when the model must pick between actions, or when your code has to act on the result and send something back.
Making calls more reliable
- Keep the tool list short. Five clear tools beat twenty overlapping ones. Merge functions that differ only by one argument.
- Use enums. If a parameter has a fixed set of values, list them in the schema instead of describing them in prose.
- Validate before executing. Arguments are model output. Check types and ranges, and never pass them straight into a shell command or a SQL string.
- Return errors as data. When a function fails, send
{"error": "..."}back as the tool result. The model usually corrects itself on the next turn. - Cap iterations. The loop above stops after five rounds. Without a cap, a confused model can burn tokens indefinitely.
- Lower the temperature. For tool selection, 0 to 0.3 gives steadier choices than the default creative range.
When an answer is unexpected, log the X-Request-Id response header with your own trace. It makes support questions much easier to answer.
What a tool-using agent costs
Every loop round resends the conversation, including tool definitions, so input tokens grow. Take a support bot where each round has 2,500 input tokens (history plus tool schemas) and 150 output tokens, and a typical question needs 2 rounds. Input: 5,000 tokens x $0.15 / 1,000,000 = $0.00075. Output: 300 tokens x $0.50 / 1,000,000 = $0.00015. The total is $0.0009 per question, so 1,000 questions cost $0.90.
Billing is pay as you go at $0.15 per 1M input and $0.50 per 1M output tokens, and failed requests are not charged. See the pricing page for top-ups and bonuses, the documentation for the full parameter list, and the key page to claim the $0.50 trial credit. If you are comparing models for this kind of work, the comparison of unfiltered AI models explains how they differ.
The service is text only and the model is a single open-weight model from an independent provider, tuned to answer without content refusals for lawful adult use. Always test your own schemas on your own prompts before shipping.
More guides
Questions and answers
Does the model execute my functions?
No. It only returns the function name and arguments. Your code runs the function and sends the result back in a message with role tool.
Can I force the model to call a specific function?
Yes, through the tool_choice field. Use it when a step must always produce structured arguments.
Why is function.arguments a string?
It follows the OpenAI format, where arguments are a JSON-encoded string. Parse it with json.loads or JSON.parse, and handle the case where it is malformed.
Is streaming supported together with tools?
Yes. Tool calls are streamed in fragments that you concatenate by index before parsing.
Do tool definitions count toward my tokens?
Yes. They are part of the prompt, so they are billed as input tokens on every request, and a long tool list adds up over many rounds.
Your key is one form away
Create an account, copy the key, change the base URL. That is the whole setup.