o
    V۷iP	                     @   sR   d dl mZ ddlmZmZ d dlmZ ddlZed Zdede	d	e	fd
dZ
dS )   )	LLMatcher    )LiteralList)any_to_larkN)
larkgbnfebnfcfggrammarjson_schemajsonregexchoice
llguidanceformattextreturnc              
   C   s   | dkr	t |S | dv r,zt|}W n ty& } ztd| d}~ww t |S | dv r5t |S | dkr>t |S | dkr`t|trMt	
|}n|}dd	d
d |D  }t |S | dkrf|S td|  )a  
    Create a llguidance grammar definition from a given grammar text
    of the specified type.

    Args:
        format: The format of the grammar text
            "lark": Lark grammar, see https://github.com/guidance-ai/llguidance/blob/main/docs/syntax.md
            "gbnf", "ebnf", "cfg", "grammar": Lark grammar or GBNF grammar, see https://github.com/ggml-org/llama.cpp/blob/master/grammars/README.md
            "json_schema", "json": JSON schema, see https://github.com/guidance-ai/llguidance/blob/main/docs/json_schema.md
            "regex": Regular expression, see https://docs.rs/regex/latest/regex/#syntax
            "choice": JSON-formatted list of strings, e.g. '["a", "b", "c"]'
            "llguidance": JSON object like: {"grammars": [{"lark_grammar": "..."},{"json_schema": {...}}]}
        text: The grammar text

    Returns:
        The llguidance grammar definition as a string.
        This can be passed to LLInterpreter or LLMatcher.

    Raises:
        ValueError: If the format is not recognized

    Note:
        To get "any JSON object" grammar use:
            grammar_from("json_schema", '{"type": "object"}')
    r   )r   r	   r
   r   z1Failed to convert the grammar from GBNF to Lark: N)r   r   r   r   zstart: z | c                 s   s    | ]}t |V  qd S )N)r   dumps).0x r   N/home/ubuntu/vllm_env/lib/python3.10/site-packages/llguidance/_grammar_from.py	<genexpr>@   s    zgrammar_from.<locals>.<genexpr>r   zUnknown grammar type: )r   grammar_from_larkr   	Exception
ValueErrorgrammar_from_json_schemagrammar_from_regex
isinstancestrr   loadsjoin)r   r   elstr   r   r   r   grammar_from   s.   





r%   )_libr   typingr   r   gbnf_to_larkr   r   GrammarFormatr    r%   r   r   r   r   <module>   s    