guidance
You are an expert in Guidance, Microsoft's library for controlling LLM output with constrained generation. You help developers write programs that interleave text generation with control flow (loops, conditionals, regex constraints, JSON schemas, function calls) — ensuring LLM output always matches the expected format by constraining the token generation process itself, not just prompting.
What this skill does
# Guidance — Constrained LLM Generation
You are an expert in Guidance, Microsoft's library for controlling LLM output with constrained generation. You help developers write programs that interleave text generation with control flow (loops, conditionals, regex constraints, JSON schemas, function calls) — ensuring LLM output always matches the expected format by constraining the token generation process itself, not just prompting.
## Core Capabilities
### Constrained Generation
```python
import guidance
from guidance import models, gen, select, regex, one_or_more, zero_or_more
# Load model (local or API)
lm = models.OpenAI("gpt-4o")
# Or local: models.Transformers("meta-llama/Llama-3.1-8B-Instruct")
# Simple constrained generation
lm += f"""
Classify this review sentiment.
Review: "The product arrived damaged but customer service was great"
Sentiment: {select(["positive", "negative", "mixed", "neutral"], name="sentiment")}
Confidence: {gen(regex=r"0\.\d{2}", name="confidence")}
"""
print(lm["sentiment"]) # "mixed" — constrained to exactly these options
print(lm["confidence"]) # "0.82" — matches regex pattern exactly
# Structured extraction with loops
lm += f"""Extract all people mentioned:
Text: "Alice met Bob at the cafe. Charlie joined them later."
People:
{one_or_more(f'''
- Name: {gen(regex=r"[A-Z][a-z]+", name="names", list_append=True)}
''')}
"""
print(lm["names"]) # ["Alice", "Bob", "Charlie"]
```
### JSON Generation
```python
# Guaranteed valid JSON output
from guidance import json as gen_json
from pydantic import BaseModel
class ProductReview(BaseModel):
product_name: str
rating: int # Constrained to int
pros: list[str]
cons: list[str]
recommendation: bool
lm += f"""Analyze this review and extract structured data:
Review: "The XPS 15 has an amazing display and battery life, but runs hot under load. Would buy again."
{gen_json(schema=ProductReview, name="review")}
"""
review = lm["review"]
# {"product_name": "XPS 15", "rating": 4, "pros": ["amazing display", "battery life"],
# "cons": ["runs hot under load"], "recommendation": true}
# GUARANTEED valid JSON matching the Pydantic schema
```
### Control Flow
```python
# Branching based on LLM output
lm += f"""
Task: {user_input}
First, determine the task type: {select(["question", "command", "chitchat"], name="task_type")}
"""
if lm["task_type"] == "question":
lm += f"""
Answer the question with evidence:
Answer: {gen(max_tokens=200, name="answer")}
Sources: {gen(regex=r"https?://\S+", name="source")}
"""
elif lm["task_type"] == "command":
lm += f"""
Generate the command:
```bash
{gen(stop="```", name="command")}
```
Explanation: {gen(max_tokens=100, name="explanation")}
"""
else:
lm += f"Response: {gen(max_tokens=50, name="response")}"
# Multi-step reasoning
lm += f"""
Problem: {math_problem}
Let me solve this step by step:
{one_or_more(f'''
Step {gen(regex=r"\d+", name="step_num")}: {gen(stop="\n", name="steps", list_append=True)}
''')}
Final answer: {gen(regex=r"-?\d+\.?\d*", name="answer")}
"""
```
## Installation
```bash
pip install guidance
```
## Best Practices
1. **Select for classification** — Use `select()` instead of free-form text; LLM can only output valid options
2. **Regex for format** — Use `regex=` for dates, numbers, IDs; output always matches the pattern
3. **JSON schema** — Use `gen_json(schema=...)` for structured data; impossible to generate invalid JSON
4. **Local models** — Guidance works best with local models (full token control); API models use prompt-based constraints
5. **Control flow** — Mix Python logic with generation; branch on LLM output, loop for extraction
6. **Named captures** — Use `name=` parameter to capture generated values; access with `lm["name"]`
7. **Stop tokens** — Use `stop=` to control generation boundaries; prevent runaway output
8. **List extraction** — Use `one_or_more()` with `list_append=True` for extracting variable-length lists
Related in AI Agents
skill-development
IncludedComprehensive meta-skill for creating, managing, validating, auditing, and distributing Claude Code skills and slash commands (unified in v2.1.3+). Provides skill templates, creation workflows, validation patterns, audit checklists, naming conventions, YAML frontmatter guidance, progressive disclosure examples, and best practices lookup. Use when creating new skills, validating existing skills, auditing skill quality, understanding skill architecture, needing skill templates, learning about YAML frontmatter requirements, progressive disclosure patterns, tool restrictions (allowed-tools), skill composition, skill naming conventions, troubleshooting skill activation issues, creating custom slash commands, configuring command frontmatter, using command arguments ($ARGUMENTS, $1, $2), bash execution in commands, file references in commands, command namespacing, plugin commands, MCP slash commands, Skill tool configuration, or deciding between skills vs slash commands. Delegates to docs-management skill for official documentation.
reprompter
IncludedTransform messy prompts into well-structured, effective prompts — single or multi-agent. Use when: "reprompt", "reprompt this", "clean up this prompt", "structure my prompt", rough text needing XML tags and best practices, "reprompter teams", "repromptception", "run with quality", "smart run", "smart agents", multi-agent tasks, audits, parallel work, anything going to agent teams. Don't use when: simple Q&A, pure chat, immediate execution-only tasks. See "Don't Use When" section for details. Outputs: Structured XML/Markdown prompt, quality score (before/after), optional team brief + per-agent sub-prompts, agent team output files. Success criteria: Single mode quality score ≥ 7/10; Repromptception per-agent prompt quality score 8+/10; all required sections present, actionable and specific.
adaptive-compaction
IncludedAdaptive add-on policy and recovery layer that decides WHEN to compact, prune, snapshot, or fork -- replacing fixed-percent auto-compaction across Claude Code, Codex, and MCP-capable hosts. Trigger on auto-compact timing or damage: "when should I compact", "is it safe to compact now or start a fresh session", "auto-compact fires too early/mid-task", "switching to an unrelated task but the window still has space", "context rot", "answers get worse the longer the session runs", "the agent forgot the plan or my decisions after it summarized", "add a layer on top that manages context without changing the agent", raising autoCompactWindow to give the policy room, or installing/tuning a cross-tool compaction policy or PreCompact hook -- even when "compaction" is never said but the problem is context-window pressure or post-summarization memory loss. Do NOT use to summarize a conversation, build RAG, write a summarization prompt (decides WHEN not HOW), or answer max-context-length trivia.
agent-skill-creator
IncludedCreate cross-platform agent skills from workflow descriptions. Activates when users ask to create an agent, automate a repetitive workflow, create a custom skill, or need advanced agent creation. Triggers on phrases like create agent for, automate workflow, create skill for, every day I have to, daily I need to, turn process into agent, need to automate, create a cross-platform skill, validate this skill, export this skill, migrate this skill. Supports single skills, multi-agent suites, transcript processing, template-based creation, interactive configuration, cross-platform export, and spec validation.
llm-wiki
IncludedUse when building or maintaining a persistent personal knowledge base (second brain) in Obsidian where an LLM incrementally ingests sources, updates entity/concept pages, maintains cross-references, and keeps a synthesis current. Triggers include "second brain", "Obsidian wiki", "personal knowledge management", "ingest this paper/article/book", "build a research wiki", "compound knowledge", "Memex", or whenever the user wants knowledge to accumulate across sessions instead of being re-derived by RAG on every query.
skill-master
IncludedAgent Skills authoring, evaluation, and optimization. Create, edit, validate, benchmark, and improve skills following the agentskills.io specification. Use when designing SKILL.md files, structuring skill folders (references, scripts, assets), ingesting external documentation into skills, running trigger evals, benchmarking skill quality, optimizing descriptions, or performing blind A/B comparisons. Keywords: agentskills.io, SKILL.md, skill authoring, eval, benchmark, trigger optimization.