Skip to content

mistral_common.guidance.grammar_factory

GrammarFactory(tokenizer)

Generates Lark grammars that constrain model output for a given tokenizer.

Grammars cover tool calls, JSON schema output, and thinking sections, and are rendered from tokenizer-version-specific jinja templates using the tokenizer's special tokens.

Requires llguidance and jinja2 to be installed.

Parameters:

Name Type Description Default
tokenizer MistralTokenizer

The Mistral tokenizer to generate grammars for. Must be a Tekken tokenizer with version >= v11 (see is_supported).

required

Raises:

Type Description
ValueError

If the tokenizer is not supported.

ImportError

If llguidance or jinja2 is not installed.

Source code in src/mistral_common/guidance/grammar_factory.py
def __init__(self, tokenizer: MistralTokenizer) -> None:
    r"""Initialize the grammar factory.

    Requires llguidance and jinja2 to be installed.

    Args:
        tokenizer: The Mistral tokenizer to generate grammars for. Must be a
            Tekken tokenizer with version >= v11 (see
            [`is_supported`][mistral_common.guidance.grammar_factory.GrammarFactory.is_supported]).

    Raises:
        ValueError: If the tokenizer is not supported.
        ImportError: If llguidance or jinja2 is not installed.
    """
    assert_llguidance_installed()
    assert_jinja2_installed()
    self._tokenizer = tokenizer.instruct_tokenizer.tokenizer
    if not self.is_supported(tokenizer):
        raise ValueError(
            f"Guidance requires a Tekken tokenizer with version >= v11, "
            f"got {type(self._tokenizer).__name__} {self._tokenizer.version.value}"
        )
    self._llg_tokenizer = from_mistral_tokenizer(tokenizer)
    self._special_token_map = self._build_special_token_map()

llg_tokenizer property

The llguidance tokenizer used to validate grammars.

Returns:

Type Description
LLTokenizer

The LLTokenizer instance adapted from this Mistral tokenizer.

get_grammar_for_chat_request(request, template)

Resolve a chat request to its lark grammar in one pass.

Returns None when the request needs no grammar and raises InvalidRequestException for inconsistent request combinations. template is used as given; callers select their custom or default template before calling this method.

Parameters:

Name Type Description Default
request ChatCompletionRequest

Chat completion request to resolve.

required
template str

Jinja template used to render the grammar.

required

Returns:

Type Description
str | None

The rendered lark grammar, or None when no grammar is needed.

Raises:

Type Description
InvalidRequestException

If the request contains an incompatible tool choice or response format.

Source code in src/mistral_common/guidance/grammar_factory.py
def get_grammar_for_chat_request(self, request: ChatCompletionRequest, template: str) -> str | None:
    r"""Resolve a chat request to its lark grammar in one pass.

    Returns `None` when the request needs no grammar and raises
    `InvalidRequestException` for inconsistent request combinations.
    `template` is used as given; callers select their custom or default
    template before calling this method.

    Args:
        request: Chat completion request to resolve.
        template: Jinja template used to render the grammar.

    Returns:
        The rendered lark grammar, or `None` when no grammar is needed.

    Raises:
        InvalidRequestException: If the request contains an incompatible
            tool choice or response format.
    """
    spec = _get_grammar_spec(request=request)
    if spec is None:
        return None
    return self._render(
        template=template,
        mode=spec.mode,
        tools=spec.tools,
        json_schema=spec.json_schema,
        parallel_tool_calls=spec.parallel_tool_calls,
        json_only=spec.json_only,
        force_tool_names=spec.force_tool_names,
    )

get_lark_for_json_schema(template, json_schema)

Return a lark grammar that only accepts JSON matching the given schema.

Convenience wrapper around get_lark_from_jinja that disables tool calls and text alternatives, constraining output to the JSON schema alone.

Parameters:

Name Type Description Default
template str

Jinja template to render, as obtained from select_jinja_template.

required
json_schema dict[str, Any]

The JSON schema the output must conform to.

required

Returns:

Type Description
str

The rendered lark grammar string that only matches the given JSON schema.

Source code in src/mistral_common/guidance/grammar_factory.py
def get_lark_for_json_schema(self, template: str, json_schema: dict[str, Any]) -> str:
    r"""Return a lark grammar that only accepts JSON matching the given schema.

    Convenience wrapper around `get_lark_from_jinja` that disables tool calls
    and text alternatives, constraining output to the JSON schema alone.

    Args:
        template: Jinja template to render, as obtained from `select_jinja_template`.
        json_schema: The JSON schema the output must conform to.

    Returns:
        The rendered lark grammar string that only matches the given JSON schema.
    """
    return self.get_lark_from_jinja(
        template=template,
        mode=ToolChoiceEnum.none,
        tools=None,
        json_schema=json_schema,
        parallel_tool_calls=True,
        json_only=True,
        force_tool_names=False,
    )

get_lark_from_jinja(template, mode, tools, json_schema, parallel_tool_calls, json_only, force_tool_names)

Render a lark grammar from a jinja template.

This is the general entry point for grammar generation. Combines tool call, JSON schema, and thinking sections according to the requested mode.

Parameters:

Name Type Description Default
template str

Jinja template to render, as obtained from select_jinja_template.

required
mode ToolChoiceEnum

