Guidance
FrameworkFreeMicrosoft's language for efficient LLM control flow.
Capabilities14 decomposed
grammar-constrained text generation with ast-based node system
Medium confidenceGuidance uses an immutable Abstract Syntax Tree (AST) of GrammarNode subclasses (LiteralNode, RegexNode, SelectNode, JsonNode, RuleNode, RepeatNode) to define hard constraints on LLM output. The framework compiles these grammar nodes into token-level constraints that are enforced during generation, preventing invalid outputs at the token level rather than post-processing. This works by integrating with the model's tokenizer to ensure only valid token sequences can be generated, achieving 100% constraint satisfaction.
Uses token-level constraint enforcement via TokenParser and ByteParser engines that integrate with model tokenizers, ensuring constraints are satisfied during generation rather than post-hoc validation. This is distinct from prompt-based approaches because it operates at the token stream level and prevents invalid tokens from being generated in the first place.
More efficient than JSON-mode APIs (OpenAI, Anthropic) because constraints are enforced locally without requiring model-specific APIs, and more reliable than regex post-processing because invalid tokens are never generated.
interleaved control flow with constrained generation
Medium confidenceThe @guidance decorator transforms Python functions into programs that seamlessly interleave imperative control flow (conditionals, loops, variable assignment) with constrained LLM generation. The framework maintains a stateful execution context (lm object) that accumulates generated text and captured variables, allowing subsequent control flow decisions to depend on LLM outputs. This enables dynamic prompt construction where the next generation step is determined by previous outputs, all within a single continuous execution flow.
Implements a stateful execution model where Python control flow (if/else, for loops, function calls) is directly integrated with LLM generation via the lm object, which accumulates text and variable captures. This is fundamentally different from prompt chaining because the entire program (control + generation) is compiled into a single execution graph rather than separate API calls.
More efficient than prompt chaining (LangChain, LlamaIndex) because it avoids multiple round-trips to the model; more flexible than template-based systems because control flow is Turing-complete Python rather than limited DSL syntax.
visualization and debugging of guidance execution traces
Medium confidenceGuidance provides visualization tools (Jupyter widgets, HTML output) that display execution traces, showing the sequence of generation steps, constraints applied, and captured variables. The framework logs detailed execution information including token sequences, grammar node traversals, and model state at each step. This enables developers to inspect and debug guidance programs by visualizing how constraints were applied and what the model generated at each stage.
Provides Jupyter widget-based visualization of guidance execution traces, showing constraint application, token sequences, and model state at each step. This is integrated into the framework and provides transparent debugging without requiring external tools.
More detailed than generic LLM debugging tools because it shows constraint-specific information; more accessible than log-based debugging because visualization is interactive and visual.
repetition and quantifier constraints (one_or_more, zero_or_more, optional)
Medium confidenceGuidance provides RepeatNode AST nodes and convenience functions (one_or_more, zero_or_more, optional) that enable repetition constraints on generation. These allow developers to specify that a pattern should appear one or more times, zero or more times, or optionally once. The framework compiles these into token-level constraints that enforce the repetition logic during generation, useful for generating lists, repeated structures, or optional elements.
Implements repetition constraints via RepeatNode AST nodes that are compiled into token-level rules, enabling one_or_more, zero_or_more, and optional patterns. This allows precise control over repetition without post-processing.
More efficient than prompt-based repetition because constraints are enforced at token level; more flexible than fixed-count repetition because quantifiers allow variable-length outputs.
custom grammar rules and recursive pattern definition
Medium confidenceGuidance allows developers to define custom grammar rules using the @guidance decorator, enabling recursive and reusable pattern definitions. Rules can reference other rules, creating complex grammars that are compiled into RuleNode AST nodes. This enables developers to build domain-specific languages (DSLs) and complex output formats by composing simple rules, with the framework handling the compilation and constraint enforcement.
Allows custom grammar rules via @guidance-decorated functions that are compiled into RuleNode AST nodes, enabling recursive and reusable pattern definitions. This provides a Turing-complete grammar system that can express arbitrary patterns.
More flexible than fixed grammar libraries because users can define custom rules; more powerful than regex-only approaches because rules can be recursive and context-aware.
capture and variable extraction from generated text
Medium confidenceGuidance enables capturing and extracting specific parts of generated text into variables using the capture() function or implicit capture in grammar nodes. Captured variables are stored in the lm state object and can be accessed in subsequent control flow or generation steps. This allows developers to extract structured information from LLM outputs (e.g., entity names, values, decisions) and use them in downstream logic without manual parsing.
Integrates variable capture into the generation flow via capture() function and grammar node annotations, allowing extracted values to be accessed in subsequent control flow. This is transparent to the user and works seamlessly with constrained generation.
More efficient than post-hoc parsing because capture happens during generation; more reliable than regex-based extraction because capture is integrated with grammar constraints.
token healing and text-level boundary handling
Medium confidenceGuidance implements token healing by processing text at the character/byte level rather than the token level, ensuring correct tokenization at text boundaries. When constraints are applied or text is concatenated, the framework re-tokenizes affected regions to prevent token boundary misalignment (e.g., a space character being merged into an adjacent token). This is handled by the TokenParser and ByteParser engines, which work with the model's tokenizer to ensure seamless transitions between constrained and unconstrained generation.
Explicitly handles token boundary issues by working at the text level and re-tokenizing affected regions when constraints are applied, rather than assuming token boundaries remain stable. This is implemented via TokenParser and ByteParser engines that integrate with the model's tokenizer to ensure seamless transitions.
More robust than naive token-level constraint enforcement because it prevents token boundary artifacts that can cause generation failures or unexpected outputs in other frameworks.
multi-backend model abstraction with unified api
Medium confidenceGuidance provides a unified model interface that abstracts over multiple backend implementations (LlamaCpp for local inference, Transformers for HuggingFace models, OpenAI/Azure/VertexAI for remote APIs). The framework defines a common Model base class with consistent methods (generate, __call__) that work identically across backends, allowing users to write guidance programs once and execute them on any supported model. Backend selection is transparent to the user; the same @guidance decorated function works with local or remote models by simply changing the model parameter.
Implements a Model base class abstraction that unifies local (llama.cpp, Transformers) and remote (OpenAI, Azure, VertexAI) backends with identical APIs, allowing guidance programs to be backend-agnostic. This is achieved through a common interface (generate, __call__) and backend-specific subclasses that handle provider-specific details.
More flexible than LangChain's model abstraction because Guidance's constraints work consistently across backends (with caveats for remote APIs); simpler than building custom adapters for each provider.
json schema-constrained generation with validation
Medium confidenceGuidance provides a json() function that accepts a JSON schema and generates valid JSON objects that conform to the schema. The framework uses JsonNode AST nodes to compile schemas into token-level constraints, ensuring generated JSON is syntactically valid and matches the schema structure (required fields, types, nested objects). This works by converting JSON schema constraints into grammar rules that are enforced during generation, preventing invalid JSON from being produced.
Compiles JSON schemas into token-level constraints via JsonNode AST nodes, ensuring generated JSON is valid and schema-compliant during generation rather than post-hoc validation. This prevents invalid JSON from being produced in the first place.
More reliable than JSON-mode APIs (OpenAI, Anthropic) because it works with any model backend and provides stronger guarantees; more efficient than retry-based validation because invalid JSON is never generated.
select/choice-based generation with option constraints
Medium confidenceGuidance provides a select() function that constrains generation to a predefined set of options (strings, numbers, or complex objects). The framework uses SelectNode AST nodes to compile choice constraints into token-level rules, ensuring the model can only generate one of the specified options. This is useful for classification tasks, enum selection, or multi-choice scenarios where the output must be one of a fixed set of values.
Uses SelectNode AST nodes to compile choice constraints into token-level rules, ensuring the model can only generate one of the specified options. This is more efficient than prompt-based selection because constraints are enforced at the token level.
More reliable than prompt-based classification because the model cannot generate invalid options; more efficient than retry-based selection because invalid outputs are never generated.
regex pattern-constrained generation
Medium confidenceGuidance provides a gen(regex=...) function that constrains generation to match a regular expression pattern. The framework uses RegexNode AST nodes to compile regex patterns into token-level constraints via DFA/NFA compilation, ensuring generated text matches the pattern. This enables precise control over output format (e.g., phone numbers, dates, code snippets) without post-processing validation.
Compiles regex patterns into DFA/NFA automata that are enforced at the token level during generation, ensuring output matches the pattern without post-processing. This is more efficient than regex validation because constraints are applied during generation.
More efficient than post-hoc regex validation because invalid tokens are never generated; more flexible than fixed format templates because patterns can express complex variations.
chat role and template-based prompt construction
Medium confidenceGuidance provides chat role abstractions (system, user, assistant) and template functions that simplify multi-turn conversation construction. The framework includes built-in templates for common chat formats (OpenAI, Anthropic, Llama) that automatically handle role markers, message formatting, and token boundaries. Users can define custom chat templates for specific model instruction formats, enabling consistent prompt construction across different models.
Provides built-in chat templates for common models (OpenAI, Anthropic, Llama) and allows custom template definition, ensuring consistent formatting across different model providers. Templates handle role markers, message boundaries, and token healing automatically.
More robust than manual chat formatting because templates handle edge cases and token boundaries; more flexible than hardcoded formats because custom templates can be defined for any model.
tool calling and function invocation with schema-based routing
Medium confidenceGuidance enables tool calling by constraining generation to select from a set of available tools/functions and generate valid function call arguments. The framework uses schema-based constraints to ensure generated function calls match the tool's signature, including parameter types and required fields. This works by combining SelectNode (for tool selection) with JsonNode (for argument validation), creating a unified system for tool use without requiring model-specific function calling APIs.
Implements tool calling via schema-based constraints (SelectNode for tool selection + JsonNode for arguments) that work with any model backend, not just those with native function calling APIs. This enables tool use with local models and provides stronger guarantees than prompt-based tool calling.
More flexible than model-specific function calling APIs (OpenAI, Anthropic) because it works with any model; more reliable than prompt-based tool calling because invalid function calls are prevented at the token level.
caching and stateless execution modes for performance optimization
Medium confidenceGuidance supports two execution modes: stateful (default, maintains context across calls) and stateless (cache=True, reuses cached computations). The framework caches intermediate generation results and model states, allowing subsequent calls with similar prefixes to reuse cached tokens rather than regenerating them. This is particularly useful for batch processing or repeated prompts with different suffixes, reducing token consumption and latency.
Implements optional caching of intermediate generation results and model states, allowing token reuse across calls with similar prefixes. This is controlled via the cache parameter in the guidance() function and provides transparent performance optimization.
More efficient than naive batch processing because it reuses cached tokens; more flexible than model-specific caching (KV cache) because it works across different backends.
Capabilities are decomposed by AI analysis. Each maps to specific user intents and improves with match feedback.
Related Artifactssharing capabilities
Artifacts that share capabilities with Guidance, ranked by overlap. Discovered automatically through the match graph.
guidance
A guidance language for controlling large language models.
javaparser
Java 1-25 Parser and Abstract Syntax Tree for Java with advanced analysis functionalities.
llama-cpp-python
Python bindings for the llama.cpp library
Google: Gemini 2.0 Flash
Gemini Flash 2.0 offers a significantly faster time to first token (TTFT) compared to [Gemini Flash 1.5](/google/gemini-flash-1.5), while maintaining quality on par with larger models like [Gemini Pro 1.5](/google/gemini-pro-1.5). It...
Outlines
Structured text generation — guarantees LLM outputs match JSON schemas or grammars.
Google: Gemma 2 27B
Gemma 2 27B by Google is an open model built from the same research and technology used to create the [Gemini models](/models?q=gemini). Gemma models are well-suited for a variety of...
Best For
- ✓developers building reliable LLM applications requiring deterministic output formats
- ✓teams implementing structured extraction pipelines with strict schema requirements
- ✓builders creating chatbots with constrained action spaces or tool selection
- ✓developers building agentic systems with dynamic decision trees
- ✓teams implementing chain-of-thought reasoning with conditional branching
- ✓builders creating adaptive prompting systems that adjust based on model outputs
- ✓developers debugging complex guidance programs
- ✓teams analyzing model behavior and constraint effectiveness
Known Limitations
- ⚠Grammar complexity can impact token generation speed; deeply nested grammars may add 50-200ms latency per generation
- ⚠Regex constraints are compiled to DFA/NFA, which can be memory-intensive for complex patterns
- ⚠Some model architectures (e.g., very small quantized models) may have limited tokenizer compatibility with constraint enforcement
- ⚠Stateful execution adds complexity to debugging; execution traces can be difficult to inspect without built-in visualization tools
- ⚠Control flow logic is tightly coupled to generation, making it harder to reuse prompts across different control structures
- ⚠Recursive control flow (loops with nested guidance calls) can lead to exponential token consumption if not carefully managed
Requirements
Input / Output
UnfragileRank
UnfragileRank is computed from adoption signals, documentation quality, ecosystem connectivity, match graph feedback, and freshness. No artifact can pay for a higher rank.
About
Microsoft's efficient language for controlling LLMs that interleaves generation, prompting, and logical control into a single continuous flow, enabling constrained generation, JSON output, and tool use with token efficiency.
Categories
Alternatives to Guidance
Are you the builder of Guidance?
Claim this artifact to get a verified badge, access match analytics, see which intents users search for, and manage your listing.
Get the weekly brief
New tools, rising stars, and what's actually worth your time. No spam.
Data Sources
Looking for something else?
Search →