readme

215 lines 9.6 kB

This project has been created as part of the 42 curriculum by mleitao.

Description

This project turns natural-language requests into structured function calls. It doesn't answer the request. If asked for the sum of 40 and 2, it replies with {"name": "fn_add_numbers", "parameters": {"a": 40.0, "b": 2.0}}.

The available functions are read from a definitions file, the requests from a prompts file, and one call per prompt is written to the results file. The model chooses the function and the arguments; the program decides what it is allowed to say.

Instructions

Build

CommandDescription
make, make installCreate the venv and install dependencies
make runAnswer the promps of data/input/
make debugStart up the debugger
make lintRun flake8 and mypy with mandatory flags
make lint-strictRun flake8 and mypy with --strict flag
make cleanRemove Python caches
make fcleanRemove Python caches and the venv
make testRun the test suite with pytest

make run accepts arguments through ARGS, and the program can also be called directly:

uv run python -m src [--functions_definition <file>] [--input <file>] [--output <file>]
                     [--model <name>] [--verbose] [--trace]

Inputs default to data/input/, and the results are written to data/output/function_calling_results.json.

Example usage
$ uv run python -m src
wrote data/output/function_calling_results.json
[
  {
    "prompt": "What is the sum of 2 and 3?",
    "name": "fn_add_numbers",
    "parameters": {
     "a": 2.0,
     "b": 3.0
    }
  },
  {
    "prompt": "Greet shrek",
    "name": "fn_greet",
    "parameters": {
      "name": "shrek"
    }
  }
]

Algorithm explanation

Generation is a loop: the prompt is tokenized, the model scores every token of its vocabulary, one token is picked, and the picked token is appended to the context before the next round. Constrained decoding intervenes between the scores and the pick.

Rather than masking the whole vocabulary at every step, the scores are sorted once and walked from best to worst, and the first token the rule accepts is taken. This is the same answer a mask would give, and it costs almost nothing: the first candidate is usually already legal.

Deciding whether a token is legal happens on bytes, not on text. src/vocab.py rebuilds the bytes behind every token id from the vocabulary file, undoing the printable mapping the file uses to stay readable. A candidate token is fed to the rule byte by byte, and any byte the rule refuses rejects the whole token, without anything to undo — every rule keeps its progress in an immutable value.

The rules themselves live in src/grammar.py, as small machines exposing start, advance and is_complete:

