mellea-pratt 0.1.0__tar.gz
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.
- mellea_pratt-0.1.0/.gitignore +8 -0
- mellea_pratt-0.1.0/PKG-INFO +64 -0
- mellea_pratt-0.1.0/README.md +54 -0
- mellea_pratt-0.1.0/examples/coding_agent.py +64 -0
- mellea_pratt-0.1.0/pyproject.toml +21 -0
- mellea_pratt-0.1.0/src/mellea_pratt/__init__.py +37 -0
- mellea_pratt-0.1.0/src/mellea_pratt/core.py +223 -0
- mellea_pratt-0.1.0/src/mellea_pratt/llm.py +73 -0
- mellea_pratt-0.1.0/src/mellea_pratt/policies.py +30 -0
- mellea_pratt-0.1.0/src/mellea_pratt/state.py +88 -0
- mellea_pratt-0.1.0/tests/test_pratt.py +193 -0
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: mellea-pratt
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Guarded {pre, act, post} agent loops for Mellea (simple version).
|
|
5
|
+
Requires-Python: >=3.10
|
|
6
|
+
Requires-Dist: mellea
|
|
7
|
+
Provides-Extra: test
|
|
8
|
+
Requires-Dist: pytest; extra == 'test'
|
|
9
|
+
Description-Content-Type: text/markdown
|
|
10
|
+
|
|
11
|
+
# mellea-pratt (simple)
|
|
12
|
+
|
|
13
|
+
The "act fast" version of `pratt`: an agent loop over guarded actions
|
|
14
|
+
`{pre, act, post}`, extending Mellea's Instruct-Validate-Repair to open loops.
|
|
15
|
+
No automata compilation / improving search here.
|
|
16
|
+
|
|
17
|
+
```python
|
|
18
|
+
from mellea_pratt import pratt_agent
|
|
19
|
+
|
|
20
|
+
agent = pratt_agent(actions=[
|
|
21
|
+
{"pre": pre_1, "act": act_1, "post": post_1},
|
|
22
|
+
...
|
|
23
|
+
], state={...}, goal=lambda s: ...)
|
|
24
|
+
|
|
25
|
+
result = agent.run() # result.status in {"goal", "deadlock", "max_steps", "error"}
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
## Semantics (shielding, as in Verifiably Safe RL)
|
|
29
|
+
|
|
30
|
+
Each step:
|
|
31
|
+
|
|
32
|
+
1. `enabled` = actions whose `pre(state)` is true (an action that failed
|
|
33
|
+
`max_attempts` times since the last successful step is excluded);
|
|
34
|
+
2. `policy(enabled, state)` picks one (`first_enabled` default, `random_policy(seed)`,
|
|
35
|
+
or `LLMPolicy(session)` which asks a Mellea session to name an action);
|
|
36
|
+
3. `act(state)` runs; it may mutate `state` or return a dict of updates;
|
|
37
|
+
4. `post(state)` is checked. On failure (or if `act` raises), `on_post_failure`
|
|
38
|
+
decides: `"rollback"` (default; restore a deep-copy snapshot and count the
|
|
39
|
+
failure), `"raise"` (`PostconditionError`), or `"continue"` (keep the state).
|
|
40
|
+
|
|
41
|
+
The loop stops when `goal(state)` holds, nothing is enabled (`deadlock`), or
|
|
42
|
+
`max_steps` attempts were made.
|
|
43
|
+
|
|
44
|
+
## State
|
|
45
|
+
|
|
46
|
+
`State` is a dict with attribute access (`s.x == s["x"]`; use `s["items"]` for
|
|
47
|
+
keys that shadow dict methods), plus `s.step`, `s.trace` (list of `TraceEntry`,
|
|
48
|
+
including failed attempts) and `s.history` (names of successful actions).
|
|
49
|
+
|
|
50
|
+
## Conditions
|
|
51
|
+
|
|
52
|
+
`pre`, `post` and `goal` may be a Python callable `state -> bool`, an English
|
|
53
|
+
string, or a `mellea.Requirement`. Strings/Requirements are judged by
|
|
54
|
+
`condition_verifier=(condition: str, state) -> bool`; without one a
|
|
55
|
+
`MissingVerifierError` is raised. `LLMConditionVerifier(session)` is a
|
|
56
|
+
Mellea-backed verifier (lazily starts a session; not needed by tests).
|
|
57
|
+
|
|
58
|
+
## Run
|
|
59
|
+
|
|
60
|
+
```
|
|
61
|
+
uv pip install -e '.[test]'
|
|
62
|
+
pytest
|
|
63
|
+
python examples/coding_agent.py
|
|
64
|
+
```
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
# mellea-pratt (simple)
|
|
2
|
+
|
|
3
|
+
The "act fast" version of `pratt`: an agent loop over guarded actions
|
|
4
|
+
`{pre, act, post}`, extending Mellea's Instruct-Validate-Repair to open loops.
|
|
5
|
+
No automata compilation / improving search here.
|
|
6
|
+
|
|
7
|
+
```python
|
|
8
|
+
from mellea_pratt import pratt_agent
|
|
9
|
+
|
|
10
|
+
agent = pratt_agent(actions=[
|
|
11
|
+
{"pre": pre_1, "act": act_1, "post": post_1},
|
|
12
|
+
...
|
|
13
|
+
], state={...}, goal=lambda s: ...)
|
|
14
|
+
|
|
15
|
+
result = agent.run() # result.status in {"goal", "deadlock", "max_steps", "error"}
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
## Semantics (shielding, as in Verifiably Safe RL)
|
|
19
|
+
|
|
20
|
+
Each step:
|
|
21
|
+
|
|
22
|
+
1. `enabled` = actions whose `pre(state)` is true (an action that failed
|
|
23
|
+
`max_attempts` times since the last successful step is excluded);
|
|
24
|
+
2. `policy(enabled, state)` picks one (`first_enabled` default, `random_policy(seed)`,
|
|
25
|
+
or `LLMPolicy(session)` which asks a Mellea session to name an action);
|
|
26
|
+
3. `act(state)` runs; it may mutate `state` or return a dict of updates;
|
|
27
|
+
4. `post(state)` is checked. On failure (or if `act` raises), `on_post_failure`
|
|
28
|
+
decides: `"rollback"` (default; restore a deep-copy snapshot and count the
|
|
29
|
+
failure), `"raise"` (`PostconditionError`), or `"continue"` (keep the state).
|
|
30
|
+
|
|
31
|
+
The loop stops when `goal(state)` holds, nothing is enabled (`deadlock`), or
|
|
32
|
+
`max_steps` attempts were made.
|
|
33
|
+
|
|
34
|
+
## State
|
|
35
|
+
|
|
36
|
+
`State` is a dict with attribute access (`s.x == s["x"]`; use `s["items"]` for
|
|
37
|
+
keys that shadow dict methods), plus `s.step`, `s.trace` (list of `TraceEntry`,
|
|
38
|
+
including failed attempts) and `s.history` (names of successful actions).
|
|
39
|
+
|
|
40
|
+
## Conditions
|
|
41
|
+
|
|
42
|
+
`pre`, `post` and `goal` may be a Python callable `state -> bool`, an English
|
|
43
|
+
string, or a `mellea.Requirement`. Strings/Requirements are judged by
|
|
44
|
+
`condition_verifier=(condition: str, state) -> bool`; without one a
|
|
45
|
+
`MissingVerifierError` is raised. `LLMConditionVerifier(session)` is a
|
|
46
|
+
Mellea-backed verifier (lazily starts a session; not needed by tests).
|
|
47
|
+
|
|
48
|
+
## Run
|
|
49
|
+
|
|
50
|
+
```
|
|
51
|
+
uv pip install -e '.[test]'
|
|
52
|
+
pytest
|
|
53
|
+
python examples/coding_agent.py
|
|
54
|
+
```
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
"""Toy "coding agent": read_file -> edit_file -> run_tests -> commit.
|
|
2
|
+
|
|
3
|
+
Files live in an in-memory dict. The first edit is buggy; its postcondition
|
|
4
|
+
(the file still parses) fails, so the loop rolls it back and retries.
|
|
5
|
+
Run: python examples/coding_agent.py
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from mellea_pratt import pratt_agent
|
|
9
|
+
|
|
10
|
+
attempts = {"edit": 0}
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def read_file(s):
|
|
14
|
+
s.buffer = s.files["calc.py"]
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def edit_file(s):
|
|
18
|
+
attempts["edit"] += 1
|
|
19
|
+
if attempts["edit"] == 1: # a botched first edit (syntax error)
|
|
20
|
+
s.files["calc.py"] = "def add(a, b):\n return a +\n"
|
|
21
|
+
else:
|
|
22
|
+
s.files["calc.py"] = s.buffer.replace("a - b", "a + b")
|
|
23
|
+
s.edited = True
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def parses(s):
|
|
27
|
+
try:
|
|
28
|
+
compile(s.files["calc.py"], "calc.py", "exec")
|
|
29
|
+
return True
|
|
30
|
+
except SyntaxError:
|
|
31
|
+
return False
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def run_tests(s):
|
|
35
|
+
ns = {}
|
|
36
|
+
exec(s.files["calc.py"], ns)
|
|
37
|
+
s.tests_pass = ns["add"](2, 3) == 5
|
|
38
|
+
s.tests_ran_on = s.files["calc.py"]
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def commit(s):
|
|
42
|
+
s.commits.append(dict(s.files))
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
agent = pratt_agent(
|
|
46
|
+
actions=[
|
|
47
|
+
{"pre": lambda s: "buffer" not in s, "act": read_file, "post": lambda s: "buffer" in s},
|
|
48
|
+
{"pre": lambda s: "buffer" in s and not s.get("edited"), "act": edit_file, "post": parses},
|
|
49
|
+
{"pre": lambda s: s.get("edited") and s.get("tests_ran_on") != s.files["calc.py"],
|
|
50
|
+
"act": run_tests, "post": lambda s: "tests_pass" in s},
|
|
51
|
+
{"pre": lambda s: s.get("tests_pass") and not s.commits, "act": commit,
|
|
52
|
+
"post": lambda s: len(s.commits) == 1},
|
|
53
|
+
],
|
|
54
|
+
state={"files": {"calc.py": "def add(a, b):\n return a - b\n"}, "commits": []},
|
|
55
|
+
goal=lambda s: len(s.commits) == 1,
|
|
56
|
+
on_step=lambda e, s: print(f"step {e.step}: {e.action:<10} {e.status}"),
|
|
57
|
+
)
|
|
58
|
+
|
|
59
|
+
if __name__ == "__main__":
|
|
60
|
+
result = agent.run()
|
|
61
|
+
print("status:", result.status)
|
|
62
|
+
print("history:", result.history)
|
|
63
|
+
print("committed calc.py:\n" + result.state.commits[-1]["calc.py"])
|
|
64
|
+
assert result.status == "goal"
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "mellea-pratt"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Guarded {pre, act, post} agent loops for Mellea (simple version)."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
dependencies = ["mellea"]
|
|
12
|
+
|
|
13
|
+
[project.optional-dependencies]
|
|
14
|
+
test = ["pytest"]
|
|
15
|
+
|
|
16
|
+
[tool.hatch.build.targets.wheel]
|
|
17
|
+
packages = ["src/mellea_pratt"]
|
|
18
|
+
|
|
19
|
+
[tool.pytest.ini_options]
|
|
20
|
+
testpaths = ["tests"]
|
|
21
|
+
pythonpath = ["src"]
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"""mellea_pratt: agent loops of guarded {pre, act, post} actions for Mellea."""
|
|
2
|
+
|
|
3
|
+
from .core import (
|
|
4
|
+
Action,
|
|
5
|
+
MissingVerifierError,
|
|
6
|
+
PostconditionError,
|
|
7
|
+
PrattAgent,
|
|
8
|
+
PrattError,
|
|
9
|
+
RunResult,
|
|
10
|
+
pratt_agent,
|
|
11
|
+
)
|
|
12
|
+
from .policies import first_enabled, random_policy
|
|
13
|
+
from .state import State, TraceEntry
|
|
14
|
+
|
|
15
|
+
__all__ = [
|
|
16
|
+
"Action",
|
|
17
|
+
"LLMConditionVerifier",
|
|
18
|
+
"LLMPolicy",
|
|
19
|
+
"MissingVerifierError",
|
|
20
|
+
"PostconditionError",
|
|
21
|
+
"PrattAgent",
|
|
22
|
+
"PrattError",
|
|
23
|
+
"RunResult",
|
|
24
|
+
"State",
|
|
25
|
+
"TraceEntry",
|
|
26
|
+
"first_enabled",
|
|
27
|
+
"pratt_agent",
|
|
28
|
+
"random_policy",
|
|
29
|
+
]
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def __getattr__(name: str): # lazy: keep LLM helpers out of the import path
|
|
33
|
+
if name in ("LLMPolicy", "LLMConditionVerifier"):
|
|
34
|
+
from . import llm
|
|
35
|
+
|
|
36
|
+
return getattr(llm, name)
|
|
37
|
+
raise AttributeError(name)
|
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
"""The pratt agent loop: guarded {pre, act, post} actions with shielding and repair.
|
|
2
|
+
|
|
3
|
+
Each step (cf. shielding in Verifiably Safe RL):
|
|
4
|
+
|
|
5
|
+
1. ``enabled`` = actions whose ``pre(state)`` holds (minus actions blocked after
|
|
6
|
+
repeated failures in the current state);
|
|
7
|
+
2. the ``policy`` picks one enabled action;
|
|
8
|
+
3. its ``act(state)`` runs (it may mutate ``state`` or return a dict of updates);
|
|
9
|
+
4. ``post(state)`` is checked; on failure Instruct-Validate-Repair applies
|
|
10
|
+
according to ``on_post_failure``.
|
|
11
|
+
|
|
12
|
+
The loop stops when ``goal(state)`` holds, nothing is enabled (deadlock), or
|
|
13
|
+
``max_steps`` attempts have been made.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
from dataclasses import dataclass, field
|
|
19
|
+
from typing import Any, Callable, Literal, Mapping, Sequence, Union
|
|
20
|
+
|
|
21
|
+
from .policies import Policy, first_enabled
|
|
22
|
+
from .state import State, TraceEntry
|
|
23
|
+
|
|
24
|
+
ConditionVerifier = Callable[[str, State], bool]
|
|
25
|
+
# A condition is a Python predicate over the state, an English string, or a
|
|
26
|
+
# ``mellea.Requirement`` (its ``description`` is checked by the verifier).
|
|
27
|
+
Condition = Union[Callable[[State], bool], str, Any, None]
|
|
28
|
+
OnPostFailure = Literal["rollback", "raise", "continue"]
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class PrattError(Exception):
|
|
32
|
+
"""Base class for pratt errors."""
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class PostconditionError(PrattError):
|
|
36
|
+
"""Raised when an action's postcondition fails and ``on_post_failure="raise"``."""
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class MissingVerifierError(PrattError):
|
|
40
|
+
"""An English/Requirement condition was used without a ``condition_verifier``."""
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@dataclass
|
|
44
|
+
class Action:
|
|
45
|
+
"""A guarded action. ``pre``/``post`` default to ``True``."""
|
|
46
|
+
|
|
47
|
+
act: Callable[[State], Any]
|
|
48
|
+
pre: Condition = None
|
|
49
|
+
post: Condition = None
|
|
50
|
+
name: str | None = None
|
|
51
|
+
|
|
52
|
+
def __post_init__(self) -> None:
|
|
53
|
+
if not callable(self.act):
|
|
54
|
+
raise TypeError(f"act must be callable, got {self.act!r}")
|
|
55
|
+
if self.name is None:
|
|
56
|
+
self.name = getattr(self.act, "__name__", None) or repr(self.act)
|
|
57
|
+
|
|
58
|
+
@classmethod
|
|
59
|
+
def coerce(cls, spec: "Action | Mapping[str, Any]") -> "Action":
|
|
60
|
+
if isinstance(spec, Action):
|
|
61
|
+
return spec
|
|
62
|
+
if isinstance(spec, Mapping):
|
|
63
|
+
unknown = set(spec) - {"pre", "act", "post", "name"}
|
|
64
|
+
if unknown:
|
|
65
|
+
raise ValueError(f"unknown action keys: {sorted(unknown)}")
|
|
66
|
+
if "act" not in spec:
|
|
67
|
+
raise ValueError("action dict requires an 'act' key")
|
|
68
|
+
return cls(**spec)
|
|
69
|
+
raise TypeError(f"cannot build an Action from {spec!r}")
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
@dataclass
|
|
73
|
+
class RunResult:
|
|
74
|
+
"""Outcome of :meth:`PrattAgent.run`.
|
|
75
|
+
|
|
76
|
+
``status`` is one of ``"goal"``, ``"deadlock"``, ``"max_steps"``, ``"error"``.
|
|
77
|
+
"""
|
|
78
|
+
|
|
79
|
+
status: str
|
|
80
|
+
state: State
|
|
81
|
+
trace: list[TraceEntry] = field(default_factory=list)
|
|
82
|
+
error: BaseException | None = None
|
|
83
|
+
|
|
84
|
+
@property
|
|
85
|
+
def ok(self) -> bool:
|
|
86
|
+
return self.status == "goal"
|
|
87
|
+
|
|
88
|
+
@property
|
|
89
|
+
def history(self) -> list[str]:
|
|
90
|
+
return [t.action for t in self.trace if t.status == "ok"]
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _condition_text(cond: Any) -> str | None:
|
|
94
|
+
"""Return the English text of a string / Requirement condition, else None."""
|
|
95
|
+
if isinstance(cond, str):
|
|
96
|
+
return cond
|
|
97
|
+
from mellea.core.requirement import Requirement # cheap, no backend needed
|
|
98
|
+
|
|
99
|
+
if isinstance(cond, Requirement):
|
|
100
|
+
return cond.description or ""
|
|
101
|
+
return None
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
class PrattAgent:
|
|
105
|
+
"""An agent loop over a fixed set of guarded actions."""
|
|
106
|
+
|
|
107
|
+
def __init__(
|
|
108
|
+
self,
|
|
109
|
+
actions: Sequence[Action | Mapping[str, Any]],
|
|
110
|
+
*,
|
|
111
|
+
state: State | Mapping[str, Any] | None = None,
|
|
112
|
+
goal: Condition = None,
|
|
113
|
+
policy: Policy = first_enabled,
|
|
114
|
+
condition_verifier: ConditionVerifier | None = None,
|
|
115
|
+
on_post_failure: OnPostFailure = "rollback",
|
|
116
|
+
max_attempts: int = 2,
|
|
117
|
+
max_steps: int = 100,
|
|
118
|
+
on_step: Callable[[TraceEntry, State], None] | None = None,
|
|
119
|
+
):
|
|
120
|
+
if on_post_failure not in ("rollback", "raise", "continue"):
|
|
121
|
+
raise ValueError(f"invalid on_post_failure: {on_post_failure!r}")
|
|
122
|
+
self.actions = [Action.coerce(a) for a in actions]
|
|
123
|
+
names = [a.name for a in self.actions]
|
|
124
|
+
if len(set(names)) != len(names):
|
|
125
|
+
raise ValueError(f"action names must be unique: {names}")
|
|
126
|
+
self.state = state if isinstance(state, State) else State(dict(state or {}))
|
|
127
|
+
self.goal = goal
|
|
128
|
+
self.policy = policy
|
|
129
|
+
self.condition_verifier = condition_verifier
|
|
130
|
+
self.on_post_failure = on_post_failure
|
|
131
|
+
self.max_attempts = max_attempts
|
|
132
|
+
self.max_steps = max_steps
|
|
133
|
+
self.on_step = on_step
|
|
134
|
+
# failures per action name since the last successful step
|
|
135
|
+
self._failures: dict[str, int] = {}
|
|
136
|
+
|
|
137
|
+
# -- predicates --------------------------------------------------------
|
|
138
|
+
def check(self, cond: Condition, state: State | None = None) -> bool:
|
|
139
|
+
"""Evaluate a condition (callable, English string or Requirement)."""
|
|
140
|
+
state = self.state if state is None else state
|
|
141
|
+
if cond is None:
|
|
142
|
+
return True
|
|
143
|
+
text = _condition_text(cond)
|
|
144
|
+
if text is not None:
|
|
145
|
+
if self.condition_verifier is None:
|
|
146
|
+
raise MissingVerifierError(
|
|
147
|
+
f"condition {text!r} is natural language; pass "
|
|
148
|
+
"condition_verifier=(condition, state) -> bool to pratt_agent"
|
|
149
|
+
)
|
|
150
|
+
return bool(self.condition_verifier(text, state))
|
|
151
|
+
if callable(cond):
|
|
152
|
+
return bool(cond(state))
|
|
153
|
+
raise TypeError(f"unsupported condition: {cond!r}")
|
|
154
|
+
|
|
155
|
+
def enabled(self, state: State | None = None) -> list[Action]:
|
|
156
|
+
"""Actions whose precondition holds and that are not blocked."""
|
|
157
|
+
state = self.state if state is None else state
|
|
158
|
+
return [
|
|
159
|
+
a
|
|
160
|
+
for a in self.actions
|
|
161
|
+
if self._failures.get(a.name, 0) < self.max_attempts and self.check(a.pre, state)
|
|
162
|
+
]
|
|
163
|
+
|
|
164
|
+
# -- loop --------------------------------------------------------------
|
|
165
|
+
def step(self, action: Action) -> TraceEntry:
|
|
166
|
+
"""Run one action with post-condition checking and repair."""
|
|
167
|
+
s = self.state
|
|
168
|
+
snap = s.snapshot() if self.on_post_failure == "rollback" else None
|
|
169
|
+
status, err = "ok", None
|
|
170
|
+
try:
|
|
171
|
+
out = action.act(s)
|
|
172
|
+
if isinstance(out, Mapping):
|
|
173
|
+
s.update(out)
|
|
174
|
+
if not self.check(action.post, s):
|
|
175
|
+
status, err = "post_failed", "postcondition failed"
|
|
176
|
+
except PrattError:
|
|
177
|
+
raise
|
|
178
|
+
except Exception as e: # act (or post) blew up: treat as a failed attempt
|
|
179
|
+
if self.on_post_failure == "raise":
|
|
180
|
+
raise
|
|
181
|
+
status, err = "act_error", f"{type(e).__name__}: {e}"
|
|
182
|
+
|
|
183
|
+
entry = TraceEntry(step=s.step, action=action.name, status=status, error=err)
|
|
184
|
+
s.trace.append(entry)
|
|
185
|
+
s.step += 1
|
|
186
|
+
if status == "ok":
|
|
187
|
+
self._failures.clear() # state changed: give everything a fresh chance
|
|
188
|
+
else:
|
|
189
|
+
if self.on_post_failure == "raise":
|
|
190
|
+
raise PostconditionError(f"postcondition of {action.name!r} failed at step {entry.step}")
|
|
191
|
+
if self.on_post_failure == "rollback":
|
|
192
|
+
s.restore(snap)
|
|
193
|
+
self._failures[action.name] = self._failures.get(action.name, 0) + 1
|
|
194
|
+
if self.on_step:
|
|
195
|
+
self.on_step(entry, s)
|
|
196
|
+
return entry
|
|
197
|
+
|
|
198
|
+
def run(self) -> RunResult:
|
|
199
|
+
s = self.state
|
|
200
|
+
try:
|
|
201
|
+
while True:
|
|
202
|
+
if self.goal is not None and self.check(self.goal, s):
|
|
203
|
+
return RunResult("goal", s, s.trace)
|
|
204
|
+
if s.step >= self.max_steps:
|
|
205
|
+
return RunResult("max_steps", s, s.trace)
|
|
206
|
+
enabled = self.enabled(s)
|
|
207
|
+
if not enabled:
|
|
208
|
+
return RunResult("deadlock", s, s.trace)
|
|
209
|
+
choice = self.policy(enabled, s)
|
|
210
|
+
if choice not in enabled:
|
|
211
|
+
raise PrattError(f"policy chose a non-enabled action: {choice!r}")
|
|
212
|
+
self.step(choice)
|
|
213
|
+
except (PostconditionError, MissingVerifierError):
|
|
214
|
+
raise
|
|
215
|
+
except Exception as e:
|
|
216
|
+
if self.on_post_failure == "raise":
|
|
217
|
+
raise
|
|
218
|
+
return RunResult("error", s, s.trace, error=e)
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def pratt_agent(actions: Sequence[Action | Mapping[str, Any]], **kwargs: Any) -> PrattAgent:
|
|
222
|
+
"""Build a :class:`PrattAgent`. See :class:`PrattAgent` for keyword options."""
|
|
223
|
+
return PrattAgent(actions, **kwargs)
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
"""Mellea-backed policy and condition verifier.
|
|
2
|
+
|
|
3
|
+
Nothing here touches a backend until it is actually called; the session is
|
|
4
|
+
created lazily with ``mellea.start_session()`` if none is supplied.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from typing import TYPE_CHECKING, Any, Callable
|
|
10
|
+
|
|
11
|
+
if TYPE_CHECKING:
|
|
12
|
+
from .core import Action
|
|
13
|
+
from .state import State
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _describe(state: "State", max_chars: int = 4000) -> str:
|
|
17
|
+
text = repr(state.to_dict())
|
|
18
|
+
return text if len(text) <= max_chars else text[:max_chars] + "...(truncated)"
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _ask(session_ref: list, prompt: str) -> str:
|
|
22
|
+
if session_ref[0] is None:
|
|
23
|
+
import mellea
|
|
24
|
+
|
|
25
|
+
session_ref[0] = mellea.start_session()
|
|
26
|
+
msg = session_ref[0].chat(prompt)
|
|
27
|
+
return str(getattr(msg, "content", msg)).strip()
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class LLMPolicy:
|
|
31
|
+
"""Ask an LLM (via a Mellea session) which enabled action to take next.
|
|
32
|
+
|
|
33
|
+
Falls back to ``fallback`` (default: first enabled) if the reply names no
|
|
34
|
+
enabled action.
|
|
35
|
+
"""
|
|
36
|
+
|
|
37
|
+
def __init__(self, session: Any = None, task: str = "", fallback: Callable | None = None):
|
|
38
|
+
self._session = [session]
|
|
39
|
+
self.task = task
|
|
40
|
+
self.fallback = fallback
|
|
41
|
+
|
|
42
|
+
def __call__(self, enabled: "list[Action]", state: "State") -> "Action":
|
|
43
|
+
names = [a.name for a in enabled]
|
|
44
|
+
prompt = (
|
|
45
|
+
(f"Task: {self.task}\n" if self.task else "")
|
|
46
|
+
+ f"Current state: {_describe(state)}\n"
|
|
47
|
+
+ f"Actions taken so far: {state.history}\n"
|
|
48
|
+
+ f"Enabled actions: {', '.join(names)}\n"
|
|
49
|
+
+ "Reply with exactly one action name from the enabled list and nothing else."
|
|
50
|
+
)
|
|
51
|
+
reply = _ask(self._session, prompt)
|
|
52
|
+
for a in enabled:
|
|
53
|
+
if reply.strip("`'\" .") == a.name:
|
|
54
|
+
return a
|
|
55
|
+
for a in sorted(enabled, key=lambda a: -len(a.name)): # lenient match
|
|
56
|
+
if a.name in reply:
|
|
57
|
+
return a
|
|
58
|
+
return (self.fallback or (lambda e, s: e[0]))(enabled, state)
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class LLMConditionVerifier:
|
|
62
|
+
"""Judge an English condition against the state with a Mellea session."""
|
|
63
|
+
|
|
64
|
+
def __init__(self, session: Any = None):
|
|
65
|
+
self._session = [session]
|
|
66
|
+
|
|
67
|
+
def __call__(self, condition: str, state: "State") -> bool:
|
|
68
|
+
prompt = (
|
|
69
|
+
f"Program state: {_describe(state)}\n"
|
|
70
|
+
f"Condition: {condition}\n"
|
|
71
|
+
"Does the condition hold for this state? Answer only 'yes' or 'no'."
|
|
72
|
+
)
|
|
73
|
+
return _ask(self._session, prompt).lower().startswith("yes")
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
"""Policies choose one action among the currently enabled ones.
|
|
2
|
+
|
|
3
|
+
A policy is any callable ``(enabled: list[Action], state: State) -> Action``.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import random as _random
|
|
9
|
+
from typing import TYPE_CHECKING, Callable
|
|
10
|
+
|
|
11
|
+
if TYPE_CHECKING:
|
|
12
|
+
from .core import Action
|
|
13
|
+
from .state import State
|
|
14
|
+
|
|
15
|
+
Policy = Callable[["list[Action]", "State"], "Action"]
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def first_enabled(enabled: "list[Action]", state: "State") -> "Action":
|
|
19
|
+
"""Deterministic default: the first enabled action in declaration order."""
|
|
20
|
+
return enabled[0]
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def random_policy(seed: int | None = None) -> Policy:
|
|
24
|
+
"""Uniformly random choice among enabled actions."""
|
|
25
|
+
rng = _random.Random(seed)
|
|
26
|
+
|
|
27
|
+
def policy(enabled: "list[Action]", state: "State") -> "Action":
|
|
28
|
+
return rng.choice(enabled)
|
|
29
|
+
|
|
30
|
+
return policy
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
"""Mutable program state shared by every pre/act/post in a pratt loop."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import copy
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from typing import Any, Iterator, MutableMapping
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
@dataclass
|
|
11
|
+
class TraceEntry:
|
|
12
|
+
"""One attempted action. ``status`` is ``"ok"``, ``"post_failed"`` or ``"act_error"``."""
|
|
13
|
+
|
|
14
|
+
step: int
|
|
15
|
+
action: str
|
|
16
|
+
status: str
|
|
17
|
+
error: str | None = None
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class State(MutableMapping[str, Any]):
|
|
21
|
+
"""Dict-like state with attribute access, a step counter and a trace.
|
|
22
|
+
|
|
23
|
+
``state["x"]`` and ``state.x`` are equivalent (except for keys that shadow
|
|
24
|
+
mapping methods such as ``items``/``keys``/``get``: use ``state["items"]``). ``step`` and ``trace`` are
|
|
25
|
+
bookkeeping maintained by the agent and are not part of the user data
|
|
26
|
+
(they are not rolled back on failure, so the trace records failed attempts).
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
__slots__ = ("_data", "step", "trace")
|
|
30
|
+
|
|
31
|
+
def __init__(self, data: dict[str, Any] | None = None, /, **kwargs: Any):
|
|
32
|
+
object.__setattr__(self, "_data", {**(data or {}), **kwargs})
|
|
33
|
+
object.__setattr__(self, "step", 0)
|
|
34
|
+
object.__setattr__(self, "trace", [])
|
|
35
|
+
|
|
36
|
+
# -- mapping protocol --------------------------------------------------
|
|
37
|
+
def __getitem__(self, key: str) -> Any:
|
|
38
|
+
return self._data[key]
|
|
39
|
+
|
|
40
|
+
def __setitem__(self, key: str, value: Any) -> None:
|
|
41
|
+
self._data[key] = value
|
|
42
|
+
|
|
43
|
+
def __delitem__(self, key: str) -> None:
|
|
44
|
+
del self._data[key]
|
|
45
|
+
|
|
46
|
+
def __iter__(self) -> Iterator[str]:
|
|
47
|
+
return iter(self._data)
|
|
48
|
+
|
|
49
|
+
def __len__(self) -> int:
|
|
50
|
+
return len(self._data)
|
|
51
|
+
|
|
52
|
+
# -- attribute access --------------------------------------------------
|
|
53
|
+
def __getattr__(self, key: str) -> Any:
|
|
54
|
+
try:
|
|
55
|
+
return self._data[key]
|
|
56
|
+
except KeyError:
|
|
57
|
+
raise AttributeError(key) from None
|
|
58
|
+
|
|
59
|
+
def __setattr__(self, key: str, value: Any) -> None:
|
|
60
|
+
if key in State.__slots__:
|
|
61
|
+
object.__setattr__(self, key, value)
|
|
62
|
+
else:
|
|
63
|
+
self._data[key] = value
|
|
64
|
+
|
|
65
|
+
def __delattr__(self, key: str) -> None:
|
|
66
|
+
try:
|
|
67
|
+
del self._data[key]
|
|
68
|
+
except KeyError:
|
|
69
|
+
raise AttributeError(key) from None
|
|
70
|
+
|
|
71
|
+
# -- snapshots ---------------------------------------------------------
|
|
72
|
+
def snapshot(self) -> dict[str, Any]:
|
|
73
|
+
"""Deep copy of the user data (used for rollback)."""
|
|
74
|
+
return copy.deepcopy(self._data)
|
|
75
|
+
|
|
76
|
+
def restore(self, snap: dict[str, Any]) -> None:
|
|
77
|
+
object.__setattr__(self, "_data", copy.deepcopy(snap))
|
|
78
|
+
|
|
79
|
+
@property
|
|
80
|
+
def history(self) -> list[str]:
|
|
81
|
+
"""Names of actions that fired successfully, in order."""
|
|
82
|
+
return [t.action for t in self.trace if t.status == "ok"]
|
|
83
|
+
|
|
84
|
+
def to_dict(self) -> dict[str, Any]:
|
|
85
|
+
return dict(self._data)
|
|
86
|
+
|
|
87
|
+
def __repr__(self) -> str:
|
|
88
|
+
return f"State({self._data!r}, step={self.step})"
|
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
import pytest
|
|
2
|
+
from mellea import Requirement
|
|
3
|
+
|
|
4
|
+
from mellea_pratt import (
|
|
5
|
+
Action,
|
|
6
|
+
LLMPolicy,
|
|
7
|
+
MissingVerifierError,
|
|
8
|
+
PostconditionError,
|
|
9
|
+
State,
|
|
10
|
+
pratt_agent,
|
|
11
|
+
random_policy,
|
|
12
|
+
)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def counter_actions():
|
|
16
|
+
def inc(s):
|
|
17
|
+
s.n = s.get("n", 0) + 1
|
|
18
|
+
|
|
19
|
+
return [{"pre": lambda s: s.get("n", 0) < 3, "act": inc, "post": lambda s: s.n <= 3}]
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def test_spec_usage_shape():
|
|
23
|
+
pre_1 = lambda s: "x" not in s
|
|
24
|
+
act_1 = lambda s: {"x": 1}
|
|
25
|
+
post_1 = lambda s: s.x == 1
|
|
26
|
+
agent = pratt_agent(actions=[{"pre": pre_1, "act": act_1, "post": post_1}])
|
|
27
|
+
result = agent.run()
|
|
28
|
+
assert result.status == "deadlock" # nothing left to do, no goal given
|
|
29
|
+
assert result.state.x == 1
|
|
30
|
+
assert len(result.trace) == 1 and result.trace[0].status == "ok"
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def test_state_access():
|
|
34
|
+
s = State({"a": 1}, b=2)
|
|
35
|
+
s.c = 3
|
|
36
|
+
s["d"] = 4
|
|
37
|
+
assert (s.a, s["b"], s.c, s.d) == (1, 2, 3, 4)
|
|
38
|
+
assert dict(s) == {"a": 1, "b": 2, "c": 3, "d": 4}
|
|
39
|
+
with pytest.raises(AttributeError):
|
|
40
|
+
s.missing
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def test_preconditions_guard_actions():
|
|
44
|
+
order = []
|
|
45
|
+
actions = [
|
|
46
|
+
Action(name="b", pre=lambda s: s.get("a_done", False), act=lambda s: order.append("b") or {"b_done": True}),
|
|
47
|
+
Action(name="a", pre=lambda s: not s.get("a_done"), act=lambda s: order.append("a") or {"a_done": True}),
|
|
48
|
+
]
|
|
49
|
+
agent = pratt_agent(actions, goal=lambda s: s.get("b_done"))
|
|
50
|
+
assert [a.name for a in agent.enabled()] == ["a"]
|
|
51
|
+
r = agent.run()
|
|
52
|
+
assert r.status == "goal" and order == ["a", "b"] and r.history == ["a", "b"]
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def test_goal_termination_and_goal_already_true():
|
|
56
|
+
r = pratt_agent(counter_actions(), goal=lambda s: s.get("n", 0) == 2).run()
|
|
57
|
+
assert r.status == "goal" and r.state.n == 2 and r.state.step == 2
|
|
58
|
+
r = pratt_agent(counter_actions(), state={"n": 2}, goal=lambda s: s.n == 2).run()
|
|
59
|
+
assert r.status == "goal" and r.trace == []
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def test_deadlock():
|
|
63
|
+
r = pratt_agent(counter_actions(), goal=lambda s: s.get("n", 0) == 10).run()
|
|
64
|
+
assert r.status == "deadlock" and r.state.n == 3 and not r.ok
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def test_max_steps():
|
|
68
|
+
r = pratt_agent([{"act": lambda s: None}], goal=lambda s: False, max_steps=5).run()
|
|
69
|
+
assert r.status == "max_steps" and r.state.step == 5
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def test_rollback_restores_and_blocks():
|
|
73
|
+
def bad(s):
|
|
74
|
+
s.log.append("junk")
|
|
75
|
+
|
|
76
|
+
actions = [
|
|
77
|
+
{"name": "bad", "act": bad, "post": lambda s: "junk" not in s.log},
|
|
78
|
+
{"name": "good", "act": lambda s: s.log.append("ok"), "post": lambda s: "ok" in s.log},
|
|
79
|
+
]
|
|
80
|
+
r = pratt_agent(actions, state={"log": []}, goal=lambda s: "ok" in s.log, max_attempts=2).run()
|
|
81
|
+
assert r.status == "goal"
|
|
82
|
+
assert r.state.log == ["ok"] # junk was rolled back
|
|
83
|
+
assert [t.status for t in r.trace] == ["post_failed", "post_failed", "ok"]
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def test_rollback_retry_then_succeeds():
|
|
87
|
+
attempts = {"n": 0}
|
|
88
|
+
|
|
89
|
+
def flaky(s):
|
|
90
|
+
attempts["n"] += 1
|
|
91
|
+
s.v = attempts["n"]
|
|
92
|
+
|
|
93
|
+
r = pratt_agent([{"act": flaky, "post": lambda s: s.v >= 3}], state={"v": 0},
|
|
94
|
+
goal=lambda s: s.v >= 3, max_attempts=3).run()
|
|
95
|
+
assert r.status == "goal" and r.state.v == 3
|
|
96
|
+
assert [t.status for t in r.trace] == ["post_failed", "post_failed", "ok"]
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def test_rollback_exhausted_is_deadlock():
|
|
100
|
+
r = pratt_agent([{"act": lambda s: {"v": 1}, "post": lambda s: False}], state={"v": 0},
|
|
101
|
+
goal=lambda s: s.v == 1, max_attempts=2).run()
|
|
102
|
+
assert r.status == "deadlock" and r.state.v == 0 and len(r.trace) == 2
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def test_act_exception_is_a_failed_attempt():
|
|
106
|
+
def boom(s):
|
|
107
|
+
s.v = 99
|
|
108
|
+
raise RuntimeError("nope")
|
|
109
|
+
|
|
110
|
+
r = pratt_agent([{"act": boom}], state={"v": 0}, max_attempts=1).run()
|
|
111
|
+
assert r.status == "deadlock" and r.state.v == 0
|
|
112
|
+
assert r.trace[0].status == "act_error" and "nope" in r.trace[0].error
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def test_raise_mode():
|
|
116
|
+
agent = pratt_agent([{"act": lambda s: {"v": 1}, "post": lambda s: False}],
|
|
117
|
+
on_post_failure="raise", goal=lambda s: False)
|
|
118
|
+
with pytest.raises(PostconditionError):
|
|
119
|
+
agent.run()
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def test_continue_mode_keeps_state():
|
|
123
|
+
r = pratt_agent([{"pre": lambda s: s.get("v", 0) < 2, "act": lambda s: {"v": s.get("v", 0) + 1},
|
|
124
|
+
"post": lambda s: False}], on_post_failure="continue").run()
|
|
125
|
+
assert r.status == "deadlock" and r.state.v == 2
|
|
126
|
+
assert all(t.status == "post_failed" for t in r.trace)
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def test_string_and_requirement_predicates_with_fake_verifier():
|
|
130
|
+
seen = []
|
|
131
|
+
|
|
132
|
+
def verifier(cond, state):
|
|
133
|
+
seen.append(cond)
|
|
134
|
+
if cond.startswith("There's a user"):
|
|
135
|
+
return "user" in state and "uuid" not in state.user
|
|
136
|
+
if cond == "the user info dictionary has a uuid":
|
|
137
|
+
return "uuid" in state.user
|
|
138
|
+
raise AssertionError(cond)
|
|
139
|
+
|
|
140
|
+
def upsert_user(s):
|
|
141
|
+
s.user["uuid"] = "1234"
|
|
142
|
+
|
|
143
|
+
agent = pratt_agent(
|
|
144
|
+
actions=[{"pre": "There's a user info dictionary in locals() that doesn't have a uuid yet",
|
|
145
|
+
"act": upsert_user,
|
|
146
|
+
"post": Requirement("the user info dictionary has a uuid")}],
|
|
147
|
+
state={"user": {"name": "ada"}},
|
|
148
|
+
condition_verifier=verifier,
|
|
149
|
+
)
|
|
150
|
+
r = agent.run()
|
|
151
|
+
assert r.state.user["uuid"] == "1234" and r.history == ["upsert_user"]
|
|
152
|
+
assert "the user info dictionary has a uuid" in seen
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def test_string_predicate_without_verifier_raises():
|
|
156
|
+
with pytest.raises(MissingVerifierError, match="condition_verifier"):
|
|
157
|
+
pratt_agent([{"pre": "it is sunny", "act": lambda s: None}]).run()
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def test_random_policy_is_seeded_and_valid():
|
|
161
|
+
acts = [{"name": n, "pre": lambda s: s.step < 6, "act": lambda s: None} for n in "abc"]
|
|
162
|
+
h1 = pratt_agent(acts, policy=random_policy(0)).run().history
|
|
163
|
+
h2 = pratt_agent(acts, policy=random_policy(0)).run().history
|
|
164
|
+
assert h1 == h2 and len(h1) == 6 and set(h1) <= set("abc")
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def test_bad_policy_gives_error_status():
|
|
168
|
+
r = pratt_agent([{"act": lambda s: None}], policy=lambda e, s: "nonsense").run()
|
|
169
|
+
assert r.status == "error" and r.error is not None
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def test_llm_policy_with_fake_session():
|
|
173
|
+
class FakeMsg:
|
|
174
|
+
def __init__(self, c):
|
|
175
|
+
self.content = c
|
|
176
|
+
|
|
177
|
+
class FakeSession:
|
|
178
|
+
def chat(self, prompt):
|
|
179
|
+
assert "Enabled actions: a, b" in prompt
|
|
180
|
+
return FakeMsg("b")
|
|
181
|
+
|
|
182
|
+
acts = [{"name": "a", "act": lambda s: {"done": "a"}}, {"name": "b", "act": lambda s: {"done": "b"}}]
|
|
183
|
+
r = pratt_agent(acts, policy=LLMPolicy(session=FakeSession()), goal=lambda s: "done" in s).run()
|
|
184
|
+
assert r.state.done == "b"
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def test_action_validation():
|
|
188
|
+
with pytest.raises(ValueError):
|
|
189
|
+
pratt_agent([{"act": lambda s: None, "prec": None}])
|
|
190
|
+
with pytest.raises(ValueError):
|
|
191
|
+
pratt_agent([{"name": "x", "act": print}, {"name": "x", "act": print}])
|
|
192
|
+
with pytest.raises(ValueError):
|
|
193
|
+
pratt_agent([], on_post_failure="ignore")
|