mistral_common.guidance.grammar_factory
GrammarFactory(tokenizer)
Generates grammars for a given tokenizer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tokenizer
|
MistralTokenizer
|
The Mistral tokenizer to generate grammars for. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the tokenizer is not supported (see
|
Source code in src/mistral_common/guidance/grammar_factory.py
get_lark_for_json_schema(template, json_schema)
Returns a lark grammar that only accepts JSON objects matching the given schema.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
template
|
str
|
Jinja template to render as a string. |
required |
json_schema
|
dict[str, Any]
|
The JSON schema to validate against. |
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
get_lark_from_jinja(template, mode, tools, json_schema, parallel_tool_calls, json_only=False)
Renders a lark grammar from a jinja template.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
template
|
str
|
Jinja template to render as a string. |
required |
mode
|
ToolChoice
|
The function calling mode (auto, any, none). |
required |
tools
|
list[Tool] | None
|
The list of tools available. |
required |
json_schema
|
dict[str, Any] | None
|
JSON schema to additionally allow, unioned with the grammar. |
required |
parallel_tool_calls
|
bool
|
Whether parallel tool calls are allowed. |
required |
json_only
|
bool
|
If True, generates only JSON schema grammar without text/tool call alternatives. |
False
|
Returns:
| Type | Description |
|---|---|
str
|
The rendered lark grammar string. |
Source code in src/mistral_common/guidance/grammar_factory.py
is_supported(tokenizer)
staticmethod
Checks 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
|
Whether the tokenizer is supported. |
Source code in src/mistral_common/guidance/grammar_factory.py
select_jinja_template(reasoning)
Selects and returns the appropriate jinja template content based on tokenizer version and reasoning mode.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
reasoning
|
bool
|
Whether reasoning/thinking mode is enabled. |
required |
Returns:
| Type | Description |
|---|---|
str
|
The jinja template content as a string. |