# เอกสารอ้างอิง: Constraints

Guide to regex constraints, grammar-based generation, and token healing in Guidance.

## Table of Contents
- Regex Constraints
- Grammar-Based Generation
- Token Healing
- Selection Constraints
- Complex Patterns
- Performance Optimization

## Regex Constraints

### Basic Patterns

#### Numeric Constraints

```python
from guidance import models, gen

lm = models.Anthropic("claude-sonnet-4-5-20250929")

# เอกสารอ้างอิง: Constraints
lm += "Age: " + gen("age", regex=r"[0-9]+")

# เอกสารอ้างอิง: Constraints
lm += "Temperature: " + gen("temp", regex=r"-?[0-9]+")

# เอกสารอ้างอิง: Constraints
lm += "Price: $" + gen("price", regex=r"[0-9]+\.[0-9]{2}")

# เอกสารอ้างอิง: Constraints
lm += "Value: " + gen("value", regex=r"-?[0-9]+(\.[0-9]+)?")

# เอกสารอ้างอิง: Constraints
lm += "Progress: " + gen("progress", regex=r"(100|[0-9]{1,2})")

# เอกสารอ้างอิง: Constraints
lm += "Rating: " + gen("rating", regex=r"[1-5]") + " stars"
```

#### Text Constraints

```python
# เอกสารอ้างอิง: Constraints
lm += "Name: " + gen("name", regex=r"[A-Za-z]+")

# เอกสารอ้างอิง: Constraints
lm += "Full Name: " + gen("full_name", regex=r"[A-Za-z ]+")

# เอกสารอ้างอิง: Constraints
lm += "Username: " + gen("username", regex=r"[A-Za-z0-9_]+")

# เอกสารอ้างอิง: Constraints
lm += "Title: " + gen("title", regex=r"[A-Z][a-z]+( [A-Z][a-z]+)*")

# เอกสารอ้างอิง: Constraints
lm += "Code: " + gen("code", regex=r"[a-z0-9-]+")

# เอกสารอ้างอิง: Constraints
lm += "ID: " + gen("id", regex=r"[A-Z]{3}-[0-9]{6}")  # e.g., "ABC-123456"
```

#### Date and Time Constraints

```python
# เอกสารอ้างอิง: Constraints
lm += "Date: " + gen("date", regex=r"\d{4}-\d{2}-\d{2}")

# เอกสารอ้างอิง: Constraints
lm += "Date: " + gen("date_us", regex=r"\d{2}/\d{2}/\d{4}")

# เอกสารอ้างอิง: Constraints
lm += "Time: " + gen("time", regex=r"\d{2}:\d{2}")

# เอกสารอ้างอิง: Constraints
lm += "Time: " + gen("time_full", regex=r"\d{2}:\d{2}:\d{2}")

# เอกสารอ้างอิง: Constraints
lm += "Timestamp: " + gen(
    "timestamp",
    regex=r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z"
)

# เอกสารอ้างอิง: Constraints
lm += "Year: " + gen("year", regex=r"(19|20)\d{2}")

# เอกสารอ้างอิง: Constraints
lm += "Month: " + gen(
    "month",
    regex=r"(January|February|March|April|May|June|July|August|September|October|November|December)"
)
```

#### Contact Information

```python
# เอกสารอ้างอิง: Constraints
lm += "Email: " + gen(
    "email",
    regex=r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}"
)

# เอกสารอ้างอิง: Constraints
lm += "Phone: " + gen("phone", regex=r"\d{3}-\d{3}-\d{4}")

# เอกสารอ้างอิง: Constraints
lm += "Phone: " + gen("phone_intl", regex=r"\+[0-9]{1,3}-[0-9]{1,14}")

# เอกสารอ้างอิง: Constraints
lm += "ZIP: " + gen("zip", regex=r"\d{5}(-\d{4})?")

# เอกสารอ้างอิง: Constraints
lm += "Postal: " + gen("postal", regex=r"[A-Z]\d[A-Z] \d[A-Z]\d")

# เอกสารอ้างอิง: Constraints
lm += "URL: " + gen(
    "url",
    regex=r"https?://[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}(/[a-zA-Z0-9._~:/?#\[\]@!$&'()*+,;=-]*)?"
)
```

