Skip to content

Commit 4d173b2

Browse files
FOWEPJF255lhl-lhieavanvalkenburg
authored
Python: Update Monty bridge for pydantic-monty pool API (#8152) (#8162)
* Python: Update Monty bridge for pydantic-monty pool API (#8152) * Python: Refresh uv.lock for pydantic-monty>=0.0.23 (#8152) * Python: drop obsolete pydantic-monty version migration comment (#8152) Floor is already >=0.0.23; no need to document the old API transition. * Python: add uv.lock platform markers for monty deps (#8152) * Revert "Python: add uv.lock platform markers for monty deps (#8152)" This reverts commit 14a48a2. * Python: refresh uv.lock for pydantic-monty 0.0.23 (#8152) Keep main's prerelease-mode and platform-marker lock format so CI uv-lock stays clean while resolving pydantic-monty>=0.0.23. --------- Co-authored-by: minelhi <[email protected]> Co-authored-by: Eduard van Valkenburg <[email protected]>
1 parent 5a8cef9 commit 4d173b2

6 files changed

Lines changed: 181 additions & 142 deletions

File tree

‎python/packages/monty/AGENTS.md‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -59,15 +59,16 @@ Tool-management methods on both classes: `add_tools`, `get_tools`,
5959
adapted from the reference Monty CodeAct repo. Pauses on `FunctionSnapshot`
6060
to dispatch host calls, then resumes; supports direct typed tool calls,
6161
the `call_tool` fallback, `asyncio.gather` fan-out, and forwards
62-
``mount`` / ``limits`` to `Monty(...).start(...)`.
62+
``limits`` / type-check options via `pool.checkout(...)`, and ``mount`` /
63+
``print_callback`` via `session.feed_start(...)`.
6364
- **`_instructions.py`** — dynamic instruction / tool-description builders
6465
(include filesystem capability summaries when mounts are configured).
6566

6667
## Not implemented (yet)
6768

6869
| Capability | Monty primitive | Status |
6970
|------------|-----------------|--------|
70-
| Custom virtual filesystem | `OSAccess` subclass passed to `Monty(...).start(os=...)` | Not exposed. Strictly more general than file mounts; useful when you want a fully synthetic FS. |
71+
| Custom virtual filesystem | `OSAccess` subclass passed to `session.feed_start(..., os=...)` | Not exposed. Strictly more general than file mounts; useful when you want a fully synthetic FS. |
7172
| Outbound URL allow-list | No Monty primitive — expose `fetch_url` as a host tool with the allow-list check in your tool function. | Not exposed in this package; users add it as a regular tool. |
7273

7374
## Out of scope (for now)

‎python/packages/monty/README.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -145,8 +145,8 @@ codeact = MontyCodeActProvider(
145145
nothing is captured). `read-only` mounts reject writes.
146146
- **`resource_limits`** is forwarded straight to Monty's
147147
[`ResourceLimits`](https://github.com/pydantic/monty) TypedDict
148-
(`max_allocations`, `max_duration_secs`, `max_memory`, `gc_interval`,
149-
`max_recursion_depth`).
148+
(`max_duration_secs`, `max_memory`, `gc_interval`, `max_recursion_depth`,
149+
`max_suspensions`).
150150

151151
## DSL inside `execute_code`
152152

‎python/packages/monty/agent_framework_monty/_monty_bridge.py‎

Lines changed: 36 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -229,38 +229,46 @@ async def run(self, code: str) -> dict[str, Any]:
229229
NameLookupSnapshot = monty_module.NameLookupSnapshot
230230

231231
printer = _PrintCollector()
232-
monty = Monty(
233-
_build_code(code),
234-
script_name="codeact.py",
235-
type_check=self.type_stubs is not None,
236-
type_check_stubs=self.type_stubs,
237-
)
238-
start_kwargs: dict[str, Any] = {"print_callback": printer}
239-
if self._mounts:
240-
start_kwargs["mount"] = list(self._mounts)
232+
checkout_kwargs: dict[str, Any] = {
233+
"script_name": "codeact.py",
234+
"type_check": self.type_stubs is not None,
235+
"type_check_stubs": self.type_stubs,
236+
}
241237
if self._resource_limits:
242-
start_kwargs["limits"] = self._resource_limits
243-
progress = monty.start(**start_kwargs)
244-
245-
while True:
246-
if isinstance(progress, MontyComplete):
247-
return {
248-
"output": _ensure_json_value(progress.output),
249-
"stdout": printer.output,
250-
"truncated": printer.truncated,
251-
}
252-
if isinstance(progress, FunctionSnapshot):
253-
progress = self._handle_function(progress)
254-
continue
255-
if isinstance(progress, FutureSnapshot):
256-
progress = await self._handle_future(progress)
257-
continue
258-
if isinstance(progress, NameLookupSnapshot):
259-
raise RuntimeError(f"Name lookup not supported: {progress.variable_name!r}")
260-
raise RuntimeError(f"Unsupported Monty progress type: {type(progress).__name__}")
238+
checkout_kwargs["limits"] = self._resource_limits
239+
240+
feed_kwargs: dict[str, Any] = {"print_callback": printer}
241+
if self._mounts:
242+
feed_kwargs["mount"] = list(self._mounts)
243+
244+
with Monty() as pool:
245+
with pool.checkout(**checkout_kwargs) as session:
246+
progress = session.feed_start(_build_code(code), **feed_kwargs)
247+
248+
while True:
249+
if isinstance(progress, MontyComplete):
250+
return {
251+
"output": _ensure_json_value(progress.output),
252+
"stdout": printer.output,
253+
"truncated": printer.truncated,
254+
}
255+
if isinstance(progress, FunctionSnapshot):
256+
progress = self._handle_function(progress)
257+
continue
258+
if isinstance(progress, FutureSnapshot):
259+
progress = await self._handle_future(progress)
260+
continue
261+
if isinstance(progress, NameLookupSnapshot):
262+
raise RuntimeError(f"Name lookup not supported: {progress.variable_name!r}")
263+
raise RuntimeError(f"Unsupported Monty progress type: {type(progress).__name__}")
261264

262265
def _handle_function(self, snapshot: Any) -> Any:
263266
if snapshot.is_os_function:
267+
# pydantic-monty pool API: feed_start always surfaces OS calls as
268+
# snapshots. Mounts (and os=) are consulted only by resume_auto(),
269+
# not by a plain resume(...) payload.
270+
if self._mounts:
271+
return snapshot.resume_auto()
264272
return snapshot.resume({
265273
"exc_type": "PermissionError",
266274
"message": "OS and filesystem calls are not available.",

‎python/packages/monty/pyproject.toml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ classifiers = [
2424
]
2525
dependencies = [
2626
"agent-framework-core>=1.13.0,<2",
27-
"pydantic-monty>=0.0.1,<0.1",
27+
"pydantic-monty>=0.0.23,<0.1",
2828
]
2929

3030
[tool.uv]

‎python/packages/monty/tests/monty/test_monty_codeact.py‎

Lines changed: 59 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,10 @@ def resume(self, payload: Any) -> Any:
5050
assert self._script is not None, "Snapshot must be attached to a script."
5151
return self._script.advance(("function_resume", self, payload))
5252

53+
def resume_auto(self) -> Any:
54+
assert self._script is not None, "Snapshot must be attached to a script."
55+
return self._script.advance(("function_resume_auto", self, None))
56+
5357

5458
@dataclass
5559
class _FakeFutureSnapshot:
@@ -116,30 +120,80 @@ def _get_script() -> _FakeScript:
116120
return script
117121

118122

119-
class _FakeMonty:
123+
class _FakeSession:
124+
"""Fake ``MontySession`` matching the pydantic-monty pool/checkout API."""
125+
120126
def __init__(
121127
self,
122-
code: str,
123128
*,
124129
script_name: str,
125130
type_check: bool,
126131
type_check_stubs: str | None,
132+
limits: dict[str, Any] | None = None,
127133
) -> None:
128-
self.code = code
129134
self.script_name = script_name
130135
self.type_check = type_check
131136
self.type_check_stubs = type_check_stubs
137+
self.limits = limits
138+
self.code: str | None = None
132139
self._script = _get_script()
133140

134-
def start(self, *, print_callback: Any) -> Any:
141+
def __enter__(self) -> _FakeSession:
142+
return self
143+
144+
def __exit__(self, *args: Any) -> None:
145+
return None
146+
147+
def feed_start(
148+
self,
149+
code: str,
150+
*,
151+
print_callback: Any = None,
152+
mount: Any = None,
153+
**kwargs: Any,
154+
) -> Any:
155+
self.code = code
156+
self.mount = mount
135157
while True:
136158
item = self._script.next_item()
137159
if isinstance(item, _PrintAction):
138-
print_callback("stdout", item.text)
160+
if print_callback is not None:
161+
print_callback("stdout", item.text)
139162
continue
140163
return item
141164

142165

166+
class _FakeMonty:
167+
"""Fake ``Monty`` pool: ``with Monty() as pool: with pool.checkout() as session``."""
168+
169+
def __init__(self, **kwargs: Any) -> None:
170+
self.pool_kwargs = kwargs
171+
self.last_session: _FakeSession | None = None
172+
173+
def __enter__(self) -> _FakeMonty:
174+
return self
175+
176+
def __exit__(self, *args: Any) -> None:
177+
return None
178+
179+
def checkout(
180+
self,
181+
*,
182+
script_name: str = "main.py",
183+
type_check: bool = False,
184+
type_check_stubs: str | None = None,
185+
limits: dict[str, Any] | None = None,
186+
**kwargs: Any,
187+
) -> _FakeSession:
188+
self.last_session = _FakeSession(
189+
script_name=script_name,
190+
type_check=type_check,
191+
type_check_stubs=type_check_stubs,
192+
limits=limits,
193+
)
194+
return self.last_session
195+
196+
143197
@pytest.fixture(autouse=True)
144198
def fake_monty_module(monkeypatch: pytest.MonkeyPatch) -> Iterator[None]:
145199
"""Install a fake ``pydantic_monty`` module for the duration of each test."""

0 commit comments

Comments
 (0)