About this notebook
Companion to Module 8: Code execution and skills. Every cell below was executed with the offline backend, so you can reproduce these outputs exactly with no API key. Download the notebook (.ipynb)
Notebook 8a gave the model a Python interpreter. This one gives it a place to work: a folder with files it can list, read, write and run commands in, and a way to install new know-how into that folder without growing its prompt. You will
- open a workspace: one directory and four tools (
list_files,read_file,write_file,run_command); - keep the agent inside it: refuse
.., absolute paths and symlinks that point out; - watch an agent solve a data question by writing and running its own script;
- package instructions and scripts as skills, folders with a
SKILL.mdfile; - measure progressive disclosure: what the prompt costs when only skill names are listed and the rest loads on demand;
- run an agent that picks a skill, loads it and follows it.
Which model answers here?
With no
MODELset, the offline policy model answers. It is a set of deterministic rules, not a language model: it chooses a skill by counting words shared between the question and each skill’s description, and it writes its script from a template. A real model chooses by meaning and writes its own code, so it can pick a better skill or a wrong one. The files, the path checks and the sandboxed commands are real. SetMODELand re-run to see a real model’s choices.
from agentlab.nbsetup import setup
nb = setup("08b_workspace_skills", packs=["skills"])
llm = nb.llmLLM backend
offline policy model (deterministic, rule-based, no API key used)
1. A workspace: files, a shell and code
A workspace is what a developer has at a terminal: a project folder, a shell and an interpreter. Hur and Song argue that for an agent this combination replaces a long tail of special-purpose tools, since listing, searching, converting and computing are all a short command or a few lines of Python away.
list_files read_file write_file run_command
| | | |
+------------+-----+------+ |
| |
path check: inside root? LocalSandbox (8a):
| cwd = root, limits,
v macOS jail
+--------------------------------------------+
| workspace root: README.md data/orders.csv |
+--------------------------------------------+Workspace.from_copy copies a fixture folder into this notebook’s work directory, so the
agent can change the copy freely and every run starts from the same files.
from agentlab.config import repo_root
from agentlab.workspace import Workspace
FIXTURES = repo_root() / "fixtures"
ws = Workspace.from_copy(FIXTURES / "workspace", nb.workdir / "ws")
print(ws.list_files())
print()
print(ws.read_file("README.md"))README.md (270 bytes) data/ data/orders.csv (1003 bytes) # Shop analytics workspace `data/orders.csv` holds one row per order placed in September 2026 (24 orders, four regions). Amounts are in euros and already include the quantity. Scripts written for this workspace go in the top folder; nothing here is real customer data.
The four tools are bound methods of the workspace, so the model never sees or chooses the root folder; it only names paths relative to it.
for t in ws.tools():
params = t.tool_definition["function"]["parameters"]["properties"]
print(f"{t.name}({', '.join(params)}): {t.description}")list_files(path): List the files under a folder of the workspace, with their sizes in bytes. read_file(path): Read a text file in the workspace (long files are cut). write_file(path, content): Create or overwrite a text file in the workspace. run_command(command): Run a shell command in the workspace root (sandboxed) and return its output.
2. Staying inside the folder
The file tools resolve every path before touching the disk: .. is collapsed, symlinks are
followed, and the result must still lie inside the root. Checking the string (does it
contain ..?) is not enough, because a symlink inside the workspace can point anywhere. To
test that, put a file next to the workspace and a link to it inside.
from agentlab.workspace import PathEscape
secret = nb.workdir / "secret.txt"
secret.write_text("for the notebook only\n")
link = ws.root / "shortcut.txt"
link.unlink(missing_ok=True)
link.symlink_to(secret)
for path in ["data/orders.csv", "data/../README.md", "../secret.txt", "/etc/hosts",
"shortcut.txt"]:
try:
ws.resolve(path)
print(f"{path:<20} allowed")
except PathEscape as exc:
print(f"{path:<20} refused: {exc}")
link.unlink()data/orders.csv allowed data/../README.md allowed ../secret.txt refused: '../secret.txt' is outside the workspace; use a path relative to its root /etc/hosts refused: '/etc/hosts' is outside the workspace; use a path relative to its root shortcut.txt refused: 'shortcut.txt' is outside the workspace; use a path relative to its root
The refusal is an ordinary exception, so inside an agent it becomes an error observation
with a hint (use a relative path), not a crash. The shell is a different matter: a command
can name any path, and no string check on cat ../secret.txt is reliable. run_command
therefore relies on the sandbox from Notebook 8a, whose kernel policy on macOS hides the
home folder outside the workspace and refuses writes outside it.
from agentlab.sandbox import jail
out = await ws.run_command("cat ../secret.txt; echo written > ../escape.txt")
if jail.available():
print(out)
print("escape.txt exists:", (nb.workdir / "escape.txt").exists())
else:
print("no sandbox-exec here:", ws.sandbox.isolation)exit code 1 stderr: cat: ../secret.txt: Operation not permitted /bin/sh: ../escape.txt: Operation not permitted escape.txt exists: False
Two checks for two kinds of access: a path check for the file tools, where the path is a separate argument, and an operating-system jail for the shell, where it is not.
3. An agent at work
Give an agent the four tools and a question that needs a small computation. With no “count rows” or “sum column” tool, it has to look at the data, write a script and run it.
from agentlab import Agent
from agentlab.display import show_trajectory
WS_PROMPT = ("You work inside a project folder. Use the tools to look at files, write "
"scripts and run commands. Answer from what the tools return.")
worker = Agent(llm, tools=ws.tools(), instructions=WS_PROMPT, max_steps=10, name="worker")
result = await worker.run("How many orders are in data/orders.csv, and what is the "
"total amount?")
show_trajectory(result, width=84)
print("\nanswer:", result.output)[user] How many orders are in data/orders.csv, and what is the total amount?
[worker -> list_files] {"path": "."}
[list_files ok] README.md (270 bytes) data/ data/orders.csv (1003 bytes)
[worker -> read_file] {"path": "data/orders.csv"}
[read_file ok] order_id,date,region,product,qty,amount_eur A-1001,2026-09-01,east,keyboard,4,182...
[worker -> write_file] {"path": "order_totals.py", "content": "import csv\n\nwith open('data/orders.csv'...
[write_file ok] wrote 221 bytes to order_totals.py
[worker -> run_command] {"command": "python order_totals.py"}
[run_command ok] exit code 0 stdout: orders: 24 total amount_eur: 4929.40
[worker] From the script I wrote and ran (order_totals.py): orders: 24; total amount_eur: ...
--- status: complete, steps: 5
answer: From the script I wrote and ran (order_totals.py): orders: 24; total amount_eur: 4929.40.
Five model calls: look, read, write, run, answer. The script is still in the workspace, so a later turn (or another agent) can run it again instead of rewriting it.
print(ws.list_files())
print()
print(ws.read_file("order_totals.py"))README.md (270 bytes)
data/
data/orders.csv (1003 bytes)
order_totals.py (221 bytes)
import csv
with open('data/orders.csv', newline="") as f:
rows = list(csv.DictReader(f))
print("orders:", len(rows))
total = sum(float(r['amount_eur']) for r in rows)
print("total amount_eur:", format(total, ".2f"))
Reading the whole CSV into the context was fine for 24 rows and would not be for 24
million. read_file caps what it returns (4,000 characters here) and says so, which nudges
the model toward run_command for big files. Writing a script once and keeping it in the
folder points at the next idea: if a procedure is worth keeping, package it.
4. Skills: know-how in a folder
A skill is a folder with a SKILL.md file: a few lines of front matter, a name and
a description that says what the skill does and when to use it, followed by instructions
in Markdown. The folder can also hold scripts, templates and reference documents. Three
small skills ship with the course:
SKILLS = FIXTURES / "skills"
for p in sorted(SKILLS.rglob("*")):
if p.is_file():
print(p.relative_to(SKILLS).as_posix())
print()
print((SKILLS / "csv-report" / "SKILL.md").read_text())csv-report/SKILL.md csv-report/scripts/summarize.py house-style/SKILL.md house-style/reference/style-guide.md release-notes/SKILL.md release-notes/templates/release-notes.md --- name: csv-report description: Summarize a CSV file - row count, column types, and a total of one numeric column grouped by another. Use when asked to summarize, total or break down a table of data. --- # CSV report Use the bundled script rather than reading the whole file into the conversation. 1. Run it with only the file path first. It prints the number of rows and each column with its type (`number` or `text`): ```bash python skills/csv-report/scripts/summarize.py <csv-path> ``` 2. Pick the grouping column and the numeric column from that list, then run: ```bash python skills/csv-report/scripts/summarize.py <csv-path> --by <column> --sum <numeric-column> ``` 3. Report the groups exactly as the script prints them: largest total first, two decimals, and the grand total on the last line. Do not recompute the numbers yourself.
SkillLibrary reads every folder, checks the front matter, and keeps the valid skills. The
checks follow the public Agent Skills format: a name of lowercase letters, digits and
hyphens (at most 64 characters) that matches its folder, and a non-empty description of at
most 1,024 characters. To see the checks at work, copy the library and add two broken
skills.
import shutil
from agentlab.skills import SkillLibrary
extra = nb.workdir / "more-skills"
shutil.rmtree(extra, ignore_errors=True)
shutil.copytree(SKILLS, extra)
(extra / "Quick_Notes").mkdir()
(extra / "Quick_Notes" / "SKILL.md").write_text(
"---\nname: Quick_Notes\ndescription: Take notes.\n---\nWrite notes.\n")
(extra / "summarise").mkdir()
(extra / "summarise" / "SKILL.md").write_text(
"---\nname: summarise\n---\nSummarise things.\n")
checked = SkillLibrary(extra)
print("loaded: ", list(checked.skills))
for folder, problem in checked.rejected.items():
print(f"rejected: {folder}: {problem}")loaded: ['csv-report', 'house-style', 'release-notes'] rejected: Quick_Notes: name 'Quick_Notes' must be lowercase letters, digits and hyphens, at most 64 chars rejected: summarise: missing 'description' (the agent chooses skills by it)
The missing description is the more serious defect: the description is the only thing the agent sees before deciding to use a skill, so a skill without one can never be chosen.
5. Progressive disclosure
The point of the format is that an agent pays for a skill in three instalments:
| level | what | when it enters the context |
|---|---|---|
| 1 | name and description | always, one line per skill in the system prompt |
| 2 | the SKILL.md body | when the agent calls load_skill |
| 3 | bundled files | when the instructions say to read or run one |
Level 1 is all the agent sees up front:
library = SkillLibrary(SKILLS)
print(library.summary_prompt())## Skills Each skill is a folder of instructions and files. Only names and descriptions are listed here; call load_skill(name) to read a skill's instructions before using it. - csv-report: Summarize a CSV file - row count, column types, and a total of one numeric column grouped by another. Use when asked to summarize, total or break down a table of data. - house-style: Rewrite a customer-facing message (email, reply or announcement) in the team's house style. Use before sending anything a customer will read. - release-notes: Draft release notes from a list of merged changes, grouped into Added, Changed and Fixed. Use when asked for release notes or a changelog entry.
Count the tokens each level costs for the three skills, using the same estimate as the usage table (about four bytes per token).
from agentlab.llm.pricing import estimate_tokens
print(f"{'skill':<14}{'level 1':>9}{'level 2':>9}{'level 3':>9}")
sizes = {}
for s in library:
l1 = estimate_tokens(s.summary_line())
l2 = estimate_tokens(library.load(s.name))
l3 = sum(estimate_tokens(library.read_resource(s.name, f)) for f in s.resources())
sizes[s.name] = (l1, l2, l3)
print(f"{s.name:<14}{l1:>9}{l2:>9}{l3:>9}")
print()
print("everything inline:", estimate_tokens(library.inline_prompt()), "tokens")
print("names only: ", estimate_tokens(library.summary_prompt()), "tokens")skill level 1 level 2 level 3 csv-report 46 188 313 house-style 39 163 321 release-notes 41 134 44 everything inline: 549 tokens names only: 169 tokens
With three skills the difference is a few hundred tokens. It matters because it repeats on every request and grows with every skill installed. Hur and Song work an example with 100 capabilities: described in full at 500 tokens each they cost 50,000 tokens per request; listed at 50 tokens each, with two loaded in full at 2,000 tokens apiece, about 9,000. The figure scales our measured averages the same way.
import matplotlib.pyplot as plt
import numpy as np
l1 = np.mean([v[0] for v in sizes.values()])
l2 = np.mean([v[1] for v in sizes.values()])
n = np.arange(0, 101, 5)
inline = n * (l1 + l2)
listed = n * l1 + 2 * l2
fig, ax = plt.subplots(figsize=(6.4, 3.4))
ax.plot(n, inline, color="#b5523b", label="every skill inline")
ax.plot(n, listed, color="#2c5f9e", label="names only, two skills loaded")
ax.plot(n, n * l1, color="#81796f", linestyle="--", label="names only, nothing loaded")
for y, colour in [(inline[-1], "#b5523b"), (listed[-1], "#2c5f9e")]:
ax.annotate(f"{y:,.0f}", (n[-1], y), xytext=(-6, 6), textcoords="offset points",
ha="right", color=colour)
ax.set_ylim(0, inline[-1] * 1.12)
ax.yaxis.set_major_formatter(lambda y, _: f"{y:,.0f}")
ax.set_xlabel("installed skills")
ax.set_ylabel("prompt tokens per request")
ax.legend(frameon=False, loc="upper left")
ax.spines[["top", "right"]].set_visible(False)
fig.tight_layout()
plt.show()
System-prompt tokens per request as the number of installed skills grows, using the average sizes of the three course skills. Pasting every skill inline grows several times faster than listing names and loading two skills on demand.
Two costs are not in the figure. Loading is a tool call, so a skill costs one extra model turn the first time it is used. And a library is only as good as its descriptions: the agent cannot load what it cannot recognise from one line.
6. An agent that uses a skill
Install the skills into the workspace (so their scripts can run there) and give the agent
the load_skill tool next to the workspace tools. The tool also adds the level-1 list to
every request, so the prompt and the installed skills cannot drift apart.
print(library.install_into(ws))
skilled = Agent(llm, tools=[library.tool(), *ws.tools()], instructions=WS_PROMPT,
max_steps=10, name="skilled")
start = len(llm.calls)
result = await skilled.run("Give me the total amount by region for data/orders.csv.")
show_trajectory(result, width=84)
print()
print(result.output)['skills/csv-report', 'skills/house-style', 'skills/release-notes']
[user] Give me the total amount by region for data/orders.csv.
[skilled -> load_skill] {"name": "csv-report"}
[load_skill ok] # Skill: csv-report # CSV report Use the bundled script rather than reading the w...
[skilled -> run_command] {"command": "python skills/csv-report/scripts/summarize.py data/orders.csv"}
[run_command ok] exit code 0 stdout: 24 rows order_id: text date: text region: text product: text ...
[skilled -> run_command] {"command": "python skills/csv-report/scripts/summarize.py data/orders.csv --by r...
[run_command ok] exit code 0 stdout: sum of amount_eur by region: east 1643.10 north 1427.00 south...
[skilled] Here is the breakdown from the csv-report skill's script: sum of amount_eur by re...
--- status: complete, steps: 4
Here is the breakdown from the csv-report skill's script:
sum of amount_eur by region:
east 1643.10
north 1427.00
south 1105.50
west 753.80
total 4929.40
The agent matched the question to csv-report by its description, loaded the
instructions, and then did what they said: inspect the columns first, choose the grouping
and the total, and report the script’s numbers without recomputing them. None of those
steps was in its system prompt. The skill’s body entered the context only after the
load_skill call, which shows in the size of each request:
from agentlab.tracing import usage_of
for i, (request, response) in enumerate(llm.calls[start:], 1):
system = sum(estimate_tokens(x) for x in request.instructions)
total = usage_of(request, response)[0]
print(f"call {i}: system prompt {system:>4} tokens, whole request {total:>5} tokens")
print("loaded:", result.context.state["skills_loaded"])call 1: system prompt 202 tokens, whole request 700 tokens call 2: system prompt 202 tokens, whole request 926 tokens call 3: system prompt 202 tokens, whole request 1009 tokens call 4: system prompt 202 tokens, whole request 1114 tokens loaded: ['csv-report']
The system prompt stays the same size on every call: the skill list and nothing else. The request grows by the instructions once they are loaded and by each command’s output, and the other two skills never cost more than their one line.
Skills sit in the middle of a hierarchy that Hur and Song describe: a few core tools
that are always present (here the four workspace tools and load_skill), installable
capabilities that arrive as skills, and generated tools, scripts the agent writes for
itself, like order_totals.py in section 3. Each level is cheaper to add and less
trustworthy than the one before, which is the subject of Module 12.
Try this
- Ask the skilled agent to “write release notes for: added CSV export; fixed the login timeout”. Which skill does it load, and what does the offline model do once the instructions contain no command to run? What would a real model do?
- Write a fourth skill,
invoice-check, with a script that flags orders whoseamount_euris notqtytimes a list price. Give it a description that the question “are any orders priced wrong?” will match.- Make the description of
csv-reportvague (“Helps with files.”) and re-run section 6. What happens to the choice?- Shrink
read_file’s cap withWorkspace(ws.root, max_read_chars=200)and re-run section 3. Does the script still get the right column name?
nb.usage()| model calls | input tokens | output tokens | cost |
|---|---|---|---|
| 9 (fake: 9) | ≈ 7,140 | ≈ 222 | ≈ USD 0.0080 (reference price) |