### Advanced Patterns

#### JSON Field Constraints

```python
from guidance import models, gen

lm = models.Anthropic("claude-sonnet-4-5-20250929")

# เอกสารอ้างอิง: Constraints
lm += '"name": ' + gen("name", regex=r'"[A-Za-z ]+"')

# เอกสารอ้างอิง: Constraints
lm += '"age": ' + gen("age", regex=r"[0-9]+")

# เอกสารอ้างอิง: Constraints
lm += '"active": ' + gen("active", regex=r"(true|false)")

# เอกสารอ้างอิง: Constraints
lm += '"optional": ' + gen("optional", regex=r"(null|[0-9]+)")

# เอกสารอ้างอิง: Constraints
lm += '"tags": [' + gen(
    "tags",
    regex=r'"[a-z]+"(, "[a-z]+")*'
) + ']'

# เอกสารอ้างอิง: Constraints
lm += """{
    "name": """ + gen("name", regex=r'"[A-Za-z ]+"') + """,
    "age": """ + gen("age", regex=r"[0-9]+") + """,
    "email": """ + gen(
        "email",
        regex=r'"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}"'
    ) + """
}"""
```

#### Code Patterns

```python
# เอกสารอ้างอิง: Constraints
lm += "Variable: " + gen("var", regex=r"[a-z_][a-z0-9_]*")

# เอกสารอ้างอิง: Constraints
lm += "Function: " + gen("func", regex=r"[a-z_][a-z0-9_]*")

# เอกสารอ้างอิง: Constraints
lm += "Color: #" + gen("color", regex=r"[0-9A-Fa-f]{6}")

# เอกสารอ้างอิง: Constraints
lm += "UUID: " + gen(
    "uuid",
    regex=r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"
)

# เอกสารอ้างอิง: Constraints
lm += "Commit: " + gen("commit", regex=r"[0-9a-f]{7}")

# เอกสารอ้างอิง: Constraints
lm += "Version: " + gen("version", regex=r"[0-9]+\.[0-9]+\.[0-9]+")

# เอกสารอ้างอิง: Constraints
lm += "IP: " + gen(
    "ip",
    regex=r"((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)"
)
```

#### Domain-Specific Patterns

```python
# เอกสารอ้างอิง: Constraints
lm += "Card: " + gen("card", regex=r"\d{4}-\d{4}-\d{4}-\d{4}")

# เอกสารอ้างอิง: Constraints
lm += "SSN: " + gen("ssn", regex=r"\d{3}-\d{2}-\d{4}")

# เอกสารอ้างอิง: Constraints
lm += "ISBN: " + gen("isbn", regex=r"978-\d{1,5}-\d{1,7}-\d{1,7}-\d")

# เอกสารอ้างอิง: Constraints
lm += "Plate: " + gen("plate", regex=r"[A-Z]{3}-\d{4}")

# เอกสารอ้างอิง: Constraints
lm += "Amount: $" + gen("amount", regex=r"[0-9]{1,3}(,[0-9]{3})*\.[0-9]{2}")

# เอกสารอ้างอิง: Constraints
lm += "Rate: " + gen("rate", regex=r"[0-9]+\.[0-9]{1,2}%")
```

## Grammar-Based Generation

### JSON Grammar

```python
from guidance import models, gen, guidance

@guidance
def json_object(lm):
    """Generate valid JSON object."""
    lm += "{\n"

    # Name field (required)
    lm += '    "name": ' + gen("name", regex=r'"[A-Za-z ]+"') + ",\n"

    # Age field (required)
    lm += '    "age": ' + gen("age", regex=r"[0-9]+") + ",\n"

    # Email field (required)
    lm += '    "email": ' + gen(
        "email",
        regex=r'"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}"'
    ) + ",\n"

    # Active field (required, boolean)
    lm += '    "active": ' + gen("active", regex=r"(true|false)") + "\n"

    lm += "}"
    return lm

lm = models.Anthropic("claude-sonnet-4-5-20250929")
lm = json_object(lm)
print(lm)  # Valid JSON guaranteed
```