RuleWhat it allows
Fixedone exact piece of text, such as { or a parameter name
Choiceone word out of a set, such as a function name or true/false
Quoteda JSON string, escapes included
Numbera JSON number, integer only when the parameter says so
Spacesoptional blanks, wherever JSON allows them
Templateseveral rules one after another

Each prompt takes two constrained generations. The first runs under a Choice over the declared names, so the chosen function always exists. The second runs under a Template built from that function's parameters, so the object always has the declared keys in the declared order, with values of the declared types. Schema compliance is therefore not checked after the fact — it cannot be broken in the first place.

Where an answer ends is the model's call too. A rule that is satisfied may still allow more, as a list of names does when one name begins another. There the decoder offers the model its end-of-turn marker: once the rule is satisfied and the model scores that marker above every legal continuation, the answer is finished.

Design decisions

The rules judge bytes. Tokens do not line up with characters, and a single token may carry half of one. Working on bytes means the rules never have to know what a token is.

Two generations instead of one. Choosing a function and filling in its arguments are different questions, and the second one is easier to ask well once the first is answered.

Optional blanks. A model writes {"a": 2.0}. A rule refusing that space would turn down the token the model really wants and leave only poor ones behind, and a rule demanding it would do the same to a model that writes {"a":2.0}. Blanks are allowed where JSON allows them, and never required.

The layout is read off the model. Conversation markers differ between models, and using one a model was never trained on costs accuracy for nothing. A marker the model really knows comes back from its tokenizer as a single token, and that is how the layout is chosen — which is also what lets --model work.

Nothing crashes. A bad entry is skipped with a warning, a prompt that fails falls back to empty arguments so the results file keeps one entry per prompt, and the command line catches everything else.

Performance analysis

One prompt costs two generations, and one generation costs one forward pass per token written. On the sample data a prompt takes roughly twenty passes in total: three to spell a function name, the rest to write the arguments object. The per-step work outside the model is one sort of the score vector plus a byte-by-byte check of the few best candidates, which is negligible next to the forward pass itself.

The vocabulary is read once, at start-up, and kept as a table of bytes indexed by token id. The texts the rules compare against — the braces, the parameter names, the function names — are converted to bytes once and remembered, rather than at every byte of every candidate token. Measured against a fake model, so that only the constraint work is timed, that is worth about 4% of an already small figure: 8.3 ms per generation instead of 8.7 ms. It is not where the time goes, and the honest conclusion is that there is little to win outside the model itself.

Model loading dominates the run for a small number of prompts; the answers themselves are fast, and the eleven sample prompts finish well inside the five minutes the subject allows.

Challenges faced

The hardest part was not the JSON — it was stopping the model from being helpful. Asked for the argument of fn_reverse_string on Reverse the string 'hello', a model happily answers olleh. The wanted answer is hello. The prompt in src/prompting.py spends most of its words saying so, and the comments there record which line counters which failure.

Ending an answer was the other one. A rule being satisfied is not a reason to stop, since fn_greet also begins fn_greet_loudly; the end-of-turn marker had to become a choice the model makes, rather than something the loop decides for it.

Testing strategy

make test runs the suite. Nothing in it downloads a model or touches the network: the vocabulary is made up on the spot, and the models are fakes. Most are noise, which proves the guarantee the project rests on — a model with no opinion at all still cannot write invalid JSON. Others are rigged to rank an illegal token first, or to fail outright, so the rule and the fallback are exercised where they matter. The edge cases the subject lists are covered too: missing files, invalid JSON, empty vocabularies, tokens carrying several characters, and every declared type.

Resources

  • The subject, en.subject.pdf (v1.5).
  • The llm_sdk package shipped with it.
  • The JSON grammar, json.org.
  • The byte-level mapping used by GPT-2-style vocabularies, from the original GPT-2 encoder.
LLM Usage

Claude (Claude Code) was used as a working assistant, not as an author of record. It helped with the design discussions behind the constrained decoding loop, with writing and reviewing tests, and with the --trace reporting and the public decode. Every line was read, kept or rewritten by hand, and the behaviour was checked against the real model.

Bonus

Models beyond Qwen/Qwen3-0.6B. --model <name> drives another model. The conversation layout, the end-of-turn markers and the vocabulary file are all discovered from the model itself rather than assumed.

Watching the generation. --trace reports every step on stderr: the answer so far, the best-scoring tokens, and what became of each one — taken, allowed (legal but passed over) or blocked (refused by the rule). The token actually taken is always shown, however deep it sat. Standard output stays clean, and the answer is the same as in an untraced run.

trace: choosing a function
  step 0  so far ""
    taken       33.72  id    8822  "fn"
    blocked     23.47  id    4064  "None"
    blocked     22.41  id    5168  " fn"
  step 1  so far "fn"
    taken       37.41  id    2891  "_add"
    allowed     23.22  id    5228  "_sub"
    blocked     23.83  id    8581  "_ADD"
  done "fn_add_numbers" (the rule allows nothing more)

The closing line also names why the generation stopped: the rule allowing nothing more, the model ending its turn, no legal token being left, or the token budget running out.

Reading tokens back. decode in src/vocab.py turns token ids into text using only the vocabulary file. Every answer the program writes goes through it; the SDK's own decode is never called.

  1*This project has been created as part of the 42 curriculum by mleitao.*
  2
  3# Description
  4
  5This project turns natural-language requests into structured function calls. It doesn't
  6answer the request. If asked for the sum of 40 and 2, it replies with
  7`{"name": "fn_add_numbers", "parameters": {"a": 40.0, "b": 2.0}}`.
  8
  9The available functions are read from a definitions file, the requests from a prompts
 10file, and one call per prompt is written to the results file. The model chooses the
 11function and the arguments; the program decides what it is allowed to say.
 12
 13# Instructions
 14
 15### Build
 16
 17Command | Description
 18--|--
 19`make`, `make install` | Create the venv and install dependencies
 20`make run` | Answer the promps of data/input/
 21`make debug` | Start up the debugger
 22`make lint` | Run `flake8` and `mypy` with mandatory flags
 23`make lint-strict` | Run `flake8` and `mypy` with `--strict` flag
 24`make clean` | Remove Python caches
 25`make fclean` | Remove Python caches and the venv
 26`make test` | Run the test suite with `pytest`
 27
 28`make run` accepts arguments through `ARGS`, and the program can also be called directly:
 29
 30```
 31uv run python -m src [--functions_definition <file>] [--input <file>] [--output <file>]
 32                     [--model <name>] [--verbose] [--trace]
 33```
 34
 35Inputs default to `data/input/`, and the results are written to
 36`data/output/function_calling_results.json`.
 37
 38#### Example usage
 39
 40```
 41$ uv run python -m src
 42wrote data/output/function_calling_results.json
 43```
 44
 45```json
 46[
 47  {
 48    "prompt": "What is the sum of 2 and 3?",
 49    "name": "fn_add_numbers",
 50    "parameters": {
 51     "a": 2.0,
 52     "b": 3.0
 53    }
 54  },
 55  {
 56    "prompt": "Greet shrek",
 57    "name": "fn_greet",
 58    "parameters": {
 59      "name": "shrek"
 60    }
 61  }
 62]
 63```
 64
 65
 66# Algorithm explanation
 67
 68Generation is a loop: the prompt is tokenized, the model scores every token of its
 69vocabulary, one token is picked, and the picked token is appended to the context before
 70the next round. Constrained decoding intervenes between the scores and the pick.
 71
 72Rather than masking the whole vocabulary at every step, the scores are sorted once and
 73walked from best to worst, and the first token the rule accepts is taken. This is the
 74same answer a mask would give, and it costs almost nothing: the first candidate is
 75usually already legal.
 76
 77Deciding whether a token is legal happens on bytes, not on text. `src/vocab.py` rebuilds
 78the bytes behind every token id from the vocabulary file, undoing the printable mapping
 79the file uses to stay readable. A candidate token is fed to the rule byte by byte, and
 80any byte the rule refuses rejects the whole token, without anything to undo — every rule
 81keeps its progress in an immutable value.
 82
 83The rules themselves live in `src/grammar.py`, as small machines exposing `start`,
 84`advance` and `is_complete`:
 85
 86| Rule | What it allows |
 87| --- | --- |
 88| `Fixed` | one exact piece of text, such as `{` or a parameter name |
 89| `Choice` | one word out of a set, such as a function name or `true`/`false` |
 90| `Quoted` | a JSON string, escapes included |
 91| `Number` | a JSON number, integer only when the parameter says so |
 92| `Spaces` | optional blanks, wherever JSON allows them |
 93| `Template` | several rules one after another |
 94
 95Each prompt takes two constrained generations. The first runs under a `Choice` over the
 96declared names, so the chosen function always exists. The second runs under a `Template`
 97built from that function's parameters, so the object always has the declared keys in the
 98declared order, with values of the declared types. Schema compliance is therefore not
 99checked after the fact — it cannot be broken in the first place.
100
101Where an answer ends is the model's call too. A rule that is satisfied may still allow
102more, as a list of names does when one name begins another. There the decoder offers the
103model its end-of-turn marker: once the rule is satisfied and the model scores that marker
104above every legal continuation, the answer is finished.
105
106# Design decisions
107
108**The rules judge bytes.** Tokens do not line up with characters, and a single token may
109carry half of one. Working on bytes means the rules never have to know what a token is.
110
111**Two generations instead of one.** Choosing a function and filling in its arguments are
112different questions, and the second one is easier to ask well once the first is answered.
113
114**Optional blanks.** A model writes `{"a": 2.0}`. A rule refusing that space would turn
115down the token the model really wants and leave only poor ones behind, and a rule
116demanding it would do the same to a model that writes `{"a":2.0}`. Blanks are allowed
117where JSON allows them, and never required.
118
119**The layout is read off the model.** Conversation markers differ between models, and
120using one a model was never trained on costs accuracy for nothing. A marker the model
121really knows comes back from its tokenizer as a single token, and that is how the layout
122is chosen — which is also what lets `--model` work.
123
124**Nothing crashes.** A bad entry is skipped with a warning, a prompt that fails falls
125back to empty arguments so the results file keeps one entry per prompt, and the command
126line catches everything else.
127
128# Performance analysis
129
130One prompt costs two generations, and one generation costs one forward pass per token
131written. On the sample data a prompt takes roughly twenty passes in total: three to spell
132a function name, the rest to write the arguments object. The per-step work outside the
133model is one sort of the score vector plus a byte-by-byte check of the few best
134candidates, which is negligible next to the forward pass itself.
135
136The vocabulary is read once, at start-up, and kept as a table of bytes indexed by token
137id. The texts the rules compare against — the braces, the parameter names, the function
138names — are converted to bytes once and remembered, rather than at every byte of every
139candidate token. Measured against a fake model, so that only the constraint work is
140timed, that is worth about 4% of an already small figure: 8.3 ms per generation instead
141of 8.7 ms. It is not where the time goes, and the honest conclusion is that there is
142little to win outside the model itself.
143
144Model loading dominates the run for a small number of prompts; the answers themselves
145are fast, and the eleven sample prompts finish well inside the five minutes the subject
146allows.
147
148# Challenges faced
149
150The hardest part was not the JSON — it was stopping the model from being helpful. Asked
151for the argument of `fn_reverse_string` on `Reverse the string 'hello'`, a model happily
152answers `olleh`. The wanted answer is `hello`. The prompt in `src/prompting.py` spends
153most of its words saying so, and the comments there record which line counters which
154failure.
155
156Ending an answer was the other one. A rule being satisfied is not a reason to stop, since
157`fn_greet` also begins `fn_greet_loudly`; the end-of-turn marker had to become a choice
158the model makes, rather than something the loop decides for it.
159
160# Testing strategy
161
162`make test` runs the suite. Nothing in it downloads a model or touches the network: the
163vocabulary is made up on the spot, and the models are fakes. Most are noise, which proves
164the guarantee the project rests on — a model with no opinion at all still cannot write
165invalid JSON. Others are rigged to rank an illegal token first, or to fail outright, so
166the rule and the fallback are exercised where they matter. The edge cases the subject
167lists are covered too: missing files, invalid JSON, empty vocabularies, tokens carrying
168several characters, and every declared type.
169
170# Resources
171
172- The subject, `en.subject.pdf` (v1.5).
173- The `llm_sdk` package shipped with it.
174- The JSON grammar, [json.org](https://www.json.org/json-en.html).
175- The byte-level mapping used by GPT-2-style vocabularies, from the original
176  [GPT-2 encoder](https://github.com/openai/gpt-2/blob/master/src/encoder.py).
177
178#### LLM Usage
179
180Claude (Claude Code) was used as a working assistant, not as an author of record. It
181helped with the design discussions behind the constrained decoding loop, with writing and
182reviewing tests, and with the `--trace` reporting and the public `decode`. Every line was
183read, kept or rewritten by hand, and the behaviour was checked against the real model.
184
185# Bonus
186
187**Models beyond `Qwen/Qwen3-0.6B`.** `--model <name>` drives another model. The
188conversation layout, the end-of-turn markers and the vocabulary file are all discovered
189from the model itself rather than assumed.
190
191**Watching the generation.** `--trace` reports every step on stderr: the answer so far,
192the best-scoring tokens, and what became of each one — `taken`, `allowed` (legal but
193passed over) or `blocked` (refused by the rule). The token actually taken is always
194shown, however deep it sat. Standard output stays clean, and the answer is the same as in
195an untraced run.
196
197```
198trace: choosing a function
199  step 0  so far ""
200    taken       33.72  id    8822  "fn"
201    blocked     23.47  id    4064  "None"
202    blocked     22.41  id    5168  " fn"
203  step 1  so far "fn"
204    taken       37.41  id    2891  "_add"
205    allowed     23.22  id    5228  "_sub"
206    blocked     23.83  id    8581  "_ADD"
207  done "fn_add_numbers" (the rule allows nothing more)
208```
209
210The closing line also names why the generation stopped: the rule allowing nothing more,
211the model ending its turn, no legal token being left, or the token budget running out.
212
213**Reading tokens back.** `decode` in `src/vocab.py` turns token ids into text using only
214the vocabulary file. Every answer the program writes goes through it; the SDK's own
215`decode` is never called.