promptantic 0.0.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- promptantic/__init__.py +10 -0
- promptantic/completers.py +103 -0
- promptantic/exceptions.py +19 -0
- promptantic/generator.py +266 -0
- promptantic/handlers/__init__.py +0 -0
- promptantic/handlers/base.py +27 -0
- promptantic/handlers/constrained.py +144 -0
- promptantic/handlers/date_time.py +148 -0
- promptantic/handlers/enums.py +55 -0
- promptantic/handlers/literal.py +63 -0
- promptantic/handlers/models.py +40 -0
- promptantic/handlers/network.py +90 -0
- promptantic/handlers/primitives.py +130 -0
- promptantic/handlers/sequences.py +130 -0
- promptantic/handlers/special.py +151 -0
- promptantic/handlers/unions.py +73 -0
- promptantic/py.typed +0 -0
- promptantic/type_utils.py +64 -0
- promptantic/ui/__init__.py +0 -0
- promptantic/ui/dialogs.py +0 -0
- promptantic/ui/formatting.py +31 -0
- promptantic/ui/prompts.py +0 -0
- promptantic/ui/style.py +13 -0
- promptantic/utils/__init__.py +0 -0
- promptantic/utils/pydantic.py +0 -0
- promptantic/utils/type_utils.py +0 -0
- promptantic/utils/validation.py +0 -0
- promptantic-0.0.1.dist-info/METADATA +241 -0
- promptantic-0.0.1.dist-info/RECORD +31 -0
- promptantic-0.0.1.dist-info/WHEEL +4 -0
- promptantic-0.0.1.dist-info/licenses/LICENSE +22 -0
promptantic/__init__.py
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
"""Interactive prompt_toolkit based generator for Pydantic models."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from promptantic.generator import ModelGenerator
|
|
6
|
+
from promptantic.exceptions import PromptanticError
|
|
7
|
+
|
|
8
|
+
__version__ = "0.0.1"
|
|
9
|
+
|
|
10
|
+
__all__ = ["ModelGenerator", "PromptanticError"]
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
"""Completers for various types."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import TYPE_CHECKING
|
|
7
|
+
from zoneinfo import available_timezones
|
|
8
|
+
|
|
9
|
+
from prompt_toolkit.completion import CompleteEvent, Completer, Completion, PathCompleter
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
if TYPE_CHECKING:
|
|
13
|
+
from collections.abc import Iterable
|
|
14
|
+
|
|
15
|
+
from prompt_toolkit.document import Document
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class TimezoneCompleter(Completer):
|
|
19
|
+
"""Completer for timezone names."""
|
|
20
|
+
|
|
21
|
+
def __init__(self) -> None:
|
|
22
|
+
self._timezones = list(available_timezones())
|
|
23
|
+
|
|
24
|
+
def get_completions(
|
|
25
|
+
self, document: Document, complete_event: CompleteEvent
|
|
26
|
+
) -> Iterable[Completion]:
|
|
27
|
+
"""Get timezone completions."""
|
|
28
|
+
word = document.get_word_before_cursor()
|
|
29
|
+
|
|
30
|
+
for tz in self._timezones:
|
|
31
|
+
if tz.lower().startswith(word.lower()):
|
|
32
|
+
yield Completion(
|
|
33
|
+
tz,
|
|
34
|
+
start_position=-len(word),
|
|
35
|
+
display_meta="timezone",
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class EnhancedPathCompleter(PathCompleter):
|
|
40
|
+
"""Enhanced path completer with better defaults."""
|
|
41
|
+
|
|
42
|
+
def __init__(self) -> None:
|
|
43
|
+
super().__init__(
|
|
44
|
+
only_directories=False,
|
|
45
|
+
min_input_len=0,
|
|
46
|
+
get_paths=lambda: [str(Path.cwd())],
|
|
47
|
+
expanduser=True,
|
|
48
|
+
file_filter=None,
|
|
49
|
+
)
|
|
50
|
+
|
|
51
|
+
def get_completions(
|
|
52
|
+
self, document: Document, complete_event: CompleteEvent
|
|
53
|
+
) -> Iterable[Completion]:
|
|
54
|
+
"""Get path completions with additional metadata."""
|
|
55
|
+
path_text = document.text_before_cursor
|
|
56
|
+
|
|
57
|
+
# Expand user directory
|
|
58
|
+
path = Path(path_text)
|
|
59
|
+
if path_text.startswith("~"):
|
|
60
|
+
path = Path(path_text).expanduser()
|
|
61
|
+
|
|
62
|
+
directory = path.parent
|
|
63
|
+
prefix = path.name
|
|
64
|
+
|
|
65
|
+
# Get all entries in the directory
|
|
66
|
+
try:
|
|
67
|
+
paths = list((directory or Path()).iterdir())
|
|
68
|
+
except OSError:
|
|
69
|
+
return
|
|
70
|
+
|
|
71
|
+
# Filter and yield completions
|
|
72
|
+
for entry_path in paths:
|
|
73
|
+
if entry_path.name.startswith(prefix):
|
|
74
|
+
full_path = directory / entry_path.name
|
|
75
|
+
display = entry_path.name + ("/" if entry_path.is_dir() else "")
|
|
76
|
+
meta = "dir" if entry_path.is_dir() else "file"
|
|
77
|
+
|
|
78
|
+
yield Completion(
|
|
79
|
+
str(full_path),
|
|
80
|
+
start_position=-len(prefix) if prefix else 0,
|
|
81
|
+
display=display,
|
|
82
|
+
display_meta=meta,
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
class FieldCompleter(Completer):
|
|
87
|
+
"""Completer for fields with custom completion values."""
|
|
88
|
+
|
|
89
|
+
def __init__(self, values: list[str]) -> None:
|
|
90
|
+
self.values = values
|
|
91
|
+
|
|
92
|
+
def get_completions(
|
|
93
|
+
self, document: Document, complete_event: CompleteEvent
|
|
94
|
+
) -> Iterable[Completion]:
|
|
95
|
+
"""Get completions from the predefined values."""
|
|
96
|
+
word = document.get_word_before_cursor()
|
|
97
|
+
|
|
98
|
+
for value in self.values:
|
|
99
|
+
if value.lower().startswith(word.lower()):
|
|
100
|
+
yield Completion(
|
|
101
|
+
value,
|
|
102
|
+
start_position=-len(word),
|
|
103
|
+
)
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
"""Exceptions for promptantic."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class PromptanticError(Exception):
|
|
7
|
+
"""Base exception for promptantic."""
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class ValidationError(PromptanticError):
|
|
11
|
+
"""Raised when validation fails."""
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class TypeHandlerError(PromptanticError):
|
|
15
|
+
"""Raised when a type handler fails."""
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class NoHandlerError(TypeHandlerError):
|
|
19
|
+
"""Raised when no handler is found for a type."""
|
promptantic/generator.py
ADDED
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
"""Main generator implementation."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import datetime
|
|
6
|
+
from decimal import Decimal
|
|
7
|
+
from enum import Enum
|
|
8
|
+
import ipaddress
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import TYPE_CHECKING, Any
|
|
11
|
+
from uuid import UUID
|
|
12
|
+
from zoneinfo import ZoneInfo
|
|
13
|
+
|
|
14
|
+
from prompt_toolkit.styles import Style, merge_styles
|
|
15
|
+
from pydantic import BaseModel, SecretStr, ValidationError
|
|
16
|
+
|
|
17
|
+
from promptantic.exceptions import NoHandlerError
|
|
18
|
+
from promptantic.handlers.constrained import ConstrainedIntHandler, ConstrainedStrHandler
|
|
19
|
+
from promptantic.handlers.date_time import (
|
|
20
|
+
DateHandler,
|
|
21
|
+
DateTimeHandler,
|
|
22
|
+
TimeDeltaHandler,
|
|
23
|
+
TimeHandler,
|
|
24
|
+
TimezoneHandler,
|
|
25
|
+
)
|
|
26
|
+
from promptantic.handlers.enums import EnumHandler
|
|
27
|
+
from promptantic.handlers.literal import LiteralHandler
|
|
28
|
+
from promptantic.handlers.models import ModelHandler
|
|
29
|
+
from promptantic.handlers.network import IPv4Handler, IPv6Handler, NetworkHandler
|
|
30
|
+
from promptantic.handlers.primitives import (
|
|
31
|
+
BoolHandler,
|
|
32
|
+
DecimalHandler,
|
|
33
|
+
FloatHandler,
|
|
34
|
+
IntHandler,
|
|
35
|
+
StrHandler,
|
|
36
|
+
)
|
|
37
|
+
from promptantic.handlers.sequences import ListHandler, SetHandler, TupleHandler
|
|
38
|
+
from promptantic.handlers.special import (
|
|
39
|
+
EmailHandler,
|
|
40
|
+
PathHandler,
|
|
41
|
+
SecretStrHandler,
|
|
42
|
+
URLHandler,
|
|
43
|
+
UUIDHandler,
|
|
44
|
+
)
|
|
45
|
+
from promptantic.handlers.unions import UnionHandler
|
|
46
|
+
from promptantic.type_utils import (
|
|
47
|
+
is_constrained_int,
|
|
48
|
+
is_constrained_str,
|
|
49
|
+
is_literal_type,
|
|
50
|
+
is_model_type,
|
|
51
|
+
is_union_type,
|
|
52
|
+
)
|
|
53
|
+
from promptantic.ui.style import DEFAULT_STYLE
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
if TYPE_CHECKING:
|
|
57
|
+
from promptantic.type_utils import ModelType, TypeHandler
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class ModelGenerator:
|
|
61
|
+
"""Generate Pydantic model instances through interactive prompts."""
|
|
62
|
+
|
|
63
|
+
def __init__(
|
|
64
|
+
self,
|
|
65
|
+
style: Style | None = None,
|
|
66
|
+
show_progress: bool = True,
|
|
67
|
+
allow_back: bool = True,
|
|
68
|
+
retry_on_validation_error: bool = True,
|
|
69
|
+
) -> None:
|
|
70
|
+
"""Initialize the generator.
|
|
71
|
+
|
|
72
|
+
Args:
|
|
73
|
+
style: Optional custom style to use
|
|
74
|
+
show_progress: Whether to show progress indication
|
|
75
|
+
allow_back: Whether to allow going back to previous fields
|
|
76
|
+
retry_on_validation_error: Whether to retry when validation fails
|
|
77
|
+
"""
|
|
78
|
+
self.style = merge_styles([DEFAULT_STYLE, style]) if style else DEFAULT_STYLE
|
|
79
|
+
self.show_progress = show_progress
|
|
80
|
+
self.allow_back = allow_back
|
|
81
|
+
self.retry_on_validation_error = retry_on_validation_error
|
|
82
|
+
self._handlers: dict[type, TypeHandler] = {}
|
|
83
|
+
self._register_default_handlers()
|
|
84
|
+
|
|
85
|
+
def _register_default_handlers(self) -> None:
|
|
86
|
+
"""Register the default type handlers."""
|
|
87
|
+
# Primitive types
|
|
88
|
+
self.register_handler(str, StrHandler(self))
|
|
89
|
+
self.register_handler(int, IntHandler(self))
|
|
90
|
+
self.register_handler(float, FloatHandler(self))
|
|
91
|
+
self.register_handler(bool, BoolHandler(self))
|
|
92
|
+
self.register_handler(Decimal, DecimalHandler(self))
|
|
93
|
+
|
|
94
|
+
# Sequence types
|
|
95
|
+
self.register_handler(list, ListHandler(self))
|
|
96
|
+
self.register_handler(set, SetHandler(self))
|
|
97
|
+
self.register_handler(tuple, TupleHandler(self))
|
|
98
|
+
# Model handler
|
|
99
|
+
self.register_handler(BaseModel, ModelHandler(self))
|
|
100
|
+
# Special types
|
|
101
|
+
self.register_handler(SecretStr, SecretStrHandler(self))
|
|
102
|
+
self.register_handler(Path, PathHandler(self))
|
|
103
|
+
self.register_handler(UUID, UUIDHandler(self))
|
|
104
|
+
|
|
105
|
+
# Network types
|
|
106
|
+
self.register_handler(ipaddress.IPv4Address, IPv4Handler(self))
|
|
107
|
+
self.register_handler(ipaddress.IPv6Address, IPv6Handler(self))
|
|
108
|
+
self.register_handler(ipaddress.IPv4Network, NetworkHandler(self))
|
|
109
|
+
self.register_handler(ipaddress.IPv6Network, NetworkHandler(self))
|
|
110
|
+
|
|
111
|
+
# DateTime types
|
|
112
|
+
self.register_handler(datetime.date, DateHandler(self))
|
|
113
|
+
self.register_handler(datetime.time, TimeHandler(self))
|
|
114
|
+
self.register_handler(datetime.datetime, DateTimeHandler(self))
|
|
115
|
+
self.register_handler(datetime.timedelta, TimeDeltaHandler(self))
|
|
116
|
+
self.register_handler(ZoneInfo, TimezoneHandler(self))
|
|
117
|
+
# Enum handler
|
|
118
|
+
self.register_handler(Enum, EnumHandler(self))
|
|
119
|
+
|
|
120
|
+
# Note: Union handler is special and handled in get_handler
|
|
121
|
+
self._email_handler = EmailHandler(self)
|
|
122
|
+
self._url_handler = URLHandler(self)
|
|
123
|
+
# Store constrained handlers separately since they're not types
|
|
124
|
+
self._constrained_str_handler = ConstrainedStrHandler(self)
|
|
125
|
+
self._constrained_int_handler = ConstrainedIntHandler(self)
|
|
126
|
+
|
|
127
|
+
def register_handler(self, typ: type, handler: TypeHandler) -> None:
|
|
128
|
+
"""Register a custom type handler.
|
|
129
|
+
|
|
130
|
+
Args:
|
|
131
|
+
typ: The type to handle
|
|
132
|
+
handler: The handler instance
|
|
133
|
+
"""
|
|
134
|
+
self._handlers[typ] = handler
|
|
135
|
+
|
|
136
|
+
def get_handler(self, typ: type, field_info: Any = None) -> TypeHandler: # noqa: PLR0911
|
|
137
|
+
"""Get a handler for the given type.
|
|
138
|
+
|
|
139
|
+
Args:
|
|
140
|
+
typ: The type to get a handler for
|
|
141
|
+
field_info: Optional field info for additional type detection
|
|
142
|
+
|
|
143
|
+
Returns:
|
|
144
|
+
The appropriate type handler
|
|
145
|
+
|
|
146
|
+
Raises:
|
|
147
|
+
NoHandlerError: If no handler is found for the type
|
|
148
|
+
"""
|
|
149
|
+
# Handle None type (use str as default)
|
|
150
|
+
if typ is None:
|
|
151
|
+
return self._handlers[str]
|
|
152
|
+
|
|
153
|
+
# Check for constrained types
|
|
154
|
+
if is_constrained_str(typ):
|
|
155
|
+
return self._constrained_str_handler
|
|
156
|
+
if is_constrained_int(typ):
|
|
157
|
+
return self._constrained_int_handler
|
|
158
|
+
|
|
159
|
+
# Check for Literal type
|
|
160
|
+
if is_literal_type(typ):
|
|
161
|
+
return LiteralHandler(self)
|
|
162
|
+
|
|
163
|
+
# Check if it's a union type first
|
|
164
|
+
if is_union_type(typ):
|
|
165
|
+
return UnionHandler(self)
|
|
166
|
+
|
|
167
|
+
# For model types, use the model handler
|
|
168
|
+
if is_model_type(typ):
|
|
169
|
+
return self._handlers[BaseModel]
|
|
170
|
+
|
|
171
|
+
# Check for special string fields based on field info
|
|
172
|
+
if typ is str and field_info is not None:
|
|
173
|
+
if getattr(field_info, "email", False):
|
|
174
|
+
return self._email_handler
|
|
175
|
+
if getattr(field_info, "url", False):
|
|
176
|
+
return self._url_handler
|
|
177
|
+
|
|
178
|
+
# For regular types, look up the handler
|
|
179
|
+
handler = self._handlers.get(typ)
|
|
180
|
+
if handler is None:
|
|
181
|
+
msg = f"No handler registered for type: {typ}"
|
|
182
|
+
raise NoHandlerError(msg)
|
|
183
|
+
return handler
|
|
184
|
+
|
|
185
|
+
async def populate(self, model: ModelType) -> BaseModel:
|
|
186
|
+
"""Populate a model instance through interactive prompts.
|
|
187
|
+
|
|
188
|
+
Args:
|
|
189
|
+
model: The model class or instance to populate
|
|
190
|
+
|
|
191
|
+
Returns:
|
|
192
|
+
A populated model instance
|
|
193
|
+
|
|
194
|
+
Raises:
|
|
195
|
+
NoHandlerError: If no handler is found for a field type
|
|
196
|
+
"""
|
|
197
|
+
# Get the model class if an instance was passed
|
|
198
|
+
if isinstance(model, type) and issubclass(model, BaseModel):
|
|
199
|
+
model_cls = model
|
|
200
|
+
elif isinstance(model, BaseModel):
|
|
201
|
+
model_cls = model.__class__
|
|
202
|
+
else:
|
|
203
|
+
msg = f"Expected BaseModel class or instance, got {type(model)}"
|
|
204
|
+
raise ValueError(msg) # noqa: TRY004
|
|
205
|
+
|
|
206
|
+
values: dict[str, Any] = {}
|
|
207
|
+
total = len(model_cls.model_fields)
|
|
208
|
+
current = 0
|
|
209
|
+
|
|
210
|
+
try:
|
|
211
|
+
for name, field in model_cls.model_fields.items():
|
|
212
|
+
current += 1
|
|
213
|
+
if self.show_progress:
|
|
214
|
+
print(f"\nField {current}/{total}")
|
|
215
|
+
|
|
216
|
+
field_type = field.annotation if field.annotation is not None else str
|
|
217
|
+
|
|
218
|
+
handler = self.get_handler(
|
|
219
|
+
field_type,
|
|
220
|
+
field_info=field,
|
|
221
|
+
)
|
|
222
|
+
description = field.description
|
|
223
|
+
|
|
224
|
+
while True:
|
|
225
|
+
try:
|
|
226
|
+
value = await handler.handle(
|
|
227
|
+
field_name=name,
|
|
228
|
+
field_type=field_type, # type: ignore
|
|
229
|
+
description=description,
|
|
230
|
+
)
|
|
231
|
+
values[name] = value
|
|
232
|
+
break
|
|
233
|
+
except ValidationError as e:
|
|
234
|
+
if not self.retry_on_validation_error:
|
|
235
|
+
raise
|
|
236
|
+
print(f"\033[91mValidation error: {e!s}\033[0m")
|
|
237
|
+
print("Please try again...")
|
|
238
|
+
except Exception as e:
|
|
239
|
+
msg = f"Error handling field {name}: {e!s}"
|
|
240
|
+
raise NoHandlerError(msg) from e
|
|
241
|
+
|
|
242
|
+
return model_cls.model_validate(values)
|
|
243
|
+
|
|
244
|
+
except KeyboardInterrupt:
|
|
245
|
+
print("\nOperation cancelled by user")
|
|
246
|
+
raise
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
if __name__ == "__main__":
|
|
250
|
+
from pydantic import BaseModel, Field
|
|
251
|
+
|
|
252
|
+
from promptantic import ModelGenerator
|
|
253
|
+
|
|
254
|
+
class Person(BaseModel):
|
|
255
|
+
name: str = Field(description="Person's full name")
|
|
256
|
+
age: int = Field(description="Age in years")
|
|
257
|
+
|
|
258
|
+
async def main():
|
|
259
|
+
# Create and use the generator
|
|
260
|
+
generator = ModelGenerator()
|
|
261
|
+
person = await generator.populate(Person)
|
|
262
|
+
print(person)
|
|
263
|
+
|
|
264
|
+
import asyncio
|
|
265
|
+
|
|
266
|
+
asyncio.run(main())
|
|
File without changes
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"""Base handler implementation."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any, Generic, TypeVar
|
|
6
|
+
|
|
7
|
+
from promptantic.type_utils import TypeHandler
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
T = TypeVar("T")
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class BaseHandler(Generic[T], TypeHandler[T]):
|
|
14
|
+
"""Base class for type handlers."""
|
|
15
|
+
|
|
16
|
+
def __init__(self, generator: Any) -> None: # Any for now to avoid circular import
|
|
17
|
+
self.generator = generator
|
|
18
|
+
|
|
19
|
+
async def handle(
|
|
20
|
+
self,
|
|
21
|
+
field_name: str,
|
|
22
|
+
field_type: type[T],
|
|
23
|
+
description: str | None = None,
|
|
24
|
+
**options: Any,
|
|
25
|
+
) -> T:
|
|
26
|
+
"""Handle input for this type."""
|
|
27
|
+
raise NotImplementedError
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
"""Handlers for constrained types."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from prompt_toolkit.shortcuts import PromptSession
|
|
9
|
+
|
|
10
|
+
from promptantic.exceptions import ValidationError
|
|
11
|
+
from promptantic.handlers.base import BaseHandler
|
|
12
|
+
from promptantic.ui.formatting import create_field_prompt
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class ConstrainedStrHandler(BaseHandler):
|
|
16
|
+
"""Handler for constrained string input."""
|
|
17
|
+
|
|
18
|
+
async def handle(
|
|
19
|
+
self,
|
|
20
|
+
field_name: str,
|
|
21
|
+
field_type: Any, # Can't use precise type due to Pydantic internals
|
|
22
|
+
description: str | None = None,
|
|
23
|
+
**options: Any,
|
|
24
|
+
) -> str:
|
|
25
|
+
"""Handle constrained string input."""
|
|
26
|
+
# Get constraints from the type object
|
|
27
|
+
min_length = getattr(field_type, "min_length", None)
|
|
28
|
+
max_length = getattr(field_type, "max_length", None)
|
|
29
|
+
pattern = getattr(field_type, "pattern", None)
|
|
30
|
+
|
|
31
|
+
constraints = []
|
|
32
|
+
if min_length is not None:
|
|
33
|
+
constraints.append(f"min length: {min_length}")
|
|
34
|
+
if max_length is not None:
|
|
35
|
+
constraints.append(f"max length: {max_length}")
|
|
36
|
+
if pattern is not None:
|
|
37
|
+
constraints.append(f"pattern: {pattern}")
|
|
38
|
+
|
|
39
|
+
constraint_desc = " | ".join(constraints)
|
|
40
|
+
full_desc = f"{description or ''}\nConstraints: {constraint_desc}"
|
|
41
|
+
|
|
42
|
+
session = PromptSession()
|
|
43
|
+
while True:
|
|
44
|
+
result = await session.prompt_async(
|
|
45
|
+
create_field_prompt(field_name, full_desc),
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
try:
|
|
49
|
+
# Validate length constraints
|
|
50
|
+
if (
|
|
51
|
+
field_type.min_length is not None
|
|
52
|
+
and len(result) < field_type.min_length
|
|
53
|
+
):
|
|
54
|
+
msg = f"String too short (min: {field_type.min_length})"
|
|
55
|
+
raise ValueError(msg) # noqa: TRY301
|
|
56
|
+
|
|
57
|
+
if (
|
|
58
|
+
field_type.max_length is not None
|
|
59
|
+
and len(result) > field_type.max_length
|
|
60
|
+
):
|
|
61
|
+
msg = f"String too long (max: {field_type.max_length})"
|
|
62
|
+
raise ValueError(msg) # noqa: TRY301
|
|
63
|
+
|
|
64
|
+
# Validate pattern
|
|
65
|
+
if field_type.pattern is not None and not re.match(
|
|
66
|
+
field_type.pattern, result
|
|
67
|
+
):
|
|
68
|
+
msg = f"String does not match pattern: {field_type.pattern}"
|
|
69
|
+
raise ValueError(msg) # noqa: TRY301
|
|
70
|
+
|
|
71
|
+
except ValueError as e:
|
|
72
|
+
msg = f"Validation failed: {e!s}"
|
|
73
|
+
raise ValidationError(msg) from e
|
|
74
|
+
else:
|
|
75
|
+
return result
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
class ConstrainedIntHandler(BaseHandler):
|
|
79
|
+
"""Handler for constrained integer input."""
|
|
80
|
+
|
|
81
|
+
async def handle(
|
|
82
|
+
self,
|
|
83
|
+
field_name: str,
|
|
84
|
+
field_type: Any, # Can't use precise type due to Pydantic internals
|
|
85
|
+
description: str | None = None,
|
|
86
|
+
**options: Any,
|
|
87
|
+
) -> int:
|
|
88
|
+
"""Handle constrained integer input."""
|
|
89
|
+
# Get constraints from the type object
|
|
90
|
+
gt = getattr(field_type, "gt", None)
|
|
91
|
+
ge = getattr(field_type, "ge", None)
|
|
92
|
+
lt = getattr(field_type, "lt", None)
|
|
93
|
+
le = getattr(field_type, "le", None)
|
|
94
|
+
multiple_of = getattr(field_type, "multiple_of", None)
|
|
95
|
+
|
|
96
|
+
# Build constraint description
|
|
97
|
+
constraints = []
|
|
98
|
+
if gt is not None:
|
|
99
|
+
constraints.append(f"greater than {gt}")
|
|
100
|
+
if ge is not None:
|
|
101
|
+
constraints.append(f"greater or equal to {ge}")
|
|
102
|
+
if lt is not None:
|
|
103
|
+
constraints.append(f"less than {lt}")
|
|
104
|
+
if le is not None:
|
|
105
|
+
constraints.append(f"less or equal to {le}")
|
|
106
|
+
if multiple_of is not None:
|
|
107
|
+
constraints.append(f"multiple of {multiple_of}")
|
|
108
|
+
|
|
109
|
+
constraint_desc = " | ".join(constraints)
|
|
110
|
+
full_desc = (
|
|
111
|
+
f"{description or ''}\nConstraints: {constraint_desc}"
|
|
112
|
+
if constraints
|
|
113
|
+
else description
|
|
114
|
+
)
|
|
115
|
+
|
|
116
|
+
session = PromptSession()
|
|
117
|
+
while True:
|
|
118
|
+
try:
|
|
119
|
+
result = await session.prompt_async(
|
|
120
|
+
create_field_prompt(field_name, full_desc),
|
|
121
|
+
)
|
|
122
|
+
value = int(result)
|
|
123
|
+
|
|
124
|
+
# Validate constraints
|
|
125
|
+
if gt is not None and value <= gt:
|
|
126
|
+
msg = f"Must be greater than {gt}"
|
|
127
|
+
raise ValueError(msg) # noqa: TRY301
|
|
128
|
+
if ge is not None and value < ge:
|
|
129
|
+
msg = f"Must be greater than or equal to {ge}"
|
|
130
|
+
raise ValueError(msg) # noqa: TRY301
|
|
131
|
+
if lt is not None and value >= lt:
|
|
132
|
+
msg = f"Must be less than {lt}"
|
|
133
|
+
raise ValueError(msg) # noqa: TRY301
|
|
134
|
+
if le is not None and value > le:
|
|
135
|
+
msg = f"Must be less than or equal to {le}"
|
|
136
|
+
raise ValueError(msg) # noqa: TRY301
|
|
137
|
+
if multiple_of is not None and value % multiple_of != 0:
|
|
138
|
+
msg = f"Must be multiple of {multiple_of}"
|
|
139
|
+
raise ValueError(msg) # noqa: TRY301
|
|
140
|
+
except ValueError as e:
|
|
141
|
+
msg = f"Validation failed: {e!s}"
|
|
142
|
+
raise ValidationError(msg) from e
|
|
143
|
+
else:
|
|
144
|
+
return value
|