Give your agent an interpreter: Deep Agents and QuickJS

Give your agent an interpreter: Deep Agents and QuickJS
up to 35%fewer tokens on some tasks, in LangChain's early testing
3context surfaces: message history, filesystem, and interpreter state
0capabilities by default: no files, no network, no shell, no packages, no clock
1line to add it: a middleware when you create the agent
Give your agent an interpreter
I also explain it in this video, on my channel Articulator EN.

What's an interpreter?link

An interpreter is a small embedded runtime that the agent writes code against while it's working. In practice, it feels like giving it a Python or Node REPL: it can define variables, inspect values, write helper functions, and reuse all of that from one call to the next.

Plenty of agents already run code by sending commands to a host or a sandbox, and that's great for environment-level work: running programs, installing dependencies, or moving around a filesystem. The interpreter targets a different layer: the code runs inside the agent loop itself, to coordinate subagents, compose tool calls, transform structured data, and decide what information goes back to the model.

The article's example is tiny. The agent writes a few lines of JavaScript with three teams and their tickets:

const rows = [
  { team: "support", tickets: 18 },
  { team: "infra", tickets: 7 },
  { team: "sales", tickets: 11 },
];
const total = rows.reduce((sum, row) => sum + row.tickets, 0);
const busiest = rows.sort((a, b) => b.tickets - a.tickets)[0];
`${busiest.team} has the most tickets. ${total} tickets total.`;

What comes back to the model is a single sentence: support has the most tickets, 36 in total. The interpreter holds the temporary state and returns only the part that matters; the model never has to see each row.

The tickets code in the interpreter and the single sentence that goes back to the model.
The interpreter does the math; only the result reaches the model.

Where it fitslink

When we picture an agent, we picture giving it tools. In its simplest form it uses them in a loop: the model calls a tool, looks at what comes back, and decides the next step. That step-by-step style is easy to debug and evaluate, and many workflows need it, because you have to reason over each observation.

Sandboxes go further: they give the agent a bash tool against a real environment, where it can run commands, install dependencies, and work with files. Since it can write code, it can handle any local procedure on its own.

Both ends have downsides:

  • Sandboxes are harder to provision and scale.
  • Serial tool loops get awkward when intermediate steps only feed the next one: every full result goes through the model, even when it has nothing to decide about it.

Some agent work lives between those two extremes, and that's where the interpreter slots in. It gives the agent code-level composition over scoped capabilities without handing it a whole environment: the model writes a small program with the control flow, and the harness decides which capabilities are within reach. Instead of model → tool → full result → model, the model calls eval once, the code fires off several tools, and a computed result comes back.

Typical tool loop versus interpreter loop: one eval call, several tools, and a computed result.
On the left, every full result goes back to the model; on the right, only the computed result.

Limited by designlink

LangChain calls it an interpreter, and not just a code runtime, because it's limited on purpose. By default it has no filesystem, no network, no shell, no package installs, and no wall-time access. It starts with only control flow and object manipulation: objects, arrays, maps, JSON, and not much else.

The interpreter starts without files, network, shell, packages, or clock.
Just the language: everything else has to be granted.

Everything else arrives through explicit bridges to the host runtime, the same one that runs the harness. If the agent needs to call a tool, read from a scoped filesystem, fetch a page, or delegate to a subagent, the harness has to expose that capability deliberately. This code only works because someone wired fetch, readFile, and task into the interpreter:

const response = tools.fetch("https://docs.langchain.com");
const file = tools.readFile("SPEC.md");
const subagentOutput = tools.task({
  description: "Do you know the muffin man?"
});

The article sums it up in a table:

  • Filesystem: not available; if you need it, expose a scoped file API.
  • Network: not available; expose specific fetch or API tools.
  • Shell: not available; use a sandbox instead.
  • Packages: not available; preload approved helpers or use a sandbox.
  • Agent tools: not available automatically; add them to the PTC allowlist.
  • Subagents: not available automatically; allowlist the task tool.
Capability table: not available by default, and what to do if you need it.
Every capability crosses a bridge you choose.

Why do it this way? Two reasons:

  1. A smaller action surface. With bash or a sandbox you start from something shaped like a computer and take things away; with an interpreter you start from a language and add capabilities back one by one. Mind you, it doesn't replace sandboxing if your threat model needs process or VM isolation. But the agent no longer inherits broad host access by default.
  2. Predictability. With broad access or a huge library, the same goal could be reached through many strategies, and results would be less consistent and harder to test. With a minimal environment, the action space is narrower, failure modes are clearer, and results are more repeatable.

According to the author, it's the same shape you see in systems from Figma, Shopify, or AWS: constrained code on one side, and a controlled boundary on the other.

State as contextlink

