Skip to content

Commit 95a1533

Browse files
authored
fix: Added back from_file method to LlamaGrammar (abetlen#1673)
1 parent 4244151 commit 95a1533

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed

llama_cpp/llama_grammar.py

+18
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
"""Python implementation of llama grammar parser directly translated from C++ source file in vendor/llama.cpp/common/grammar-parser.cpp."""
22

33
# flake8: noqa
4+
from pathlib import Path
45
import sys
56
import ctypes
67
import enum
@@ -893,6 +894,23 @@ def from_string(cls, grammar: str, verbose: bool = True) -> "LlamaGrammar":
893894
if verbose:
894895
print_grammar(file=sys.stdout, state=parsed_grammar)
895896
return cls(parsed_grammar)
897+
898+
@classmethod
899+
def from_file(cls, file: Union[str, Path], verbose: bool = True) -> "LlamaGrammar":
900+
try:
901+
with open(file) as f:
902+
grammar = f.read()
903+
except Exception as err:
904+
raise Exception(
905+
f"{cls.from_file.__name__}: error reading grammar file: {err}"
906+
)
907+
908+
if grammar:
909+
return cls.from_string(grammar, verbose=verbose)
910+
911+
raise ValueError(
912+
f"{cls.from_file.__name__}: error parsing grammar file: params_grammer is empty"
913+
)
896914

897915
@classmethod
898916
def from_json_schema(cls, json_schema: str, verbose: bool = True) -> "LlamaGrammar":

0 commit comments

Comments
 (0)