Field Constraints for Tool Arguments in Needle: Complete JSON-Schema Reference
Needle's Field class supports 15 constraint parameters—including ge, le, pattern, enum, and unique_items—that map directly to JSON-Schema keywords defined in needle/agent/tools.py.
The Needle framework automatically generates OpenAI-compatible JSON schemas from Python function signatures. When you annotate tool arguments with the Field class, you specify precise validation rules that enforce data integrity before your functions execute.
Complete List of Supported Field Constraints
The Field.__init__ method in needle/agent/tools.py (lines 18-31) accepts the following constraint parameters, each mapping to a specific JSON-Schema keyword:
Numeric Range Constraints
ge: Minimum inclusive value (maps tominimum)le: Maximum inclusive value (maps tomaximum)gt: Minimum exclusive value (maps toexclusiveMinimum)lt: Maximum exclusive value (maps toexclusiveMaximum)multiple_of: Value must be divisible by this number (maps tomultipleOf)
String Validation Constraints
min_length: Minimum character count (maps tominLength)max_length: Maximum character count (maps tomaxLength)pattern: Regular expression the string must match (maps topattern)format: Pre-defined string format such as"email"(maps toformat)
Array Collection Constraints
min_items: Minimum number of elements (maps tominItems)max_items: Maximum number of elements (maps tomaxItems)unique_items: Requires all array elements to be distinct (maps touniqueItems)
Value Definition Constraints
description: Human-readable documentation text (maps todescription)enum: List of allowed literal valuesconst: Single fixed value the argument must equal
How Field Constraints Map to JSON-Schema
The transformation logic resides in needle/agent/tools.py. When you instantiate a Field with constraints, the apply method (lines 36-49) injects these parameters into the generated schema dictionary using the corresponding JSON-Schema keywords listed above.
According to the source code, if you specify a const value, Needle adds it to the schema unconditionally, regardless of what other constraints are present. This ensures fixed-value arguments are strictly enforced at the schema level.
Practical Code Examples
Numeric Bounds with ge and le
Use inclusive bounds to restrict numeric arguments to valid operating ranges:
from needle import tool, Field
@tool
def set_temperature(
value: int = Field(description="Target temperature in °C", ge=0, le=100)
):
"""Set the thermostat to a specific temperature."""
pass
String Validation with pattern and min_length
Enforce username formats using regex patterns and length constraints:
@tool
def create_user(
username: str = Field(min_length=3, max_length=20, pattern=r"^[a-z0-9_]+$"),
role: str = Field(enum=["admin", "editor", "viewer"], default="viewer")
):
"""Create a new user account."""
pass
Array Constraints with unique_items
Prevent duplicate task IDs and limit batch sizes:
@tool
def schedule_tasks(
tasks: list = Field(min_items=1, max_items=10, unique_items=True)
):
"""Schedule a list of task IDs."""
pass
Key Source Files and Implementation Details
Understanding these three files helps you master Needle's constraint system:
needle/agent/tools.py: Contains theFieldclass definition, its constructor parameters (lines 18-31), and theapplymethod (lines 36-49) that maps constraints to JSON-Schema keys.needle/__init__.py: ExportstoolandFieldat the package level for convenient imports.tests/test_tools.py: Provides unit tests demonstrating valid usage patterns for constraints likege,le, andpattern.
Summary
- Needle's
Fieldclass supports 15 constraint parameters ranging from numeric bounds to array uniqueness rules. - Constraints are defined in
needle/agent/tools.pyand applied via theapplymethod to generate OpenAI-compatible JSON schemas. - The
constparameter takes precedence and is always included in the generated schema, independent of other constraints. - Numeric constraints (
ge,le,gt,lt) map directly to JSON-Schema minimum/maximum keywords. - String and array constraints allow precise validation of text patterns and collection uniqueness.
Frequently Asked Questions
What is the difference between ge and gt in Needle Field constraints?
The ge parameter sets a minimum inclusive bound (greater than or equal to), mapping to JSON-Schema's minimum keyword. The gt parameter sets a minimum exclusive bound (strictly greater than), mapping to exclusiveMinimum. Use ge when the boundary value itself is acceptable, and gt when the value must be strictly larger than the threshold.
Can I combine multiple constraints on a single Field argument?
Yes. According to needle/agent/tools.py, you can specify multiple constraints simultaneously in the Field constructor. For example, you can combine min_length, max_length, and pattern on string arguments, or ge and le for inclusive numeric ranges. The apply method processes all provided constraints and adds them to the generated schema.
How does the const constraint differ from enum in Needle?
While enum accepts a list of allowable values, const enforces a single fixed value that the argument must equal. The source code specifically handles const separately in the apply method, ensuring it is always added to the schema regardless of other constraints present. Use const when an argument must exactly match one specific value.
Where are Needle's Field constraints processed in the source code?
The constraint definitions reside in needle/agent/tools.py. The Field.__init__ method (lines 18-31) defines the accepted parameters, while Field.apply (lines 36-49) translates these into JSON-Schema keywords. Unit tests in tests/test_tools.py verify the correct generation of schemas containing these constraints.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →