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

Class SchemaConverter

llama_cpp/llama_grammar.py:380–941  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

378
379
380class SchemaConverter:
381 def __init__(self, *, prop_order, allow_fetch, dotall, raw_pattern):
382 self._prop_order = prop_order
383 self._allow_fetch = allow_fetch
384 self._dotall = dotall
385 self._raw_pattern = raw_pattern
386 self._rules = {
387 "space": SPACE_RULE,
388 }
389 self._refs = {}
390 self._refs_being_resolved = set()
391
392 def _format_literal(self, literal):
393 escaped = GRAMMAR_LITERAL_ESCAPE_RE.sub(
394 lambda m: GRAMMAR_LITERAL_ESCAPES.get(m.group(0)), literal
395 )
396 return f'"{escaped}"'
397
398 def not_literal(
399 self, literal: str, dotall: bool = True, maybe_escaped_underscores=False
400 ) -> str:
401 """
402 not_literal('a') -> '[^a]'
403 not_literal('abc') -> '([^a] | "a" ([^b] | "b" ([^c])?)?)?'
404 """
405 assert len(literal) > 0, "Empty literal not supported"
406
407 def recurse(i: int):
408 c = literal[i]
409 if maybe_escaped_underscores and c == "_":
410 yield f"[^{c}\\\\]"
411 yield " | "
412 yield f'"\\\\"? "{c}"'
413 else:
414 yield f"[^{c}]"
415 if i < len(literal) - 1:
416 yield " | "
417 yield self._format_literal(c)
418 yield " ("
419 yield from recurse(i + 1)
420 yield ")?"
421
422 return "".join(("(", *recurse(0), ")"))
423
424 def _add_rule(self, name, rule):
425 esc_name = INVALID_RULE_CHARS_RE.sub("-", name)
426 if esc_name not in self._rules or self._rules[esc_name] == rule:
427 key = esc_name
428 else:
429 i = 0
430 while (
431 f"{esc_name}{i}" in self._rules
432 and self._rules[f"{esc_name}{i}"] != rule
433 ):
434 i += 1
435 key = f"{esc_name}{i}"
436 self._rules[key] = rule
437 return key

Callers 1

json_schema_to_gbnfFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…