### Nested JSON Grammar

```python
@guidance
def nested_json(lm):
    """Generate nested JSON structure."""
    lm += "{\n"

    # User object
    lm += '    "user": {\n'
    lm += '        "name": ' + gen("name", regex=r'"[A-Za-z ]+"') + ",\n"
    lm += '        "age": ' + gen("age", regex=r"[0-9]+") + "\n"
    lm += "    },\n"

    # Address object
    lm += '    "address": {\n'
    lm += '        "street": ' + gen("street", regex=r'"[A-Za-z0-9 ]+"') + ",\n"
    lm += '        "city": ' + gen("city", regex=r'"[A-Za-z ]+"') + ",\n"
    lm += '        "zip": ' + gen("zip", regex=r'"\d{5}"') + "\n"
    lm += "    }\n"

    lm += "}"
    return lm
```

### Array Grammar

```python
@guidance
def json_array(lm, count=3):
    """Generate JSON array with fixed count."""
    lm += "[\n"

    for i in range(count):
        lm += "    {\n"
        lm += '        "id": ' + gen(f"id_{i}", regex=r"[0-9]+") + ",\n"
        lm += '        "name": ' + gen(f"name_{i}", regex=r'"[A-Za-z ]+"') + "\n"
        lm += "    }"
        if i < count - 1:
            lm += ","
        lm += "\n"

    lm += "]"
    return lm
```

### XML Grammar

```python
@guidance
def xml_document(lm):
    """Generate valid XML document."""
    lm += '<?xml version="1.0"?>\n'
    lm += "<person>\n"

    # Name element
    lm += "    <name>" + gen("name", regex=r"[A-Za-z ]+") + "</name>\n"

    # Age element
    lm += "    <age>" + gen("age", regex=r"[0-9]+") + "</age>\n"

    # Email element
    lm += "    <email>" + gen(
        "email",
        regex=r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}"
    ) + "</email>\n"

    lm += "</person>"
    return lm
```

### CSV Grammar

```python
@guidance
def csv_row(lm):
    """Generate CSV row."""
    lm += gen("name", regex=r"[A-Za-z ]+") + ","
    lm += gen("age", regex=r"[0-9]+") + ","
    lm += gen("email", regex=r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}")
    return lm

@guidance
def csv_document(lm, rows=5):
    """Generate complete CSV."""
    # Header
    lm += "Name,Age,Email\n"

    # Rows
    for i in range(rows):
        lm = csv_row(lm)
        if i < rows - 1:
            lm += "\n"

    return lm
```

## Token Healing

### How Token Healing Works

**Problem:** Tokenization creates unnatural boundaries.

```python
# เอกสารอ้างอิง: Constraints
prompt = "The capital of France is "
# เอกสารอ้างอิง: Constraints
# เอกสารอ้างอิง: Constraints
# เอกสารอ้างอิง: Constraints
# เอกสารอ้างอิง: Constraints
```

**Solution:** Guidance backs up and regenerates the last token.

```python
from guidance import models, gen

lm = models.Anthropic("claude-sonnet-4-5-20250929")

# เอกสารอ้างอิง: Constraints
lm += "The capital of France is " + gen("capital", max_tokens=5)

# เอกสารอ้างอิง: Constraints
# เอกสารอ้างอิง: Constraints
# เอกสารอ้างอิง: Constraints
# เอกสารอ้างอิง: Constraints
```

### Token Healing Examples

#### Natural Continuations

```python
# เอกสารอ้างอิง: Constraints
lm += "The function name is get" + gen("rest")
# เอกสารอ้างอิง: Constraints

# เอกสารอ้างอิง: Constraints
lm += "The function name is get" + gen("rest")
# เอกสารอ้างอิง: Constraints
```

#### Code Generation

