File tree Expand file tree Collapse file tree 1 file changed +18
-0
lines changed
Filter options
Expand file tree Collapse file tree 1 file changed +18
-0
lines changed
Original file line number Diff line number Diff line change 1
1
"""Python implementation of llama grammar parser directly translated from C++ source file in vendor/llama.cpp/common/grammar-parser.cpp."""
2
2
3
3
# flake8: noqa
4
+ from pathlib import Path
4
5
import sys
5
6
import ctypes
6
7
import enum
@@ -893,6 +894,23 @@ def from_string(cls, grammar: str, verbose: bool = True) -> "LlamaGrammar":
893
894
if verbose :
894
895
print_grammar (file = sys .stdout , state = parsed_grammar )
895
896
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
+ )
896
914
897
915
@classmethod
898
916
def from_json_schema (cls , json_schema : str , verbose : bool = True ) -> "LlamaGrammar" :
You can’t perform that action at this time.
0 commit comments