Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ dependencies = [
"langchain-google-genai>=2.0.0",
"langchain-daytona>=0.0.5",
"daytona>=0.100.0,<1",
"langchain-quickjs>=0.3.2",
"langchain-quickjs>=0.4.0",
"langgraph>=1.2.5",
"langgraph-checkpoint-sqlite>=3.1.1",
"langsmith>=0.14.12",
Expand Down
13 changes: 3 additions & 10 deletions src/code-samples/deepagents/dynamic-subagents.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

from deepagents import create_deep_agent
from langchain_quickjs import CodeInterpreterMiddleware
from langchain_quickjs._repl import _Registry
from langchain_quickjs._repl import _Slot, _SlotConfig

# :snippet-start: dynamic-subagents-quickstart-py
from deepagents import create_deep_agent
Expand Down Expand Up @@ -156,15 +156,8 @@

# :remove-start:
def _eval_js(code: str) -> str:
repl = _Registry(
memory_limit=64 * 1024 * 1024,
timeout=5.0,
capture_console=True,
max_stdout_chars=4000,
max_ptc_calls=256,
subagents_enabled=True,
).get("dynamic-subagents-eval-test")
outcome = repl.eval_sync(code, outer_runtime=None)
repl = _Slot("dynamic-subagents-eval-test", _SlotConfig(subagents_enabled=True))
outcome = repl.eval_sync(code)
if outcome.error_type:
msg = outcome.error_message or outcome.error_type
raise AssertionError(msg)
Expand Down
39 changes: 20 additions & 19 deletions src/code-samples/deepagents/interpreters.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from langchain.tools import tool
from langchain_quickjs import CodeInterpreterMiddleware
from langchain_quickjs._ptc import filter_tools_for_ptc
from langchain_quickjs._repl import _Registry
from langchain_quickjs._repl import _Slot, _SlotConfig
from langgraph.checkpoint.memory import MemorySaver

# :snippet-start: interpreters-quickstart-py
Expand All @@ -29,6 +29,16 @@
)
# :snippet-end:

# :snippet-start: interpreters-enable-fs-py
from deepagents import create_deep_agent
from langchain_quickjs import CodeInterpreterMiddleware

agent = create_deep_agent(
model="anthropic:claude-sonnet-4-6",
middleware=[CodeInterpreterMiddleware(fs=True)],
)
# :snippet-end:

# :snippet-start: interpreters-persistence-default-py
from deepagents import create_deep_agent
from langchain_quickjs import CodeInterpreterMiddleware
Expand Down Expand Up @@ -62,20 +72,12 @@ def web_search(query: str) -> str:
return f"results for {query}"


def _registry() -> _Registry:
return _Registry(
memory_limit=64 * 1024 * 1024,
timeout=5.0,
capture_console=True,
max_stdout_chars=4000,
max_ptc_calls=256,
subagents_enabled=False,
)
def _slot(name: str) -> _Slot:
return _Slot(name, _SlotConfig(subagents_enabled=False))


def _eval_js(code: str) -> str:
repl = _registry().get("interpreters-eval-test")
outcome = repl.eval_sync(code, outer_runtime=None)
outcome = _slot("interpreters-eval-test").eval_sync(code)
if outcome.error_type:
msg = outcome.error_message or outcome.error_type
raise AssertionError(msg)
Expand All @@ -86,6 +88,7 @@ def _eval_js(code: str) -> str:
assert CodeInterpreterMiddleware().tools
assert CodeInterpreterMiddleware(ptc=["web_search"]).tools
assert CodeInterpreterMiddleware(mode="thread").tools
assert CodeInterpreterMiddleware(fs=True).tools
persistence_agent = create_deep_agent(
model="anthropic:claude-sonnet-4-6",
checkpointer=MemorySaver(),
Expand All @@ -112,18 +115,16 @@ def _eval_js(code: str) -> str:
)
assert "alpha" in totals_result and "29" in totals_result

