GitHubGet started

BrekkyLab team · · 17 min read

Build Your First AI Agent in Python With a microVM

Build Your First AI Agent in Python With a microVM. Your program, holding agent.py and the model, sends a tool call to the agent's own VM, which holds a shell and your data.

TL;DR

  • An AI agent is a model that uses tools in a loop: it asks for a tool, your program runs it, and the result goes back until the task is done. This tutorial builds one in Python.
  • Tools that run commands need somewhere to run. With Ailoy, every agent gets a Linux microVM of its own on your machine, with no Docker and no sandbox account. It sees only the files you put on its volumes, the network is off if you choose, and the model key stays in your program.
  • You will build an agent that cleans a messy CSV, answers a revenue question and writes a chart and summary to a folder on your machine. The scripts and outputs below come from our runs on Windows 11.
  • Do not trust the agent’s last sentence. Step 4 checks that the files exist and recomputes the answer with your own code.

A first agent usually gets a calculator or a web search tool. Those teach the loop, but they skip the first real question once an agent can do real work: when the model asks to run a command, where does that command run?

This tutorial answers it step by step. You start with a script that can only talk, then give it a machine of its own and check what it did there. Once the prerequisites are in place, allow about 20 minutes. Building the image takes a couple of minutes on its own.

What you will build

The agent gets one file, orders.csv: 241 rows of sales orders with the mess real exports tend to have. It has to answer a question from that file, fix what it finds along the way and leave two files for you.

Part What it does Where it runs
Your Python script Starts everything and prints what happens Your computer
The model Decides the next step The provider, called through its CLI or API
Shell and file tools Run the commands the model asks for A Linux microVM, the sandbox
The data volume Holds the input, read-only virtx storage, mounted read-only at /data
The artifacts volume Receives the chart and summary virtx storage, copied to ./artifacts at the end

Prerequisites

You need:

  • Python 3.11 or later.
  • A supported host: Linux, macOS on Apple silicon or Windows 11.
  • On Windows, the Windows Hypervisor Platform: it is off by default and the VM runs on it. Turn it on from an administrator PowerShell with Enable-WindowsOptionalFeature -Online -FeatureName HypervisorPlatform, then restart. Virtualization must also be enabled in your firmware.
  • A model: the examples use anthropic/claude-haiku-5-5. By default, Ailoy runs it through Claude Code, so you need Claude Code installed and logged in on this machine. If you would rather use an API key, set it in your program before build(), as Where to go next shows. Model providers covers Codex, Gemini CLI, API keys, Bedrock, OpenRouter and self-hosted servers such as vLLM.

Make a project folder and run everything from it, because the scripts use relative paths. Then install Ailoy, pinned to the versions we tested. ailoy-py also installs virtx, the library that creates sandboxes. Ailoy is still at 0.3, so its API can change between minor versions.

pip install "ailoy-py==0.3.3" "virtx==0.2.1"

Then create the sample data. Save this as make_orders.py and run it. The seed is fixed, so you get the same file we did.

