MCPcopy Create free account
hub / github.com/abetlen/llama-cpp-python / _build_repetition

Method _build_repetition

examples/server/server.py:167–216  ·  view source on GitHub ↗
(
        item_rule: str,
        min_items: int,
        max_items: Optional[int],
        separator_rule: Optional[str] = None,
        item_rule_is_literal: bool = False,
    )

Source from the content-addressed store, hash-verified

165
166 @staticmethod
167 def _build_repetition(
168 item_rule: str,
169 min_items: int,
170 max_items: Optional[int],
171 separator_rule: Optional[str] = None,
172 item_rule_is_literal: bool = False,
173 ) -> str:
174 if not separator_rule:
175 if min_items == 0 and max_items == 1:
176 return f"{item_rule}?"
177 if min_items == 1 and max_items is None:
178 return f"{item_rule}+"
179
180 result = ""
181
182 if min_items > 0:
183 if item_rule_is_literal and separator_rule is None:
184 result = '"' + (item_rule[1:-1] * min_items) + '"'
185 else:
186 result = (f" {separator_rule} " if separator_rule else " ").join(
187 [item_rule] * min_items
188 )
189
190 def opt_repetitions(up_to_n: int, prefix_with_sep: bool = False) -> str:
191 content = (
192 f"{separator_rule} {item_rule}"
193 if prefix_with_sep and separator_rule
194 else item_rule
195 )
196 if up_to_n == 0:
197 return ""
198 if up_to_n == 1:
199 return f"({content})?"
200 if separator_rule and not prefix_with_sep:
201 return f"({content} {opt_repetitions(up_to_n - 1, prefix_with_sep=True)})?"
202 return (f"({content} " * up_to_n).rstrip() + (")?" * up_to_n)
203
204 if min_items > 0 and max_items != min_items:
205 result += " "
206
207 if max_items is not None:
208 result += opt_repetitions(max_items - min_items, prefix_with_sep=min_items > 0)
209 else:
210 item_operator = f"({separator_rule + ' ' if separator_rule else ''}{item_rule})"
211 if min_items == 0 and separator_rule:
212 result = f"({item_rule} {item_operator}*)?"
213 else:
214 result += f"{item_operator}*"
215
216 return result
217
218 @classmethod
219 def _primitive_rules(cls) -> Dict[str, "JsonSchemaConverter.BuiltinRule"]:

Callers 3

transformMethod · 0.95
visitMethod · 0.95
_primitive_rulesMethod · 0.80

Calls 1

opt_repetitionsFunction · 0.85

Tested by

no test coverage detected