EN ▾
Get API key

LLM API Function Calling: A Working Example

LLM API function calling lets the model ask your code to run a function and then use the result in its answer. This guide builds a working example against an OpenAI-compatible endpoint, including the second round trip and streaming.

Updated

A chat bubble reaching toward a wrench, gear and database icon, showing an LLM calling external functions

Key points

  • You describe functions in a tools array; the model replies with tool_calls instead of text when it wants one run.
  • Your code runs the function and sends the result back as a message with role tool and the matching tool_call_id.
  • Streamed tool calls arrive in pieces; join the argument strings by index before parsing.
  • Always validate arguments and cap the number of loop rounds.

How the exchange works

A model cannot look up the weather or query your database. It can only produce text. Function calling is a protocol that turns a request for such an action into structured data your code can act on. The exchange has four steps:

  1. You send the conversation plus a tools list that describes the functions you offer.
  2. If the model decides a function is needed, its reply has no final text. It has a tool_calls list with the function name and a JSON string of arguments.
  3. You run the function yourself and append the result to the conversation as a message with role: "tool".
  4. You call the API again. The model now writes the answer using the result.

The model never runs anything. Your code decides whether to run the function at all, which is where you add permission checks. This API follows the OpenAI format for all of it, so existing agent frameworks work after you change the base URL and key. The docs list the request fields.

Step 1: define the tools

A tool is a name, a plain-language description and a JSON Schema for the parameters. The description is what the model reads when deciding whether to call it, so write it for a person who has never seen your code.

import json
from openai import OpenAI

client = OpenAI(base_url="https://api.uncensoredllm.cc/v1", api_key="YOUR_KEY")

tools = [{
    "type": "function",
    "function": {
        "name": "get_weather",
        "description": "Get the current weather for a city. Use when the user asks about weather or what to wear.",
        "parameters": {
            "type": "object",
            "properties": {
                "city": {"type": "string", "description": "City name, for example Oslo"},
                "unit": {"type": "string", "enum": ["c", "f"]},
            },
            "required": ["city"],
        },
    },
}]

def get_weather(city, unit="c"):
    return {"city": city, "temp": 7, "unit": unit, "sky": "cloudy"}

REGISTRY = {"get_weather": get_weather}

The function here returns fixed data so you can test the flow without a real weather service. Replace the body with a real lookup later. Keep the registry as a dictionary: it gives you an explicit allow-list of what the model may trigger.

Step 2: send the request and read tool_calls

messages = [{"role": "user", "content": "Should I bring a jacket in Oslo today?"}]

r = client.chat.completions.create(
    model="uncensored",
    messages=messages,
    tools=tools,
    tool_choice="auto",
)
msg = r.choices[0].message
print(msg.tool_calls)

With tool_choice="auto" the model chooses. Use "none" to forbid calls, or name one function to force it. If the model calls get_weather, you will see an entry with an id, the function name and an arguments string such as {"city": "Oslo"}. Note that arguments is a string, not an object. You must parse it.

The model may also return several calls at once, for example weather for two cities. Handle the list, not just the first item, and reply to each call with its own tool message. Logging the raw tool_calls during development saves a lot of guessing later.

Step 3: run the function and return the result

messages.append(msg.model_dump(exclude_none=True))

for call in msg.tool_calls or []:
    name = call.function.name
    try:
        args = json.loads(call.function.arguments)
        result = REGISTRY[name](**args)
    except Exception as e:
        result = {"error": str(e)}
    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)

Three rules keep this working. First, append the assistant message that contains the tool calls before the tool results; the model needs to see its own request. Second, each tool message must carry the tool_call_id of the call it answers. Third, send errors back as results instead of crashing. The model can often recover, for example by asking the user for a valid city.

The same tools list goes into the second request, because the model may want another call after seeing the first result. In real agents this becomes a loop: call, run tools, call again, until a reply has no tool_calls. Always cap the loop, for example at 5 rounds, so a confused model cannot spin forever and spend your credit. A compact version of that loop looks like this:

def run(messages, max_rounds=5):
    for _ in range(max_rounds):
        r = client.chat.completions.create(
            model="uncensored", messages=messages, tools=tools
        )
        msg = r.choices[0].message
        if not msg.tool_calls:
            return msg.content
        messages.append(msg.model_dump(exclude_none=True))
        for call in msg.tool_calls:
            out = REGISTRY[call.function.name](**json.loads(call.function.arguments))
            messages.append({"role": "tool", "tool_call_id": call.id, "content": json.dumps(out)})
    return "stopped: too many tool rounds"

Add the try block from the earlier snippet around the function call before using this in anything real.

Streaming tool calls

With stream: true, a tool call arrives as fragments inside delta.tool_calls. The first fragment for a call carries its id and function name. Later fragments carry slices of the arguments string. Each fragment has an index that tells you which call it belongs to.

stream = client.chat.completions.create(
    model="uncensored", messages=messages, tools=tools, stream=True
)

calls = {}
text = []
for chunk in stream:
    if not chunk.choices:
        continue
    delta = chunk.choices[0].delta
    if delta.content:
        text.append(delta.content)
    for tc in 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

for slot in calls.values():
    args = json.loads(slot["args"] or "{}")

Parse the JSON only after the stream ends. A half-received arguments string is not valid JSON, and parsing it early is the most common bug here. Remember that a streamed request holds a concurrency slot until the stream closes: 8 at once on a full key, 2 on a trial key.

Pitfalls and how to fix them

  • The model never calls the tool. Make the description more specific about when to use it, and mention the function in the system prompt. Lower temperature helps with consistency.
  • Arguments are not valid JSON. Wrap json.loads in a try block and return the error as the tool result. The model usually retries with a fixed call.
  • Wrong or invented function name. The registry lookup raises a KeyError; send that back as an error result instead of letting it crash.
  • Missing tool_call_id. If one call gets no matching tool message, the next request is malformed. Reply to every call, even if only with an error.
  • Dangerous functions. Do not give the model a tool that deletes data or sends money without a confirmation step in your own code.

Models differ in how reliably they follow schemas. If you need strict output rather than actions, response_format: {"type": "json_object"} is a simpler tool. Compare model behaviour on your own prompts; the notes on choosing an uncensored model explain what to test.

What a tool-calling turn costs

Tool definitions count as input tokens on every request, so three tools of about 150 tokens each add 450 tokens to each call. Take the weather example: the first call sends 800 input tokens and gets 60 back; the second sends 1,000 input tokens (the history plus the result) and gets 150 back.

Input:  1,800 tokens x $0.15 / 1M = $0.00027
Output:   210 tokens x $0.50 / 1M = $0.000105
Total for the exchange: $0.000375

Less than four hundredths of a cent. Costs only add up with many tools, long histories or deep loops, so keep descriptions short and tool lists focused. See the pricing page for rates. To try the example, get an API key; the $0.50 trial credit (one click, 7 days, no card) covers more than a thousand exchanges like this one.

Questions and answers

Is function calling the same as JSON mode?

No. JSON mode forces the reply itself to be valid JSON. Function calling lets the model request that your code run a named function with arguments.

Do I need a special library?

No. The OpenAI SDKs for Python and Node work after you change the base URL, key and model name. Frameworks that support OpenAI-style tools also work.

How do tool results go back to the model?

Append a message with role tool, the matching tool_call_id and the result as a string, then call the API again with the full message list.

Can tool calls be streamed?

Yes. They arrive as tool_calls deltas with an index. Join the argument fragments for each index and parse the JSON when the stream ends.

Your key is one form away

Create an account, copy the key, change the base URL. That is the whole setup.

Get API key