# needle.Field Constraints: Complete JSON-Schema Validation Guide for Cactus Needle

> Explore needle.Field constraints for robust JSON-Schema validation. Discover support for ranges, string patterns, array limits, and value controls within the Cactus Needle framework.

- Repository: [Cactus Compute, Inc./needle](https://github.com/cactus-compute/needle)
- Tags: deep-dive
- Published: 2026-09-02

---

**`needle.Field` supports 16 JSON-Schema constraints including numeric ranges (`ge`, `le`, `gt`, `lt`), string validation (`min_length`, `max_length`, `pattern`, `format`), array restrictions (`min_items`, `max_items`, `unique_items`), and value controls (`enum`, `const`), all of which map directly to JSON-Schema keywords when generating tool schemas.**

The `needle.Field` class in the `cactus-compute/needle` repository provides a declarative way to enforce validation rules on LLM function tool parameters. By attaching `Field` instances to Python type annotations, you automatically generate precise JSON-Schema definitions that validate incoming arguments before execution.

## Supported needle.Field Constraint Parameters

In [`needle/agent/tools.py`](https://github.com/cactus-compute/needle/blob/main/needle/agent/tools.py), the `Field` constructor accepts optional parameters that map directly to JSON-Schema validation keywords. The `apply` method (lines 36-49) transfers these values into the final schema dictionary.

### Numeric Range Constraints

Control acceptable number ranges using inclusive or exclusive boundaries:

- **`ge`** (≥) → JSON-Schema `minimum`
- **`le`** (≤) → JSON-Schema `maximum`
- **`gt`** (>) → JSON-Schema `exclusiveMinimum`
- **`lt`** (<) → JSON-Schema `exclusiveMaximum`
- **`multiple_of`** → JSON-Schema `multipleOf`

### String Validation Constraints

Enforce text formatting and length requirements:

- **`min_length`** → `minLength` (minimum character count)
- **`max_length`** → `maxLength` (maximum character count)
- **`pattern`** → `pattern` (regular expression the string must match)
- **`format`** → `format` (semantic formats like `"email"`, `"uri"`, `"date-time"`)

### Array Collection Constraints

Validate list properties when the parameter accepts sequences:

- **`min_items`** → `minItems` (minimum array length)
- **`max_items`** → `maxItems` (maximum array length)
- **`unique_items`** → `uniqueItems` (boolean requiring all array elements to be distinct)

### Value Enumeration Constraints

Restrict parameters to specific allowed values:

- **`enum`** → `enum` (list of valid values; transformed into a list before schema insertion)
- **`const`** → `const` (single constant value that must be matched exactly)
- **`description`** → `description` (human-readable documentation string)

## How Constraints Are Applied in the Source Code

According to the `cactus-compute/needle` source code, the schema generation process follows a specific pipeline in [`needle/agent/tools.py`](https://github.com/cactus-compute/needle/blob/main/needle/agent/tools.py):

1. **`build_schema`** parses the function signature and extracts type hints.
2. **`_field_of`** locates any `Field` instances attached via `typing.Annotated` or default values.
3. **`Field.apply`** (lines 36-49) iterates through the constraint parameters and populates the JSON-Schema dictionary with any non-`None` values.
4. The resulting schema object is returned for use by the Needle tool infrastructure to describe expected arguments to LLM callers.

Only the `enum` parameter receives special handling—it is explicitly converted to a list type before schema insertion. All other constraints pass directly to the JSON-Schema output without transformation.

## Practical Implementation Examples

The following examples demonstrate how to declare `needle.Field` constraints using `typing.Annotated`:

```python
from needle.agent.tools import Field, tool
from typing import Annotated

# Numeric range with multipleOf constraint

@tool
def set_temperature(
    temperature: Annotated[float, Field(ge=0, le=100, multiple_of=0.5)]
) -> str:
    """Set the thermostat to a specific temperature."""
    return f"Temperature set to {temperature}°C"

```

```python

# String length, pattern matching, and enum restrictions

@tool
def create_user(
    username: Annotated[str, Field(min_length=3, max_length=12, pattern=r'^[a-zA-Z0-9_]+$')],
    role: Annotated[str, Field(enum=["admin", "member", "guest"])]
) -> str:
    """Create a new user with a limited set of roles."""
    return f"User {username} created with role {role}"

```

```python

# Array size and uniqueness constraints

@tool
def upload_files(
    files: Annotated[list, Field(min_items=1, max_items=5, unique_items=True)]
) -> str:
    """Upload a collection of files (1-5, no duplicates)."""
    return f"{len(files)} files uploaded"

```

Running `build_schema(set_temperature)` generates a JSON-Schema object containing `minimum`, `maximum`, and `multipleOf` keys reflecting the `Field` constraints defined in the source code.

## Summary

- **`needle.Field`** provides 16 constraint parameters that map 1:1 to JSON-Schema validation keywords for precise input validation.
- **Numeric constraints** (`ge`, `le`, `gt`, `lt`, `multiple_of`) enforce mathematical boundaries on number parameters.
- **String constraints** (`min_length`, `max_length`, `pattern`, `format`) validate text content, length, and semantic formats.
- **Array constraints** (`min_items`, `max_items`, `unique_items`) control list cardinality and element uniqueness.
- **Value constraints** (`enum`, `const`) restrict inputs to specific allowed values or single constants.
- The **`apply`** method in [`needle/agent/tools.py`](https://github.com/cactus-compute/needle/blob/main/needle/agent/tools.py) (lines 36-49) injects these constraints into the generated schema during the `build_schema` execution.

## Frequently Asked Questions

### What is the difference between ge and gt in needle.Field?

**`ge`** sets an inclusive minimum (greater than or equal to), mapping to JSON-Schema's `minimum` keyword, while **`gt`** sets an exclusive minimum (strictly greater than), mapping to `exclusiveMinimum`. Use `ge=0` to allow zero and positive numbers; use `gt=0` to exclude zero while allowing positive values.

### Can I combine multiple constraints on a single needle.Field?

Yes. The `Field` constructor accepts any combination of compatible constraints simultaneously. For example, `Field(ge=0, le=100, multiple_of=0.5)` applies all three numeric constraints to the same parameter, and the `apply` method will populate the schema with `minimum`, `maximum`, and `multipleOf` keys accordingly.

### How does needle.Field handle enum values compared to const?

**`enum`** accepts a list of allowed values and validates that the input matches any entry in that list, while **`const`** enforces that the input matches exactly one specific value. In the source code, `enum` receives special transformation into a list before schema insertion, whereas `const` passes through directly as the JSON-Schema `const` keyword.

### Where are the constraint mappings defined in the cactus-compute/needle repository?

The constraint parameter definitions and the `apply` method logic reside in [`needle/agent/tools.py`](https://github.com/cactus-compute/needle/blob/main/needle/agent/tools.py). The `Field` class is defined beginning at line 18, with the `apply` method implementing the constraint-to-schema mapping at lines 36-49. The `build_schema` function coordinates the detection and application of these fields during tool schema generation.