```python
# เอกสารอ้างอิง: Constraints
lm += "def calculate_" + gen("rest", stop="(")
# เอกสารอ้างอิง: Constraints

# เอกสารอ้างอิง: Constraints
lm += "my_" + gen("var_name", regex=r"[a-z_]+")
# เอกสารอ้างอิง: Constraints
```

#### Domain-Specific Terms

```python
# เอกสารอ้างอิง: Constraints
lm += "The patient has hyper" + gen("condition")
# เอกสารอ้างอิง: Constraints

# เอกสารอ้างอิง: Constraints
lm += "Using micro" + gen("tech")
# เอกสารอ้างอิง: Constraints
```

### Disabling Token Healing

```python
# เอกสารอ้างอิง: Constraints
lm += gen("text", token_healing=False)
```

## Selection Constraints

### Basic Selection

```python
from guidance import models, select

lm = models.Anthropic("claude-sonnet-4-5-20250929")

# เอกสารอ้างอิง: Constraints
lm += "Status: " + select(["active", "inactive", "pending"], name="status")

# เอกสารอ้างอิง: Constraints
lm += "Approved: " + select(["Yes", "No"], name="approved")

# เอกสารอ้างอิง: Constraints
lm += "Answer: " + select(
    ["A) Paris", "B) London", "C) Berlin", "D) Madrid"],
    name="answer"
)
```

### Conditional Selection

```python
from guidance import models, select, gen, guidance

@guidance
def conditional_fields(lm):
    """Generate fields conditionally based on type."""
    lm += "Type: " + select(["person", "company"], name="type")

    if lm["type"] == "person":
        lm += "\nName: " + gen("name", regex=r"[A-Za-z ]+")
        lm += "\nAge: " + gen("age", regex=r"[0-9]+")
    else:
        lm += "\nCompany Name: " + gen("company", regex=r"[A-Za-z ]+")
        lm += "\nEmployees: " + gen("employees", regex=r"[0-9]+")

    return lm
```

### Repeated Selection

```python
@guidance
def multiple_selections(lm):
    """Select multiple items."""
    lm += "Select 3 colors:\n"

    colors = ["red", "blue", "green", "yellow", "purple"]

    for i in range(3):
        lm += f"{i+1}. " + select(colors, name=f"color_{i}") + "\n"

    return lm
```

## Complex Patterns

### Pattern 1: Structured Forms

```python
@guidance
def user_form(lm):
    """Generate structured user form."""
    lm += "=== User Registration ===\n\n"

    # Name (alphabetic only)
    lm += "Full Name: " + gen("name", regex=r"[A-Za-z ]+", stop="\n") + "\n"

    # Age (numeric)
    lm += "Age: " + gen("age", regex=r"[0-9]+", max_tokens=3) + "\n"

    # Email (validated format)
    lm += "Email: " + gen(
        "email",
        regex=r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}",
        stop="\n"
    ) + "\n"

    # Phone (US format)
    lm += "Phone: " + gen("phone", regex=r"\d{3}-\d{3}-\d{4}") + "\n"

    # Account type (selection)
    lm += "Account Type: " + select(
        ["Standard", "Premium", "Enterprise"],
        name="account_type"
    ) + "\n"

    # Active status (boolean)
    lm += "Active: " + select(["Yes", "No"], name="active") + "\n"

    return lm
```

### Pattern 2: Multi-Entity Extraction

```python
@guidance
def extract_entities(lm, text):
    """Extract multiple entities with constraints."""
    lm += f"Text: {text}\n\n"

    # Person name (alphabetic)
    lm += "Person: " + gen("person", regex=r"[A-Za-z ]+", stop="\n") + "\n"

    # Organization (alphanumeric with spaces)
    lm += "Organization: " + gen(
        "organization",
        regex=r"[A-Za-z0-9 ]+",
        stop="\n"
    ) + "\n"

    # Date (YYYY-MM-DD format)
    lm += "Date: " + gen("date", regex=r"\d{4}-\d{2}-\d{2}") + "\n"

    # Location (alphabetic with spaces)
    lm += "Location: " + gen("location", regex=r"[A-Za-z ]+", stop="\n") + "\n"

    # Amount (currency)
    lm += "Amount: $" + gen("amount", regex=r"[0-9,]+\.[0-9]{2}") + "\n"

    return lm
```