import csv
import os
import random
random.seed(7)
rows = []
for i in range(1, 241):
date = f"2026-{random.randint(1, 9):02d}-{random.randint(1, 28):02d}"
region = random.choice(["North", "South", "East", "West"])
rows.append([f"A-{1000 + i}", date, region, round(random.uniform(12, 480), 2)])
# The mess real exports tend to have.
rows[17][3] = "$129.50"
rows[88][3] = "1,240.00"
rows[143][3] = ""
rows[201][2] = "north"
rows.append(list(rows[50])) # a duplicated order
os.makedirs("data", exist_ok=True)
with open("data/orders.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerow(["order_id", "date", "region", "amount"])
writer.writerows(rows)
python make_orders.py
mkdir artifacts

This gives you data/orders.csv and an empty artifacts folder.

Step 1: Start with a script that can only talk

Begin with the smallest thing that works: a model, a question and no tools. Save this as chat.py:

import asyncio
from ailoy import AgentBuilder
async def main() -> None:
agent = await AgentBuilder("anthropic/claude-haiku-5-5").build()
async for output in agent.run("How many orders are in data/orders.csv?"):
for part in output["message"]["contents"]:
if part["type"] == "text":
print(part["text"])
asyncio.run(main())

Run python chat.py. AgentBuilder names the model, build() creates the agent, and run() yields a message for each step. In our run, the model replied with this:

<invoke name="PowerShell">
<parameter name="command">cd "C:\Users\...\first-ai-agent-python"; if (Test-Path data/orders.csv) { $rows = @(Import-Csv data/orders.csv); "Data rows (excluding header): $($rows.Count)" } ...</parameter>
</invoke>

That looks like work, but nothing ran. The tool call is only text the model wrote, and a second run did the same with different wording. Your reply may read differently, and it may simply say the model cannot open the file. Either way, the file was never read.

This is the gap between a chatbot and an agent. Anthropic describes agents as “typically just LLMs using tools based on environmental feedback in a loop”. This script has the LLM. It has no tools, no feedback and no loop.

Step 2: Give it a machine

A sandbox is a Linux microVM with its own kernel. virtx runs it, and Client.spawn() starts the virtx server on your machine, downloading it the first time. You decide what the sandbox holds before the agent exists. Before handing it to a model, prove what it can and cannot do. Save this as check_machine.py:

The agent loop and its machine. Your program holds the model call, the agent loop, your functions and the API key, and the keys stay there. A tool call goes to the agent's own VM, which holds the shell and files, /data read-only, /artifacts for your output and the network off, with no keys; the result comes back to your program.
import asyncio
from pathlib import Path
from virtx import Client, Recipe, SandboxVolume
CHECKS = """
uname -sr
ls /data /artifacts
touch /data/test || true
python -c "import urllib.request as u; u.urlopen('https://pypi.org', timeout=5)" 2>&1 | tail -1
"""
async def main() -> None:
client = Client.spawn()
recipe = Recipe("python:3.12-slim-trixie").run("pip install --no-cache-dir pandas matplotlib")
await client.build_image(recipe, "orders-agent:latest").complete()
data = await client.create_volume()
await data.write_file("orders.csv", Path("data/orders.csv").read_text())
artifacts = await client.create_volume()
sandbox = await client.create_sandbox(
"orders-agent:latest",
volumes=[SandboxVolume(data, "/data", readonly=True), SandboxVolume(artifacts, "/artifacts")],
network=False,
)
await sandbox.exec(["sh", "-c", CHECKS]).complete(print=True)
await sandbox.remove()
asyncio.run(main())

Each part is a decision about what the agent gets:

  • build_image(recipe, "orders-agent:latest") builds the image. It takes a base image plus install steps, much like a Dockerfile, and keeps the result on the virtx server under that tag.
  • The data volume holds the input. It holds a copy of orders.csv that your code writes, and readonly=True refuses the agent’s writes to it.
  • The artifacts volume receives the output. It is mounted at /artifacts, and your code copies it to ./artifacts at the end.
  • network=False turns networking off in the running sandbox. The pip install still works, because it happens while the image is built.

Run python check_machine.py. The first run takes a couple of minutes and prints a long pip log while the image builds. virtx keeps the image under its tag, so later runs skip the install, and Make it start faster removes the rest of the wait. Pip’s warning about running as root is harmless here, because it applies to the image, not your computer. After the log, here is what we got on a Windows 11 host:

touch: cannot touch '/data/test': Read-only file system
Linux 6.12.109
/artifacts:
/data:
orders.csv
urllib.error.URLError: <urlopen error [Errno -3] Temporary failure in name resolution>

The VM runs a Linux kernel even on Windows. It sees both volumes, it cannot write to /data, and it cannot resolve an internet address. You checked all of that with sandbox.exec, with no model involved. For images, CPUs, memory and the GPU, see Give an agent a sandbox.

Step 3: Run the agent on its machine

Now hand the sandbox to the agent with .sandbox(sandbox). Save this as agent.py:

import asyncio
from pathlib import Path
from ailoy import AgentBuilder
from virtx import Client, Recipe, SandboxVolume
async def run_turn(agent, prompt: str) -> None:
async for output in agent.run(prompt):
message = output["message"]
for call in message.get("tool_calls") or []:
print(f"[{call['function']['name']}] {call['function']['arguments']}"[:300])
for part in message["contents"]:
if part["type"] == "text":
print(part["text"])
async def main() -> None:
client = Client.spawn()
recipe = Recipe("python:3.12-slim-trixie").run("pip install --no-cache-dir pandas matplotlib")
await client.build_image(recipe, "orders-agent:latest").complete()
data = await client.create_volume()
await data.write_file("orders.csv", Path("data/orders.csv").read_text())
artifacts = await client.create_volume()
sandbox = await client.create_sandbox(
"orders-agent:latest",
volumes=[SandboxVolume(data, "/data", readonly=True), SandboxVolume(artifacts, "/artifacts")],
network=False,
)
agent = await (
AgentBuilder("anthropic/claude-haiku-5-5")
.instruction(
"You work on a Linux machine with a shell. Input data is read-only at /data. "
"Write everything you produce to /artifacts."
)
.sandbox(sandbox)
.build()
)
await run_turn(
agent,
"Which region earned the most revenue in /data/orders.csv, and what was its best month? "
"Check the data first and tell me what you had to fix. Save a chart of monthly revenue "
"by region to /artifacts/revenue.png and a short summary to /artifacts/summary.md.",
)
for entry in await artifacts.read_dir(""):
Path("artifacts", entry.name).write_bytes(await artifacts.read_file(entry.name))
await agent.close()
await sandbox.remove()
asyncio.run(main())

Three details to notice:

  • The instruction says which folder is for output. Only the artifacts volume is copied back to ./artifacts, and anything else the agent writes is deleted with the sandbox.
  • run_turn prints tool calls. You can watch the agent work instead of waiting for a final answer.
  • Your code owns the sandbox. The agent never starts or removes it, so agent.close() and sandbox.remove() clean up at the end.

Run python agent.py. It took just under two minutes for us, with the image already built by check_machine.py. Here is the trace, with long commands and some of the model’s narration cut:

[shell] {'cmd': 'ls -la /data /artifacts 2>&1; echo "---"; head -n 20 /data/orders.csv 2>&1; ...
[shell] {'cmd': 'cd /data && echo "--- regions:" && cut -d, -f3 orders.csv | sort | uniq -c && ...
I'll look through the whole file for formatting problems before computing anything.
[shell] {'cmd': 'cd /data && grep -n -i -E "^A-1051|^A-1089|^A-1144|^A-1018|north|,region" orders.csv; ...
I've flagged several problems: a lowercase "north", a stray "region" row, a "$" prefix, a quoted amount with a thousands comma, an empty amount, and a duplicate ID. Next I'll look at those rows in context before deciding how to handle each one.
[shell] {'cmd': 'mkdir -p /tmp/work && cat > /tmp/work/analyze.py << \'EOF\'\nimport csv\n...
[shell] {'cmd': 'mkdir -p /artifacts && cat > /tmp/work/chart.py << \'EOF\'\nimport csv\n...

Nobody told it to scan every column for bad values or to write its own analysis script. It chose those steps itself from what each result showed, which is what makes this an agent rather than a script with a model in it. Its final answer began:

**North** earned the most revenue: **16,234.19** (28.5% of the 57,019.25 total). Its best month was **March 2026**, at 2,789.62.
**What I fixed in the data (241 data rows, 239 kept):**
- **Row 203, A-1202:** region was `north`. I changed it to `North`, so its 460.78 counts toward North.
- **Row 19, A-1018:** amount was `$129.50`. I removed the `$`.
- **Row 90, A-1089:** amount was `"1,240.00"`. I removed the quotes and the thousands comma.
- **Row 145, A-1144:** amount was blank. I dropped the row.
- **Rows 52 and 242, A-1051:** exact duplicate. I kept one copy.

That is all five problems planted in make_orders.py. Your trace will differ, because the model picks its own path each time. We ran this file twice on Ailoy 0.3.3 and three times on an earlier version, and every run took its own route to the same totals.

Step 4: Check the work where it landed

A sentence saying “saved to /artifacts/revenue.png” proves nothing. Check that the files exist, then recompute the answer without the model. Save this as verify.py and run it. The file sizes will differ from ours, because the agent writes them fresh each time:

import csv
import os
from collections import defaultdict
for name in ["revenue.png", "summary.md"]:
path = os.path.join("artifacts", name)
print(f"{name}: {os.path.getsize(path)} bytes")
seen = set()
totals = defaultdict(float)
months = defaultdict(float)
for row in csv.DictReader(open("data/orders.csv", newline="")):
amount = row["amount"].replace("$", "").replace(",", "")
if row["order_id"] in seen or not amount:
continue
seen.add(row["order_id"])
region = row["region"].title()
totals[region] += float(amount)
months[region, row["date"][:7]] += float(amount)
for region, total in sorted(totals.items(), key=lambda item: -item[1]):
print(f"{region:6} {total:10.2f}")
top = max(totals, key=totals.get)
month = max((m for r, m in months if r == top), key=lambda m: months[top, m])
print(f"Best month for {top}: {month} ({months[top, month]:.2f})")
revenue.png: 174345 bytes
summary.md: 618 bytes
North 16234.19
East 14279.53
South 13794.01
West 12711.52
Best month for North: 2026-03 (2789.62)

North at 16,234.19 and March at 2,789.62 both match the agent’s answer. verify.py shows the files exist and the numbers are right, but open the chart and read the summary yourself, because no script can judge those. This was our chart:

The agent's chart of monthly revenue by region, January to September 2026, for North, South, East and West.

Reading the full answer paid off as well. Early on, the agent reported a stray “region” row. In its answer it said that was a mistake: the row was the header line, which its own uniq count had picked up. It also said it had not opened the chart to check it. That is honest, but it is also why you keep your own check. A wrong total can sound just as confident.

Step 5: Add a second turn and a function of your own

An agent keeps its conversation, and the sandbox keeps its files between turns. Calling run_turn again continues the same job. Your own Python functions can become tools too, and these run in your program, not in the sandbox. That makes them the right place for anything that needs credentials the sandbox should never hold.

Write the function, then register it with a description and a JSON schema. The schema’s property names become the function’s keyword arguments:

TARGETS = {"North": 15000, "South": 15000, "East": 15000, "West": 15000}
def revenue_target(region: str) -> dict:
return {"region": region, "target": TARGETS[region]}
target_tool = register_tool(
{
"name": "revenue_target",
"description": "Look up a region's revenue target for the year.",
"parameters": {
"type": "object",
"properties": {"region": {"type": "string", "description": "North, South, East or West"}},
"required": ["region"],
},
},
revenue_target,
)

Import register_tool from ailoy, and pass the tool to the builder with .tool(target_tool) next to .sandbox(sandbox). Then add a second run_turn before the cleanup at the end:

await run_turn(
agent,
"Did the winning region beat its revenue target? Add the answer to /artifacts/summary.md.",
)

The complete script is at the end of this post. Step 3’s sandbox was removed when that script exited, so this run starts a new one and asks the first question again. Our second turn used both kinds of tool. This is the output with long commands and the end of the answer cut:

[revenue_target] {'region': 'North'}
[shell] {'cmd': "cat >> /artifacts/summary.md <<'EOF'\n\n## Revenue target\n\n- **Did North beat its target?** Yes. ...
[edit] {'path': '/artifacts/summary.md', 'old_string': '- **Did North beat its target?** Yes. ...
Yes. North earned 16,234.19 against a target of 15,000, which is 1,234.19 over, or 108.2% of target.
The target lookup returned only the number, so I'm relying on its description ("for the year") to read 15,000 as a full-year target. The data covers only January to September 2026, so this is a year-to-date figure. I added that caveat to /artifacts/summary.md.

The lookup ran in your program, and the file edit ran in the sandbox. If your function raises an exception, the run does not stop: the model gets the error as the result and can try something else. See the tools guide for the details.

Make it start faster

build_image keeps the image on the virtx server under its tag, and later sandboxes boot it without installing anything. The first build took just under two minutes for us. But agent.py calls build_image on every run, and even with the image already built, that call took about 35 seconds while virtx checked the recipe. Build the image once in its own script instead. Save this as build_image.py, and run it again only when you change the recipe:

import asyncio
from virtx import Client, Recipe
async def main() -> None:
client = Client.spawn()
recipe = Recipe("python:3.12-slim-trixie").run("pip install --no-cache-dir pandas matplotlib")
print(await client.build_image(recipe, "orders-agent:latest").complete())
asyncio.run(main())

Then delete the recipe and build_image lines from agent.py, and drop Recipe from the import. The sandbox boots straight from the tag:

from virtx import Client, SandboxVolume
client = Client.spawn()
data = await client.create_volume()
await data.write_file("orders.csv", Path("data/orders.csv").read_text())
artifacts = await client.create_volume()
sandbox = await client.create_sandbox(
"orders-agent:latest",
volumes=[SandboxVolume(data, "/data", readonly=True), SandboxVolume(artifacts, "/artifacts")],
network=False,
)

On our Windows laptop, booting the sandbox from the built image took one to two seconds, down from about 35 seconds with the build_image call in place. That covers only the sandbox, and the model’s work takes as long as it takes. Your numbers depend on your host and image.

Troubleshooting

What you see Cause Fix
create_sandbox fails with a 404 The image tag is not on the virtx server Run build_image.py first, or check the tag
The agent says it cannot run commands or read files The builder has no sandbox, so the agent has no shell or file tools Add .sandbox(sandbox) to the builder
failed to start the claude CLI Claude Code is not installed or not on PATH Install it and log in, or switch to an API key
The paging file is too small for this operation to complete Windows is out of memory for the VM. We hit this on a 7.3 GB laptop with many apps open Close memory-heavy apps and try again
ANTHROPIC_API_KEY is not set You chose the api backend with no key Set the key before build()
UnicodeEncodeError when printing on Windows Output is redirected, and Python falls back to cp1252 In PowerShell, run $env:PYTHONIOENCODING="utf-8" first
The agent says it saved a file, and ./artifacts is empty The instruction named no path, or the files were never copied off the volume Name the guest path in the instruction, and copy results out with read_file

Where to go next

You now have the whole shape of an agent: a model, tools, a loop and a machine with limits you chose. Three small changes take it further:

  • Change the model. Replace the model string with openai/gpt-6-luna with Codex logged in, or another name from Model providers. For unattended runs, where nobody can log in to a CLI, add import ailoy, call ailoy.set_lang_model_provider("anthropic", "api") and set the API key.
  • Connect other tools. Using MCP adds the tools of an MCP server.
  • See bigger agents. The CAD agent looks at its own renders and fixes its model, and the Offshore Leaks agent analyses a large read-only dataset with SQL and Python it writes itself. The rest are on the use cases page.

FAQs

What is the difference between a chatbot and an AI agent?

A chatbot replies with text. An agent can also act: it calls tools, reads the results and decides what to do next until the task is finished. In this tutorial, Step 1 is the chatbot and Step 3 is the agent, using the same model.

Do I need Docker to run this?

No. The Recipe looks like a Dockerfile and starts from an image such as python:3.12-slim-trixie, but the agent runs in a microVM that virtx starts. Client.spawn() downloads the virtx server the first time you call it.

If the VM’s network is off, how does the model still respond?

The model call comes from your program on the host, not from inside the sandbox. network=False only limits the commands the agent runs in the sandbox. Web tools such as web_search and web_fetch also run in your program, so they keep working if you add them.

Can the agent read the rest of my files?

Its shell and file tools can only reach what is inside the sandbox, which means the image plus the volumes you mount. Your own functions and any stdio MCP servers are different: they run on your computer with your program’s access, so register only those you trust.

What happens to the agent’s files when the script ends?

Your script copies the artifacts volume to ./artifacts before it removes the sandbox, so those files stay on your disk. Tell the agent in the instruction where to save what you want back. Files it leaves elsewhere, such as /tmp/work in our trace, are deleted with the sandbox.

Complete source code

Here is the full agent.py from Step 5, with the function tool and the second turn. It needs data/orders.csv from make_orders.py and an artifacts folder.

import asyncio
from pathlib import Path
from ailoy import AgentBuilder, register_tool
from virtx import Client, Recipe, SandboxVolume
TARGETS = {"North": 15000, "South": 15000, "East": 15000, "West": 15000}
def revenue_target(region: str) -> dict:
return {"region": region, "target": TARGETS[region]}
async def run_turn(agent, prompt: str) -> None:
async for output in agent.run(prompt):
message = output["message"]
for call in message.get("tool_calls") or []:
print(f"[{call['function']['name']}] {call['function']['arguments']}"[:300])
for part in message["contents"]:
if part["type"] == "text":
print(part["text"])
async def main() -> None:
target_tool = register_tool(
{
"name": "revenue_target",
"description": "Look up a region's revenue target for the year.",
"parameters": {
"type": "object",
"properties": {"region": {"type": "string", "description": "North, South, East or West"}},
"required": ["region"],
},
},
revenue_target,
)
client = Client.spawn()
recipe = Recipe("python:3.12-slim-trixie").run("pip install --no-cache-dir pandas matplotlib")
await client.build_image(recipe, "orders-agent:latest").complete()
data = await client.create_volume()
await data.write_file("orders.csv", Path("data/orders.csv").read_text())
artifacts = await client.create_volume()
sandbox = await client.create_sandbox(
"orders-agent:latest",
volumes=[SandboxVolume(data, "/data", readonly=True), SandboxVolume(artifacts, "/artifacts")],
network=False,
)
agent = await (
AgentBuilder("anthropic/claude-haiku-5-5")
.instruction(
"You work on a Linux machine with a shell. Input data is read-only at /data. "
"Write everything you produce to /artifacts."
)
.sandbox(sandbox)
.tool(target_tool)
.build()
)
await run_turn(
agent,
"Which region earned the most revenue in /data/orders.csv, and what was its best month? "
"Check the data first and tell me what you had to fix. Save a chart of monthly revenue "
"by region to /artifacts/revenue.png and a short summary to /artifacts/summary.md.",
)
await run_turn(
agent,
"Did the winning region beat its revenue target? Add the answer to /artifacts/summary.md.",
)
for entry in await artifacts.read_dir(""):
Path("artifacts", entry.name).write_bytes(await artifacts.read_file(entry.name))
await agent.close()
await sandbox.remove()
asyncio.run(main())

To start from the shortest path instead, follow the Ailoy quick start.

Run your first agent
in its own microVM

Install the package, name a model and run it