Function Calling with an OpenAI-Compatible API
Function calling lets a model ask your code to run a function and then use the result. This guide shows the full loop against an OpenAI-compatible endpoint, plus JSON mode and streaming.

Key points
- You describe functions in the tools parameter; the model replies with tool_calls instead of text.
- Your code runs the function and sends the result back as a message with role tool.
- JSON mode (response_format json_object) is the simpler choice when you only need structured output.
- Open-weight models can produce malformed arguments, so validate before you execute.
How function calling works
Searching for function calling openai api usually means one thing: you want the model to trigger code in your app, such as looking up an order, checking the weather or saving a note. The model never runs anything itself. It reads a list of function descriptions you supply, decides whether one is needed, and returns the function name plus a JSON string of arguments. Your program runs the function and sends the result back so the model can write the final answer.
The exchange has four steps:
- You send the messages plus a
toolslist that describes each function with a JSON Schema. - The model answers with
tool_callsin the assistant message, and no normal text. - You run each call and append the output as a message with
role: "tool"and the matchingtool_call_id. - You call the API again. The model now writes the answer using the tool output.
This API follows the same format, so code written for the OpenAI SDK works after you change the base URL, the key and the model name. Tool calling, tool_choice, streamed tool_calls and role: "tool" results are all supported with the model uncensored.
A complete example in Python
This script defines one function, get_order_status, and runs the whole loop. Replace the fake lookup with your own code.
import json
from openai import OpenAI
client = OpenAI(base_url="https://api.openainsfw.top/v1", api_key="YOUR_KEY")
tools = [{
"type": "function",
"function": {
"name": "get_order_status",
"description": "Look up the shipping status of an order by its id.",
"parameters": {
"type": "object",
"properties": {
"order_id": {"type": "string", "description": "Order id such as A1042"}
},
"required": ["order_id"],
},
},
}]
def get_order_status(order_id):
return {"order_id": order_id, "status": "shipped", "eta_days": 2}
messages = [{"role": "user", "content": "Where is order A1042?"}]
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 details trip people up. First, the assistant message that contains the tool calls must stay in the history before the tool results, otherwise the second request has no context for the tool_call_id. Second, arguments is a string, not an object, so you parse it with json.loads.
Choosing tool_choice
The tool_choice parameter controls whether the model may skip the tools.
| Value | Behavior | Use it when |
|---|---|---|
"auto" | The model decides between text and a call | General assistants |
"none" | Tools are ignored for this turn | You want a plain answer after the tools already ran |
"required" | The model must call some tool | Routing or extraction steps |
| A named function | The model must call that function | You always want one specific action |
Forcing a call is a good way to turn the model into a structured extractor. If your pipeline always needs a record of the form name, date, amount, define one function with those fields and force it. Read the arguments and ignore the function; it never has to exist.
Keep the tool list short. Every tool description is sent as input on each request, so ten large schemas add real tokens. At $0.15 per 1M input tokens, 1,500 tokens of tool definitions across 10,000 requests is 15M tokens, which is $2.25. That is small, but it adds up on a busy bot, and fewer tools also make the model pick the right one more often.
JSON mode when you only need structure
Sometimes there is no function to run. You just want the answer as JSON that your code can parse. Use JSON mode with response_format, and say in the prompt what shape you want.
resp = client.chat.completions.create(
model="uncensored",
response_format={"type": "json_object"},
messages=[
{"role": "system", "content": "Reply with JSON only: {\"title\": string, \"tags\": [string]}"},
{"role": "user", "content": "Summarize: a short story about a lighthouse keeper."},
],
)
data = json.loads(resp.choices[0].message.content)
print(data["title"], data["tags"])
JSON mode makes sure the output is valid JSON. It does not make sure the keys match your plan, so describe the keys in the prompt and check them after parsing. Use tools when the model must choose between actions, and JSON mode when the output is the product.
Curl version
curl https://api.openainsfw.top/v1/chat/completions \
-H "Authorization: Bearer YOUR_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "uncensored",
"response_format": {"type": "json_object"},
"messages": [
{"role": "system", "content": "Reply with JSON only."},
{"role": "user", "content": "List three colors as {\"colors\": [...]}"}
]
}'Streaming tool calls
With stream: true, tool calls arrive in pieces. Each chunk carries a delta.tool_calls list, and each entry has an index. The function name usually comes in the first chunk for that index, and the arguments string arrives as fragments you must join. Do not try to parse JSON until the stream ends.
import OpenAI from "openai";
const client = new OpenAI({
baseURL: "https://api.openainsfw.top/v1",
apiKey: process.env.API_KEY,
});
const stream = await client.chat.completions.create({
model: "uncensored",
stream: true,
messages: [{ role: "user", content: "Where is order A1042?" }],
tools: [{
type: "function",
function: {
name: "get_order_status",
parameters: {
type: "object",
properties: { order_id: { type: "string" } },
required: ["order_id"],
},
},
}],
});
const calls = {};
for await (const chunk of stream) {
const deltas = chunk.choices[0]?.delta?.tool_calls ?? [];
for (const d of deltas) {
const slot = (calls[d.index] ??= { id: "", name: "", args: "" });
if (d.id) slot.id = d.id;
if (d.function?.name) slot.name += d.function.name;
if (d.function?.arguments) slot.args += d.function.arguments;
}
}
console.log(Object.values(calls).map(c => ({ ...c, args: JSON.parse(c.args) })));
Usage numbers arrive at the end of the stream. Remember that a streamed request holds one of your concurrency slots until the stream is closed, so finish reading it before you start the next one on a trial key.
Pitfalls and how to fix them
The model here is an open-weight model, not a hosted flagship from a big lab, so treat tool output as untrusted input. These are the problems you will meet most often.
- Malformed or incomplete arguments. Wrap
json.loadsin a try block. On failure, send the error text back as the tool result and let the model correct itself once. Limit this to two retries. - Wrong or invented function names. Check the name against a dictionary of real handlers before calling anything. Never call a function by string name without that check.
- Missing required fields. Validate against your own schema. Marking a field required in the schema helps but does not guarantee it.
- Endless loops. Cap the number of tool rounds, for example five. If the model still wants another call, stop and return what you have.
- Vague descriptions. The model picks tools by reading their descriptions. Say what the function does, when to use it and what each argument means, in a sentence each.
- Dangerous actions. For anything that deletes data or spends money, require a human confirmation in your code, not a polite request in the prompt.
Testing the failure paths on purpose is worth an hour. Send a prompt that gives the model nothing to fill an argument with, such as asking about an order without giving an id, and watch what comes back. A good tool description tells the model to ask the user for the missing value instead of guessing. Add that sentence to the description, run the same prompt again, and compare. Doing this with five or six awkward prompts will teach you more about the model than any benchmark, and each test run costs a fraction of a cent.
Here is the arithmetic for a typical agent step. A request with 2,000 input tokens (history plus tool schemas) and a 150-token tool call costs 2,000 / 1,000,000 x $0.15 = $0.0003 for input and 150 / 1,000,000 x $0.50 = $0.000075 for output, so $0.000375. The second call, which carries the tool result and writes a 300-token answer from 2,400 input tokens, costs $0.00036 + $0.00015 = $0.00051. A full round trip is about $0.000885, so 1,000 of them cost about $0.89. Prices and top-up bonuses are on the pricing page.
Low temperature helps with all of these. Use 0 to 0.3 for tool-heavy steps and raise it only for the final user-facing answer. The documentation lists the supported parameters, and the API key page shows how to claim the $0.50 trial credit so you can test the loop without paying. Failed or refused requests are not charged, which keeps experiments cheap.
More guides
Questions and answers
Does this API support function calling?
Yes. It supports the tools and tool_choice parameters, streamed tool_calls, and results sent back as role tool messages, using the model ID uncensored.
What is the difference between function calling and JSON mode?
Function calling lets the model choose an action and return arguments for your code to run. JSON mode only guarantees that the reply is valid JSON, which suits data extraction.
Why is call.function.arguments a string?
The OpenAI format returns arguments as a JSON-encoded string. Parse it with json.loads or JSON.parse, and handle the case where the text is not valid JSON.
Can I force the model to call a specific function?
Yes. Set tool_choice to an object naming the function, or use required to make it call any one of the tools.
Do tool definitions cost tokens?
Yes. They are sent as input on every request, so long schemas add to your bill at $0.15 per 1M input tokens. Keep descriptions short and the tool list small.
Your key is one form away
Create an account, copy the key, change the base URL. That is the whole setup.