Several recent systems have landed on similar patterns: Cloudflare's Code Mode, Anthropic's Programmatic Tool Calling (PTC), and RLM-style workflows. In Deep Agents, the interpreter is how you get that pattern with any model. The article covers four uses.

The first: interpreter state as a context surface. Harnesses already split context across two places:

  • Message history is what the model has in front of it. It's expensive and attention-constrained: a model accepting a million tokens doesn't mean it reasons equally well over all of them (so-called context rot).
  • The filesystem stores durable notes and artifacts. It's flexible, but it forces the agent to serialize working state into files and rebuild it later.

Interpreter state is a third option. Values stay alive in the runtime (arrays, objects, maps, counters, queues, and helper functions), and the model doesn't have to see them as prompt text, though it can ask for them to be inspected or reused later. It's what happens in an interactive console: define a variable and it's still there on the next command, without printing it, saving it, or rebuilding it.

The three context surfaces: message history, filesystem, and interpreter state.
History for reasoning now, files for durable artifacts, interpreter state for live values.

Tools from codelink

The second use is programmatic tool calling (PTC): tools are invoked from the code the agent writes, not as a chain of actions that go through the model. If the model calls a tool, gets the full result, thinks about it, and moves to the next one, every step is another round trip. If the code invokes them instead, intermediate outputs stay inside and only the final result comes back.

In Deep Agents, PTC doesn't depend on the model provider: it's middleware. The developer passes an allowlist, those tools show up under the tools namespace, and each one is an async function the interpreter calls with await. That's why it works with any model, open ones included. In this example the code launches three subagents at once, one per topic:

const topics = ["retrieval", "memory", "evaluation"];
const reports = await Promise.all(
  topics.map((topic) =>
    tools.task({
      description: `Research ${topic} in Deep Agents and return three concise findings.`,
      subagent_type: "general-purpose",
    }),
  ),
);
reports.join("\n\n");

The trace in the article shows the three tasks running in parallel inside a single eval call, about 3.5 seconds each.

Three subagents launched in parallel from the interpreter with tools.task.
Three subagents at once, from a single eval call.

How much does it save? In early testing, on tasks from the OOLONG dataset (trec-coarse), LangChain measured up to 35% fewer tokens on some tasks. Their table:

  • Claude Opus: from 831,414 to 538,349 tokens (−35%); agent steps from 4.67 to 3.67; median latency from 14.5 to 13.3 s.
  • Claude Sonnet: from 794,182 to 595,751 tokens (−25%); steps from 4.59 to 3.44; but median latency goes up, from 8.6 to 10.7 s.

So: fewer tokens and fewer steps in both, but not always faster. The article doesn't discuss latency; that's my reading of its table.

Tokens with and without the interpreter for Claude Opus and Claude Sonnet.
Up to 35% fewer tokens with Opus and 25% with Sonnet, in early testing.

Data at scale and recursionlink

The third use is working over large datasets. Imagine the agent has to classify, extract, or summarize information from 10,000 documents (an example in the article, not an experiment). With standard tool calling you get a long chain: search, get results back into context, decide what to look at, and start over. At that scale it breaks down:

  • It's hard to verify the agent followed the intended procedure.
  • Too much intermediate context flows through the model.
  • You hit latency, context, or tool-call limits.
  • The answer degrades, because the model has to manage too much working state through history.

With an interpreter, the model writes code that keeps the documents and search state in the runtime, walks through batches, scores and filters candidates, and only calls subagents on the selected slices:

const candidates = documents
  .map((doc) => ({ doc, score: scoreDocument(doc, query) }))
  .filter(({ score }) => score > 0.75)
  .sort((a, b) => b.score - a.score)
  .slice(0, 10);

Then it launches a subagent for each of the top ten, and what comes back to the model is a compact evidence set: the matching documents, the extracted fields, the unresolved cases, or the few summaries worth reasoning over. And the author is clear: the interpreter isn't magically reasoning over all 10,000 documents; it gives the agent a better way to control the search space and decide what enters context.

From 10,000 documents to the top ten, with one subagent each.
Score, filter, keep ten, and delegate.

The fourth use is recursive orchestration. Recursive Language Models (RLMs) treat a long prompt as part of an external REPL and let the model write code to inspect it, break it down, and recursively call models over selected snippets. Deep Agents doesn't implement RLMs at the model layer, but at the harness level the idea is similar: through the tools.task bridge, the code picks a slice of work, hands it to a subagent, combines it with what it already has, and returns only the synthesis to the main model.

How it works insidelink

In the harness, the interpreter is middleware between the agent loop and a small runtime. That middleware:

  • adds an eval tool to the agent;
  • creates and maintains a QuickJS context;
  • runs the agent's TypeScript code;
  • captures console.log output when configured;
  • returns the final expression to the model.

