​call_me_maybe /
src / prompting.py
52 commits
13-08-2026
215 lines 7.9 kB
  1"""Writing the two questions the model is asked.
  2
  3The rules in grammar.py decide what the model may say; the wording here decides
  4what it wants to say, and that is what accuracy depends on.
  5
  6How a conversation is written out differs between models, and using a layout a
  7model was never trained on costs accuracy for nothing. So the layout is read off
  8the model itself rather than assumed: a marker it really knows comes back from
  9its tokenizer as a single token, and one it has never seen does not.
 10"""
 11
 12from typing import Any, List, Optional, Sequence, Tuple
 13
 14from pydantic import BaseModel, ConfigDict
 15
 16from .models import FunctionDefinition
 17
 18CHAT_START = "<|im_start|>"
 19CHAT_END = "<|im_end|>"
 20END_OF_TEXT = "<|endoftext|>"
 21THINK_OPEN = "<think>"
 22THINK_CLOSE = "</think>"
 23PRELUDE = f"{THINK_OPEN}\n\n{THINK_CLOSE}\n\n"
 24
 25_SELECTION_TASK = (
 26    "You match a user request to exactly one function from the list below.\n"
 27    "Answer with the name of the function, and nothing else."
 28)
 29
 30# Telling the model not to apply the function is what this question lives or
 31# dies on. Asked for the argument of fn_reverse_string on "Reverse the string
 32# 'hello'", a helpful model answers olleh; the answer wanted is hello. The line
 33# about patterns is the counterweight: a regex has to be written, not copied,
 34# and without it the model copies the word "numbers" out of the request. The
 35# line about quotes is a second counterweight: asked to copy Say "hello" the
 36# model rewrites the quotes as ', since spelling a double quote inside a JSON
 37# string costs it an escape it would rather not pay.
 38_ARGUMENTS_TASK = (
 39    "You extract the arguments of a function call from a user request.\n"
 40    "The function has already been chosen; your only job is to fill in its parameters.\n"
 41    "Copy each value out of the request exactly as it appears there. Never apply the\n"
 42    "function, never compute a result, never answer the request itself.\n"
 43    "Punctuation inside a value is part of the value: a quote character in the request\n"
 44    "stays that same character in the answer, a double quote written as \\\".\n"
 45    "A parameter that asks for a pattern or an expression is written, not copied:\n"
 46    "supply the one that matches what the request describes.\n"
 47    "Answer with a JSON object holding every parameter, and nothing else."
 48)
 49
 50
 51class ChatLayout(BaseModel):
 52    """How one model expects a conversation to be written out.
 53
 54    Attributes:
 55        turn_start: The marker opening a turn, empty for a model that has none.
 56        turn_end: The marker closing a turn.
 57        prelude: What the answer opens with, such as the empty reasoning block
 58            Qwen3 uses to say it is answering straight away.
 59    """
 60
 61    model_config = ConfigDict(frozen=True)
 62
 63    turn_start: str = CHAT_START
 64    turn_end: str = CHAT_END
 65    prelude: str = PRELUDE
 66
 67    @classmethod
 68    def for_model(cls, llm: Any) -> "ChatLayout":
 69        """Work out the layout from the markers the model actually knows.
 70
 71        A marker the model never learnt would be read as ordinary text, so it
 72        is only used when the model turns it into one token of its own.
 73
 74        Args:
 75            llm: The model to ask.
 76
 77        Returns:
 78            The layout to write its contexts with.
 79        """
 80        chats = _is_one_token(llm, CHAT_START) and _is_one_token(llm, CHAT_END)
 81        thinks = _is_one_token(llm, THINK_OPEN) and _is_one_token(llm, THINK_CLOSE)
 82        return cls(
 83            turn_start=CHAT_START if chats else "",
 84            turn_end=CHAT_END if chats else "",
 85            prelude=PRELUDE if thinks else "",
 86        )
 87
 88    def render(self, system: str, request: str) -> str:
 89        """Lay out one conversation, up to where the answer begins.
 90
 91        Args:
 92            system: The instructions describing the task.
 93            request: The user request to answer.
 94
 95        Returns:
 96            The text the model is asked to continue.
 97        """
 98        if not self.turn_start:
 99            return f"{system}\n\nRequest: {request}\nAnswer: {self.prelude}"
