bots-garden/razorbillpublic Fork
⑂ v1.0.0
Commits
⬇ Clone ▾
git clone https://git.rickub.com/bots-garden/razorbill.git
git clone ssh://git@rickub.com/bots-garden/razorbill.git

Host key fingerprint (ed25519): SHA256:iycHnxEyq0Q7uyVpB7JlznP0G7JrTPXLYRcAU5CSLhc — verify it before your first connect.

Download ZIP
use-function-calling.md · 75 lines · 3.5 KBmarkdown
Blame HistoryOpen raw

How to use function calling

This guide lets a model call functions of your program: it asks for a call, your code runs it, and the model uses the result in its answer. It assumes a server running with a chat model that supports tools; the examples use mlx-community/Qwen3-4B-4bit.

1. Describe the functions

tools = [{
    "type": "function",
    "function": {
        "name": "get_weather",
        "description": "Current weather for a city",
        "parameters": {
            "type": "object",
            "properties": {"city": {"type": "string"}},
            "required": ["city"],
        },
    },
}]

2. Ask, run the calls, send the results back

import json
from openai import OpenAI

client = OpenAI(base_url="http://127.0.0.1:7920/v1", api_key="unused")
messages = [{"role": "user", "content": "What's the weather like in Lyon?"}]

def get_weather(city):
    return {"city": city, "temp_c": 7, "sky": "rain"}

while True:
    answer = client.chat.completions.create(
        model="mlx-community/Qwen3-4B-4bit", messages=messages, tools=tools
    ).choices[0]
    if answer.finish_reason != "tool_calls":
        print(answer.message.content)
        break
    messages.append(answer.message.model_dump(exclude_none=True))
    for call in answer.message.tool_calls:
        result = get_weather(**json.loads(call.function.arguments))
        messages.append({"role": "tool", "tool_call_id": call.id, "content": json.dumps(result)})

Each request carries the whole conversation, the assistant's calls and the tool results included: the server keeps nothing between requests.

Force a call

  • tool_choice="required": the answer is a call to one of the tools.
  • tool_choice={"type": "function", "function": {"name": "get_weather"}}: the answer is a call to get_weather.
  • tool_choice="none": the model answers in text, without seeing the tools.

A forced call is generated under a grammar: the name exists and the arguments match the schema. This works for models whose tool-call syntax is <tool_call>{…}</tool_call> (Qwen, Hermes…). Other families (Llama 3, Mistral, Gemma) answer 400 to a forced call: use tool_choice="auto" with them.

Get several calls at once

A forced call produces one call. To let the model ask for several in one answer (weather and time, for example), send parallel_tool_calls=True. With parallel_tool_calls=False, only the first call is kept, whatever the mode.

Guarantee valid arguments in auto mode

Add "strict": True to a function: its arguments are then generated under its schema whenever the model calls it, while the model remains free not to call it. The schema must not use keywords the decoder cannot enforce (see structured output).

Variants

  • Streaming: with stream=True, each call arrives whole in one chunk, in delta.tool_calls with its index; the last chunk has finish_reason: "tool_calls".
  • LangChain: ChatOpenAI(base_url=…, model=…).bind_tools([...]) works as with OpenAI (see use OpenAI clients).
  • Small models (below 1B) often answer in text in auto mode instead of calling; force the call or use a larger model.
  • Thinking: a reasoning model may think before calling; add extra_body={"reasoning_effort": "none"} to skip it.

See also

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# How to use function calling

This guide lets a model call functions of your program: it asks for a call, your code runs it, and the model uses the result in its answer. It assumes a server running with a chat model that supports tools; the examples use `mlx-community/Qwen3-4B-4bit`.

## 1. Describe the functions

```python
tools = [{
    "type": "function",
    "function": {
        "name": "get_weather",
        "description": "Current weather for a city",
        "parameters": {
            "type": "object",
            "properties": {"city": {"type": "string"}},
            "required": ["city"],
        },
    },
}]
```

## 2. Ask, run the calls, send the results back

```python
import json
from openai import OpenAI

client = OpenAI(base_url="http://127.0.0.1:7920/v1", api_key="unused")
messages = [{"role": "user", "content": "What's the weather like in Lyon?"}]

def get_weather(city):
    return {"city": city, "temp_c": 7, "sky": "rain"}

while True:
    answer = client.chat.completions.create(
        model="mlx-community/Qwen3-4B-4bit", messages=messages, tools=tools
    ).choices[0]
    if answer.finish_reason != "tool_calls":
        print(answer.message.content)
        break
    messages.append(answer.message.model_dump(exclude_none=True))
    for call in answer.message.tool_calls:
        result = get_weather(**json.loads(call.function.arguments))
        messages.append({"role": "tool", "tool_call_id": call.id, "content": json.dumps(result)})
```

Each request carries the whole conversation, the assistant's calls and the `tool` results included: the server keeps nothing between requests.

## Force a call

- `tool_choice="required"`: the answer is a call to one of the tools.
- `tool_choice={"type": "function", "function": {"name": "get_weather"}}`: the answer is a call to `get_weather`.
- `tool_choice="none"`: the model answers in text, without seeing the tools.

A forced call is generated under a grammar: the name exists and the arguments match the schema. This works for models whose tool-call syntax is `<tool_call>{…}</tool_call>` (Qwen, Hermes…). Other families (Llama 3, Mistral, Gemma) answer 400 to a forced call: use `tool_choice="auto"` with them.

## Get several calls at once

A forced call produces one call. To let the model ask for several in one answer (weather and time, for example), send `parallel_tool_calls=True`. With `parallel_tool_calls=False`, only the first call is kept, whatever the mode.

## Guarantee valid arguments in auto mode

Add `"strict": True` to a function: its arguments are then generated under its schema whenever the model calls it, while the model remains free not to call it. The schema must not use keywords the decoder cannot enforce (see [structured output](get-structured-output.md#variants)).

## Variants

- **Streaming**: with `stream=True`, each call arrives whole in one chunk, in `delta.tool_calls` with its `index`; the last chunk has `finish_reason: "tool_calls"`.
- **LangChain**: `ChatOpenAI(base_url=…, model=…).bind_tools([...])` works as with OpenAI (see [use OpenAI clients](use-openai-clients.md)).
- **Small models** (below 1B) often answer in text in `auto` mode instead of calling; force the call or use a larger model.
- **Thinking**: a reasoning model may think before calling; add `extra_body={"reasoning_effort": "none"}` to skip it.

## See also

- Every field of `tools` and `tool_choice`: [HTTP API reference](../reference/http-api.md#tools).
- Why forced calls depend on the model family: [constrained decoding](../explanation/constrained-decoding.md).