The tool choice. none disables tool calls; required (and the deprecated any) forces a tool call. Named tool choices go through get_grammar_for_chat_request.

required
tools list[Tool] | None

The list of tools available. Required when mode is any/required; ignored when mode is none.

required
json_schema dict[str, Any] | None

Optional JSON schema additionally allowed by the grammar, unioned with tool call and text alternatives. If None, no JSON section is added. With tools and a mode other than none, the required branch is rendered so plain text cannot replace the JSON answer; think templates still allow text that does not start like JSON before a tool call.

required
parallel_tool_calls bool

If True, the grammar allows one or more tool calls in sequence; if False, exactly one.

required
json_only bool

If True, generates only JSON schema grammar without text/tool call alternatives.

required
force_tool_names bool

If True, pins non-strict tool names to those in tools.

required

Returns:

Type Description
str

The rendered lark grammar string.

Raises:

Type Description
ValueError

If mode is a NamedToolChoice, or mode is any/required with no tools provided.

Source code in src/mistral_common/guidance/grammar_factory.py
def get_lark_from_jinja(
    self,
    template: str,
    mode: ToolChoiceEnum,
    tools: list[Tool] | None,
    json_schema: dict[str, Any] | None,
    parallel_tool_calls: bool,
    json_only: bool,
    force_tool_names: bool,
) -> str:
    r"""Render a lark grammar from a jinja template.

    This is the general entry point for grammar generation. Combines tool call,
    JSON schema, and thinking sections according to the requested mode.

    Args:
        template: Jinja template to render, as obtained from `select_jinja_template`.
        mode: The tool choice. `none` disables tool calls; `required` (and the
            deprecated `any`) forces a tool call. Named tool choices go through
            `get_grammar_for_chat_request`.
        tools: The list of tools available. Required when mode is any/required;
            ignored when mode is none.
        json_schema: Optional JSON schema additionally allowed by the grammar,
            unioned with tool call and text alternatives. If `None`, no JSON
            section is added. With tools and a mode other than `none`, the
            `required` branch is rendered so plain text cannot replace the JSON
            answer; think templates still allow text that does not start
            like JSON before a tool call.
        parallel_tool_calls: If `True`, the grammar allows one or more tool
            calls in sequence; if `False`, exactly one.
        json_only: If `True`, generates only JSON schema grammar without
            text/tool call alternatives.
        force_tool_names: If `True`, pins non-strict tool names to those in
            `tools`.

    Returns:
        The rendered lark grammar string.

    Raises:
        ValueError: If `mode` is a `NamedToolChoice`, or mode is any/required
            with no tools provided.
    """
    if isinstance(mode, NamedToolChoice):
        raise ValueError("Named tool choices are only supported by `get_grammar_for_chat_request`.")
    return self._render(
        template=template,
        mode=_TOOL_CHOICE_TO_GRAMMAR_MODE[ToolChoiceEnum(mode)],
        tools=tools,
        json_schema=json_schema,
        parallel_tool_calls=parallel_tool_calls,
        json_only=json_only,
        force_tool_names=force_tool_names,
    )

is_supported(tokenizer) staticmethod

Check whether the given tokenizer is supported by guidance.

Guidance requires a Tekken tokenizer with version >= v11.

Parameters:

Name Type Description Default
tokenizer MistralTokenizer

The Mistral tokenizer to check.

required

Returns:

Type Description
bool

True if the tokenizer is a Tekkenizer of version >= v11, False otherwise.

Source code in src/mistral_common/guidance/grammar_factory.py
@staticmethod
def is_supported(tokenizer: MistralTokenizer) -> bool:
    r"""Check whether the given tokenizer is supported by guidance.

    Guidance requires a Tekken tokenizer with version >= v11.

    Args:
        tokenizer: The Mistral tokenizer to check.

    Returns:
        `True` if the tokenizer is a Tekkenizer of version >= v11, `False` otherwise.
    """
    inner = tokenizer.instruct_tokenizer.tokenizer
    return is_tekkenizer(inner) and not inner.version < TokenizerVersion.v11

select_jinja_template()

Selects and returns the appropriate jinja template content.

Selection derives from the tokenizer version and presence of think tokens: - Returns the think template when the tokenizer version is >= v13 and both [THINK] and [/THINK] special tokens are registered. - Returns the base template in all other cases.

Returns:

Type Description
str

The jinja template content as a string.

Source code in src/mistral_common/guidance/grammar_factory.py
def select_jinja_template(self) -> str:
    r"""Selects and returns the appropriate jinja template content.

    Selection derives from the tokenizer version and presence of think tokens:
    - Returns the `think` template when the tokenizer version is >= v13 and both
      `[THINK]` and `[/THINK]` special tokens are registered.
    - Returns the `base` template in all other cases.

    Returns:
        The jinja template content as a string.
    """
    has_begin_think = SpecialTokens.begin_think.value in self._special_token_map
    has_end_think = SpecialTokens.end_think.value in self._special_token_map
    assert has_begin_think == has_end_think, (
        f"both {SpecialTokens.begin_think.value} and {SpecialTokens.end_think.value} "
        "should be defined or none of them."
    )
    return _cached_get_jinja_template(tokenizer_version=self._tokenizer.version, has_think_tokens=has_begin_think)