nsfwllms.comGuide
Tool Calling for LLMs: Working Code Examples
Tool calling lets a model ask your code to run a function and then use the result in its answer. This API supports it with the standard OpenAI fields, so existing client code works after you change the base URL.
Updated
Key points
- Send a tools array, read tool_calls from the reply, run the function yourself, send back a role: tool message.
- Use model
uncensoredand the base URL https://api.nsfwllms.com/v1 with any OpenAI SDK. - tool_choice, streamed tool_calls and JSON mode are all supported.
- The model never runs your code. You validate the arguments and decide what executes.

The loop in four steps
Tool calling for LLMs is a short conversation between your code and the model. The model cannot execute anything. It can only return a structured request that says which function it wants and with what arguments.
- You send the messages plus a
toolsarray that describes each function with a JSON Schema. - The model replies either with normal text or with a
tool_callslist. Each entry has anid, a function name and an arguments string. - Your code parses the arguments, runs the function and appends the result as a message with
role: "tool"and the matchingtool_call_id. - You call the API again. The model reads the result and writes the final answer.
Everything here uses POST /v1/chat/completions. No extra endpoint or beta flag is involved.
First request with curl
Start with raw HTTP so you can see the shapes. Replace the key with your own. The function below rolls a die, which is the sort of small tool a tabletop or text-adventure app needs.
curl https://api.nsfwllms.com/v1/chat/completions \
-H "Authorization: Bearer YOUR_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "uncensored",
"messages": [
{"role": "user", "content": "Roll a twenty-sided die for my attack."}
],
"tools": [{
"type": "function",
"function": {
"name": "roll_dice",
"description": "Roll one die with the given number of sides.",
"parameters": {
"type": "object",
"properties": {"sides": {"type": "integer", "minimum": 2}},
"required": ["sides"]
}
}
}],
"tool_choice": "auto"
}'
If the model decides to use the tool, choices[0].message.content is empty or null and choices[0].message.tool_calls holds the request. Your code takes over from there.
The full round trip in Python
With the openai SDK the whole exchange fits in about twenty lines. Install it with pip install openai.
import json
import random
from openai import OpenAI
client = OpenAI(base_url="https://api.nsfwllms.com/v1", api_key="YOUR_KEY")
def roll_dice(sides: int) -> int:
return random.randint(1, sides)
tools = [{
"type": "function",
"function": {
"name": "roll_dice",
"description": "Roll one die with the given number of sides.",
"parameters": {
"type": "object",
"properties": {"sides": {"type": "integer", "minimum": 2}},
"required": ["sides"],
},
},
}]
messages = [{"role": "user", "content": "Roll a twenty-sided die for my attack."}]
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 = roll_dice(**args)
messages.append({
"role": "tool",
"tool_call_id": call.id,
"content": json.dumps({"result": result}),
})
final = client.chat.completions.create(
model="uncensored", messages=messages, tools=tools
)
print(final.choices[0].message.content)
else:
print(msg.content)
Two details matter. The assistant message that contains tool_calls must stay in the list before the tool results, and every result needs the tool_call_id of the call it answers. Skip either and the second request will be malformed.
Controlling when tools are used
tool_choice decides how much freedom the model has.
"auto"lets the model pick between answering and calling a tool. This is the default when tools are present."none"forbids tool calls for this request. Use it on the final turn if you want a plain text answer.{"type": "function", "function": {"name": "roll_dice"}}forces that specific function.
Write descriptions as if for a new colleague. Say what the function does, when to use it, and what each parameter means. Vague names like do_action produce vague calls. Enums for fixed choices, and required for mandatory fields, cut down on bad arguments.
If you only need structured output and no function to run, JSON mode is simpler: set response_format to {"type": "json_object"} and ask for JSON in the prompt.
Streaming tool calls
With stream: true the arguments arrive in pieces over SSE. Each chunk carries a fragment with an index, and you concatenate fragments for the same index until 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 # a final chunk may carry usage only
delta = chunk.choices[0].delta
for tc in delta.tool_calls or []:
slot = calls.setdefault(tc.index, {"id": "", "name": "", "arguments": ""})
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["arguments"] += tc.function.arguments
for slot in calls.values():
args = json.loads(slot["arguments"]) # parse only when the stream is done
print(slot["name"], args)
Do not parse the arguments until the stream has finished. A half-received string is not valid JSON. Usage is reported at the end of a stream, so you can still log token counts.
Mistakes to design around
- Trusting arguments. The model writes them, so treat them like user input. Validate types and ranges, and wrap
json.loadsin a try block. If parsing fails, send the error back as the tool result and let the model retry once. - Side effects without a gate. For anything that spends money, deletes data or messages a person, require confirmation in your own code. Never map a tool directly to a shell command.
- Endless loops. Cap the number of rounds, for example five. Without a cap, a confused model can keep calling tools.
- Bloated results. Return only the fields the model needs. Large tool output costs input tokens on every later turn.
- Rate limits. A full key allows 8 concurrent requests and 300 per minute. A tool loop makes several sequential calls per user turn, so count them.
Cost stays small. A round trip that sends 1,500 input tokens and gets back 150 output tokens costs 1,500 x $0.15 / 1M + 150 x $0.50 / 1M = $0.000225 + $0.000075 = $0.0003. Rates are listed on the pricing page.
Where to go next
Good first tools for adult fiction, roleplay and companion apps are small and local: a dice roller, a character sheet lookup, a memory store that saves facts the user states, or a clock so the character knows the time of day. The model decides when to read or write them, and your database stays the source of truth.
The quickstart documentation covers authentication and the basic request. You can get a key on the API key page, where new accounts can claim $0.50 of trial credit. That is enough for well over a thousand round trips like the one above.
More guides
Questions and answers
Does this API support tool calling?
Yes. Send tools and tool_choice to POST /v1/chat/completions, read tool_calls from the reply, and return results as role: tool messages. Streamed tool_calls work too.
Which model ID do I use?
Use uncensored in the model field. The base URL is https://api.nsfwllms.com/v1.
Does the model run my functions?
No. It only returns the function name and arguments. Your code runs the function and sends the result back.
Can I combine tool calling with JSON mode?
They are separate features. Use tools when you want your code to run something, and JSON mode when you only want the final answer as a JSON object.