​call_me_maybe /
src / pipeline.py
52 commits
13-08-2026
235 lines 8.2 kB
  1"""Answering the prompts: pick the function, then fill in its arguments.
  2
  3Every prompt takes two constrained generations. The first is written under a
  4rule that only allows the declared function names, so the answer is always a
  5real function. The second is written under a rule built from that function's
  6parameters, so the answer is always a JSON object of the right shape and types.
  7
  8A prompt that fails anyway falls back to a call with empty values, because the
  9results file has to hold exactly one entry per prompt.
 10"""
 11
 12import json
 13import sys
 14from pathlib import Path
 15from typing import Any, Dict, List, Sequence, Tuple
 16
 17from pydantic import BaseModel, ConfigDict, Field
 18
 19from .decoder import ConstrainedDecoder
 20from .grammar import Choice, parameters_template
 21from .io_utils import warn
 22from .models import FunctionCall, FunctionDefinition, JsonType
 23from .prompting import ChatLayout, arguments_prompt, selection_prompt, stop_token_ids
 24from .trace import Tracer
 25from .vocab import load_token_bytes
 26
 27DEFAULT_MODEL = "Qwen/Qwen3-0.6B"
 28
 29_EMPTY_VALUES: Dict[JsonType, Any] = {
 30    JsonType.STRING: "",
 31    JsonType.NUMBER: 0.0,
 32    JsonType.INTEGER: 0,
 33    JsonType.BOOLEAN: False,
 34}
 35
 36
 37class PipelineError(Exception):
 38    """Raised when the model cannot be loaded."""
 39
 40
 41class Pipeline(BaseModel):
 42    """Turns prompts into function calls.
 43
 44    Attributes:
 45        decoder: The constrained generation loop to drive.
 46        definitions: Every function that may be chosen.
 47        layout: How this model expects its conversations to be written.
 48        verbose: Whether to report each answer on stderr.
 49    """
 50
 51    model_config = ConfigDict(arbitrary_types_allowed=True, frozen=True)
 52
 53    decoder: ConstrainedDecoder
 54    definitions: Tuple[FunctionDefinition, ...] = Field(min_length=1)
 55    layout: ChatLayout = ChatLayout()
 56    verbose: bool = False
 57
 58    def run(self, prompts: Sequence[str]) -> List[FunctionCall]:
 59        """Answer every prompt, in order.
 60
 61        Args:
 62            prompts: The requests to answer.
 63
 64        Returns:
 65            One call per prompt.
 66        """
 67        calls = []
 68        for index, prompt in enumerate(prompts, start=1):
 69            call = self.answer(prompt)
 70            if self.verbose:
 71                print(f"[{index}/{len(prompts)}] {call.name} {call.parameters}", file=sys.stderr)
 72            calls.append(call)
 73        return calls
 74
 75    def answer(self, prompt: str) -> FunctionCall:
 76        """Answer one prompt, falling back rather than failing.
 77
 78        Args:
 79            prompt: The request to answer.
 80
 81        Returns:
 82            The call to write to the results file.
 83        """
 84        definition = self.definitions[0]
 85        try:
 86            definition = self._choose_function(prompt)
 87            parameters = self._extract_arguments(definition, prompt)
 88        except Exception as error:
 89            warn(f"falling back to empty arguments for {prompt!r}: {error}")
 90            parameters = {name: _EMPTY_VALUES[p.type] for name, p in definition.parameters.items()}
 91        return FunctionCall(prompt=prompt, name=definition.name, parameters=parameters)
 92
 93    def _choose_function(self, prompt: str) -> FunctionDefinition:
 94        """Ask the model which function answers the prompt.
 95
 96        A name that is the start of a longer one is answerable too: the rule is
 97        satisfied as soon as it is written, and the decoder then lets the model
 98        end its turn rather than forcing it to spell the longer name out.
 99
100        Args:
101            prompt: The request to answer.
102
103        Returns:
104            The chosen function, which is always one of the declared ones.
105        """
106        names = tuple(definition.name for definition in self.definitions)
107        written = selection_prompt(self.definitions, prompt, self.layout)
108        chosen = self.decoder.generate(written, Choice(options=names), "choosing a function")
109        return next(definition for definition in self.definitions if definition.name == chosen)
110
111    def _extract_arguments(self, definition: FunctionDefinition, prompt: str) -> Dict[str, Any]:
112        """Ask the model for the arguments of the chosen function.
113
114        Args:
115            definition: The function whose arguments are wanted.
116            prompt: The request to answer.
117
118        Returns:
119            The arguments, one per declared parameter.
120        """
121        written = self.decoder.generate(
122            arguments_prompt(definition, prompt, self.layout),
123            parameters_template(definition.parameters),
124            f"filling in the arguments of {definition.name}",
125        )
126        values: Dict[str, Any] = json.loads(written)
127        return {name: _as_type(values[name], parameter.type) for name, parameter in definition.parameters.items()}
128
129
130def build_pipeline(
131    definitions: Sequence[FunctionDefinition],
132    model_name: str = DEFAULT_MODEL,
133    verbose: bool = False,
134    trace: bool = False,
135) -> Pipeline:
136    """Load the model and assemble everything needed to answer prompts.
137
138    Args:
139        definitions: Every function that may be chosen.
140        model_name: The model to drive, named the way its host names it.
141        verbose: Whether to report each answer on stderr.
142        trace: Whether to report every step of every generation on stderr.
143
144    Returns:
145        The ready pipeline.
146
147    Raises:
148        PipelineError: If the model or its vocabulary cannot be loaded.
149    """
150    llm = _load_model(model_name)
151    table = _load_vocabulary(llm)
152    layout = ChatLayout.for_model(llm)
153    stop_ids = stop_token_ids(llm)
154    decoder = ConstrainedDecoder(
155        llm=llm,
156        token_bytes=tuple(table),
157        stop_ids=stop_ids,
158        tracer=Tracer() if trace else None,
159    )
160    return Pipeline(decoder=decoder, definitions=tuple(definitions), layout=layout, verbose=verbose)
161
162
163def _load_model(model_name: str) -> Any:
164    """Load the language model on the fastest device that works.
165
166    The graphics card comes first, then whatever the SDK picks by itself, then
167    the processor. The card is asked for by number: plain "cuda" makes the SDK
168    spread the weights across devices, which needs a package we do not have.
169
170    Args:
171        model_name: The model to load.
172
173    Returns:
174        The loaded model.
175
176    Raises:
177        PipelineError: If no device works.
178    """
179    from llm_sdk import Small_LLM_Model
180
181    failure = "no device was tried"
182    for device in ("cuda:0", None, "cpu"):
183        try:
184            if device is None:
185                return Small_LLM_Model(model_name=model_name)
186            return Small_LLM_Model(model_name=model_name, device=device)
187        except Exception as error:
188            failure = str(error)
189    raise PipelineError(f"{model_name} could not be loaded: {failure}")
190
191
192def _load_vocabulary(llm: Any) -> List[bytes]:
193    """Read the bytes of every token id from whichever file the model ships.
194
195    Most models ship a vocab.json; those that do not keep the same table inside
196    their tokenizer.json instead.
197
198    Args:
199        llm: The loaded model.
200
201    Returns:
202        The byte table, indexed by token id.
203
204    Raises:
205        PipelineError: If neither file can be read.
206    """
207    failure = "no vocabulary file was found"
208    for path_of in (llm.get_path_to_vocab_file, llm.get_path_to_tokenizer_file):
209        try:
210            return load_token_bytes(Path(path_of()))
211        except Exception as error:
212            failure = str(error)
213    raise PipelineError(f"the vocabulary could not be read: {failure}")
214
215
216def _as_type(value: Any, parameter_type: JsonType) -> Any:
217    """Give a generated value the exact Python type its parameter declares.
218
219    The rules already guarantee the shape, so this only turns a number written
220    without a decimal point, such as 16, into 16.0 where a number is expected.
221
222    Args:
223        value: The value read back from the generated JSON.
224        parameter_type: The declared type of the parameter.
225
226    Returns:
227        The value, converted.
228    """
229    if parameter_type is JsonType.NUMBER:
230        return float(value)
231    if parameter_type is JsonType.INTEGER:
232        return int(value)
233    if parameter_type is JsonType.BOOLEAN:
234        return bool(value)
235    return str(value)