pydantic-ai-withruntime 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.
- pydantic_ai_withruntime-0.1.0/.gitignore +8 -0
- pydantic_ai_withruntime-0.1.0/LICENSE +55 -0
- pydantic_ai_withruntime-0.1.0/PKG-INFO +77 -0
- pydantic_ai_withruntime-0.1.0/README.md +52 -0
- pydantic_ai_withruntime-0.1.0/pydantic_ai_withruntime/__init__.py +164 -0
- pydantic_ai_withruntime-0.1.0/pydantic_ai_withruntime/py.typed +0 -0
- pydantic_ai_withruntime-0.1.0/pyproject.toml +52 -0
- pydantic_ai_withruntime-0.1.0/scripts/e2e.py +66 -0
- pydantic_ai_withruntime-0.1.0/tests/test_toolset.py +191 -0
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
|
|
5
|
+
http://www.apache.org/licenses/
|
|
6
|
+
|
|
7
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
8
|
+
|
|
9
|
+
1. Definitions.
|
|
10
|
+
|
|
11
|
+
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
|
|
16
|
+
|
|
17
|
+
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
|
|
18
|
+
|
|
19
|
+
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
|
|
20
|
+
|
|
21
|
+
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
|
|
22
|
+
|
|
23
|
+
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
|
|
24
|
+
|
|
25
|
+
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
|
|
26
|
+
|
|
27
|
+
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
|
|
28
|
+
|
|
29
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
|
|
30
|
+
|
|
31
|
+
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
|
|
32
|
+
|
|
33
|
+
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
|
|
34
|
+
|
|
35
|
+
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
|
|
36
|
+
|
|
37
|
+
You must give any other recipients of the Work or Derivative Works a copy of this License; and
|
|
38
|
+
|
|
39
|
+
You must cause any modified files to carry prominent notices stating that You changed the files; and
|
|
40
|
+
|
|
41
|
+
You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
|
|
42
|
+
|
|
43
|
+
If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
|
|
44
|
+
|
|
45
|
+
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
|
|
46
|
+
|
|
47
|
+
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
|
|
48
|
+
|
|
49
|
+
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
|
|
50
|
+
|
|
51
|
+
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
|
|
52
|
+
|
|
53
|
+
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
|
|
54
|
+
|
|
55
|
+
END OF TERMS AND CONDITIONS
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: pydantic-ai-withruntime
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Runtime sandboxes as a Pydantic AI toolset: shell, files and listings in a Firecracker microVM
|
|
5
|
+
Project-URL: Homepage, https://withruntime.com
|
|
6
|
+
Project-URL: Documentation, https://withruntime.com/docs/frameworks#pydantic-ai
|
|
7
|
+
Project-URL: Repository, https://github.com/withruntime/runtime/tree/main/integrations/pydantic-ai
|
|
8
|
+
Author: Runtime LLC
|
|
9
|
+
License: Apache-2.0
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Keywords: ai agents,code execution,firecracker,microvm,pydantic,pydantic ai,pydantic-ai,runtime,sandbox,toolset
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
19
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
20
|
+
Classifier: Typing :: Typed
|
|
21
|
+
Requires-Python: <4.0,>=3.10
|
|
22
|
+
Requires-Dist: pydantic-ai-slim>=1.74
|
|
23
|
+
Requires-Dist: withruntime<1.0,>=0.6.1
|
|
24
|
+
Description-Content-Type: text/markdown
|
|
25
|
+
|
|
26
|
+
# pydantic-ai-withruntime
|
|
27
|
+
|
|
28
|
+
Runtime sandboxes as a [Pydantic AI](https://ai.pydantic.dev) toolset. Each
|
|
29
|
+
agent run gets its own [Runtime](https://withruntime.com) sandbox, a
|
|
30
|
+
Firecracker microVM with its own Linux kernel. The sandbox is created when the
|
|
31
|
+
run starts and stopped when it ends.
|
|
32
|
+
|
|
33
|
+
```bash
|
|
34
|
+
pip install pydantic-ai pydantic-ai-withruntime # pydantic-ai brings the model providers
|
|
35
|
+
npx withruntime login # or set RUNTIME_API_KEY
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
```python
|
|
39
|
+
from pydantic_ai import Agent
|
|
40
|
+
from pydantic_ai_withruntime import RuntimeToolset
|
|
41
|
+
|
|
42
|
+
agent = Agent("anthropic:claude-sonnet-4-6", toolsets=[RuntimeToolset()])
|
|
43
|
+
print(agent.run_sync("Fit a line to (1,2), (2,4.1), (3,6.2) with numpy and give the slope.").output)
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
The model sees four tools:
|
|
47
|
+
|
|
48
|
+
| Tool | What it does |
|
|
49
|
+
| -------------------- | ----------------------------------------------------- |
|
|
50
|
+
| `runtime_exec` | Runs a command under `bash -c` and returns its output |
|
|
51
|
+
| `runtime_read_file` | Reads a text file |
|
|
52
|
+
| `runtime_write_file` | Creates or replaces a text file |
|
|
53
|
+
| `runtime_list_files` | Lists a directory with each entry's type and size |
|
|
54
|
+
|
|
55
|
+
Relative paths are under `/workspace`. Output past 20,000 characters is cut
|
|
56
|
+
from the front, keeping the end, where errors are.
|
|
57
|
+
|
|
58
|
+
## Options
|
|
59
|
+
|
|
60
|
+
- `RuntimeToolset(create={...})` sets each run's sandbox: `vcpu`, `memory_mib`,
|
|
61
|
+
`image`, `network`, `labels` and the rest of `sandboxes.create`. Unless you
|
|
62
|
+
set a `timeout_seconds`, each sandbox gets a 30-minute lease that ends in a
|
|
63
|
+
stop, so a crashed process leaves nothing running.
|
|
64
|
+
- `RuntimeToolset(sandbox)` uses an `AsyncSandbox` you created. Every run
|
|
65
|
+
shares it, and it is never stopped for you. Use this to keep files between
|
|
66
|
+
runs, for example with `AsyncRuntime().sandboxes.get_or_create("user-42")`.
|
|
67
|
+
- `timeout_seconds`, `max_output_chars` and `root` tune the tools.
|
|
68
|
+
`instructions=None` leaves the agent's instructions unchanged.
|
|
69
|
+
|
|
70
|
+
## Tests
|
|
71
|
+
|
|
72
|
+
`tests/` runs the toolset under Pydantic AI's own agent loop, with a scripted
|
|
73
|
+
`FunctionModel` and a fake client;
|
|
74
|
+
`uv run --resolution lowest-direct --group test pytest` runs them at the lowest
|
|
75
|
+
versions `pyproject.toml` allows. `scripts/e2e.py` runs the agent loop against
|
|
76
|
+
the real API with `RUNTIME_API_KEY` set. It passed on 25 September 2026 with
|
|
77
|
+
Pydantic AI 2.50.0: two runs, each in its own sandbox, both stopped.
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
# pydantic-ai-withruntime
|
|
2
|
+
|
|
3
|
+
Runtime sandboxes as a [Pydantic AI](https://ai.pydantic.dev) toolset. Each
|
|
4
|
+
agent run gets its own [Runtime](https://withruntime.com) sandbox, a
|
|
5
|
+
Firecracker microVM with its own Linux kernel. The sandbox is created when the
|
|
6
|
+
run starts and stopped when it ends.
|
|
7
|
+
|
|
8
|
+
```bash
|
|
9
|
+
pip install pydantic-ai pydantic-ai-withruntime # pydantic-ai brings the model providers
|
|
10
|
+
npx withruntime login # or set RUNTIME_API_KEY
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
```python
|
|
14
|
+
from pydantic_ai import Agent
|
|
15
|
+
from pydantic_ai_withruntime import RuntimeToolset
|
|
16
|
+
|
|
17
|
+
agent = Agent("anthropic:claude-sonnet-4-6", toolsets=[RuntimeToolset()])
|
|
18
|
+
print(agent.run_sync("Fit a line to (1,2), (2,4.1), (3,6.2) with numpy and give the slope.").output)
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
The model sees four tools:
|
|
22
|
+
|
|
23
|
+
| Tool | What it does |
|
|
24
|
+
| -------------------- | ----------------------------------------------------- |
|
|
25
|
+
| `runtime_exec` | Runs a command under `bash -c` and returns its output |
|
|
26
|
+
| `runtime_read_file` | Reads a text file |
|
|
27
|
+
| `runtime_write_file` | Creates or replaces a text file |
|
|
28
|
+
| `runtime_list_files` | Lists a directory with each entry's type and size |
|
|
29
|
+
|
|
30
|
+
Relative paths are under `/workspace`. Output past 20,000 characters is cut
|
|
31
|
+
from the front, keeping the end, where errors are.
|
|
32
|
+
|
|
33
|
+
## Options
|
|
34
|
+
|
|
35
|
+
- `RuntimeToolset(create={...})` sets each run's sandbox: `vcpu`, `memory_mib`,
|
|
36
|
+
`image`, `network`, `labels` and the rest of `sandboxes.create`. Unless you
|
|
37
|
+
set a `timeout_seconds`, each sandbox gets a 30-minute lease that ends in a
|
|
38
|
+
stop, so a crashed process leaves nothing running.
|
|
39
|
+
- `RuntimeToolset(sandbox)` uses an `AsyncSandbox` you created. Every run
|
|
40
|
+
shares it, and it is never stopped for you. Use this to keep files between
|
|
41
|
+
runs, for example with `AsyncRuntime().sandboxes.get_or_create("user-42")`.
|
|
42
|
+
- `timeout_seconds`, `max_output_chars` and `root` tune the tools.
|
|
43
|
+
`instructions=None` leaves the agent's instructions unchanged.
|
|
44
|
+
|
|
45
|
+
## Tests
|
|
46
|
+
|
|
47
|
+
`tests/` runs the toolset under Pydantic AI's own agent loop, with a scripted
|
|
48
|
+
`FunctionModel` and a fake client;
|
|
49
|
+
`uv run --resolution lowest-direct --group test pytest` runs them at the lowest
|
|
50
|
+
versions `pyproject.toml` allows. `scripts/e2e.py` runs the agent loop against
|
|
51
|
+
the real API with `RUNTIME_API_KEY` set. It passed on 25 September 2026 with
|
|
52
|
+
Pydantic AI 2.50.0: two runs, each in its own sandbox, both stopped.
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
"""Runtime sandboxes as a Pydantic AI toolset.
|
|
2
|
+
|
|
3
|
+
from pydantic_ai import Agent
|
|
4
|
+
from pydantic_ai_withruntime import RuntimeToolset
|
|
5
|
+
|
|
6
|
+
agent = Agent("anthropic:claude-sonnet-4-6", toolsets=[RuntimeToolset()])
|
|
7
|
+
result = agent.run_sync("Fit a line to (1,2), (2,4.1), (3,6.2) with numpy.")
|
|
8
|
+
|
|
9
|
+
Each agent run gets its own sandbox, a Firecracker microVM, created when the
|
|
10
|
+
run starts and stopped when it ends, even on an error. Pass ``sandbox=`` to use
|
|
11
|
+
one you created instead; it is never stopped for you. The model sees four
|
|
12
|
+
tools: ``runtime_exec``, ``runtime_read_file``, ``runtime_write_file`` and
|
|
13
|
+
``runtime_list_files``. The key comes from ``RUNTIME_API_KEY`` or this
|
|
14
|
+
machine's ``withruntime login``.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import dataclasses
|
|
20
|
+
import logging
|
|
21
|
+
from typing import Any
|
|
22
|
+
|
|
23
|
+
from pydantic_ai import RunContext
|
|
24
|
+
from pydantic_ai.toolsets import AbstractToolset, FunctionToolset, ToolsetTool
|
|
25
|
+
from typing_extensions import Self
|
|
26
|
+
from withruntime import AsyncRuntime, AsyncSandbox
|
|
27
|
+
from withruntime.tools import DEFAULT_MAX_OUTPUT_CHARS, DEFAULT_TIMEOUT_SECONDS, WORKSPACE, sandbox_tools
|
|
28
|
+
|
|
29
|
+
__all__ = ["RuntimeToolset"]
|
|
30
|
+
__version__ = "0.1.0"
|
|
31
|
+
logger = logging.getLogger("pydantic_ai_withruntime")
|
|
32
|
+
|
|
33
|
+
_INSTRUCTIONS = (
|
|
34
|
+
"You have a Linux sandbox (Ubuntu 24.04 with Python, Node.js, git and passwordless sudo). "
|
|
35
|
+
"Use runtime_exec to run commands and the file tools to read and write files. "
|
|
36
|
+
"Relative paths are under /workspace."
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class RuntimeToolset(AbstractToolset[Any]):
|
|
41
|
+
"""Four tools bound to a Runtime sandbox, one sandbox per agent run.
|
|
42
|
+
|
|
43
|
+
Args:
|
|
44
|
+
sandbox: An ``AsyncSandbox`` you created and own. When given, every run
|
|
45
|
+
shares it and it is never stopped for you.
|
|
46
|
+
create: Fields for ``AsyncRuntime.sandboxes.create`` for each run's
|
|
47
|
+
sandbox, such as ``{"vcpu": 2, "image": "my-image:v1"}``. A
|
|
48
|
+
``timeout_seconds`` lease of 30 minutes, ending in a stop, applies
|
|
49
|
+
unless you set one, so a crashed process leaves nothing running.
|
|
50
|
+
runtime: The client to create sandboxes with. Default: a new
|
|
51
|
+
``AsyncRuntime()`` for each run.
|
|
52
|
+
root: Where relative paths resolve. Default ``/workspace``.
|
|
53
|
+
timeout_seconds: Limit for a command the model starts without one.
|
|
54
|
+
max_output_chars: Characters kept from each output; the rest is cut
|
|
55
|
+
from the front, keeping the end, where errors are.
|
|
56
|
+
instructions: Added to the agent's instructions. ``None`` adds none.
|
|
57
|
+
id: The toolset's id, unique within an agent.
|
|
58
|
+
"""
|
|
59
|
+
|
|
60
|
+
def __init__(
|
|
61
|
+
self,
|
|
62
|
+
sandbox: AsyncSandbox | None = None,
|
|
63
|
+
*,
|
|
64
|
+
create: dict[str, Any] | None = None,
|
|
65
|
+
runtime: AsyncRuntime | None = None,
|
|
66
|
+
root: str = WORKSPACE,
|
|
67
|
+
timeout_seconds: int = DEFAULT_TIMEOUT_SECONDS,
|
|
68
|
+
max_output_chars: int = DEFAULT_MAX_OUTPUT_CHARS,
|
|
69
|
+
instructions: str | None = _INSTRUCTIONS,
|
|
70
|
+
id: str | None = "runtime",
|
|
71
|
+
) -> None:
|
|
72
|
+
self._sandbox = sandbox
|
|
73
|
+
self._owned = sandbox is None
|
|
74
|
+
self._create = dict(create or {})
|
|
75
|
+
self._runtime = runtime
|
|
76
|
+
self._client: AsyncRuntime | None = None
|
|
77
|
+
self._tool_options = {"root": root, "timeout_seconds": timeout_seconds, "max_output_chars": max_output_chars}
|
|
78
|
+
self._instructions = instructions
|
|
79
|
+
self._id = id
|
|
80
|
+
self._tools: FunctionToolset[Any] | None = None if sandbox is None else self._bind(sandbox)
|
|
81
|
+
self._entered = 0
|
|
82
|
+
|
|
83
|
+
@property
|
|
84
|
+
def id(self) -> str | None:
|
|
85
|
+
return self._id
|
|
86
|
+
|
|
87
|
+
@property
|
|
88
|
+
def label(self) -> str:
|
|
89
|
+
return f"RuntimeToolset({self._sandbox.id if self._sandbox else 'one sandbox per run'})"
|
|
90
|
+
|
|
91
|
+
@property
|
|
92
|
+
def sandbox(self) -> AsyncSandbox | None:
|
|
93
|
+
"""The sandbox the tools run in; ``None`` outside a run when the toolset makes its own."""
|
|
94
|
+
return self._sandbox
|
|
95
|
+
|
|
96
|
+
def _bind(self, sandbox: AsyncSandbox) -> FunctionToolset[Any]:
|
|
97
|
+
return FunctionToolset(sandbox_tools(sandbox, **self._tool_options), id=f"{self._id or 'runtime'}-tools")
|
|
98
|
+
|
|
99
|
+
async def for_run(self, ctx: RunContext[Any]) -> AbstractToolset[Any]:
|
|
100
|
+
if not self._owned:
|
|
101
|
+
return self
|
|
102
|
+
return RuntimeToolset(
|
|
103
|
+
create=self._create,
|
|
104
|
+
runtime=self._runtime,
|
|
105
|
+
instructions=self._instructions,
|
|
106
|
+
id=self._id,
|
|
107
|
+
**self._tool_options,
|
|
108
|
+
)
|
|
109
|
+
|
|
110
|
+
async def __aenter__(self) -> Self:
|
|
111
|
+
self._entered += 1
|
|
112
|
+
if self._owned and self._sandbox is None:
|
|
113
|
+
try:
|
|
114
|
+
if self._runtime is None:
|
|
115
|
+
self._client = AsyncRuntime()
|
|
116
|
+
client = self._runtime or self._client
|
|
117
|
+
fields = {"timeout_seconds": 1800, "on_lease_end": "stop", **self._create}
|
|
118
|
+
fields["labels"] = {"created_by": "pydantic-ai", **(fields.get("labels") or {})}
|
|
119
|
+
self._sandbox = await client.sandboxes.create(**fields)
|
|
120
|
+
self._tools = self._bind(self._sandbox)
|
|
121
|
+
except BaseException:
|
|
122
|
+
self._entered -= 1
|
|
123
|
+
sandbox, self._sandbox, self._tools = self._sandbox, None, None
|
|
124
|
+
try:
|
|
125
|
+
try:
|
|
126
|
+
if sandbox is not None:
|
|
127
|
+
await sandbox.stop()
|
|
128
|
+
finally:
|
|
129
|
+
await self._close_client()
|
|
130
|
+
except Exception as error: # noqa: BLE001 - preserve the initialization failure
|
|
131
|
+
logger.warning("Runtime: could not clean up failed toolset initialization: %s", error)
|
|
132
|
+
raise
|
|
133
|
+
return self
|
|
134
|
+
|
|
135
|
+
async def __aexit__(self, *args: object) -> bool | None:
|
|
136
|
+
self._entered -= 1
|
|
137
|
+
if self._entered == 0 and self._owned and self._sandbox is not None:
|
|
138
|
+
sandbox, self._sandbox, self._tools = self._sandbox, None, None
|
|
139
|
+
try:
|
|
140
|
+
await sandbox.stop()
|
|
141
|
+
finally:
|
|
142
|
+
await self._close_client()
|
|
143
|
+
return None
|
|
144
|
+
|
|
145
|
+
async def _close_client(self) -> None:
|
|
146
|
+
client, self._client = self._client, None
|
|
147
|
+
if client is not None:
|
|
148
|
+
await client.close()
|
|
149
|
+
|
|
150
|
+
async def get_instructions(self, ctx: RunContext[Any]) -> str | None:
|
|
151
|
+
return self._instructions
|
|
152
|
+
|
|
153
|
+
async def get_tools(self, ctx: RunContext[Any]) -> dict[str, ToolsetTool[Any]]:
|
|
154
|
+
if self._tools is None:
|
|
155
|
+
raise RuntimeError("RuntimeToolset is used outside an agent run; its sandbox starts when the run does.")
|
|
156
|
+
tools = await self._tools.get_tools(ctx)
|
|
157
|
+
return {name: dataclasses.replace(tool, toolset=self) for name, tool in tools.items()}
|
|
158
|
+
|
|
159
|
+
async def call_tool(
|
|
160
|
+
self, name: str, tool_args: dict[str, Any], ctx: RunContext[Any], tool: ToolsetTool[Any]
|
|
161
|
+
) -> Any:
|
|
162
|
+
assert self._tools is not None
|
|
163
|
+
inner = (await self._tools.get_tools(ctx))[name]
|
|
164
|
+
return await self._tools.call_tool(name, tool_args, ctx, inner)
|
|
File without changes
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "pydantic-ai-withruntime"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Runtime sandboxes as a Pydantic AI toolset: shell, files and listings in a Firecracker microVM"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = { text = "Apache-2.0" }
|
|
11
|
+
authors = [{ name = "Runtime LLC" }]
|
|
12
|
+
keywords = ["pydantic ai", "pydantic-ai", "pydantic", "toolset", "sandbox", "ai agents", "code execution", "firecracker", "microvm", "runtime"]
|
|
13
|
+
classifiers = [
|
|
14
|
+
"Intended Audience :: Developers",
|
|
15
|
+
"License :: OSI Approved :: Apache Software License",
|
|
16
|
+
"Programming Language :: Python :: 3",
|
|
17
|
+
"Programming Language :: Python :: 3.10",
|
|
18
|
+
"Programming Language :: Python :: 3.11",
|
|
19
|
+
"Programming Language :: Python :: 3.12",
|
|
20
|
+
"Programming Language :: Python :: 3.13",
|
|
21
|
+
"Topic :: Scientific/Engineering :: Artificial Intelligence",
|
|
22
|
+
"Typing :: Typed",
|
|
23
|
+
]
|
|
24
|
+
requires-python = ">=3.10,<4.0"
|
|
25
|
+
dependencies = [
|
|
26
|
+
# AbstractToolset.for_run, which gives each agent run its own sandbox, and
|
|
27
|
+
# a toolset's get_instructions reaching the model, which 1.73 still drops.
|
|
28
|
+
"pydantic-ai-slim>=1.74",
|
|
29
|
+
"withruntime>=0.6.1,<1.0",
|
|
30
|
+
]
|
|
31
|
+
|
|
32
|
+
[project.urls]
|
|
33
|
+
Homepage = "https://withruntime.com"
|
|
34
|
+
Documentation = "https://withruntime.com/docs/frameworks#pydantic-ai"
|
|
35
|
+
Repository = "https://github.com/withruntime/runtime/tree/main/integrations/pydantic-ai"
|
|
36
|
+
|
|
37
|
+
[dependency-groups]
|
|
38
|
+
test = ["pytest>=8", "pytest-asyncio>=1.0.0"]
|
|
39
|
+
|
|
40
|
+
[tool.hatch.build.targets.wheel]
|
|
41
|
+
packages = ["pydantic_ai_withruntime"]
|
|
42
|
+
|
|
43
|
+
[tool.hatch.build.targets.sdist]
|
|
44
|
+
include = ["pydantic_ai_withruntime", "tests", "scripts", "README.md", "LICENSE"]
|
|
45
|
+
|
|
46
|
+
[tool.pytest.ini_options]
|
|
47
|
+
addopts = "--strict-markers --strict-config"
|
|
48
|
+
testpaths = ["tests"]
|
|
49
|
+
asyncio_mode = "auto"
|
|
50
|
+
|
|
51
|
+
[tool.ruff]
|
|
52
|
+
line-length = 120
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
"""End to end, against the real API: RuntimeToolset in Pydantic AI's own agent
|
|
2
|
+
loop, driven by a scripted model (FunctionModel), so no model is called.
|
|
3
|
+
|
|
4
|
+
RUNTIME_API_KEY=... python scripts/e2e.py
|
|
5
|
+
|
|
6
|
+
Two runs of one agent, each in its own trial sandbox (the default size, a
|
|
7
|
+
ten-minute lease, stopped at the end of the run): write a file, run it, read it
|
|
8
|
+
back, list the folder. Then checks that neither sandbox is still running.
|
|
9
|
+
RUNTIME_API_URL points it elsewhere. Not part of the tests."""
|
|
10
|
+
|
|
11
|
+
import asyncio
|
|
12
|
+
import os
|
|
13
|
+
import sys
|
|
14
|
+
import uuid
|
|
15
|
+
|
|
16
|
+
from pydantic_ai import Agent
|
|
17
|
+
from pydantic_ai.messages import ModelResponse, TextPart, ToolCallPart, ToolReturnPart
|
|
18
|
+
from pydantic_ai.models.function import FunctionModel
|
|
19
|
+
from withruntime import AsyncRuntime
|
|
20
|
+
|
|
21
|
+
from pydantic_ai_withruntime import RuntimeToolset
|
|
22
|
+
|
|
23
|
+
STEPS = [
|
|
24
|
+
("runtime_write_file", {"path": "hello.py", "content": "import sys\nprint('hello from', sys.version_info[:2])\n"}),
|
|
25
|
+
("runtime_exec", {"command": "python3 hello.py"}),
|
|
26
|
+
("runtime_read_file", {"path": "hello.py"}),
|
|
27
|
+
("runtime_list_files", {"path": "."}),
|
|
28
|
+
]
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def respond(messages, info):
|
|
32
|
+
step = sum(1 for m in messages if isinstance(m, ModelResponse))
|
|
33
|
+
if step < len(STEPS):
|
|
34
|
+
name, args = STEPS[step]
|
|
35
|
+
return ModelResponse(parts=[ToolCallPart(name, args, tool_call_id=f"c{step}")])
|
|
36
|
+
returns = [p.content for m in messages for p in getattr(m, "parts", []) if isinstance(p, ToolReturnPart)]
|
|
37
|
+
return ModelResponse(parts=[TextPart(repr(returns))])
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
async def main() -> int:
|
|
41
|
+
if not os.environ.get("RUNTIME_API_KEY"):
|
|
42
|
+
sys.exit("Set RUNTIME_API_KEY to a Runtime key (a test key).")
|
|
43
|
+
run = uuid.uuid4().hex[:8]
|
|
44
|
+
toolset = RuntimeToolset(create={"timeout_seconds": 600, "labels": {"e2e": run}})
|
|
45
|
+
agent = Agent(FunctionModel(respond), toolsets=[toolset])
|
|
46
|
+
failures = []
|
|
47
|
+
for attempt in (1, 2):
|
|
48
|
+
result = await agent.run("go")
|
|
49
|
+
text = result.output
|
|
50
|
+
ok = "hello from (3," in text and "hello.py" in text and "'exit_code': 0" in text
|
|
51
|
+
print(f"{'ok ' if ok else 'FAIL'} run {attempt}: write, exec, read, list", flush=True)
|
|
52
|
+
if not ok:
|
|
53
|
+
failures.append(text[:500])
|
|
54
|
+
async with AsyncRuntime() as runtime:
|
|
55
|
+
left = [s for s in await (await runtime.sandboxes.list(labels={"e2e": run})).to_list()]
|
|
56
|
+
made = await (await runtime.sandboxes.list(labels={"e2e": run}, include_stopped=True)).to_list()
|
|
57
|
+
print(f"{'ok ' if len(made) == 2 else 'FAIL'} two sandboxes were made: {len(made)}")
|
|
58
|
+
print(f"{'ok ' if not left else 'FAIL'} none still running: {[s.id for s in left]}")
|
|
59
|
+
if len(made) != 2 or left:
|
|
60
|
+
failures.append("sandboxes")
|
|
61
|
+
print("All checks passed." if not failures else f"Failed: {failures}")
|
|
62
|
+
return 1 if failures else 0
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
if __name__ == "__main__":
|
|
66
|
+
sys.exit(asyncio.run(main()))
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
"""RuntimeToolset under Pydantic AI's own agent loop, with a scripted model
|
|
2
|
+
(FunctionModel) and a fake Runtime client, so nothing leaves the machine."""
|
|
3
|
+
|
|
4
|
+
import pytest
|
|
5
|
+
from pydantic_ai import Agent
|
|
6
|
+
from pydantic_ai.messages import ModelMessage, ModelResponse, TextPart, ToolCallPart, ToolReturnPart
|
|
7
|
+
from pydantic_ai.models.function import AgentInfo, FunctionModel
|
|
8
|
+
from withruntime import CommandResult
|
|
9
|
+
|
|
10
|
+
from pydantic_ai_withruntime import RuntimeToolset
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class FakeFiles:
|
|
14
|
+
def __init__(self):
|
|
15
|
+
self.data = {}
|
|
16
|
+
|
|
17
|
+
async def read(self, path):
|
|
18
|
+
if path not in self.data:
|
|
19
|
+
from withruntime import NotFoundError
|
|
20
|
+
|
|
21
|
+
raise NotFoundError("missing", code="file_not_found", status=404)
|
|
22
|
+
return self.data[path]
|
|
23
|
+
|
|
24
|
+
async def write(self, path, content):
|
|
25
|
+
self.data[path] = content.encode() if isinstance(content, str) else content
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class FakeSandbox:
|
|
29
|
+
def __init__(self, n, fields):
|
|
30
|
+
self.id, self.fields, self.stopped, self.commands = f"sbx_{n}", fields, False, []
|
|
31
|
+
self.files = FakeFiles()
|
|
32
|
+
|
|
33
|
+
async def exec(self, command, **options):
|
|
34
|
+
self.commands.append((command, options))
|
|
35
|
+
return CommandResult(exit_code=0, stdout=f"ran in {self.id}\n", stderr="")
|
|
36
|
+
|
|
37
|
+
async def stop(self, **_):
|
|
38
|
+
self.stopped = True
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class FakeRuntime:
|
|
42
|
+
def __init__(self, fail=False):
|
|
43
|
+
self.sandboxes = self
|
|
44
|
+
self.made, self.fail = [], fail
|
|
45
|
+
|
|
46
|
+
async def create(self, **fields):
|
|
47
|
+
if self.fail:
|
|
48
|
+
raise ConnectionError("no capacity")
|
|
49
|
+
sandbox = FakeSandbox(len(self.made), fields)
|
|
50
|
+
self.made.append(sandbox)
|
|
51
|
+
return sandbox
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def scripted(calls):
|
|
55
|
+
"""Calls each (tool, args) in turn, then answers with what the last tool returned."""
|
|
56
|
+
seen: list[list[str]] = []
|
|
57
|
+
|
|
58
|
+
def respond(messages: list[ModelMessage], info: AgentInfo) -> ModelResponse:
|
|
59
|
+
seen.append(sorted(tool.name for tool in info.function_tools))
|
|
60
|
+
step = sum(1 for m in messages if isinstance(m, ModelResponse))
|
|
61
|
+
if step < len(calls):
|
|
62
|
+
name, args = calls[step]
|
|
63
|
+
return ModelResponse(parts=[ToolCallPart(name, args, tool_call_id=f"c{step}")])
|
|
64
|
+
returns = [p for m in messages for p in getattr(m, "parts", []) if isinstance(p, ToolReturnPart)]
|
|
65
|
+
return ModelResponse(parts=[TextPart(str(returns[-1].content) if returns else "none")])
|
|
66
|
+
|
|
67
|
+
return FunctionModel(respond), seen
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
TOOLS = ["runtime_exec", "runtime_list_files", "runtime_read_file", "runtime_write_file"]
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
async def test_each_run_gets_its_own_sandbox_and_stops_it():
|
|
74
|
+
runtime = FakeRuntime()
|
|
75
|
+
model, seen = scripted([("runtime_exec", {"command": "python3 --version"})])
|
|
76
|
+
agent = Agent(model, toolsets=[RuntimeToolset(runtime=runtime, create={"vcpu": 2})])
|
|
77
|
+
|
|
78
|
+
first = await agent.run("go")
|
|
79
|
+
second = await agent.run("go")
|
|
80
|
+
|
|
81
|
+
assert [s.id for s in runtime.made] == ["sbx_0", "sbx_1"]
|
|
82
|
+
assert all(s.stopped for s in runtime.made)
|
|
83
|
+
assert "ran in sbx_0" in first.output and "ran in sbx_1" in second.output
|
|
84
|
+
assert seen[0] == TOOLS
|
|
85
|
+
fields = runtime.made[0].fields
|
|
86
|
+
assert fields["vcpu"] == 2 and fields["timeout_seconds"] == 1800 and fields["on_lease_end"] == "stop"
|
|
87
|
+
assert fields["labels"] == {"created_by": "pydantic-ai"}
|
|
88
|
+
assert runtime.made[0].commands[0][0] == "python3 --version"
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
async def test_the_sandbox_is_stopped_when_the_run_fails():
|
|
92
|
+
runtime = FakeRuntime()
|
|
93
|
+
|
|
94
|
+
def boom(messages, info):
|
|
95
|
+
raise ValueError("model down")
|
|
96
|
+
|
|
97
|
+
agent = Agent(FunctionModel(boom), toolsets=[RuntimeToolset(runtime=runtime)])
|
|
98
|
+
with pytest.raises(ValueError, match="model down"):
|
|
99
|
+
await agent.run("go")
|
|
100
|
+
assert runtime.made[0].stopped
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
async def test_a_failed_create_fails_the_run_and_leaves_nothing():
|
|
104
|
+
agent = Agent(scripted([])[0], toolsets=[RuntimeToolset(runtime=FakeRuntime(fail=True))])
|
|
105
|
+
with pytest.raises(ConnectionError, match="no capacity"):
|
|
106
|
+
await agent.run("go")
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
async def test_a_sandbox_you_pass_is_shared_and_never_stopped():
|
|
110
|
+
runtime = FakeRuntime()
|
|
111
|
+
sandbox = await runtime.create()
|
|
112
|
+
model, _ = scripted(
|
|
113
|
+
[
|
|
114
|
+
("runtime_write_file", {"path": "notes.md", "content": "hello"}),
|
|
115
|
+
("runtime_read_file", {"path": "notes.md"}),
|
|
116
|
+
]
|
|
117
|
+
)
|
|
118
|
+
toolset = RuntimeToolset(sandbox, instructions=None)
|
|
119
|
+
result = await Agent(model, toolsets=[toolset]).run("go")
|
|
120
|
+
assert result.output == "hello"
|
|
121
|
+
assert sandbox.files.data == {"/workspace/notes.md": b"hello"}
|
|
122
|
+
assert not sandbox.stopped and toolset.sandbox is sandbox
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
async def test_instructions_reach_the_model_and_can_be_turned_off():
|
|
126
|
+
captured = []
|
|
127
|
+
|
|
128
|
+
def respond(messages, info):
|
|
129
|
+
captured.append(info.instructions)
|
|
130
|
+
return ModelResponse(parts=[TextPart("ok")])
|
|
131
|
+
|
|
132
|
+
await Agent(FunctionModel(respond), toolsets=[RuntimeToolset(runtime=FakeRuntime())]).run("go")
|
|
133
|
+
await Agent(FunctionModel(respond), toolsets=[RuntimeToolset(runtime=FakeRuntime(), instructions=None)]).run("go")
|
|
134
|
+
assert "/workspace" in (captured[0] or "")
|
|
135
|
+
assert not captured[1]
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def test_used_outside_a_run_says_why():
|
|
139
|
+
import asyncio
|
|
140
|
+
|
|
141
|
+
with pytest.raises(RuntimeError, match="outside an agent run"):
|
|
142
|
+
asyncio.run(RuntimeToolset(runtime=FakeRuntime()).get_tools(None))
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
async def test_binding_failure_stops_the_guest_and_closes_the_owned_client(monkeypatch):
|
|
146
|
+
import pydantic_ai_withruntime as adapter
|
|
147
|
+
|
|
148
|
+
class OwnedRuntime(FakeRuntime):
|
|
149
|
+
closed = False
|
|
150
|
+
|
|
151
|
+
async def close(self):
|
|
152
|
+
self.closed = True
|
|
153
|
+
|
|
154
|
+
runtime = OwnedRuntime()
|
|
155
|
+
monkeypatch.setattr(adapter, "AsyncRuntime", lambda: runtime)
|
|
156
|
+
toolset = RuntimeToolset()
|
|
157
|
+
|
|
158
|
+
def fail_binding(sandbox):
|
|
159
|
+
raise ValueError("bad binding")
|
|
160
|
+
|
|
161
|
+
monkeypatch.setattr(toolset, "_bind", fail_binding)
|
|
162
|
+
with pytest.raises(ValueError, match="bad binding"):
|
|
163
|
+
await toolset.__aenter__()
|
|
164
|
+
assert runtime.made[0].stopped and runtime.closed
|
|
165
|
+
assert toolset.sandbox is None and toolset._entered == 0
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
async def test_binding_failure_survives_cleanup_failure_and_closes_the_client(monkeypatch):
|
|
169
|
+
import pydantic_ai_withruntime as adapter
|
|
170
|
+
|
|
171
|
+
class OwnedRuntime(FakeRuntime):
|
|
172
|
+
closed = False
|
|
173
|
+
|
|
174
|
+
async def close(self):
|
|
175
|
+
self.closed = True
|
|
176
|
+
|
|
177
|
+
runtime = OwnedRuntime()
|
|
178
|
+
monkeypatch.setattr(adapter, "AsyncRuntime", lambda: runtime)
|
|
179
|
+
toolset = RuntimeToolset()
|
|
180
|
+
|
|
181
|
+
def fail_binding(sandbox):
|
|
182
|
+
async def fail_stop():
|
|
183
|
+
raise ConnectionError("stop failed")
|
|
184
|
+
|
|
185
|
+
sandbox.stop = fail_stop
|
|
186
|
+
raise ValueError("bad binding")
|
|
187
|
+
|
|
188
|
+
monkeypatch.setattr(toolset, "_bind", fail_binding)
|
|
189
|
+
with pytest.raises(ValueError, match="bad binding"):
|
|
190
|
+
await toolset.__aenter__()
|
|
191
|
+
assert runtime.closed and toolset.sandbox is None and toolset._entered == 0
|