repl = _registry().get("interpreters-ptc-test")
repl.install_tools(
filter_tools_for_ptc([web_search], [web_search], self_tool_name="eval"),
)
repl = _slot("interpreters-ptc-test")
ptc_tools = filter_tools_for_ptc([web_search], [web_search], self_tool_name="eval")
ptc_outcome = repl.eval_sync(
"""
const result = await tools.webSearch({
query: "deepagents interpreters",
});
result;
""",
outer_runtime=None,
tools=ptc_tools,
)
assert ptc_outcome.result == "results for deepagents interpreters"

Expand All @@ -139,7 +140,7 @@ def _eval_js(code: str) -> str:

results.join("\\n\\n");
""",
outer_runtime=None,
tools=ptc_tools,
)
assert "retrieval best practices 2025" in (parallel_outcome.result or "")

Expand All @@ -148,7 +149,7 @@ def _eval_js(code: str) -> str:
const paths = ["src/auth.ts", "src/routes/api.ts"];
paths.length;
""",
outer_runtime=None,
tools=ptc_tools,
)
assert task_outcome.result == "2"

Expand Down
60 changes: 56 additions & 4 deletions src/oss/deepagents/interpreters.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import InterpretersPtcCallEvalJs from '/snippets/code-samples/interpreters-ptc-c
import InterpretersEnablePtcPy from '/snippets/code-samples/interpreters-enable-ptc-py.mdx';
import InterpretersEnablePtcJs from '/snippets/code-samples/interpreters-enable-ptc-js.mdx';
import InterpretersPtcParallelEvalJs from '/snippets/code-samples/interpreters-ptc-parallel-eval-js.mdx';
import InterpretersEnableFsPy from '/snippets/code-samples/interpreters-enable-fs-py.mdx';
import InterpretersTaskFanoutEvalJs from '/snippets/code-samples/interpreters-task-fanout-eval-js.mdx';
import InterpretersPersistenceDefaultPy from '/snippets/code-samples/interpreters-persistence-default-py.mdx';
import InterpretersPersistenceCheckpointerPy from '/snippets/code-samples/interpreters-persistence-checkpointer-py.mdx';
Expand Down Expand Up @@ -126,12 +127,19 @@ By default (`mode="thread"`), interpreter state persists across turns in the sam

