[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6QET2JDP9JE1T7GRVRQ5JYD":3,"skill-same:01M6QET2JDP9JE1T7GRVRQ5JYD":104},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":26,"publishedAt":46,"linkOnly":47,"markdownContent":48,"markdownBody":49,"frontMatter":50,"refName":57,"commitSha":58,"skillDirectory":59,"forksCount":14,"repositoryHtmlUrl":60,"repositoryHomepageUrl":61,"ownerHtmlUrl":62,"ownerBlogUrl":63,"ownerDescription":64,"updatedAt":65,"install":66,"resources":79},"01M6QET2JDP9JE1T7GRVRQ5JYD","guidance",null,"Constrains LLM output during generation with Guidance (Microsoft Research), using regex, select() choices, context-free grammars, token healing, and @guidance functions, with Anthropic, OpenAI, Transformers, and llama.cpp backends. Use when you need generated text to match a regex or fixed format such as dates, emails, or IDs. Use when you need guaranteed valid JSON, XML, or code from a model. Use when building multi-step generation workflows or ReAct-style agents with Python control flow. Use when classifying text into fixed categories with select(). Use when running local models and wanting grammar constraints. Not for Pydantic validation with automatic retries; use Instructor for that.","Tashima-Tarsh\u002FDisha6.6","Tashima-Tarsh","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F269906498?v=4","01M6PBH98X03XERH0HFT4PFB1P","NITISH KUMAR","01M6PBH9DA0M6KM3Z12P848F0K",0,"MIT","https:\u002F\u002Fgithub.com\u002FTashima-Tarsh\u002FDisha6.6\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fkal-guidance\u002FSKILL.md",[18,23],{"categoryNo":19,"categoryName":20,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000021","资料检索与研究","SCENARIO","使用场景",{"categoryNo":24,"categoryName":25,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000023","Skill与智能体开发",[5,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45],"local","automatic","for","categories","you","retries","structured output","free","as","regex","python","enforcement","context","text","applications","ids","react","workflows","valid","2026-11-10 10:12:30",false,"---\nname: guidance\ndescription: Constrains LLM output during generation with Guidance (Microsoft Research), using regex, select() choices, context-free grammars, token healing, and @guidance functions, with Anthropic, OpenAI, Transformers, and llama.cpp backends. Use when you need generated text to match a regex or fixed format such as dates, emails, or IDs. Use when you need guaranteed valid JSON, XML, or code from a model. Use when building multi-step generation workflows or ReAct-style agents with Python control flow. Use when classifying text into fixed categories with select(). Use when running local models and wanting grammar constraints. Not for Pydantic validation with automatic retries; use Instructor for that.\nlicense: MIT\nmetadata:\n  version: 1.0.0\n  category: llm-applications\n  maintainer: Kalaris Labs\n  tags: Prompt Engineering, Guidance, Constrained Generation, Structured Output, JSON Validation, Grammar, Microsoft Research, Format Enforcement, Multi-Step Workflows\n  dependencies: guidance, transformers\n---\n\n# Guidance: Constrained LLM Generation\n\n## When to Use This Skill\n\nUse Guidance when you need to:\n- **Control LLM output syntax** with regex or grammars\n- **Guarantee valid JSON\u002FXML\u002Fcode** generation\n- **Reduce latency** vs traditional prompting approaches\n- **Enforce structured formats** (dates, emails, IDs, etc.)\n- **Build multi-step workflows** with Pythonic control flow\n- **Prevent invalid outputs** through grammatical constraints\n\n\n## Installation\n\n```bash\n# Base installation\npip install guidance\n\n# With specific backends\npip install guidance[transformers]  # Hugging Face models\npip install guidance[llama_cpp]     # llama.cpp models\n```\n\n## Quick Start\n\n### Basic Example: Structured Generation\n\n```python\nfrom guidance import models, gen\n\n# Load model (supports OpenAI, Transformers, llama.cpp)\nlm = models.OpenAI(\"gpt-4\")\n\n# Generate with constraints\nresult = lm + \"The capital of France is \" + gen(\"capital\", max_tokens=5)\n\nprint(result[\"capital\"])  # \"Paris\"\n```\n\n### With Anthropic Claude\n\n```python\nfrom guidance import models, gen, system, user, assistant\n\n# Configure Claude\nlm = models.Anthropic(\"claude-sonnet-4-5-20250929\")\n\n# Use context managers for chat format\nwith system():\n    lm += \"You are a helpful assistant.\"\n\nwith user():\n    lm += \"What is the capital of France?\"\n\nwith assistant():\n    lm += gen(max_tokens=20)\n```\n\n## Core Concepts\n\n### 1. Context Managers\n\nGuidance uses Pythonic context managers for chat-style interactions.\n\n```python\nfrom guidance import system, user, assistant, gen\n\nlm = models.Anthropic(\"claude-sonnet-4-5-20250929\")\n\n# System message\nwith system():\n    lm += \"You are a JSON generation expert.\"\n\n# User message\nwith user():\n    lm += \"Generate a person object with name and age.\"\n\n# Assistant response\nwith assistant():\n    lm += gen(\"response\", max_tokens=100)\n\nprint(lm[\"response\"])\n```\n\n**Benefits:**\n- Natural chat flow\n- Clear role separation\n- Easy to read and maintain\n\n### 2. Constrained Generation\n\nGuidance ensures outputs match specified patterns using regex or grammars.\n\n#### Regex Constraints\n\n```python\nfrom guidance import models, gen\n\nlm = models.Anthropic(\"claude-sonnet-4-5-20250929\")\n\n# Constrain to valid email format\nlm += \"Email: \" + gen(\"email\", regex=r\"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}\")\n\n# Constrain to date format (YYYY-MM-DD)\nlm += \"Date: \" + gen(\"date\", regex=r\"\\d{4}-\\d{2}-\\d{2}\")\n\n# Constrain to phone number\nlm += \"Phone: \" + gen(\"phone\", regex=r\"\\d{3}-\\d{3}-\\d{4}\")\n\nprint(lm[\"email\"])  # Guaranteed valid email\nprint(lm[\"date\"])   # Guaranteed YYYY-MM-DD format\n```\n\n**How it works:**\n- Regex converted to grammar at token level\n- Invalid tokens filtered during generation\n- Model can only produce matching outputs\n\n#### Selection Constraints\n\n```python\nfrom guidance import models, gen, select\n\nlm = models.Anthropic(\"claude-sonnet-4-5-20250929\")\n\n# Constrain to specific choices\nlm += \"Sentiment: \" + select([\"positive\", \"negative\", \"neutral\"], name=\"sentiment\")\n\n# Multiple-choice selection\nlm += \"Best answer: \" + select(\n    [\"A) Paris\", \"B) London\", \"C) Berlin\", \"D) Madrid\"],\n    name=\"answer\"\n)\n\nprint(lm[\"sentiment\"])  # One of: positive, negative, neutral\nprint(lm[\"answer\"])     # One of: A, B, C, or D\n```\n\n### 3. Token Healing\n\nGuidance automatically \"heals\" token boundaries between prompt and generation.\n\n**Problem:** Tokenization creates unnatural boundaries.\n\n```python\n# Without token healing\nprompt = \"The capital of France is \"\n# Last token: \" is \"\n# First generated token might be \" Par\" (with leading space)\n# Result: \"The capital of France is  Paris\" (double space!)\n```\n\n**Solution:** Guidance backs up one token and regenerates.\n\n```python\nfrom guidance import models, gen\n\nlm = models.Anthropic(\"claude-sonnet-4-5-20250929\")\n\n# Token healing enabled by default\nlm += \"The capital of France is \" + gen(\"capital\", max_tokens=5)\n# Result: \"The capital of France is Paris\" (correct spacing)\n```\n\n**Benefits:**\n- Natural text boundaries\n- No awkward spacing issues\n- Better model performance (sees natural token sequences)\n\n### 4. Grammar-Based Generation\n\nDefine complex structures using context-free grammars.\n\n```python\nfrom guidance import models, gen\n\nlm = models.Anthropic(\"claude-sonnet-4-5-20250929\")\n\n# JSON grammar (simplified)\njson_grammar = \"\"\"\n{\n    \"name\": \u003Cgen name regex=\"[A-Za-z ]+\" max_tokens=20>,\n    \"age\": \u003Cgen age regex=\"[0-9]+\" max_tokens=3>,\n    \"email\": \u003Cgen email regex=\"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\\\.[a-zA-Z]{2,}\" max_tokens=50>\n}\n\"\"\"\n\n# Generate valid JSON\nlm += gen(\"person\", grammar=json_grammar)\n\nprint(lm[\"person\"])  # Guaranteed valid JSON structure\n```\n\n**Use cases:**\n- Complex structured outputs\n- Nested data structures\n- Programming language syntax\n- Domain-specific languages\n\n### 5. Guidance Functions\n\nCreate reusable generation patterns with the `@guidance` decorator.\n\n```python\nfrom guidance import guidance, gen, models\n\n@guidance\ndef generate_person(lm):\n    \"\"\"Generate a person with name and age.\"\"\"\n    lm += \"Name: \" + gen(\"name\", max_tokens=20, stop=\"\\n\")\n    lm += \"\\nAge: \" + gen(\"age\", regex=r\"[0-9]+\", max_tokens=3)\n    return lm\n\n# Use the function\nlm = models.Anthropic(\"claude-sonnet-4-5-20250929\")\nlm = generate_person(lm)\n\nprint(lm[\"name\"])\nprint(lm[\"age\"])\n```\n\n**Stateful Functions:**\n\n```python\n@guidance(stateless=False)\ndef react_agent(lm, question, tools, max_rounds=5):\n    \"\"\"ReAct agent with tool use.\"\"\"\n    lm += f\"Question: {question}\\n\\n\"\n\n    for i in range(max_rounds):\n        # Thought\n        lm += f\"Thought {i+1}: \" + gen(\"thought\", stop=\"\\n\")\n\n        # Action\n        lm += \"\\nAction: \" + select(list(tools.keys()), name=\"action\")\n\n        # Execute tool\n        tool_result = tools[lm[\"action\"]]()\n        lm += f\"\\nObservation: {tool_result}\\n\\n\"\n\n        # Check if done\n        lm += \"Done? \" + select([\"Yes\", \"No\"], name=\"done\")\n        if lm[\"done\"] == \"Yes\":\n            break\n\n    # Final answer\n    lm += \"\\nFinal Answer: \" + gen(\"answer\", max_tokens=100)\n    return lm\n```\n\n## Backend Configuration\n\n### Anthropic Claude\n\n```python\nfrom guidance import models\n\nlm = models.Anthropic(\n    model=\"claude-sonnet-4-5-20250929\",\n    api_key=\"your-api-key\"  # Or set ANTHROPIC_API_KEY env var\n)\n```\n\n### OpenAI\n\n```python\nlm = models.OpenAI(\n    model=\"gpt-4o-mini\",\n    api_key=\"your-api-key\"  # Or set OPENAI_API_KEY env var\n)\n```\n\n### Local Models (Transformers)\n\n```python\nfrom guidance.models import Transformers\n\nlm = Transformers(\n    \"microsoft\u002FPhi-4-mini-instruct\",\n    device=\"cuda\"  # Or \"cpu\"\n)\n```\n\n### Local Models (llama.cpp)\n\n```python\nfrom guidance.models import LlamaCpp\n\nlm = LlamaCpp(\n    model_path=\"\u002Fpath\u002Fto\u002Fmodel.gguf\",\n    n_ctx=4096,\n    n_gpu_layers=35\n)\n```\n\n## Common Patterns\n\nDetails, code examples and parameter tables: [references\u002Fcommon-patterns.md](references\u002Fcommon-patterns.md). Read it when this step applies.\n\n## Best Practices\n\n### 1. Use Regex for Format Validation\n\n```python\n# ✅ Good: Regex ensures valid format\nlm += \"Email: \" + gen(\"email\", regex=r\"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}\")\n\n# ❌ Bad: Free generation may produce invalid emails\nlm += \"Email: \" + gen(\"email\", max_tokens=50)\n```\n\n### 2. Use select() for Fixed Categories\n\n```python\n# ✅ Good: Guaranteed valid category\nlm += \"Status: \" + select([\"pending\", \"approved\", \"rejected\"], name=\"status\")\n\n# ❌ Bad: May generate typos or invalid values\nlm += \"Status: \" + gen(\"status\", max_tokens=20)\n```\n\n### 3. Leverage Token Healing\n\n```python\n# Token healing is enabled by default\n# No special action needed - just concatenate naturally\nlm += \"The capital is \" + gen(\"capital\")  # Automatic healing\n```\n\n### 4. Use stop Sequences\n\n```python\n# ✅ Good: Stop at newline for single-line outputs\nlm += \"Name: \" + gen(\"name\", stop=\"\\n\")\n\n# ❌ Bad: May generate multiple lines\nlm += \"Name: \" + gen(\"name\", max_tokens=50)\n```\n\n### 5. Create Reusable Functions\n\n```python\n# ✅ Good: Reusable pattern\n@guidance\ndef generate_person(lm):\n    lm += \"Name: \" + gen(\"name\", stop=\"\\n\")\n    lm += \"\\nAge: \" + gen(\"age\", regex=r\"[0-9]+\")\n    return lm\n\n# Use multiple times\nlm = generate_person(lm)\nlm += \"\\n\\n\"\nlm = generate_person(lm)\n```\n\n### 6. Balance Constraints\n\n```python\n# ✅ Good: Reasonable constraints\nlm += gen(\"name\", regex=r\"[A-Za-z ]+\", max_tokens=30)\n\n# ❌ Too strict: May fail or be very slow\nlm += gen(\"name\", regex=r\"^(John|Jane)$\", max_tokens=10)\n```\n\n## Comparison to Alternatives\n\n| Feature | Guidance | Instructor | Outlines | LMQL |\n|---------|----------|------------|----------|------|\n| Regex Constraints | ✅ Yes | ❌ No | ✅ Yes | ✅ Yes |\n| Grammar Support | ✅ CFG | ❌ No | ✅ CFG | ✅ CFG |\n| Pydantic Validation | ❌ No | ✅ Yes | ✅ Yes | ❌ No |\n| Token Healing | ✅ Yes | ❌ No | ✅ Yes | ❌ No |\n| Local Models | ✅ Yes | ⚠️ Limited | ✅ Yes | ✅ Yes |\n| API Models | ✅ Yes | ✅ Yes | ⚠️ Limited | ✅ Yes |\n| Pythonic Syntax | ✅ Yes | ✅ Yes | ✅ Yes | ❌ SQL-like |\n| Learning Curve | Low | Low | Medium | High |\n\n**When to choose Guidance:**\n- Need regex\u002Fgrammar constraints\n- Want token healing\n- Building complex workflows with control flow\n- Using local models (Transformers, llama.cpp)\n- Prefer Pythonic syntax\n\n**When to choose alternatives:**\n- Instructor: Need Pydantic validation with automatic retrying\n- Outlines: Need JSON schema validation\n- LMQL: Prefer declarative query syntax\n\n## Performance Characteristics\n\n**Latency Reduction:**\n- 30-50% faster than traditional prompting for constrained outputs\n- Token healing reduces unnecessary regeneration\n- Grammar constraints prevent invalid token generation\n\n**Memory Usage:**\n- Minimal overhead vs unconstrained generation\n- Grammar compilation cached after first use\n- Efficient token filtering at inference time\n\n**Token Efficiency:**\n- Prevents wasted tokens on invalid outputs\n- No need for retry loops\n- Direct path to valid outputs\n\n## Resources\n\n- **Documentation**: https:\u002F\u002Fguidance.readthedocs.io\n- **GitHub**: https:\u002F\u002Fgithub.com\u002Fguidance-ai\u002Fguidance\n- **Notebooks**: https:\u002F\u002Fgithub.com\u002Fguidance-ai\u002Fguidance\u002Ftree\u002Fmain\u002Fnotebooks\n- **Discord**: Community support available\n\n## See Also\n\n- `references\u002Fconstraints.md` - Comprehensive regex and grammar patterns\n- `references\u002Fbackends.md` - Backend-specific configuration\n- `references\u002Fexamples.md` - Production-ready examples\n\n## Agent operating procedure\n\n1. **Check the environment.** Confirm the framework version, model provider, API keys and rate limits.\n2. **Pin down the inputs.** Confirm formats, identifiers and parameters from the data or the user. Ask rather than guess any value that changes the result.\n3. **Run a small version first.** Test a single call or chain with a known input and inspect raw outputs.\n4. **Execute the full task** using the instructions and references above.\n5. **Validate the result.** Evaluate on a small labeled set; check structured outputs against their schema; log prompts and responses.\n6. **Report.** State what was run (versions, commands, parameters), what was checked, and what is still uncertain.\n\n| If this happens | Do this |\n|---|---|\n| Outputs do not match the expected schema | Add validation and retries, tighten the schema, or simplify the prompt. |\n| A function, flag or endpoint in these instructions is missing in the installed version | Check the installed version's own documentation (`help()`, `--help`, official docs), adapt, and tell the user. Never invent an API. |\n| A required input, identifier or parameter is ambiguous | Ask the user, or state the assumption explicitly before running. |\n\n**Integrity rules**\n\n- Never fabricate results, parameters, identifiers, citations or statistics. If something cannot be run or verified, say so plainly.\n- Never send private or sensitive data to external APIs without the user's consent.\n- Treat version-specific details here as possibly outdated: confirm them against the official documentation for the installed version.\n- Ask before actions that cost money, consume shared GPUs or cloud quota, touch personal or patient data, or cannot be undone.\n","# Guidance: Constrained LLM Generation\n\n## When to Use This Skill\n\nUse Guidance when you need to:\n- **Control LLM output syntax** with regex or grammars\n- **Guarantee valid JSON\u002FXML\u002Fcode** generation\n- **Reduce latency** vs traditional prompting approaches\n- **Enforce structured formats** (dates, emails, IDs, etc.)\n- **Build multi-step workflows** with Pythonic control flow\n- **Prevent invalid outputs** through grammatical constraints\n\n\n## Installation\n\n```bash\n# Base installation\npip install guidance\n\n# With specific backends\npip install guidance[transformers]  # Hugging Face models\npip install guidance[llama_cpp]     # llama.cpp models\n```\n\n## Quick Start\n\n### Basic Example: Structured Generation\n\n```python\nfrom guidance import models, gen\n\n# Load model (supports OpenAI, Transformers, llama.cpp)\nlm = models.OpenAI(\"gpt-4\")\n\n# Generate with constraints\nresult = lm + \"The capital of France is \" + gen(\"capital\", max_tokens=5)\n\nprint(result[\"capital\"])  # \"Paris\"\n```\n\n### With Anthropic Claude\n\n```python\nfrom guidance import models, gen, system, user, assistant\n\n# Configure Claude\nlm = models.Anthropic(\"claude-sonnet-4-5-20250929\")\n\n# Use context managers for chat format\nwith system():\n    lm += \"You are a helpful assistant.\"\n\nwith user():\n    lm += \"What is the capital of France?\"\n\nwith assistant():\n    lm += gen(max_tokens=20)\n```\n\n## Core Concepts\n\n### 1. Context Managers\n\nGuidance uses Pythonic context managers for chat-style interactions.\n\n```python\nfrom guidance import system, user, assistant, gen\n\nlm = models.Anthropic(\"claude-sonnet-4-5-20250929\")\n\n# System message\nwith system():\n    lm += \"You are a JSON generation expert.\"\n\n# User message\nwith user():\n    lm += \"Generate a person object with name and age.\"\n\n# Assistant response\nwith assistant():\n    lm += gen(\"response\", max_tokens=100)\n\nprint(lm[\"response\"])\n```\n\n**Benefits:**\n- Natural chat flow\n- Clear role separation\n- Easy to read and maintain\n\n### 2. Constrained Generation\n\nGuidance ensures outputs match specified patterns using regex or grammars.\n\n#### Regex Constraints\n\n```python\nfrom guidance import models, gen\n\nlm = models.Anthropic(\"claude-sonnet-4-5-20250929\")\n\n# Constrain to valid email format\nlm += \"Email: \" + gen(\"email\", regex=r\"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}\")\n\n# Constrain to date format (YYYY-MM-DD)\nlm += \"Date: \" + gen(\"date\", regex=r\"\\d{4}-\\d{2}-\\d{2}\")\n\n# Constrain to phone number\nlm += \"Phone: \" + gen(\"phone\", regex=r\"\\d{3}-\\d{3}-\\d{4}\")\n\nprint(lm[\"email\"])  # Guaranteed valid email\nprint(lm[\"date\"])   # Guaranteed YYYY-MM-DD format\n```\n\n**How it works:**\n- Regex converted to grammar at token level\n- Invalid tokens filtered during generation\n- Model can only produce matching outputs\n\n#### Selection Constraints\n\n```python\nfrom guidance import models, gen, select\n\nlm = models.Anthropic(\"claude-sonnet-4-5-20250929\")\n\n# Constrain to specific choices\nlm += \"Sentiment: \" + select([\"positive\", \"negative\", \"neutral\"], name=\"sentiment\")\n\n# Multiple-choice selection\nlm += \"Best answer: \" + select(\n    [\"A) Paris\", \"B) London\", \"C) Berlin\", \"D) Madrid\"],\n    name=\"answer\"\n)\n\nprint(lm[\"sentiment\"])  # One of: positive, negative, neutral\nprint(lm[\"answer\"])     # One of: A, B, C, or D\n```\n\n### 3. Token Healing\n\nGuidance automatically \"heals\" token boundaries between prompt and generation.\n\n**Problem:** Tokenization creates unnatural boundaries.\n\n```python\n# Without token healing\nprompt = \"The capital of France is \"\n# Last token: \" is \"\n# First generated token might be \" Par\" (with leading space)\n# Result: \"The capital of France is  Paris\" (double space!)\n```\n\n**Solution:** Guidance backs up one token and regenerates.\n\n```python\nfrom guidance import models, gen\n\nlm = models.Anthropic(\"claude-sonnet-4-5-20250929\")\n\n# Token healing enabled by default\nlm += \"The capital of France is \" + gen(\"capital\", max_tokens=5)\n# Result: \"The capital of France is Paris\" (correct spacing)\n```\n\n**Benefits:**\n- Natural text boundaries\n- No awkward spacing issues\n- Better model performance (sees natural token sequences)\n\n### 4. Grammar-Based Generation\n\nDefine complex structures using context-free grammars.\n\n```python\nfrom guidance import models, gen\n\nlm = models.Anthropic(\"claude-sonnet-4-5-20250929\")\n\n# JSON grammar (simplified)\njson_grammar = \"\"\"\n{\n    \"name\": \u003Cgen name regex=\"[A-Za-z ]+\" max_tokens=20>,\n    \"age\": \u003Cgen age regex=\"[0-9]+\" max_tokens=3>,\n    \"email\": \u003Cgen email regex=\"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\\\.[a-zA-Z]{2,}\" max_tokens=50>\n}\n\"\"\"\n\n# Generate valid JSON\nlm += gen(\"person\", grammar=json_grammar)\n\nprint(lm[\"person\"])  # Guaranteed valid JSON structure\n```\n\n**Use cases:**\n- Complex structured outputs\n- Nested data structures\n- Programming language syntax\n- Domain-specific languages\n\n### 5. Guidance Functions\n\nCreate reusable generation patterns with the `@guidance` decorator.\n\n```python\nfrom guidance import guidance, gen, models\n\n@guidance\ndef generate_person(lm):\n    \"\"\"Generate a person with name and age.\"\"\"\n    lm += \"Name: \" + gen(\"name\", max_tokens=20, stop=\"\\n\")\n    lm += \"\\nAge: \" + gen(\"age\", regex=r\"[0-9]+\", max_tokens=3)\n    return lm\n\n# Use the function\nlm = models.Anthropic(\"claude-sonnet-4-5-20250929\")\nlm = generate_person(lm)\n\nprint(lm[\"name\"])\nprint(lm[\"age\"])\n```\n\n**Stateful Functions:**\n\n```python\n@guidance(stateless=False)\ndef react_agent(lm, question, tools, max_rounds=5):\n    \"\"\"ReAct agent with tool use.\"\"\"\n    lm += f\"Question: {question}\\n\\n\"\n\n    for i in range(max_rounds):\n        # Thought\n        lm += f\"Thought {i+1}: \" + gen(\"thought\", stop=\"\\n\")\n\n        # Action\n        lm += \"\\nAction: \" + select(list(tools.keys()), name=\"action\")\n\n        # Execute tool\n        tool_result = tools[lm[\"action\"]]()\n        lm += f\"\\nObservation: {tool_result}\\n\\n\"\n\n        # Check if done\n        lm += \"Done? \" + select([\"Yes\", \"No\"], name=\"done\")\n        if lm[\"done\"] == \"Yes\":\n            break\n\n    # Final answer\n    lm += \"\\nFinal Answer: \" + gen(\"answer\", max_tokens=100)\n    return lm\n```\n\n## Backend Configuration\n\n### Anthropic Claude\n\n```python\nfrom guidance import models\n\nlm = models.Anthropic(\n    model=\"claude-sonnet-4-5-20250929\",\n    api_key=\"your-api-key\"  # Or set ANTHROPIC_API_KEY env var\n)\n```\n\n### OpenAI\n\n```python\nlm = models.OpenAI(\n    model=\"gpt-4o-mini\",\n    api_key=\"your-api-key\"  # Or set OPENAI_API_KEY env var\n)\n```\n\n### Local Models (Transformers)\n\n```python\nfrom guidance.models import Transformers\n\nlm = Transformers(\n    \"microsoft\u002FPhi-4-mini-instruct\",\n    device=\"cuda\"  # Or \"cpu\"\n)\n```\n\n### Local Models (llama.cpp)\n\n```python\nfrom guidance.models import LlamaCpp\n\nlm = LlamaCpp(\n    model_path=\"\u002Fpath\u002Fto\u002Fmodel.gguf\",\n    n_ctx=4096,\n    n_gpu_layers=35\n)\n```\n\n## Common Patterns\n\nDetails, code examples and parameter tables: [references\u002Fcommon-patterns.md](references\u002Fcommon-patterns.md). Read it when this step applies.\n\n## Best Practices\n\n### 1. Use Regex for Format Validation\n\n```python\n# ✅ Good: Regex ensures valid format\nlm += \"Email: \" + gen(\"email\", regex=r\"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}\")\n\n# ❌ Bad: Free generation may produce invalid emails\nlm += \"Email: \" + gen(\"email\", max_tokens=50)\n```\n\n### 2. Use select() for Fixed Categories\n\n```python\n# ✅ Good: Guaranteed valid category\nlm += \"Status: \" + select([\"pending\", \"approved\", \"rejected\"], name=\"status\")\n\n# ❌ Bad: May generate typos or invalid values\nlm += \"Status: \" + gen(\"status\", max_tokens=20)\n```\n\n### 3. Leverage Token Healing\n\n```python\n# Token healing is enabled by default\n# No special action needed - just concatenate naturally\nlm += \"The capital is \" + gen(\"capital\")  # Automatic healing\n```\n\n### 4. Use stop Sequences\n\n```python\n# ✅ Good: Stop at newline for single-line outputs\nlm += \"Name: \" + gen(\"name\", stop=\"\\n\")\n\n# ❌ Bad: May generate multiple lines\nlm += \"Name: \" + gen(\"name\", max_tokens=50)\n```\n\n### 5. Create Reusable Functions\n\n```python\n# ✅ Good: Reusable pattern\n@guidance\ndef generate_person(lm):\n    lm += \"Name: \" + gen(\"name\", stop=\"\\n\")\n    lm += \"\\nAge: \" + gen(\"age\", regex=r\"[0-9]+\")\n    return lm\n\n# Use multiple times\nlm = generate_person(lm)\nlm += \"\\n\\n\"\nlm = generate_person(lm)\n```\n\n### 6. Balance Constraints\n\n```python\n# ✅ Good: Reasonable constraints\nlm += gen(\"name\", regex=r\"[A-Za-z ]+\", max_tokens=30)\n\n# ❌ Too strict: May fail or be very slow\nlm += gen(\"name\", regex=r\"^(John|Jane)$\", max_tokens=10)\n```\n\n## Comparison to Alternatives\n\n| Feature | Guidance | Instructor | Outlines | LMQL |\n|---------|----------|------------|----------|------|\n| Regex Constraints | ✅ Yes | ❌ No | ✅ Yes | ✅ Yes |\n| Grammar Support | ✅ CFG | ❌ No | ✅ CFG | ✅ CFG |\n| Pydantic Validation | ❌ No | ✅ Yes | ✅ Yes | ❌ No |\n| Token Healing | ✅ Yes | ❌ No | ✅ Yes | ❌ No |\n| Local Models | ✅ Yes | ⚠️ Limited | ✅ Yes | ✅ Yes |\n| API Models | ✅ Yes | ✅ Yes | ⚠️ Limited | ✅ Yes |\n| Pythonic Syntax | ✅ Yes | ✅ Yes | ✅ Yes | ❌ SQL-like |\n| Learning Curve | Low | Low | Medium | High |\n\n**When to choose Guidance:**\n- Need regex\u002Fgrammar constraints\n- Want token healing\n- Building complex workflows with control flow\n- Using local models (Transformers, llama.cpp)\n- Prefer Pythonic syntax\n\n**When to choose alternatives:**\n- Instructor: Need Pydantic validation with automatic retrying\n- Outlines: Need JSON schema validation\n- LMQL: Prefer declarative query syntax\n\n## Performance Characteristics\n\n**Latency Reduction:**\n- 30-50% faster than traditional prompting for constrained outputs\n- Token healing reduces unnecessary regeneration\n- Grammar constraints prevent invalid token generation\n\n**Memory Usage:**\n- Minimal overhead vs unconstrained generation\n- Grammar compilation cached after first use\n- Efficient token filtering at inference time\n\n**Token Efficiency:**\n- Prevents wasted tokens on invalid outputs\n- No need for retry loops\n- Direct path to valid outputs\n\n## Resources\n\n- **Documentation**: https:\u002F\u002Fguidance.readthedocs.io\n- **GitHub**: https:\u002F\u002Fgithub.com\u002Fguidance-ai\u002Fguidance\n- **Notebooks**: https:\u002F\u002Fgithub.com\u002Fguidance-ai\u002Fguidance\u002Ftree\u002Fmain\u002Fnotebooks\n- **Discord**: Community support available\n\n## See Also\n\n- `references\u002Fconstraints.md` - Comprehensive regex and grammar patterns\n- `references\u002Fbackends.md` - Backend-specific configuration\n- `references\u002Fexamples.md` - Production-ready examples\n\n## Agent operating procedure\n\n1. **Check the environment.** Confirm the framework version, model provider, API keys and rate limits.\n2. **Pin down the inputs.** Confirm formats, identifiers and parameters from the data or the user. Ask rather than guess any value that changes the result.\n3. **Run a small version first.** Test a single call or chain with a known input and inspect raw outputs.\n4. **Execute the full task** using the instructions and references above.\n5. **Validate the result.** Evaluate on a small labeled set; check structured outputs against their schema; log prompts and responses.\n6. **Report.** State what was run (versions, commands, parameters), what was checked, and what is still uncertain.\n\n| If this happens | Do this |\n|---|---|\n| Outputs do not match the expected schema | Add validation and retries, tighten the schema, or simplify the prompt. |\n| A function, flag or endpoint in these instructions is missing in the installed version | Check the installed version's own documentation (`help()`, `--help`, official docs), adapt, and tell the user. Never invent an API. |\n| A required input, identifier or parameter is ambiguous | Ask the user, or state the assumption explicitly before running. |\n\n**Integrity rules**\n\n- Never fabricate results, parameters, identifiers, citations or statistics. If something cannot be run or verified, say so plainly.\n- Never send private or sensitive data to external APIs without the user's consent.\n- Treat version-specific details here as possibly outdated: confirm them against the official documentation for the installed version.\n- Ask before actions that cost money, consume shared GPUs or cloud quota, touch personal or patient data, or cannot be undone.\n",{"name":5,"license":15,"metadata":51,"description":7},{"tags":52,"version":53,"category":54,"maintainer":55,"dependencies":56},"Prompt Engineering, Guidance, Constrained Generation, Structured Output, JSON Validation, Grammar, Microsoft Research, Format Enforcement, Multi-Step Workflows","1.0.0","llm-applications","Kalaris Labs","guidance, transformers","main","0da4485785ee599388900be50db1635489d53056",".agents\u002Fskills\u002Fkal-guidance","https:\u002F\u002Fgithub.com\u002FTashima-Tarsh\u002FDisha6.6","https:\u002F\u002Fdisha6.6.thenitishkr.in\u002F","https:\u002F\u002Fgithub.com\u002FTashima-Tarsh","www.thenitishkr","thenitishkr | AI • Cyber-security • Research\r\n","2026-11-08 03:33:25",{"source":8,"skillName":5,"commands":67,"prompt":77,"zipAvailable":78},[68,71,74],{"tool":69,"command":70},"npx","npx skills add Tashima-Tarsh\u002FDisha6.6 --skill guidance",{"tool":72,"command":73},"bunx","bunx skills add Tashima-Tarsh\u002FDisha6.6 --skill guidance",{"tool":75,"command":76},"pnpm","pnpm dlx skills add Tashima-Tarsh\u002FDisha6.6 --skill guidance","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FTashima-Tarsh\u002FDisha6.6\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fkal-guidance\u002FSKILL.md",true,[80,86,90,94,98],{"path":81,"resourceType":82,"resourceTypeDesc":83,"sizeBytes":84,"sourceHtmlUrl":85},"references\u002Fbackends.md","REFERENCE","参考文档",12010,"https:\u002F\u002Fgithub.com\u002FTashima-Tarsh\u002FDisha6.6\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fkal-guidance\u002Freferences\u002Fbackends.md",{"path":87,"resourceType":82,"resourceTypeDesc":83,"sizeBytes":88,"sourceHtmlUrl":89},"references\u002Fcommon-patterns.md",3770,"https:\u002F\u002Fgithub.com\u002FTashima-Tarsh\u002FDisha6.6\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fkal-guidance\u002Freferences\u002Fcommon-patterns.md",{"path":91,"resourceType":82,"resourceTypeDesc":83,"sizeBytes":92,"sourceHtmlUrl":93},"references\u002Fconstraints.md",15886,"https:\u002F\u002Fgithub.com\u002FTashima-Tarsh\u002FDisha6.6\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fkal-guidance\u002Freferences\u002Fconstraints.md",{"path":95,"resourceType":82,"resourceTypeDesc":83,"sizeBytes":96,"sourceHtmlUrl":97},"references\u002Fexamples.md",20111,"https:\u002F\u002Fgithub.com\u002FTashima-Tarsh\u002FDisha6.6\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fkal-guidance\u002Freferences\u002Fexamples.md",{"path":99,"resourceType":100,"resourceTypeDesc":101,"sizeBytes":102,"sourceHtmlUrl":103},"scripts\u002Fsafe_arithmetic.py","SCRIPT","脚本",1295,"https:\u002F\u002Fgithub.com\u002FTashima-Tarsh\u002FDisha6.6\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fkal-guidance\u002Fscripts\u002Fsafe_arithmetic.py",[105,134,159,184,208,230],{"skillNo":106,"name":107,"nameZh":6,"description":108,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":109,"categories":110,"keywords":114,"publishedAt":46},"01M6QRD07D4TGNDK6VJ4EHF8BV","youtube-full","Use when the user needs YouTube transcripts, video search, channel browsing, playlist extraction, or content monitoring. Trigger phrases: 'get the transcript for', 'search YouTube for', 'what are the latest videos on', 'list this playlist', 'monitor this channel', or any request involving a YouTube URL, video ID, or @handle. Do NOT use for downloading video or audio files, YouTube engagement data (likes, comments), or private\u002Fage-restricted videos.","https:\u002F\u002Fgithub.com\u002FTashima-Tarsh\u002FDisha6.6\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fyoutube-full\u002FSKILL.md",[111],{"categoryNo":112,"categoryName":113,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000016","图像与多媒体",[115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,29,131,132,133],"youtube full","youtube","full","transcript","search","monitoring","data","Video","Audio","list","files","do","get","age","trigger","URL","browsing","request","youtube transcripts",{"skillNo":135,"name":136,"nameZh":6,"description":137,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":138,"categories":139,"keywords":140,"publishedAt":46},"01M6QRCJ3112VYPA97YG7KGMC2","x-twitter-growth","X\u002FTwitter growth engine for building audience, crafting viral content, and analyzing engagement. Use when the user wants to grow on X\u002FTwitter, write tweets or threads, analyze their X profile, research competitors on X, plan a posting strategy, or optimize engagement. Complements social-content (generic multi-platform) with X-specific depth: algorithm mechanics, thread engineering, reply strategy, profile optimization, and competitive intelligence via web search.","https:\u002F\u002Fgithub.com\u002FTashima-Tarsh\u002FDisha6.6\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fx-twitter-growth\u002FSKILL.md",[],[141,142,143,144,119,145,146,147,148,149,150,151,152,153,154,155,156,157,158,29],"twitter","x twitter growth","growth","research","content","engineering","plan","web search","competitors","analyze","engine","write","strategy","use","platform","grow","posting","competitive",{"skillNo":160,"name":161,"nameZh":6,"description":162,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":163,"categories":164,"keywords":166,"publishedAt":46},"01M6QRBN3EHQNJY42RERP7A149","write-a-skill","Create new agent skills with proper structure, progressive disclosure, and bundled resources. Use when user wants to create, write, build, or author a new skill.","https:\u002F\u002Fgithub.com\u002FTashima-Tarsh\u002FDisha6.6\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fwrite-a-skill\u002FSKILL.md",[165],{"categoryNo":24,"categoryName":25,"taxonomyType":21,"taxonomyTypeDesc":22},[167,152,168,169,170,171,172,173,154,174,175,57,176,177,178,179,180,181,182,183],"write a skill","github","create","https","productivity","matt pocock","direct","example","build","new skill","structure","new agent","resources","with","tree","progressive disclosure","author",{"skillNo":185,"name":186,"nameZh":6,"description":187,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":188,"categories":189,"keywords":190,"publishedAt":46},"01M6QRB6G8P33PNGAF9Y69EJ9T","wrap-up","Close out a launched Claude Managed Agent — recap every primitive the founder now owns, regenerate the single-file overview page, and suggest the next 1-2 upgrades. Use when the user says \"wrap up\", \"close this out\", \"what do I own now\", \"give me the summary\", \"recap the agent\", or when the orchestrator routes phase=wrap-up. primitives_inventory.py tables everything owned (agent, environment, session, memory, outcome, deployment); overview_page.py regenerates a self-contained .\u002Fmy-agent\u002Fagent-overview.html; upgrade_suggester.py ranks the next moves from recorded deferrals plus standing hardening steps. Companion to run-without-you; the last stop before phase=done.","https:\u002F\u002Fgithub.com\u002FTashima-Tarsh\u002FDisha6.6\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fwrap-up\u002FSKILL.md",[],[191,192,193,194,195,196,197,198,199,154,200,126,201,202,203,204,31,205,206,207],"wrap up","up","wrap","gemini","deployment","run","file","hardening","closeout","stop","upgrade","founder","close","companion","tables","directions","phase",{"skillNo":209,"name":210,"nameZh":6,"description":211,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":212,"categories":213,"keywords":215,"publishedAt":46},"01M6QRA5AYC1RBFZ39GTWGS3N8","workflow-builder","Design and write deterministic multi-agent workflow scripts (.js files in .claude\u002Fworkflows\u002F) for Claude Code's Workflow tool. Use when a user wants to build, create, author, scaffold, or run a custom Claude Code workflow, orchestrate sub-agents (fan-out, pipeline, loop, judge-panel), or automate a repeatable multi-step task across fresh-context agents.","https:\u002F\u002Fgithub.com\u002FTashima-Tarsh\u002FDisha6.6\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fworkflow-builder\u002FSKILL.md",[214],{"categoryNo":24,"categoryName":25,"taxonomyType":21,"taxonomyTypeDesc":22},[216,217,218,219,44,169,196,220,221,222,223,224,152,39,125,225,226,227,228,229],"workflow","workflow builder","builder","design","code","orchestrate","pipeline","loop","multi-agent","across","fresh","scripts","judge","claude code workflow",{"skillNo":231,"name":232,"nameZh":6,"description":233,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":234,"categories":235,"keywords":236,"publishedAt":46},"01M6QR7QMCZESKQA0ERW1E657M","weekly-review","Use when someone wants to run a weekly review, close open loops, audit stalled projects and commitments, get their system back to trusted, restart a lapsed review habit, or says \"\u002Fcs:weekly-review\". Walks David Allen's three-phase loop — GET CLEAR, GET CURRENT, GET CREATIVE — with deterministic scripts that inventory open loops, gate the checklist with named gaps, and score commitment health 0-100.","https:\u002F\u002Fgithub.com\u002FTashima-Tarsh\u002FDisha6.6\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fweekly-review\u002FSKILL.md",[],[237,238,239,240,241,242,243,244,245,223,246,247,248,249,250,251,127,252,253,207],"review","weekly review","weekly","deterministic scripts","reflect","feeds","inventory","open","team","projects","project-management","scanner","conversation","back","project","sprint","cadence"]