### Pattern 3: Code Generation

```python
@guidance
def generate_python_function(lm):
    """Generate Python function with constraints."""
    # Function name (valid Python identifier)
    lm += "def " + gen("func_name", regex=r"[a-z_][a-z0-9_]*") + "("

    # Parameter name
    lm += gen("param", regex=r"[a-z_][a-z0-9_]*") + "):\n"

    # Docstring
    lm += '    """' + gen("docstring", stop='"""', max_tokens=50) + '"""\n'

    # Function body (constrained to valid Python)
    lm += "    return " + gen("return_value", stop="\n") + "\n"

    return lm
```

### Pattern 4: Hierarchical Data

```python
@guidance
def org_chart(lm):
    """Generate organizational chart."""
    lm += "Company: " + gen("company", regex=r"[A-Za-z ]+") + "\n\n"

    # CEO
    lm += "CEO: " + gen("ceo", regex=r"[A-Za-z ]+") + "\n"

    # Departments
    for dept in ["Engineering", "Sales", "Marketing"]:
        lm += f"\n{dept} Department:\n"
        lm += "  Head: " + gen(f"{dept.lower()}_head", regex=r"[A-Za-z ]+") + "\n"
        lm += "  Size: " + gen(f"{dept.lower()}_size", regex=r"[0-9]+") + " employees\n"

    return lm
```

## Performance Optimization

### Best Practices

#### 1. Use Specific Patterns

```python
# เอกสารอ้างอิง: Constraints
lm += gen("age", regex=r"[0-9]{1,3}")  # Fast

# เอกสารอ้างอิง: Constraints
lm += gen("age", regex=r"[0-9]+")  # Slower
```

#### 2. Limit Max Tokens

```python
# เอกสารอ้างอิง: Constraints
lm += gen("name", max_tokens=30)

# เอกสารอ้างอิง: Constraints
lm += gen("name")  # May generate forever
```

#### 3. Use stop Sequences

```python
# เอกสารอ้างอิง: Constraints
lm += gen("line", stop="\n")

# เอกสารอ้างอิง: Constraints
lm += gen("line", max_tokens=100)
```

#### 4. Cache Compiled Grammars

```python
# เอกสารอ้างอิง: Constraints
# เอกสารอ้างอิง: Constraints
@guidance
def reusable_pattern(lm):
    """This grammar is compiled once and cached."""
    lm += gen("email", regex=r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}")
    return lm

# เอกสารอ้างอิง: Constraints
lm = reusable_pattern(lm)

# เอกสารอ้างอิง: Constraints
lm = reusable_pattern(lm)
```

#### 5. Avoid Overlapping Constraints

```python
# เอกสารอ้างอิง: Constraints
lm += gen("age", regex=r"[0-9]+", max_tokens=3)

# เอกสารอ้างอิง: Constraints
lm += gen("age", regex=r"[0-9]{2}", max_tokens=10)  # max_tokens unnecessary
```

### Performance Benchmarks

**Regex vs Free Generation:**
- Simple regex (digits): ~1.2x slower than free gen
- Complex regex (email): ~1.5x slower than free gen
- Grammar-based: ~2x slower than free gen

**But:**
- 100% valid outputs (vs ~70% with free gen + validation)
- No retry loops needed
- Overall faster end-to-end for structured outputs

**Optimization Tips:**
- Use regex for critical fields only
- Use `select()` for small fixed sets (fastest)
- Use `stop` sequences when possible (faster than max_tokens)
- Cache compiled grammars by reusing functions

## Resources

- **Token Healing Paper**: https://arxiv.org/abs/2306.17648
- **Guidance Docs**: https://guidance.readthedocs.io
- **GitHub**: https://github.com/guidance-ai/guidance