Code runs against [**QuickJS**](https://github.com/quickjs-ng/quickjs), a lightweight JavaScript runtime. By default, interpreter code has no access to the host filesystem, network, shell, package manager, or clock. It can compute, hold state, and write to `console.log`, `console.warn`, or `console.error`, and nothing more.

Two explicit bridges extend that reach:
Explicit bridges extend that reach:

- **Tools**, through [programmatic tool calling (PTC)](#programmatic-tool-calling-ptc). Provide an allowlist of tools as async functions under the `tools` namespace. These can be the agent's own tools or standalone tools you define and pass in.
- **Subagents**, through [dynamic subagents](/oss/deepagents/dynamic-subagents). When the agent has subagents configured, the interpreter exposes a `task()` global for dispatching them from code.

Programmatic tool calling is off until you [enable it](#enable-ptc). Subagent dispatch through `task()` is on by default whenever the agent has subagents, and you can turn it off. Nothing else crosses the QuickJS boundary.
Programmatic tool calling is off until you [enable it](#enable-ptc). Subagent dispatch through `task()` is on by default whenever the agent has subagents, and you can turn it off.

:::python
A third bridge, [files](#files-fs), gives interpreter code an opt-in `fs` global over the agent's backend. Nothing else crosses the QuickJS boundary.
:::
:::js
Nothing else crosses the QuickJS boundary.
:::

## Programmatic tool calling (PTC)

Expand Down Expand Up @@ -170,6 +178,49 @@ After PTC is enabled, the agent can call the allowlisted tool from interpreter c
</Warning>
:::

:::python
## Files (`fs`)

The `fs` option gives interpreter code a Node-style `fs` global over the agent's [backend](/oss/deepagents/backends), the same files the built-in filesystem tools see. Code can read many files, process them, and write the results without a tool call per file.

<Note>
`fs` requires `langchain-quickjs>=0.4.0`.
</Note>
Comment thread
robin-agent[bot] marked this conversation as resolved.
Resolved

Set `fs=True` to use the backend that `create_deep_agent` gives its file tools:

<InterpretersEnableFsPy />

With another agent factory, such as `create_agent`, pass the backend itself: `CodeInterpreterMiddleware(fs=backend)`. One middleware instance with `fs=True` cannot serve agents with different backends, so create a separate middleware for each such agent.

`fs` functions are async and return promises, as Node's `fs/promises` does. `fs.promises` exposes the same functions:

- **`fs.readFile(path)`**: Return the whole file as a string.
- **`fs.writeFile(path, text)`**: Create or replace a file, creating parent directories.
- **`fs.readdir(dir)`**: List the entry names in one directory.
- **`fs.access(path)`**: Resolve if the path exists, and reject with `ENOENT` otherwise.
- **`fs.rm(path, { recursive, force })`**: Delete a path. A directory requires `recursive: true`, and `force: true` ignores a missing path.

This example totals every report in a directory and writes the summary back to the backend:

```js
const names = await fs.readdir("/reports");
const totals = {};
for (const name of names) {
const { region, revenue } = JSON.parse(await fs.readFile(`/reports/${name}`));
totals[region] = (totals[region] ?? 0) + revenue;
}
await fs.writeFile("/summary/totals.json", JSON.stringify(totals));
totals;
```

`fs` reads and writes UTF-8 text only. Failed calls throw Node errors with a `code` such as `ENOENT`, `EISDIR`, or `EACCES`. Sync functions such as `readFileSync`, along with `stat`, `glob`, `mkdir`, and `appendFile`, throw `ERR_METHOD_NOT_IMPLEMENTED`, and `require` is not available. A file too large for the interpreter's `memory_limit` ends the `eval` call with a `MarshalError`.

<Warning>
`fs` calls the backend directly, not the filesystem tools, so [permissions](/oss/deepagents/permissions) and `interrupt_on` approvals do not apply to it. Interpreter code can read, write, and delete anything the backend can reach. On a `FilesystemBackend` with `virtual_mode=False`, or a local shell backend, that is the host filesystem. Leave `fs` unset for agents that rely on filesystem permissions or approvals, and enable it only for trusted use or with a backend scoped to files the agent may change.
</Warning>
:::

## Dynamic subagents

The following overview below covers when to use dynamic subagents and a minimal `task()` pattern. For configuration, orchestration examples, workflow triggers, and safety notes, see [Dynamic subagents](/oss/deepagents/dynamic-subagents).
Expand Down Expand Up @@ -230,7 +281,7 @@ Every tool you expose through PTC is an outside capability that interpreter code
| Top-level `await` | Yes | Use promises in interpreter code |
| `console.log`, `warn`, `error` capture | Yes | Disable with `capture_console=False` |
| Agent tools | No | Add a PTC allowlist |
| Filesystem access | No | Add the [built-in filesystem tools](/oss/deepagents/overview#virtual-filesystem-access) via the PTC allowlist |
| Filesystem access | No | Set [`fs`](#files-fs), or add the [built-in filesystem tools](/oss/deepagents/overview#virtual-filesystem-access) via the PTC allowlist |
| Network access | No | Expose a specific network tool through PTC |
| Wall-clock or datetime access | No | Expose an explicit time tool if needed |
| Shell commands, package installs, tests, OS-level execution | No | Use a [sandbox backend](/oss/deepagents/sandboxes) |
Expand All @@ -256,7 +307,7 @@ Every tool you expose through PTC is an outside capability that interpreter code

The sandbox runs inside the host process on [wasmtime](https://wasmtime.dev/), so a wasmtime vulnerability is the remaining path out of the sandbox. Keep `wasmtime` updated. For hostile multi-tenant workloads, also run agents in isolated worker processes or containers. For details, see the `quickjs-rs` [Security guide](https://github.com/langchain-ai/quickjs-rs#security).

The sandbox contains the engine, not the capabilities you give it. Interpreter code can call every tool bridged into it, so keep the PTC allowlist narrow.
The sandbox contains the engine, not the capabilities you give it. Interpreter code can call every tool bridged into it and, with `fs`, reach every file the backend can, so keep the PTC allowlist narrow and set `fs` only when code needs files.
</Note>
:::

Expand All @@ -283,6 +334,7 @@ Every tool you expose through PTC is an outside capability that interpreter code
| `ptc` | `None` | Allowlist of tool names or `BaseTool` instances exposed as `tools.*` inside the interpreter. Omit to disable. See [Enable PTC](#enable-ptc). |
| `max_ptc_calls` | `256` | Maximum `tools.*` calls allowed per `eval`. Set to `None` only in trusted environments. See [Programmatic tool calling (PTC)](#programmatic-tool-calling-ptc) and [Security](#security). |
| `subagents` | `True` | Expose the built-in `task()` global when the agent has subagents. Set to `False` to require dispatch through the normal `task` tool. See [Dynamic subagents](#dynamic-subagents). |
| `fs` | `None` | Give interpreter code a Node-style `fs` global over a backend. `True` uses the backend from `create_deep_agent`. See [Files (`fs`)](#files-fs). |
| `mode` | `"thread"` | Control interpreter persistence: `"thread"` (across turns), `"turn"` (within one turn), or `"call"` (fresh REPL per `eval`). See [Persistence](#persistence). |
| `max_snapshot_bytes` | `None` | Drop snapshots larger than this byte limit. Defaults to `memory_limit`. See [Persistence](#persistence). |
:::
Expand Down
71 changes: 71 additions & 0 deletions src/snippets/code-samples/interpreters-enable-fs-py.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
<CodeGroup>
```python Google
from deepagents import create_deep_agent
from langchain_quickjs import CodeInterpreterMiddleware

agent = create_deep_agent(
model="google_genai:gemini-4-hydrogen",
middleware=[CodeInterpreterMiddleware(fs=True)],
)
```

```python OpenAI
from deepagents import create_deep_agent
from langchain_quickjs import CodeInterpreterMiddleware

agent = create_deep_agent(
model="openai:gpt-6.1-sol",
middleware=[CodeInterpreterMiddleware(fs=True)],
)
```

```python Anthropic
from deepagents import create_deep_agent
from langchain_quickjs import CodeInterpreterMiddleware

agent = create_deep_agent(
model="anthropic:claude-sonnet-5",
middleware=[CodeInterpreterMiddleware(fs=True)],
)
```

```python OpenRouter
from deepagents import create_deep_agent
from langchain_quickjs import CodeInterpreterMiddleware

agent = create_deep_agent(
model="openrouter:z-ai/glm-5.2",
middleware=[CodeInterpreterMiddleware(fs=True)],
)
```

```python Fireworks
from deepagents import create_deep_agent
from langchain_quickjs import CodeInterpreterMiddleware

agent = create_deep_agent(
model="fireworks:accounts/fireworks/models/glm-5p2",
middleware=[CodeInterpreterMiddleware(fs=True)],
)
```

```python Baseten
from deepagents import create_deep_agent
from langchain_quickjs import CodeInterpreterMiddleware

agent = create_deep_agent(
model="baseten:zai-org/GLM-5.2",
middleware=[CodeInterpreterMiddleware(fs=True)],
)
```

```python Ollama
from deepagents import create_deep_agent
from langchain_quickjs import CodeInterpreterMiddleware

agent = create_deep_agent(
model="ollama:north-mini-code-1.0",
middleware=[CodeInterpreterMiddleware(fs=True)],
)
```
</CodeGroup>
Loading
Loading