eval doesn't mean "run arbitrary code on the host": the code runs inside the interpreter and only gets out through the bridges. The flow looks like this:

  1. The model writes code and calls eval.
  2. QuickJS evaluates it inside the interpreter.
  3. If needed, the code calls allowlisted tools.
  4. The host runtime executes the real tool calls.
  5. Results cross back into the interpreter.
  6. The final expression crosses back into the model's context.
The path of an eval call: model, QuickJS, allowlisted tools, host, and back to the model.
From the model to the interpreter, from the interpreter to the host, and back.

Repeated eval calls in a run share the same live context, which is why values behave like REPL state. Snapshotting between conversation turns is also available, but only for serializable data, not live handles or host resources. The runtime controls live at that boundary too: memory limit, per-eval timeout, maximum programmatic tool calls, maximum result size, console capture, and snapshots between turns.

The interpreter's controls: memory, per-eval timeout, tool calls, result size, console, and snapshots.
The limits live at the boundary.

How to use itlink

You install Deep Agents with the QuickJS extra and add the middleware when you create the agent. In Python:

uv add "deepagents[quickjs]"

from deepagents import create_deep_agent
from langchain_quickjs import CodeInterpreterMiddleware

agent = create_deep_agent(
    model="openai:gpt-5.5",
    middleware=[CodeInterpreterMiddleware(ptc=["task"])],
)

And in TypeScript:

pnpm install deepagents @langchain/quickjs

import { createDeepAgent } from "deepagents";
import { createCodeInterpreterMiddleware } from "@langchain/quickjs";

const agent = createDeepAgent({
  model: "openai:gpt-5.5",
  middleware: [createCodeInterpreterMiddleware({ ptc: ["task"] })],
});

Without ptc, the interpreter sees no tools: you choose which ones cross the bridge. With the allowlist, they show up under tools as async functions, and the model gets the interpreter's final output rather than every intermediate tool result.

In shortlink

An interpreter gives the agent a place to program between calls. It starts with nothing, gets only the bridges you decide, keeps state out of the context, and returns only what matters. It doesn't replace a sandbox when you need isolation, but it covers the work that lives between single tool calls and a whole machine.

In one sentence

Not a whole machine, not one tool after another: a small language with just the right bridges.

Sourceslink

Continue reading

Last posts -->

Have you seen these projects?

Gymnasia

Gymnasia Gymnasia
Expo
React Native
TypeScript
OpenAI
Anthropic

Fitness app with two agents that run entirely on the device, with no backend, so the user's data never leaves the phone. A BYOK conversational coach with local tools and a remote system prompt with offline fallback, plus a food estimator that pulls macronutrients out of a photo of the plate, with barcode scanning against OpenFoodFacts.

LangGraph Deep Researcher

LangGraph Deep Researcher LangGraph Deep Researcher
Python
LangGraph
FastAPI
React
TypeScript
Docker

Multi-agent research system built with LangGraph. A supervisor breaks your question down into topics and launches search sub-agents in parallel; each one compresses its findings before handing them to a writer agent that produces the final sourced markdown report. Live streaming over WebSockets, a configurable model per role and bring-your-own API keys that are never persisted server-side.

Tau

Tau Tau
Python
LangChain

Multi-agent tutoring system for secondary school students, with one agent per subject and course material written and validated by a team of teachers. It was used with real students at a private school in Spain and at a secondary school in Colombia.

View all projects -->
>_ Available for projects

Do you have an AI project?

Let's talk.

maximofn@gmail.com

Machine Learning and AI specialist. I develop solutions with generative AI, intelligent agents and custom models.

Do you want to watch any talk?

Last talks -->

Do you want to improve with these tips?

Last tips -->

Use this locally

Hugging Face spaces allow us to run models with very simple demos, but what if the demo breaks? Or if the user deletes it? That's why I've created docker containers with some interesting spaces, to be able to use them locally, whatever happens. In fact, if you click on any project view button, it may take you to a space that doesn't work.

Flow edit

Flow edit Flow edit

FLUX.1-RealismLora

FLUX.1-RealismLora FLUX.1-RealismLora
View all containers -->
>_ Available for projects

Do you have an AI project?

Let's talk.

maximofn@gmail.com

Machine Learning and AI specialist. I develop solutions with generative AI, intelligent agents and custom models.

Do you want to train your model with these datasets?

short-jokes-dataset

HuggingFace

Dataset with jokes in English

Use: Fine-tuning text generation models for humor

231K rows 2 columns 45 MB
View on HuggingFace →

opus100

HuggingFace

Dataset with translations from English to Spanish

Use: Training English-Spanish translation models

1M rows 2 columns 210 MB
View on HuggingFace →

netflix_titles

HuggingFace

Dataset with Netflix movies and series

Use: Netflix catalog analysis and recommendation systems

8.8K rows 12 columns 3.5 MB
View on HuggingFace →
View more datasets -->