Skip to content

Can't create grammar from JSON schema if referencing multiple definitions #1048

Closed

Description

@DavideWalder

Prerequisites

Please answer the following questions for yourself before submitting an issue.

  • I am running the latest code. Development is very rapid so there are no tagged versions as of now.
  • I carefully followed the README.md.
  • I searched using keywords relevant to my issue to make sure that I am creating a new issue that is not already open (or closed).
  • I reviewed the Discussions, and have a new bug or useful enhancement to share.

Expected Behavior

I can't create a LlamaGrammar from a JSON schema if multiple definitions are referenced. See example below.
It might also be the root cause of #1043.

The feature should either be implemented or an explicit error should be raised.

Current Behavior

Throws an error since refs are not supported

Environment and Context

❯ uname -a
Darwin Davides-MacBook-Pro-2.local 23.2.0 Darwin Kernel Version 23.2.0: Wed Nov 15 21:55:06 PST 2023; root:xnu-10002.61.3~2/RELEASE_ARM64_T6020 arm64

Failure Information (for bugs)

AssertionError: Unrecognized schema: {'$ref': '#/definitions/A'}

Steps to Reproduce

from llama_cpp.llama_grammar import LlamaGrammar
from pydantic import BaseModel


class A(BaseModel):
    some_field: str


class B(BaseModel):
    a: A


LlamaGrammar.from_json_schema(B.schema_json())

Activity

  1. nyanp commented on Jan 3, 2024

    @nyanp

    I encountered the same issue. One workaround I found is to inlining references using jsonref:

    import json
    from llama_cpp.llama_grammar import LlamaGrammar
    from pydantic import BaseModel
    from jsonref import replace_refs
    
    
    class A(BaseModel):
        some_field: str
    
    
    class B(BaseModel):
        a: A
    
    
    def json_schema_with_inlining(model):
        replaced = replace_refs(model.schema(), proxies=False)
        if "$defs" in replaced:
            del replaced["$defs"]
        return json.dumps(replaced)
    
    
    grammar = LlamaGrammar.from_json_schema(json_schema_with_inlining(B))
  2. abetlen commented on Jan 12, 2024

    @abetlen
    Owner

    @nyanp thanks for the code, I'll test this out and integrate a fix.

  3. added
    bug
    on Jan 12, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions