File tree Expand file tree Collapse file tree 2 files changed +39
-1
lines changed
Filter options
Expand file tree Collapse file tree 2 files changed +39
-1
lines changed
Original file line number Diff line number Diff line change @@ -1433,7 +1433,6 @@ def _add_rule(self, name: str, rule: str):
1433
1433
1434
1434
def visit (self , schema : Dict [str , Any ], name : str ) -> str :
1435
1435
schema_type : Optional [str ] = schema .get ("type" ) # type: ignore
1436
- assert isinstance (schema_type , str ), f"Unrecognized schema: { schema } "
1437
1436
rule_name = name or "root"
1438
1437
1439
1438
if "$defs" in schema :
Original file line number Diff line number Diff line change 1
1
import llama_cpp
2
+ import json
2
3
3
4
tree = """
4
5
leaf ::= "."
5
6
node ::= leaf | "(" node node ")"
6
7
root ::= node
7
8
"""
8
9
10
+
9
11
def test_grammar_from_string ():
10
12
grammar = llama_cpp .LlamaGrammar .from_string (tree )
11
13
assert grammar ._n_rules == 3
12
14
assert grammar ._start_rule_index == 2
13
15
assert grammar .grammar is not None
16
+
17
+
18
+ def test_composed_pydantic_grammar ():
19
+ """
20
+ from pydantic import BaseModel
21
+
22
+ class A(BaseModel):
23
+ a: int
24
+
25
+ class B(BaseModel):
26
+ a: A
27
+ b: int
28
+ """
29
+
30
+ # This schema corresponds to the grammar in the comment above.
31
+ # We don't use the pydantic models directly to avoid the dependency.
32
+ schema = {
33
+ "$defs" : {
34
+ "A" : {
35
+ "properties" : {"a" : {"title" : "A" , "type" : "integer" }},
36
+ "required" : ["a" ],
37
+ "title" : "A" ,
38
+ "type" : "object" ,
39
+ }
40
+ },
41
+ "properties" : {
42
+ "a" : {"$ref" : "#/$defs/A" },
43
+ "b" : {"title" : "B" , "type" : "integer" },
44
+ },
45
+ "required" : ["a" , "b" ],
46
+ "title" : "B" ,
47
+ "type" : "object" ,
48
+ }
49
+
50
+ grammar = llama_cpp .LlamaGrammar .from_json_schema (json .dumps (schema ))
51
+
52
+ assert grammar .grammar is not None
You can’t perform that action at this time.
0 commit comments