100        return (
101            f"{self.turn_start}system\n{system}{self.turn_end}\n"
102            f"{self.turn_start}user\n{request}{self.turn_end}\n"
103            f"{self.turn_start}assistant\n{self.prelude}"
104        )
105
106
107def stop_token_ids(llm: Any) -> Tuple[int, ...]:
108    """Find the ids the model ends a turn with.
109
110    These write no text of their own, so the decoder never picks them up from
111    the vocabulary; it has to be told which they are. A model that knows neither
112    marker returns nothing, and then only the rule decides where an answer ends.
113
114    Args:
115        llm: The model to ask.
116
117    Returns:
118        The ids of the markers this model knows, without repeats.
119    """
120    found: List[int] = []
121    for marker in (CHAT_END, END_OF_TEXT):
122        token_id = _single_token(llm, marker)
123        if token_id is not None and token_id not in found:
124            found.append(token_id)
125    return tuple(found)
126
127
128def _is_one_token(llm: Any, marker: str) -> bool:
129    """Tell whether the model knows a marker as a token of its own.
130
131    Args:
132        llm: The model to ask.
133        marker: The text to encode.
134
135    Returns:
136        True if the marker encodes to exactly one token.
137    """
138    return _single_token(llm, marker) is not None
139
140
141def _single_token(llm: Any, marker: str) -> Optional[int]:
142    """Return the one id a marker encodes to, if it encodes to just one.
143
144    A marker the model never learnt is read as ordinary text and comes back as
145    several tokens, which is how an unknown marker is told from a known one.
146
147    Args:
148        llm: The model to ask.
149        marker: The text to encode.
150
151    Returns:
152        The token id, or None if the model does not know the marker.
153    """
154    try:
155        encoded = llm.encode(marker)[0].tolist()
156    except Exception:
157        return None
158    return int(encoded[0]) if len(encoded) == 1 else None
159
160
161def signature(definition: FunctionDefinition) -> str:
162    """Describe a function the way an annotated signature reads.
163
164    Args:
165        definition: The function to describe.
166
167    Returns:
168        A line such as "fn_add_numbers(a: number, b: number)".
169    """
170    parameters = ", ".join(f"{name}: {parameter.type.value}" for name, parameter in definition.parameters.items())
171    return f"{definition.name}({parameters})"
172
173
174def selection_prompt(
175    definitions: Sequence[FunctionDefinition],
176    request: str,
177    layout: Optional[ChatLayout] = None,
178) -> str:
179    """Build the question asking which function answers the request.
180
181    Args:
182        definitions: Every function that may be chosen.
183        request: The user request.
184        layout: The layout to write with, or None for the default one.
185
186    Returns:
187        The text the model is asked to continue with a function name.
188    """
189    catalogue = "\n".join(f"- {signature(definition)}: {definition.description}" for definition in definitions)
190    return (layout or ChatLayout()).render(f"{_SELECTION_TASK}\n\nFunctions:\n{catalogue}", request)
191
192
193def arguments_prompt(
194    definition: FunctionDefinition,
195    request: str,
196    layout: Optional[ChatLayout] = None,
197) -> str:
198    """Build the question asking for the arguments of the chosen function.
199
200    Args:
201        definition: The function whose arguments are wanted.
202        request: The user request.
203        layout: The layout to write with, or None for the default one.
204
205    Returns:
206        The text the model is asked to continue with a JSON object.
207    """
208    parameters = "\n".join(f"- {name}: {parameter.type.value}" for name, parameter in definition.parameters.items())
209    system = (
210        f"{_ARGUMENTS_TASK}\n\n"
211        f"Function: {signature(definition)}\n"
212        f"Purpose: {definition.description}\n"
213        f"Parameters:\n{parameters or '- none'}"
214    )
215    return (layout or ChatLayout()).render(system, request)