-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgroup.py
More file actions
60 lines (46 loc) · 1.72 KB
/
group.py
File metadata and controls
60 lines (46 loc) · 1.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
"""Group function for running prompts sequentially."""
from __future__ import annotations
from collections.abc import Callable
from typing import Any, TypeVar
from ._core.state import CANCEL, is_cancel
T = TypeVar("T")
def group(
prompts: dict[str, Callable[[dict[str, Any]], Any]],
*,
on_cancel: Callable[[dict[str, Any]], None] | None = None,
) -> dict[str, Any]:
"""Run multiple prompts sequentially with shared context.
Each prompt function receives the results of previous prompts,
allowing you to make decisions based on earlier answers.
Args:
prompts: Dictionary mapping keys to prompt functions.
Each function receives the results dict so far.
on_cancel: Optional callback when a prompt is cancelled.
Receives the results collected so far.
Returns:
Dictionary of all prompt results keyed by their names.
If cancelled, returns partial results up to cancellation.
Example:
>>> results = group({
... "name": lambda _: text("What is your name?"),
... "email": lambda _: text("What is your email?"),
... "confirm": lambda r: confirm(f"Create user {r['name']}?"),
... })
"""
results: dict[str, Any] = {}
for key, prompt_fn in prompts.items():
try:
result = prompt_fn(results)
except KeyboardInterrupt:
# Handle Ctrl+C outside of prompt
if on_cancel:
on_cancel(results)
results[key] = CANCEL
break
if is_cancel(result):
if on_cancel:
on_cancel(results)
results[key] = CANCEL
break
results[key] = result
return results