423 lines
13 kB
1"""The rules saying which byte may come next.
2
3Constrained decoding needs one question answered at every step: if the model
4writes this byte, is the answer still on its way to a valid result? Four small
5machines answer it, one per shape of text, and all four expose the same three
6methods, so the decoder is written once against any of them.
7
8Every machine keeps its progress in a plain immutable value. That is what lets
9the decoder try a candidate token and throw the result away when it does not
10fit, without ever having to undo anything.
11
12The rules judge bytes, while what they are built from is text, so the two
13machines comparing against text turn it into bytes over and over: once per byte
14of every candidate token the decoder tries. There are only ever a handful of
15such texts in a run — the braces, the parameter names, the function names — so
16they are converted once and remembered.
17"""
18
19import json
20from functools import lru_cache
21from typing import Any, List, Mapping, Optional, Protocol, Tuple, Union
22
23from pydantic import BaseModel, ConfigDict, Field
24
25from .models import JsonType, ParameterDefinition
26
27_QUOTE = ord('"')
28_BACKSLASH = ord("\\")
29_MINUS = ord("-")
30_DOT = ord(".")
31_ZERO = ord("0")
32_DIGITS = frozenset(b"0123456789")
33_ESCAPABLE = frozenset(b'"\\/bfnrt')
34_BLANKS = frozenset(b" \t\n\r")
35_FIRST_PRINTABLE = 0x20
36
37
38@lru_cache(maxsize=None)
39def utf8(text: str) -> bytes:
40 """Return the bytes of a piece of text, remembered between calls.
41
42 Args:
43 text: The text to convert.
44
45 Returns:
46 Its UTF-8 bytes.
47 """
48 return text.encode("utf-8")
49
50
51class Constraint(Protocol):
52 """What the decoder needs from any rule it enforces."""
53
54 def start(self) -> Any:
55 """Return the progress before anything is written."""
56
57 def advance(self, state: Any, byte: int) -> Optional[Any]:
58 """Return the progress after one byte, or None if that byte is illegal."""
59
60 def is_complete(self, state: Any) -> bool:
61 """Tell whether what is written so far is a finished answer."""
62
63
64class Fixed(BaseModel):
65 """Text that has to be written exactly as it stands.
66
67 Progress is the number of bytes written so far.
68
69 Attributes:
70 text: The expected text.
71 """
72
73 model_config = ConfigDict(frozen=True)
74
75 text: str
76
77 def start(self) -> int:
78 """Return the progress before anything is written.
79
80 Returns:
81 Zero bytes written.
82 """
83 return 0
84
85 def advance(self, state: int, byte: int) -> Optional[int]:
86 """Accept the byte only if it is the next one of the text.
87
88 Args:
89 state: How many bytes are written.
90 byte: The byte the model wants to write.
91
92 Returns:
93 The new count, or None if the byte does not match.
94 """
95 expected = utf8(self.text)
96 if state < len(expected) and expected[state] == byte:
97 return state + 1
98 return None
99
100 def is_complete(self, state: int) -> bool:
101 """Tell whether the whole text is written.
102
103 Args:
104 state: How many bytes are written.
105
106 Returns:
107 True once every byte has been written.
108 """
109 return state == len(utf8(self.text))
110
111
112class Choice(BaseModel):
113 """One word out of a fixed set, spelled to the end.
114
115 Progress is the bytes written so far. This is what forces the model to name
116 a function that really exists, and what spells out true and false.
117
118 Attributes:
119 options: The words allowed.
120 """
121
122 model_config = ConfigDict(frozen=True)
123
124 options: Tuple[str, ...] = Field(min_length=1)
125
126 def start(self) -> bytes:
127 """Return the progress before anything is written.
128
129 Returns:
130 No bytes written.
131 """
132 return b""
133
134 def advance(self, state: bytes, byte: int) -> Optional[bytes]:
135 """Accept the byte only if some option still starts with the result.
136
137 Args:
138 state: The bytes written so far.
139 byte: The byte the model wants to write.
140
141 Returns:
142 The bytes written after it, or None if no option matches.
143 """
144 written = state + bytes([byte])
145 if any(utf8(option).startswith(written) for option in self.options):
146 return written
147 return None
148
149 def is_complete(self, state: bytes) -> bool:
150 """Tell whether a whole option is written.
151
152 Args:
153 state: The bytes written so far.
154
155 Returns:
156 True if they spell one of the options.
157 """
158 return any(state == utf8(option) for option in self.options)
159
160
161class Quoted(BaseModel):
162 """A JSON string: an opening quote, its contents, a closing quote.
163
164 Progress is the name of the step reached. Only the short escapes are
165 allowed (\\n, \\" and the like); \\uXXXX is not, which just means the model
166 has to spell the character itself.
167 """
168
169 model_config = ConfigDict(frozen=True)
170
171 def start(self) -> str:
172 """Return the progress before anything is written.
173
174 Returns:
175 The step waiting for the opening quote.
176 """
177 return "open"
178
179 def advance(self, state: str, byte: int) -> Optional[str]:
180 """Take one byte of the string.
181
182 Args:
183 state: The step reached.
184 byte: The byte the model wants to write.
185
186 Returns:
187 The next step, or None if the byte would break the string.
188 """
189 if state == "open":
190 return "body" if byte == _QUOTE else None
191 if state == "body":
192 if byte == _QUOTE:
193 return "done"
194 if byte == _BACKSLASH:
195 return "escape"
196 return "body" if byte >= _FIRST_PRINTABLE else None
197 if state == "escape":
198 return "body" if byte in _ESCAPABLE else None
199 return None
200
201 def is_complete(self, state: str) -> bool:
202 """Tell whether the closing quote is written.
203
204 Args:
205 state: The step reached.
206
207 Returns:
208 True once the string is closed.
209 """
210 return state == "done"
211
212
213class Number(BaseModel):
214 """A JSON number, with or without a decimal part.
215
216 Progress is the name of the step reached. Leading zeros are refused, since
217 a value such as 007 is not valid JSON.
218
219 Attributes:
220 allow_fraction: Whether a decimal point may be written, which is what
221 tells a number apart from an integer.
222 """
223
224 model_config = ConfigDict(frozen=True)
225
226 allow_fraction: bool = True
227
228 def start(self) -> str:
229 """Return the progress before anything is written.
230
231 Returns:
232 The step waiting for a sign or a first digit.
233 """
234 return "start"
235
236 def advance(self, state: str, byte: int) -> Optional[str]:
237 """Take one byte of the number.
238
239 Args:
240 state: The step reached.
241 byte: The byte the model wants to write.
242
243 Returns:
244 The next step, or None if the byte would break the number.
245 """
246 if state == "start" and byte == _MINUS:
247 return "sign"
248 if state in ("start", "sign"):
249 if byte == _ZERO:
250 return "zero"
251 return "integer" if byte in _DIGITS else None
252 if state == "zero":
253 return "point" if byte == _DOT and self.allow_fraction else None
254 if state == "integer":
255 if byte in _DIGITS:
256 return "integer"
257 return "point" if byte == _DOT and self.allow_fraction else None
258 if state in ("point", "fraction"):
259 return "fraction" if byte in _DIGITS else None
260 return None
261
262 def is_complete(self, state: str) -> bool:
263 """Tell whether the number could stop here.
264
265 Args:
266 state: The step reached.
267
268 Returns:
269 True if the last byte written was a digit.
270 """
271 return state in ("zero", "integer", "fraction")
272
273
274class Spaces(BaseModel):
275 """Blank space where JSON allows it, none of it required.
276
277 Progress is how many blanks are written. This matters more than it sounds:
278 a model writes {"a": 2.0}, so a rule refusing that one space would turn down
279 the token it really wants and leave only poor ones behind, while a rule
280 demanding the space would do the same to a model that writes {"a":2.0}.
281
282 Attributes:
283 limit: How many blanks in a row are tolerated, so that a model cannot
284 spend its whole budget on them.
285 """
286
287 model_config = ConfigDict(frozen=True)
288
289 limit: int = Field(default=8, gt=0)
290
291 def start(self) -> int:
292 """Return the progress before anything is written.
293
294 Returns:
295 No blanks written.
296 """
297 return 0
298
299 def advance(self, state: int, byte: int) -> Optional[int]:
300 """Accept another blank, up to the limit.
301
302 Args:
303 state: How many blanks are written.
304 byte: The byte the model wants to write.
305
306 Returns:
307 The new count, or None for anything that is not a blank.
308 """
309 if byte in _BLANKS and state < self.limit:
310 return state + 1
311 return None
312
313 def is_complete(self, state: int) -> bool:
314 """Tell whether the blanks could stop here, which they always can.
315
316 Args:
317 state: How many blanks are written.
318
319 Returns:
320 True.
321 """
322 return True
323
324
325Part = Union[Fixed, Spaces, Choice, Quoted, Number]
326
327
328class Template(BaseModel):
329 """Several rules written one after another.
330
331 Progress is which part is being written, and how far that part has got.
332 Moving on happens as soon as the current part is finished and refuses the
333 byte, which the next part then takes instead.
334
335 Attributes:
336 parts: The parts, in the order they must appear.
337 """
338
339 model_config = ConfigDict(frozen=True)
340
341 parts: Tuple[Part, ...] = Field(min_length=1)
342
343 def start(self) -> Tuple[int, Any]:
344 """Return the progress before anything is written.
345
346 Returns:
347 The first part, at its own start.
348 """
349 return 0, self.parts[0].start()
350
351 def advance(self, state: Tuple[int, Any], byte: int) -> Optional[Tuple[int, Any]]:
352 """Give the byte to the current part, or to the one after it.
353
354 Args:
355 state: Which part is being written and how far it has got.
356 byte: The byte the model wants to write.
357
358 Returns:
359 The new progress, or None if no part accepts the byte.
360 """
361 index, inner = state
362 while True:
363 advanced = self.parts[index].advance(inner, byte)
364 if advanced is not None:
365 return index, advanced
366 if not self.parts[index].is_complete(inner) or index + 1 == len(self.parts):
367 return None
368 index += 1
369 inner = self.parts[index].start()
370
371 def is_complete(self, state: Tuple[int, Any]) -> bool:
372 """Tell whether the last part is finished.
373
374 Args:
375 state: Which part is being written and how far it has got.
376
377 Returns:
378 True once every part is written.
379 """
380 index, inner = state
381 return index == len(self.parts) - 1 and self.parts[index].is_complete(inner)
382
383
384def value_part(parameter_type: JsonType) -> Part:
385 """Return the rule generating one value of the given type.
386
387 Args:
388 parameter_type: The declared type of the parameter.
389
390 Returns:
391 The rule the model has to follow for that value.
392 """
393 if parameter_type is JsonType.STRING:
394 return Quoted()
395 if parameter_type is JsonType.INTEGER:
396 return Number(allow_fraction=False)
397 if parameter_type is JsonType.NUMBER:
398 return Number(allow_fraction=True)
399 return Choice(options=("true", "false"))
400
401
402def parameters_template(parameters: Mapping[str, ParameterDefinition]) -> Template:
403 """Build the rule generating a whole parameters object.
404
405 The braces, the keys and the commas are fixed text, so the model only ever
406 chooses the values, and each value only in its declared type. Blank space is
407 allowed wherever JSON allows it, so that the model may write the object the
408 way it prefers.
409
410 Args:
411 parameters: The parameters of the chosen function.
412
413 Returns:
414 The rule for the object, such as {"a": <number>, "b": <number>}.
415 """
416 parts: List[Part] = [Fixed(text="{")]
417 for index, (name, parameter) in enumerate(parameters.items()):
418 if index:
419 parts += [Spaces(), Fixed(text=",")]
420 parts += [Spaces(), Fixed(text=json.dumps(name)), Spaces(), Fixed(text=":")]
421 parts += [Spaces(), value_part(parameter.type)]
422 parts += [Spaces(), Fixed(text="}")]
423 return Template(parts=tuple(parts))