smolagents-pilldrops 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.
@@ -0,0 +1,6 @@
1
+ __pycache__/
2
+ *.pyc
3
+ *.egg-info/
4
+ build/
5
+ dist/
6
+ .pytest_cache/
@@ -0,0 +1,66 @@
1
+ Metadata-Version: 2.5
2
+ Name: smolagents-pilldrops
3
+ Version: 0.1.0
4
+ Summary: PillDrops sandboxes for smolagents CodeAgent
5
+ Project-URL: Homepage, https://pilldrops.com
6
+ Project-URL: Repository, https://github.com/pilldrops-oss/pilldrops-integrations
7
+ License-Expression: MIT
8
+ Requires-Python: >=3.10
9
+ Requires-Dist: pilldrops>=1.6.0
10
+ Requires-Dist: smolagents<2.0.0,>=1.26.0
11
+ Description-Content-Type: text/markdown
12
+
13
+ # smolagents-pilldrops
14
+
15
+ [PillDrops](https://pilldrops.com) sandboxes for [smolagents](https://github.com/huggingface/smolagents).
16
+ A `CodeAgent`'s Python runs in a PillDrops cloud sandbox, and variables carry over between
17
+ steps the way they do in a notebook.
18
+
19
+ ## Install
20
+
21
+ ```bash
22
+ pip install smolagents-pilldrops
23
+ export PILLDROPS_API_KEY=sf_live_... # from https://pilldrops.com/dashboard
24
+ ```
25
+
26
+ ## Use
27
+
28
+ ```python
29
+ from smolagents import CodeAgent, LiteLLMModel
30
+
31
+ from smolagents_pilldrops import PillDropsExecutor
32
+
33
+ executor = PillDropsExecutor(additional_imports=["requests"])
34
+ try:
35
+ agent = CodeAgent(
36
+ tools=[],
37
+ model=LiteLLMModel(model_id="anthropic/claude-opus-5-5"),
38
+ executor=executor,
39
+ )
40
+ print(agent.run("How many of the first 40 Fibonacci numbers are even?"))
41
+ finally:
42
+ executor.cleanup() # deletes the sandbox
43
+ ```
44
+
45
+ ## Options
46
+
47
+ | Argument | Default | Meaning |
48
+ |---|---|---|
49
+ | `additional_imports` | `[]` | Packages to pip install in the sandbox |
50
+ | `template` | `code-interpreter` | Any [PillDrops template](https://pilldrops.com/templates) with `python3` |
51
+ | `timeout` | `300` | Seconds each code step may run |
52
+ | `sandbox` | none | Use an existing `pilldrops.Sandbox`; `cleanup()` then leaves it running |
53
+ | other keywords | | Passed to `Sandbox.create`, e.g. `timeout=1800` for the sandbox lifetime |
54
+
55
+ ## How it works
56
+
57
+ The executor starts a small Python process in the sandbox (`kernel.py`, standard library
58
+ only) that keeps one namespace for the whole run. Each step's code is sent to it, and the reply
59
+ carries the printed output, the value of a trailing expression, or the error with its
60
+ traceback. `final_answer(...)` ends the run as with smolagents' other remote executors.
61
+
62
+ Images returned as a step's value are shown as their text form.
63
+
64
+ ## License
65
+
66
+ MIT
@@ -0,0 +1,54 @@
1
+ # smolagents-pilldrops
2
+
3
+ [PillDrops](https://pilldrops.com) sandboxes for [smolagents](https://github.com/huggingface/smolagents).
4
+ A `CodeAgent`'s Python runs in a PillDrops cloud sandbox, and variables carry over between
5
+ steps the way they do in a notebook.
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ pip install smolagents-pilldrops
11
+ export PILLDROPS_API_KEY=sf_live_... # from https://pilldrops.com/dashboard
12
+ ```
13
+
14
+ ## Use
15
+
16
+ ```python
17
+ from smolagents import CodeAgent, LiteLLMModel
18
+
19
+ from smolagents_pilldrops import PillDropsExecutor
20
+
21
+ executor = PillDropsExecutor(additional_imports=["requests"])
22
+ try:
23
+ agent = CodeAgent(
24
+ tools=[],
25
+ model=LiteLLMModel(model_id="anthropic/claude-opus-5-5"),
26
+ executor=executor,
27
+ )
28
+ print(agent.run("How many of the first 40 Fibonacci numbers are even?"))
29
+ finally:
30
+ executor.cleanup() # deletes the sandbox
31
+ ```
32
+
33
+ ## Options
34
+
35
+ | Argument | Default | Meaning |
36
+ |---|---|---|
37
+ | `additional_imports` | `[]` | Packages to pip install in the sandbox |
38
+ | `template` | `code-interpreter` | Any [PillDrops template](https://pilldrops.com/templates) with `python3` |
39
+ | `timeout` | `300` | Seconds each code step may run |
40
+ | `sandbox` | none | Use an existing `pilldrops.Sandbox`; `cleanup()` then leaves it running |
41
+ | other keywords | | Passed to `Sandbox.create`, e.g. `timeout=1800` for the sandbox lifetime |
42
+
43
+ ## How it works
44
+
45
+ The executor starts a small Python process in the sandbox (`kernel.py`, standard library
46
+ only) that keeps one namespace for the whole run. Each step's code is sent to it, and the reply
47
+ carries the printed output, the value of a trailing expression, or the error with its
48
+ traceback. `final_answer(...)` ends the run as with smolagents' other remote executors.
49
+
50
+ Images returned as a step's value are shown as their text form.
51
+
52
+ ## License
53
+
54
+ MIT
@@ -0,0 +1,19 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "smolagents-pilldrops"
7
+ version = "0.1.0"
8
+ description = "PillDrops sandboxes for smolagents CodeAgent"
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ requires-python = ">=3.10"
12
+ dependencies = ["smolagents>=1.26.0,<2.0.0", "pilldrops>=1.6.0"]
13
+
14
+ [project.urls]
15
+ Homepage = "https://pilldrops.com"
16
+ Repository = "https://github.com/pilldrops-oss/pilldrops-integrations"
17
+
18
+ [tool.hatch.build.targets.wheel]
19
+ packages = ["smolagents_pilldrops"]
@@ -0,0 +1,5 @@
1
+ """PillDrops sandboxes for smolagents."""
2
+
3
+ from smolagents_pilldrops.executor import PillDropsExecutor
4
+
5
+ __all__ = ["PillDropsExecutor"]
@@ -0,0 +1,92 @@
1
+ """PillDrops executor for smolagents' CodeAgent."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import shlex
7
+ import time
8
+ import uuid
9
+ from pathlib import Path
10
+
11
+ from pilldrops import Sandbox
12
+ from smolagents.monitoring import AgentLogger, LogLevel
13
+ from smolagents.remote_executors import RemotePythonExecutor
14
+ from smolagents.utils import AgentError
15
+ from smolagents.local_python_executor import CodeOutput
16
+
17
+ _KERNEL_SOURCE = (Path(__file__).parent / "kernel.py").read_text()
18
+ _KERNEL = ".pilldrops-kernel.py"
19
+
20
+
21
+ class PillDropsExecutor(RemotePythonExecutor):
22
+ """Runs a CodeAgent's code in a PillDrops sandbox. Variables persist between steps.
23
+
24
+ Args:
25
+ additional_imports: Python packages to pip install in the sandbox.
26
+ logger: smolagents logger; a default one is made when omitted.
27
+ allow_pickle: See `RemotePythonExecutor`; keep `False` unless you trust the sandbox output.
28
+ sandbox: An existing sandbox to use. When omitted, one is created and deleted by `cleanup()`.
29
+ template: Template for a created sandbox.
30
+ timeout: Seconds each code step may run.
31
+ **create_kwargs: Passed to `pilldrops.Sandbox.create`, e.g. `timeout=1800` for the sandbox lifetime.
32
+ """
33
+
34
+ def __init__(
35
+ self,
36
+ additional_imports: list[str] | None = None,
37
+ logger: AgentLogger | None = None,
38
+ allow_pickle: bool = False,
39
+ *,
40
+ sandbox: Sandbox | None = None,
41
+ template: str = "code-interpreter",
42
+ timeout: int = 300,
43
+ **create_kwargs,
44
+ ):
45
+ super().__init__(additional_imports or [], logger or AgentLogger(level=LogLevel.INFO), allow_pickle)
46
+ self._owns_sandbox = sandbox is None
47
+ self.sandbox = sandbox or Sandbox.create(template, **create_kwargs)
48
+ self.timeout = timeout
49
+ self._start_kernel()
50
+ self.installed_packages = self.install_packages(self.additional_imports)
51
+ self.logger.log(f"PillDrops sandbox {self.sandbox.id} is running", level=LogLevel.INFO)
52
+
53
+ def _start_kernel(self) -> None:
54
+ self.sandbox.files.write(_KERNEL, _KERNEL_SOURCE)
55
+ self.sandbox.run(f"nohup python3 {_KERNEL} serve > .pilldrops-kernel.log 2>&1 &")
56
+ for _ in range(50):
57
+ if self.sandbox.run("test -S /tmp/pilldrops-kernel.sock").exit_code == 0:
58
+ return
59
+ time.sleep(0.2)
60
+ raise RuntimeError(f"the Python kernel did not start in sandbox {self.sandbox.id}")
61
+
62
+ def install_packages(self, additional_imports: list[str]) -> list[str]:
63
+ if additional_imports:
64
+ result = self.sandbox.run(
65
+ f"python3 -m pip install -q {' '.join(shlex.quote(p) for p in additional_imports)}", timeout=600
66
+ )
67
+ self.logger.log(result.stdout + result.stderr)
68
+ return additional_imports
69
+
70
+ def run_code_raise_errors(self, code: str) -> CodeOutput:
71
+ path = f".pilldrops-step-{uuid.uuid4().hex}.py"
72
+ self.sandbox.files.write(path, code)
73
+ result = self.sandbox.run(f"python3 {_KERNEL} run {path}", timeout=self.timeout)
74
+ if result.exit_code != 0:
75
+ raise AgentError(f"Executing code failed in the sandbox:\n{result.stderr or result.stdout}", self.logger)
76
+ reply = json.loads(result.stdout)
77
+ logs, error = reply["logs"], reply["error"]
78
+ if error:
79
+ if error["name"] == RemotePythonExecutor.FINAL_ANSWER_EXCEPTION:
80
+ answer = self._deserialize_final_answer(error["value"], self.allow_pickle)
81
+ return CodeOutput(output=answer, logs=logs, is_final_answer=True)
82
+ raise AgentError(
83
+ f"{logs}\nExecuting code yielded an error:\n{error['name']}\n{error['value']}\n{error['traceback']}",
84
+ self.logger,
85
+ )
86
+ return CodeOutput(output=reply["result"], logs=logs, is_final_answer=False)
87
+
88
+ def cleanup(self) -> None:
89
+ """Delete the sandbox if this executor created it."""
90
+ if self._owns_sandbox and getattr(self, "sandbox", None) is not None:
91
+ self.sandbox.kill()
92
+ self.sandbox = None
@@ -0,0 +1,75 @@
1
+ """A minimal persistent Python kernel that runs inside the sandbox.
2
+
3
+ `python3 kernel.py serve` keeps one namespace alive and listens on a Unix socket.
4
+ `python3 kernel.py run <file>` sends that file's code to it and prints the JSON reply:
5
+ {"logs": ..., "result": repr of a trailing expression or null, "error": {name, value, traceback} or null}.
6
+ Standard library only, so it runs on any template with python3.
7
+ """
8
+
9
+ import ast
10
+ import contextlib
11
+ import io
12
+ import json
13
+ import os
14
+ import socket
15
+ import sys
16
+ import traceback
17
+
18
+ SOCKET_PATH = "/tmp/pilldrops-kernel.sock"
19
+
20
+
21
+ def execute(code, namespace):
22
+ out = io.StringIO()
23
+ try:
24
+ tree = ast.parse(code)
25
+ last = tree.body.pop() if tree.body and isinstance(tree.body[-1], ast.Expr) else None
26
+ result = None
27
+ with contextlib.redirect_stdout(out), contextlib.redirect_stderr(out):
28
+ exec(compile(tree, "<code>", "exec"), namespace)
29
+ if last is not None:
30
+ value = eval(compile(ast.Expression(last.value), "<code>", "eval"), namespace)
31
+ if value is not None:
32
+ result = repr(value)
33
+ return {"logs": out.getvalue(), "result": result, "error": None}
34
+ except BaseException as e: # the agent's code may raise anything, including SystemExit
35
+ return {
36
+ "logs": out.getvalue(),
37
+ "result": None,
38
+ "error": {"name": type(e).__name__, "value": str(e), "traceback": traceback.format_exc()},
39
+ }
40
+
41
+
42
+ def _read_all(conn):
43
+ chunks = []
44
+ while chunk := conn.recv(65536):
45
+ chunks.append(chunk)
46
+ return b"".join(chunks)
47
+
48
+
49
+ def serve():
50
+ with contextlib.suppress(FileNotFoundError):
51
+ os.unlink(SOCKET_PATH)
52
+ namespace = {"__name__": "__main__"}
53
+ server = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
54
+ server.bind(SOCKET_PATH)
55
+ server.listen()
56
+ while True:
57
+ conn, _ = server.accept()
58
+ with conn:
59
+ reply = execute(_read_all(conn).decode(), namespace)
60
+ conn.sendall(json.dumps(reply).encode())
61
+
62
+
63
+ def run(path):
64
+ with open(path) as f:
65
+ code = f.read()
66
+ os.unlink(path)
67
+ client = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
68
+ client.connect(SOCKET_PATH)
69
+ client.sendall(code.encode())
70
+ client.shutdown(socket.SHUT_WR)
71
+ sys.stdout.write(_read_all(client).decode())
72
+
73
+
74
+ if __name__ == "__main__":
75
+ serve() if sys.argv[1] == "serve" else run(sys.argv[2])
@@ -0,0 +1,63 @@
1
+ """PillDropsExecutor against a stand-in sandbox that runs commands in a local directory."""
2
+ import subprocess
3
+
4
+ import pytest
5
+ from pilldrops import ExecResult
6
+ from smolagents.default_tools import FinalAnswerTool
7
+ from smolagents.utils import AgentError
8
+
9
+ from smolagents_pilldrops import PillDropsExecutor
10
+ from smolagents_pilldrops.kernel import execute
11
+
12
+
13
+ def test_kernel_keeps_state_and_returns_the_trailing_expression():
14
+ ns = {"__name__": "__main__"}
15
+ assert execute("x = 6\nprint('set')", ns) == {"logs": "set\n", "result": None, "error": None}
16
+ assert execute("x * 7", ns)["result"] == "42"
17
+ err = execute("1 / 0", ns)["error"]
18
+ assert err["name"] == "ZeroDivisionError" and "Traceback" in err["traceback"]
19
+
20
+
21
+ class _LocalFiles:
22
+ def __init__(self, home):
23
+ self._home = home
24
+
25
+ def write(self, path, content):
26
+ (self._home / path).write_bytes(content.encode() if isinstance(content, str) else content)
27
+
28
+
29
+ class _LocalSandbox:
30
+ id = "sb-local"
31
+
32
+ def __init__(self, home):
33
+ self._home = home
34
+ self.files = _LocalFiles(home)
35
+
36
+ def run(self, cmd, cwd="", timeout=60, env=None):
37
+ p = subprocess.run(["sh", "-c", cmd], cwd=self._home, capture_output=True, text=True, timeout=timeout)
38
+ return ExecResult(p.stdout, p.stderr, p.returncode, False)
39
+
40
+
41
+ @pytest.fixture
42
+ def executor(tmp_path):
43
+ ex = PillDropsExecutor(sandbox=_LocalSandbox(tmp_path))
44
+ yield ex
45
+ subprocess.run(["pkill", "-f", "[.]pilldrops-kernel.py serve"])
46
+
47
+
48
+ def test_steps_share_variables(executor):
49
+ executor.run_code_raise_errors("total = sum(range(10))")
50
+ out = executor.run_code_raise_errors("print('ok'); total")
51
+ assert (out.output, out.logs, out.is_final_answer) == ("45", "ok\n", False)
52
+
53
+
54
+ def test_errors_raise_agent_error(executor):
55
+ with pytest.raises(AgentError, match="NameError"):
56
+ executor.run_code_raise_errors("undefined_name")
57
+
58
+
59
+ def test_final_answer_is_detected(executor):
60
+ executor.installed_packages = ["pillow", "numpy"] # the tool's requirements; nothing to install here
61
+ executor.send_tools({"final_answer": FinalAnswerTool()})
62
+ out = executor.run_code_raise_errors("final_answer({'n': 3})")
63
+ assert out.is_final_answer and out.output == {"n": 3}