Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Added back from_file method to LlamaGrammar #1673

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Aug 12, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions llama_cpp/llama_grammar.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""Python implementation of llama grammar parser directly translated from C++ source file in vendor/llama.cpp/common/grammar-parser.cpp."""

# flake8: noqa
from pathlib import Path
import sys
import ctypes
import enum
Expand Down Expand Up @@ -893,6 +894,23 @@ def from_string(cls, grammar: str, verbose: bool = True) -> "LlamaGrammar":
if verbose:
print_grammar(file=sys.stdout, state=parsed_grammar)
return cls(parsed_grammar)

@classmethod
def from_file(cls, file: Union[str, Path], verbose: bool = True) -> "LlamaGrammar":
try:
with open(file) as f:
grammar = f.read()
except Exception as err:
raise Exception(
f"{cls.from_file.__name__}: error reading grammar file: {err}"
)

if grammar:
return cls.from_string(grammar, verbose=verbose)

raise ValueError(
f"{cls.from_file.__name__}: error parsing grammar file: params_grammer is empty"
)

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