Skip to content
Open
Show file tree
Hide file tree
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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

- fix(grammar): preserve JSON escapes in schema literals by @remote-controlled-man
- fix: load cached pretrained models in offline mode by @emme1t in #2396
- fix(ci): install matching NVML headers for CUDA wheel builds

Expand Down
4 changes: 2 additions & 2 deletions llama_cpp/llama_grammar.py
Original file line number Diff line number Diff line change
Expand Up @@ -243,8 +243,8 @@ def from_json_schema(cls, json_schema: str, verbose: bool = True) -> "LlamaGramm


INVALID_RULE_CHARS_RE = re.compile(r"[^a-zA-Z0-9-]+")
GRAMMAR_LITERAL_ESCAPE_RE = re.compile(r'[\r\n"]')
GRAMMAR_LITERAL_ESCAPES = {"\r": "\\r", "\n": "\\n", '"': '\\"'}
GRAMMAR_LITERAL_ESCAPE_RE = re.compile(r'[\r\n"\\]')
GRAMMAR_LITERAL_ESCAPES = {"\r": "\\r", "\n": "\\n", '"': '\\"', "\\": "\\\\"}

# whitespace is constrained to a single space char to prevent model "running away" in
# whitespace. Also maybe improves generation quality?
Expand Down
46 changes: 46 additions & 0 deletions tests/test_llama.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,52 @@ def llama_cpp_hybrid_model_path():
return model_path


@pytest.mark.parametrize("kind", ["const", "enum", "property"])
@pytest.mark.parametrize(
"value",
[
pytest.param("line\nend", id="newline"),
pytest.param("line\rend", id="carriage-return"),
pytest.param("tab\tend", id="tab"),
pytest.param('say "hello"', id="quote"),
pytest.param("C:\\temp\\file", id="backslash"),
pytest.param(r"literal\n", id="literal-escape"),
pytest.param("caf\u00e9", id="unicode"),
pytest.param("plain", id="plain"),
pytest.param("a/b", id="slash"),
],
)
def test_json_schema_escaped_literal(llama_cpp_transformer_model_path, kind, value):
import json

if kind == "property":
schema = {
"type": "object",
"properties": {value: {"const": 42}},
"required": [value],
"additionalProperties": False,
}
expected = {value: 42}
else:
schema = {kind: [value] if kind == "enum" else value}
expected = value
grammar = llama_cpp.LlamaGrammar.from_json_schema(json.dumps(schema))
model = llama_cpp.Llama(
model_path=llama_cpp_transformer_model_path,
n_ctx=128,
n_gpu_layers=0,
verbose=False,
)
try:
result = model.create_completion(
"Output JSON:", grammar=grammar, temperature=0, max_tokens=64
)
finally:
model.close()

assert json.loads(result["choices"][0]["text"]) == expected


def test_real_model(llama_cpp_model_path):
import os

Expand Down
Loading