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.
Best use case
guidance is best used when you need a repeatable AI agent workflow instead of a one-off prompt.
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.
Teams using guidance should expect a more consistent output, faster repeated execution, less prompt rewriting.
When to use this skill
- You want a reusable workflow that can be run more than once with consistent structure.
When not to use this skill
- You only need a quick one-off answer and do not need a reusable workflow.
- You cannot install or maintain the underlying files, dependencies, or repository context.
Installation
Claude Code / Cursor / Codex
Manual Installation
- Download SKILL.md from GitHub
- Place it in
.claude/skills/guidance/SKILL.mdinside your project - Restart your AI agent — it will auto-discover the skill
How guidance Compares
| Feature / Agent | guidance | Standard Approach |
|---|---|---|
| Platform Support | Not specified | Limited / Varies |
| Context Awareness | High | Baseline |
| Installation Complexity | Unknown | N/A |
Frequently Asked Questions
What does this skill do?
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.
Where can I find the source code?
You can find the source code on GitHub using the link provided at the top of the page.
SKILL.md Source
# 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 listsRelated Skills
zustand
You are an expert in Zustand, the small, fast, and scalable state management library for React. You help developers manage global state without boilerplate using Zustand's hook-based stores, selectors for performance, middleware (persist, devtools, immer), computed values, and async actions — replacing Redux complexity with a simple, un-opinionated API in under 1KB.
zoho
Integrate and automate Zoho products. Use when a user asks to work with Zoho CRM, Zoho Books, Zoho Desk, Zoho Projects, Zoho Mail, or Zoho Creator, build custom integrations via Zoho APIs, automate workflows with Deluge scripting, sync data between Zoho apps and external systems, manage leads and deals, automate invoicing, build custom Zoho Creator apps, set up webhooks, or manage Zoho organization settings. Covers Zoho CRM, Books, Desk, Projects, Creator, and cross-product integrations.
zod
You are an expert in Zod, the TypeScript-first schema declaration and validation library. You help developers define schemas that validate data at runtime AND infer TypeScript types at compile time — eliminating the need to write types and validators separately. Used for API input validation, form validation, environment variables, config files, and any data boundary.
zipkin
Deploy and configure Zipkin for distributed tracing and request flow visualization. Use when a user needs to set up trace collection, instrument Java/Spring or other services with Zipkin, analyze service dependencies, or configure storage backends for trace data.
zig
Expert guidance for Zig, the systems programming language focused on performance, safety, and readability. Helps developers write high-performance code with compile-time evaluation, seamless C interop, no hidden control flow, and no garbage collector. Zig is used for game engines, operating systems, networking, and as a C/C++ replacement.
zed
Expert guidance for Zed, the high-performance code editor built in Rust with native collaboration, AI integration, and GPU-accelerated rendering. Helps developers configure Zed, create custom extensions, set up collaborative editing sessions, and integrate AI assistants for productive coding.
zeabur
Expert guidance for Zeabur, the cloud deployment platform that auto-detects frameworks, builds and deploys applications with zero configuration, and provides managed services like databases and message queues. Helps developers deploy full-stack applications with automatic scaling and one-click marketplace services.
zapier
Automate workflows between apps with Zapier. Use when a user asks to connect apps without code, automate repetitive tasks, sync data between services, or build no-code integrations between SaaS tools.
zabbix
Configure Zabbix for enterprise infrastructure monitoring with templates, triggers, discovery rules, and dashboards. Use when a user needs to set up Zabbix server, configure host monitoring, create custom templates, define trigger expressions, or automate host discovery and registration.
yup
Validate data with Yup schemas. Use when adding form validation, defining API request schemas, validating configuration, or building type-safe validation pipelines in JavaScript/TypeScript.
yt-dlp
Download video and audio from YouTube and other platforms with yt-dlp. Use when a user asks to download YouTube videos, extract audio from videos, download playlists, get subtitles, download specific formats or qualities, batch download, archive channels, extract metadata, embed thumbnails, download from social media platforms (Twitter, Instagram, TikTok), or build media ingestion pipelines. Covers format selection, audio extraction, playlists, subtitles, metadata, and automation.
youtube-transcription
Transcribe YouTube videos to text using OpenAI Whisper and yt-dlp. Use when the user wants to get a transcript from a YouTube video, generate subtitles, convert video speech to text, create SRT/VTT captions, or extract spoken content from YouTube URLs.