# Ailoy docs > Every page of https://ailoy.co/docs/, in the sidebar's order. The short version is https://ailoy.co/llms.txt. ## Welcome to Ailoy https://ailoy.co/docs/ What Ailoy is, what you can build with it, and where to start. Ailoy is an open-source SDK for building AI agents in Python, Node.js or Rust. Each agent can have a Linux microVM of its own, where it installs software, runs code and keeps files without touching your machine. ### What you can build With a computer of its own, an agent can do work you didn't write a function for. [ailoy.co/use-cases](https://ailoy.co/use-cases/) shows each one running: - [CAD modeling](https://ailoy.co/use-cases/cad/): Writes CadQuery, renders the part from four sides, looks at the renders and fixes it. - [Image editing](https://ailoy.co/use-cases/sam3/): Segments images and video with SAM3, on the sandbox's GPU. - [Gameplay](https://ailoy.co/use-cases/gameplay/): Plays OpenTTD in its sandbox while you watch over VNC. - [Decisions with a local model](https://ailoy.co/use-cases/laya/): Answers typed questions about tickets with a model it runs on the GPU. ### Key features - [Agents](https://ailoy.co/docs/guides/agents/): AgentBuilder puts together a model, tools, skills and a sandbox. - [Sandboxes](https://ailoy.co/docs/guides/sandbox/): A microVM made with virtx, on your machine, your server or virtx's cloud, GPU included. - [Models](https://ailoy.co/docs/guides/model-providers/): Change the model with one string. Claude, GPT and Gemini run on your CLI login. - [Tools](https://ailoy.co/docs/guides/tools/): A shell and file tools in the sandbox, plus your own functions, MCP and a browser. - [Skills](https://ailoy.co/docs/guides/skills/): Folders of instructions for one kind of task, in the Agent Skills format. - [Context manager](https://ailoy.co/docs/guides/context-manager/): Keeps a long run under the model's context limit. ### Before you start You need Python 3.11+, Node.js 22+ or Rust 1.95+, a machine that can run microVMs (Linux with KVM, Apple silicon or Windows 11), and a CLI login or API key for the model. [Quick start](https://ailoy.co/docs/guides/quick-start/) runs your first agent, and [Installation](https://ailoy.co/docs/guides/installation/) walks through each in detail. ### Choose your path | If you want to... | Go to | | --- | --- | | Give an agent a computer to work in | [Giving an agent a sandbox](https://ailoy.co/docs/guides/sandbox/) | | Pick a model, or how it runs: CLI, API, Bedrock, OpenRouter or a server you run yourself | [Model providers](https://ailoy.co/docs/guides/model-providers/) | | Let the agent call functions of your own | [Tools](https://ailoy.co/docs/guides/tools/#your-own-functions) | | Give it the tools of an MCP server | [Using MCP](https://ailoy.co/docs/guides/using-mcp/) | | Let it drive a browser | [Using a browser](https://ailoy.co/docs/guides/using-browser/) | | Give it instructions for one kind of task | [Skills](https://ailoy.co/docs/guides/skills/) | | Show its reply as the model writes it | [Running an agent](https://ailoy.co/docs/guides/running/#run-and-run_stream) | | Carry a conversation over turns, or pick it up later | [Running an agent](https://ailoy.co/docs/guides/running/#many-turns) | | Keep a long run under the model's context limit | [Context manager](https://ailoy.co/docs/guides/context-manager/) | | Save an agent's definition and build it again | [Defining an agent](https://ailoy.co/docs/guides/agents/#from-a-spec) | For AI coding assistants, [SKILL.md](https://github.com/brekkylab/ailoy/blob/main/skills/ailoy/SKILL.md) has the steps to build with Ailoy, [llms.txt](https://ailoy.co/llms.txt) sums up Ailoy, and [llms-full.txt](https://ailoy.co/llms-full.txt) has every page of these docs in one file. --- ## Quick start https://ailoy.co/docs/guides/quick-start/ Run an agent for one turn, then give it a sandbox and let it make a chart. ### Install **Python** ```sh pip install ailoy-py ``` **Node.js** ```sh npm install @brekkylab/ailoy ``` **Rust** ```sh cargo add ailoy virtx futures anyhow tokio --features tokio/macros,tokio/rt-multi-thread ``` The model runs on a CLI you are logged in to (Claude Code, for the Claude model on this page) or on an API key. [Installation](https://ailoy.co/docs/guides/installation/) covers the machine the sandbox needs, API keys, and fixes for common errors. ### Run an agent An agent needs only a model. This one has no tools and no sandbox, so it answers from what the model knows: **Python** ```python import asyncio from ailoy import AgentBuilder async def main() -> None: agent = await ( # For openai, use "openai/gpt-6-luna" AgentBuilder("anthropic/claude-haiku-5-5") .build() ) async for output in agent.run("What is the meaning of hello world?"): for part in output["message"]["contents"]: if part["type"] == "text": print(part["text"]) asyncio.run(main()) ``` **Node.js** ```js const { AgentBuilder } = require('@brekkylab/ailoy') async function main() { // For openai, use "openai/gpt-6-luna" const agent = await new AgentBuilder('anthropic/claude-haiku-5-5') .build() for await (const { message } of agent.run('What is the meaning of hello world?')) { for (const part of message.contents) { if (part.type === 'text') console.log(part.text) } } await agent.close() } main() ``` **Rust** ```rust use ailoy::{ agent::AgentBuilder, message::{Message, Part, Role}, }; use futures::StreamExt as _; #[tokio::main] async fn main() -> anyhow::Result<()> { // For openai, use "openai/gpt-6-luna" let mut agent = AgentBuilder::new("anthropic/claude-haiku-5-5") .build() .await?; let query = Message::new(Role::User).with_contents([Part::text("What is the meaning of hello world?")]); let mut stream = agent.run(query); while let Some(output) = stream.next().await { let message = output?.message; if message.role == Role::Assistant { for text in message.contents.iter().filter_map(Part::as_text) { println!("{text}"); } } } Ok(()) } ``` `agent.run` yields each message of the turn as it completes; [Running an agent](https://ailoy.co/docs/guides/running/) covers what it yields and how to stream it instead. ### Give it a sandbox The same agent with a sandbox can install software, write and run code, and keep files, in a Linux microVM of its own rather than on your machine. The added lines start virtx's server, make a sandbox from a Python image, hand it to the agent, and copy the chart the agent draws out to `population.png`: **Python** ```python ins={2,5,9-13,18-19,28} mark={23} import asyncio from pathlib import Path from ailoy import AgentBuilder from virtx import Client async def main() -> None: # Starts virtx's server, fetched into its cache the first time. client = Client.spawn() await client.pull_image("python:3.12-slim-trixie").complete() sandbox = await client.create_sandbox("python:3.12-slim-trixie") agent = await ( # For openai, use "openai/gpt-6-luna" AgentBuilder("anthropic/claude-haiku-5-5") .instruction("Write what you are asked for into /artifacts.") .sandbox(sandbox) .build() ) async for output in agent.run("Create a bar chart comparing the populations of European countries and save it to /artifacts/population.png."): for part in output["message"]["contents"]: if part["type"] == "text": print(part["text"]) Path("population.png").write_bytes(await sandbox.read_file("artifacts/population.png")) asyncio.run(main()) ``` **Node.js** ```js ins={1,3,6-9,13-14,23,25} mark={17} const { writeFileSync } = require('node:fs') const { AgentBuilder } = require('@brekkylab/ailoy') const { Client } = require('@brekkylab/virtx') async function main() { // Starts virtx's server, fetched into its cache the first time. const client = Client.spawn() await client.pullImage('python:3.12-slim-trixie').complete() const sandbox = await client.createSandbox('python:3.12-slim-trixie') // For openai, use "openai/gpt-6-luna" const agent = await new AgentBuilder('anthropic/claude-haiku-5-5') .instruction('Write what you are asked for into /artifacts.') .sandbox(sandbox) .build() for await (const { message } of agent.run('Create a bar chart comparing the populations of European countries and save it to /artifacts/population.png.')) { for (const part of message.contents) { if (part.type === 'text') console.log(part.text) } } writeFileSync('population.png', await sandbox.readFile('artifacts/population.png')) await agent.close() await client.close() } main() ``` **Rust** ```rust ins={6,10-18,22-23,38-39} mark={27} use ailoy::{ agent::AgentBuilder, message::{Message, Part, Role}, }; use futures::StreamExt as _; use virtx::{Client, Files as _, SandboxCreateArgs}; #[tokio::main] async fn main() -> anyhow::Result<()> { // Starts virtx's server, fetched into its cache the first time. let client = Client::spawn_virtx([] as [&str; 0]).await?; client.pull_image("python:3.12-slim-trixie", None).complete(false).await?; let sandbox = client .create_sandbox(&SandboxCreateArgs::new("python:3.12-slim-trixie")) .await?; // For openai, use "openai/gpt-6-luna" let mut agent = AgentBuilder::new("anthropic/claude-haiku-5-5") .instruction("Write what you are asked for into /artifacts.") .sandbox(sandbox.clone()) .build() .await?; let query = Message::new(Role::User).with_contents([Part::text("Create a bar chart comparing the populations of European countries and save it to /artifacts/population.png.")]); let mut stream = agent.run(query); while let Some(output) = stream.next().await { let message = output?.message; if message.role == Role::Assistant { for text in message.contents.iter().filter_map(Part::as_text) { println!("{text}"); } } } let png = sandbox.read_file("artifacts/population.png", 0, None).await?; std::fs::write("population.png", png)?; Ok(()) } ``` The image has no matplotlib, so the agent installs it with the shell that `sandbox(...)` gives it, along with file tools ([Tools](https://ailoy.co/docs/guides/tools/)). ### What happened - [How an agent works](https://ailoy.co/docs/concepts/#a-turn) walks through the turn: the model asks for tools, they run, and their results go back to it until it answers. - [Giving an agent a sandbox](https://ailoy.co/docs/guides/sandbox/) covers images, volumes for inputs and results, and picking up later. - [Defining an agent](https://ailoy.co/docs/guides/agents/) lists everything else an agent can be given. - If a step fails, [Troubleshooting](https://ailoy.co/docs/guides/installation/#troubleshooting) lists the usual errors and their fixes. --- ## Installation https://ailoy.co/docs/guides/installation/ Install Ailoy and virtx, and set up a way for the agent's model to run. An agent needs Ailoy and virtx's packages, a way for its model to run, and a machine that can run its sandbox. ### Requirements - Python 3.11 or later, Node.js 22 or later, or Rust 1.95 or later. - For the machine that runs the sandbox, which is yours unless the virtx server runs elsewhere, depending on its OS: - **Linux:** KVM, with `/dev/kvm` open to your user and virtualization enabled in the firmware. Most kernels have KVM built in. - **macOS:** Apple silicon. - **Windows:** Windows 11 or later, with the Windows Hypervisor Platform turned on (below). #### Windows The Windows Hypervisor Platform is off by default. With virtualization enabled in the firmware, turn it on from an administrator PowerShell, then restart: ```powershell Enable-WindowsOptionalFeature -Online -FeatureName HypervisorPlatform ``` ### Packages **Python** ```sh pip install ailoy-py ``` This installs `virtx` too, the package your code makes sandboxes with. **Node.js** ```sh npm install @brekkylab/ailoy ``` This installs `@brekkylab/virtx` too, the package your code makes sandboxes with. With pnpm, which keeps a package from importing what it did not list, add `@brekkylab/virtx` yourself. **Rust** ```sh cargo add ailoy virtx futures anyhow tokio --features tokio/macros,tokio/rt-multi-thread ``` `virtx` is the crate your code makes sandboxes with. Cargo lets your code use only the crates it lists, so add it beside `ailoy`. `tokio`, `futures` and `anyhow` are what the examples on these pages run on. You don't install virtx's server separately: the first `Client.spawn()` (`Client::spawn_virtx` in Rust) downloads it into virtx's cache. ### A model to run #### With a CLI login (default) Claude, GPT and Gemini run through their CLIs by default, so the examples need no key. Install the one for your model and log in: | CLI | Log in | Check | | --- | --- | --- | | [Claude Code](https://docs.anthropic.com/en/docs/claude-code) | `claude auth login` | `claude auth status` | | [Codex](https://github.com/openai/codex) | `codex login` | `codex login status` | | [Gemini CLI](https://github.com/google-gemini/gemini-cli) | Run `gemini` and sign in | | Without a login, the first turn fails with the CLI's own message, such as Claude Code's "Not logged in". #### With an API key Set the key, and switch the org to the `api` backend before building the agent: ```sh export ANTHROPIC_API_KEY=... # or OPENAI_API_KEY, GEMINI_API_KEY ``` **Python** ```python import ailoy ailoy.set_lang_model_provider("anthropic", "api") ``` **Node.js** ```js const { setLangModelProvider } = require('@brekkylab/ailoy') setLangModelProvider('anthropic', 'api') ``` **Rust** ```rust ailoy::model::set_lang_model_provider("anthropic", ailoy::model::Backend::Api); ``` [Model providers](https://ailoy.co/docs/guides/model-providers/) lists every backend: the CLIs, each org’s own API, Amazon Bedrock, OpenRouter and a server you run yourself (vLLM, llama-server, Ollama, LM Studio). ### Troubleshooting | What you see | Cause | Fix | | --- | --- | --- | | `boot_failed`, when a sandbox is made | This machine can't boot a VM. | **Linux:** open `/dev/kvm` to your user with `sudo usermod -aG kvm $USER`, then log in again. **Windows:** turn on the [Hypervisor Platform](#windows). **Any OS:** turn on virtualization (Intel VT-x, AMD-V) in the firmware. Set `KRUN_LOG=debug` to see the hypervisor's own messages after `last logged`. | | `no virtx-stdio release … for macos-x86_64` | virtx runs on Apple silicon only, not on an Intel Mac. | Run the virtx server on another machine and connect to it ([Hello world](https://virtx.sh/docs/hello-world/)). | | `fetching …/virtx/releases/…`, on the first `Client.spawn()` | The server's download failed. | Check the network or proxy, set `VIRTX_DIST_URL` to a mirror, or download the server yourself and point `VIRTX_STDIO` at it ([Environment variables](https://virtx.sh/docs/reference/api/#environment-variables)). | | `… does not match its SHA256SUMS` | The download came back changed, as a proxy may do. | Try again, or set `VIRTX_STDIO` as above. | | An error from the model's CLI or API on the first turn | It comes from the model's backend, not the sandbox. | See [Model providers](https://ailoy.co/docs/guides/model-providers/#troubleshooting). | ### Next - [How an agent works](https://ailoy.co/docs/concepts/): where each part runs and what happens in a turn. - [Defining an agent](https://ailoy.co/docs/guides/agents/): everything an `AgentBuilder` can give an agent. --- ## How an agent works https://ailoy.co/docs/concepts/ Where each part of an agent runs, what happens in a turn, and how an agent's spec and state divide it. [Figure: the agent in your program, its model above and its sandbox below] In this example, the agent is an object in your program, on your computer. It calls its model along the arrow up, and when the model asks for tools, the calls go down into the [sandbox](#the-agents-sandbox), a microVM with its own Linux kernel. The sandbox starts from an image, mounts folders for the agent's inputs, skills and results (here `/models`, `/skills` and `/artifacts`), and can be given a GPU. What the agent leaves in `/artifacts` reaches your disk when your code copies it out. ### A turn A turn is one query and everything the agent does to answer it, going back and forth along the two arrows: 1. Your query is added to the agent's history. 2. The model gets the history and the descriptions of the agent's tools, and writes a message. 3. If the message answers, the turn ends there. If it asks for tools, every call runs at the same time: the sandbox tools in the sandbox, the rest in your program. 4. Each call gives exactly one result, a failure included, so the model can see what went wrong and try something else. The results are added to the history, and the model is called again, back at step 2. 5. Every message, the model's and the tools', is yielded as it completes and stays in the history, so the next turn continues the same conversation. [Running an agent](https://ailoy.co/docs/guides/running/) covers iterating a turn, streaming it, and what happens when it fails. ### The agent's sandbox An Ailoy agent can be given a sandbox, a Linux microVM from [virtx](https://virtx.sh/docs/). virtx is a standalone, open-source microVM sandbox for AI agents. In the sandbox, the agent installs software, writes and runs code, and keeps files without touching your machine. Your code makes the sandbox with virtx's package and hands it to the agent, which then gets a shell and file tools that run inside it. What is in the sandbox comes from two places: - **The image and its packages.** Every sandbox booted from the image starts with them, so a package every run needs goes here. - **Folders mounted from volumes**, for inputs, skills and results. A volume stays on the virtx server between runs, and your code reads and writes it while the agent works. What the agent writes anywhere else, such as a package it installs, lasts as long as the sandbox does. A sandbox can also be given the host's GPU, through Vulkan ([Using GPUs](https://virtx.sh/docs/guides/using-gpus/)). The sandbox is yours, not the agent's. The agent never starts, stops or removes it: your code makes it, can read and write its files while the agent works, and removes it when it is done. So a sandbox can outlive the agent, for another agent to pick up its work. [Giving an agent a sandbox](https://ailoy.co/docs/guides/sandbox/) covers handing one over. Not everything an agent does happens in the sandbox: | Part | Where it runs | | --- | --- | | The model | The provider's servers, through its CLI on your machine or its API; or a server you run yourself, such as vLLM or Ollama | | The sandbox | A virtx server: your machine with `Client.spawn()`, or another one | | Your own functions, `web_search`, `web_fetch` | Your program | | MCP servers | A stdio server is a process on your machine; an HTTP server runs wherever it is hosted | | The browser | Your machine: your own browser or one the agent starts, driven from your program | ### Spec and state An Ailoy agent is two things: - **Spec**: the model, the instruction, the tools, the skills, the memory and the model options. It is plain JSON that says what the agent is, so it can be saved and an agent built from it again. - **State**: the history and the sandbox. It is what the agent has done and where. The label in the drawing's agent box, model · tools · skill, is part of its spec. `AgentBuilder` fills in both. [Defining an agent](https://ailoy.co/docs/guides/agents/) lists every call, and builds an agent from a saved spec. ### Messages Ailoy speaks one message format to every model. A message has a role (`system`, `user`, `assistant` or `tool`) and parts: text, images, tool calls and values. Streaming yields deltas, pieces of a message that add up to it. [Message format](https://ailoy.co/docs/guides/message-format/) covers the fields. ### Next - [Defining an agent](https://ailoy.co/docs/guides/agents/): everything an `AgentBuilder` can give an agent. - [Giving an agent a sandbox](https://ailoy.co/docs/guides/sandbox/): images, volumes, and picking up later. --- ## Defining an agent https://ailoy.co/docs/guides/agents/ Everything an AgentBuilder can give an agent, building one from a saved spec, and closing it. An agent is a model plus what you give it. `AgentBuilder` takes the model's name, then one call for each thing the agent should have, and `build()` makes the agent. ### AgentBuilder at a glance Every call returns the builder, so they chain. Node.js spells them in camelCase (`webSearchTool`, `contextManager`). | Call | What the agent gets | Where it is covered | | --- | --- | --- | | `instruction(text)` | The system message's text. | [Below](#instruction) | | `sandbox(sandbox)` | A virtx sandbox to work in, and a shell and file tools there. | [Giving an agent a sandbox](https://ailoy.co/docs/guides/sandbox/) | | `tool(desc)`, `tools(descs)` | Tools by name: your own functions, or a registered MCP server's. | [Tools](https://ailoy.co/docs/guides/tools/#your-own-functions), [Using MCP](https://ailoy.co/docs/guides/using-mcp/) | | `web_search_tool(engines)`, `web_fetch_tool()` | Searching the web and reading a page, from your program. | [Tools](https://ailoy.co/docs/guides/tools/#the-web) | | `browser(...)` | A browser it drives with `browser_*` tools. | [Using a browser](https://ailoy.co/docs/guides/using-browser/) | | `skill(dir)` | A folder of instructions in its sandbox, for one kind of task. | [Skills](https://ailoy.co/docs/guides/skills/) | | `memory(dir)` | Notes on the user that outlast a session, in a folder on this host. | [Tools](https://ailoy.co/docs/guides/tools/#memory) | | `context_manager(...)` | Old tool results and images cut once a run's input grows past a limit. | [Context manager](https://ailoy.co/docs/guides/context-manager/) | | `thinking_effort(effort)`, `output_schema(schema)` | How much the model thinks, and a JSON schema its answers must match. | [Model providers](https://ailoy.co/docs/guides/model-providers/#model-options) | | `history(messages)` | An earlier conversation to continue. | [Running an agent](https://ailoy.co/docs/guides/running/#many-turns) | ### Instruction `instruction(...)` is the system message's text: who the agent is, what it is for, and where in its sandbox to find inputs and leave results. The agent writes the system message from this text, the list of its [skills](https://ailoy.co/docs/guides/skills/) (those of `skill(...)` and those of its sandbox's abins) and the notes in its [memory](https://ailoy.co/docs/guides/tools/#memory), and puts that message at the front of its history, unless the history you give it already has one. ### From a spec The model, the instruction, the tools, the skills, the memory and the model options make up an agent's spec: plain JSON, which you can store and build an agent from again. The rest (its history and its sandbox) is its state, given beside the spec. `Agent.from_spec` builds an agent from both: **Python** ```python from ailoy import Agent spec = { "model": "anthropic/claude-haiku-5-5", "instruction": "Answer in one sentence.", } agent = await Agent.from_spec(spec, history=saved_messages, sandbox=sandbox) ``` **Node.js** ```js const { Agent } = require('@brekkylab/ailoy') const spec = { model: 'anthropic/claude-haiku-5-5', instruction: 'Answer in one sentence.', } const agent = await Agent.fromSpec(spec, { history: savedMessages, sandbox }) ``` **Rust** ```rust use ailoy::agent::{Agent, AgentSpec, AgentState}; use serde_json::json; let spec: AgentSpec = serde_json::from_value(json!({ "model": "anthropic/claude-haiku-5-5", "instruction": "Answer in one sentence.", }))?; let state = AgentState::new() .with_history(saved_messages) .with_sandbox(sandbox); let agent = Agent::try_with_state(spec, state).await?; ``` A spec lists its tools itself. `sandbox(...)` on the builder adds the shell and file tools to the spec; a sandbox given beside a spec does not, so the spec must list them for the agent to have them. In Rust, calling `.sandbox_tools()` on the `AgentSpec` adds them. Python and Node.js have no such call: to give an agent with a sandbox a saved history there, build it with `AgentBuilder`, `history(...)` and `sandbox(...)`. ### Closing In Python and Node.js, `close()` releases what the agent holds: its model, any browser it started itself, and its hold on the sandbox's client. It waits for a turn being iterated to finish. In Python, `async with agent:` closes it at the end of the block. A Rust agent releases them when it is dropped. Closing an agent leaves its sandbox as it is, for you to use again or remove. ### Next - [Giving an agent a sandbox](https://ailoy.co/docs/guides/sandbox/): the computer the agent works in. - [Model providers](https://ailoy.co/docs/guides/model-providers/): naming a model and choosing how it runs. --- ## Giving an agent a sandbox https://ailoy.co/docs/guides/sandbox/ Hand an agent a virtx sandbox: what it brings, what lives where, and where virtx's docs take over. The computer an agent works on is a sandbox: a Linux microVM on a [virtx](https://virtx.sh/docs/) server. Your code makes the sandbox with virtx's own package and hands it to the agent: - **Python:** the `virtx` package (`import virtx`), which `pip install ailoy-py` installs too - **Node.js:** `@brekkylab/virtx`, which `npm install @brekkylab/ailoy` installs too - **Rust:** the `virtx` crate, added beside `ailoy` (`ailoy::console::Sandbox` is `virtx::Sandbox`) This page covers what an agent needs from a sandbox. [virtx's docs](https://virtx.sh/docs/) cover the sandbox itself: servers, images, volumes and GPUs. ### Handing over a sandbox `sandbox(...)` on the `AgentBuilder` gives the agent a sandbox, and with it a shell and file tools that run there; [Tools](https://ailoy.co/docs/guides/tools/#a-shell-and-files) lists them. Here an image with matplotlib is built on the server, and an agent gets a sandbox booted from it: **Python** ```python import asyncio from pathlib import Path from ailoy import AgentBuilder from virtx import Client, Recipe async def main() -> None: client = Client.spawn() # Kept on the server under its tag: later sandboxes boot it without building again. recipe = Recipe("python:3.12-slim-trixie").run("pip install --no-cache-dir matplotlib") await client.build_image(recipe, "plot:latest").complete() sandbox = await client.create_sandbox("plot:latest") agent = await ( AgentBuilder("anthropic/claude-haiku-5-5") .instruction("Write what you are asked for into /artifacts.") .sandbox(sandbox) .build() ) async for _ in agent.run("Plot y = x^2 for x from -5 to 5 into /artifacts/square.png."): pass Path("square.png").write_bytes(await sandbox.read_file("artifacts/square.png")) await agent.close() await sandbox.remove() asyncio.run(main()) ``` **Node.js** ```js const { writeFileSync } = require('node:fs') const { AgentBuilder } = require('@brekkylab/ailoy') const { Client, Recipe } = require('@brekkylab/virtx') async function main() { const client = Client.spawn() // Kept on the server under its tag: later sandboxes boot it without building again. const recipe = new Recipe('python:3.12-slim-trixie').run('pip install --no-cache-dir matplotlib') await client.buildImage(recipe, 'plot:latest').complete() const sandbox = await client.createSandbox('plot:latest') const agent = await new AgentBuilder('anthropic/claude-haiku-5-5') .instruction('Write what you are asked for into /artifacts.') .sandbox(sandbox) .build() for await (const _ of agent.run('Plot y = x^2 for x from -5 to 5 into /artifacts/square.png.')); writeFileSync('square.png', await sandbox.readFile('artifacts/square.png')) await agent.close() await sandbox.remove() await client.close() } main() ``` **Rust** ```rust use ailoy::{ agent::AgentBuilder, message::{Message, Part, Role}, }; use futures::StreamExt as _; use virtx::{Client, Files as _, Recipe, SandboxCreateArgs}; #[tokio::main] async fn main() -> anyhow::Result<()> { let client = Client::spawn_virtx([] as [&str; 0]).await?; // Kept on the server under its tag: later sandboxes boot it without building again. let recipe = Recipe::new("python:3.12-slim-trixie").step("pip install --no-cache-dir matplotlib"); client.build_image(recipe, "plot:latest").complete(false).await?; let sandbox = client .create_sandbox(&SandboxCreateArgs::new("plot:latest")) .await?; let mut agent = AgentBuilder::new("anthropic/claude-haiku-5-5") .instruction("Write what you are asked for into /artifacts.") .sandbox(sandbox.clone()) .build() .await?; let query = Message::new(Role::User) .with_contents([Part::text("Plot y = x^2 for x from -5 to 5 into /artifacts/square.png.")]); let mut stream = agent.run(query); while let Some(output) = stream.next().await { output?; } drop(stream); std::fs::write("square.png", sandbox.read_file("artifacts/square.png", 0, None).await?)?; sandbox.remove().await?; Ok(()) } ``` The sandbox stays yours: - The agent does not start, stop or remove it, and closing the agent leaves it as it is. Remove it yourself, as above. With a server that `Client.spawn()` started, the sandboxes also go when your program does. - Your own calls on the sandbox and the agent's tool calls run side by side, and the agent's tool calls in one step run at the same time. - A failed call to the sandbox reaches you as virtx's `VirtxError`. An agent without a sandbox still runs, with the tools that need none: your own functions, `web_search`, `web_fetch`, MCP servers and a browser. It has no shell or file tools, and it cannot have [skills](https://ailoy.co/docs/guides/skills/), which it reads from the sandbox. ### What lives where A sandbox's files come from three places, and they last differently: | Where | What it holds for the agent | How long it lasts | virtx docs | | --- | --- | --- | --- | | The image | The programs and packages its commands find | Until you remove the image; every sandbox booted from it starts with it | [Images](https://virtx.sh/docs/guides/images/) | | A volume | Inputs, skills, results you want back | Until you remove the volume; several sandboxes can mount it, and your code reads and writes it while they do | [Mounting volumes](https://virtx.sh/docs/guides/mounting-volumes/) | | The sandbox's own files | What the agent writes anywhere else, such as packages it installs | Until the sandbox is removed | [Removing a sandbox](https://virtx.sh/docs/guides/setting-sandboxes/#remove-a-sandbox) | So: - A package every run needs goes in the image, not in a step the agent repeats. - The files you hand the agent or want back go on a volume. The examples in [ailoy-examples](https://github.com/brekkylab/ailoy-examples) all work this way: they build their image once, put their skill and inputs on named volumes, and copy the results back at the end. #### Building an image from a shell The `virtx` command builds the same images from a Dockerfile, with `docker`'s spelling. The virtx packages install it: `pip install ailoy-py` puts it in the environment's `bin/`, and `@brekkylab/virtx` in `node_modules/.bin`. Without either, run it with `uvx virtx` or `npx @brekkylab/virtx`. ```sh virtx build -t plot:latest . # from ./Dockerfile virtx images # the images on the server ``` A sandbox then boots from `plot:latest`. virtx's [Images](https://virtx.sh/docs/guides/images/) covers the rest of the command. ### Inputs and results - Before a turn, write what the agent should read onto a volume mounted in its sandbox, read-only if it should not change it. - After the turn, read what it wrote, from the volume or from the sandbox. - Say where in the instruction, so the agent knows where to look and where to write. virtx's [Reading and writing files](https://virtx.sh/docs/guides/reading-writing-files/) covers doing this from your code. ### Picking up later An agent's work is in two places: its history, and its sandbox's files. To carry on where a run stopped: - Build an agent with the same history (`history(...)` on the `AgentBuilder`). - Hand it the same sandbox, found again with `get_sandbox`. - A sandbox's own files go when it is removed, so put what a later run starts from on a volume. ### Sandbox options `create_sandbox` takes these options, among others. What each means for an agent: | Option | For the agent | virtx docs | | --- | --- | --- | | `volumes` | Where it reads your files and leaves its results. | [Mounting volumes](https://virtx.sh/docs/guides/mounting-volumes/) | | `network` | Whether its commands reach the internet. On unless turned off. `web_search` and `web_fetch` run in your program, not the sandbox, so they work either way. | [Networks and ports](https://virtx.sh/docs/guides/networks-ports/) | | `ports` | A server it starts in the sandbox, reached from outside. | [Networks and ports](https://virtx.sh/docs/guides/networks-ports/) | | `vcpus`, `memory_mib`, `disk_gib` | Room for heavy commands, and for what it installs or writes outside its volumes. | [Setting up sandboxes](https://virtx.sh/docs/guides/setting-sandboxes/) | | `gpu`, `gpu_memory_mib` | A GPU through Vulkan, for work such as deep learning. | [Using GPUs](https://virtx.sh/docs/guides/using-gpus/) | | `abins` (`.abin(name)` in Rust) | virtx's own programs at `/abin`, such as `index`, `docread` and `display`. Each one with a `SKILL.md` becomes one of the agent's [skills](https://ailoy.co/docs/guides/skills/). | [Setting up sandboxes](https://virtx.sh/docs/guides/setting-sandboxes/) | Node.js spells them in camelCase (`memoryMib`, `diskGib`, `gpuMemoryMib`), and Rust sets them on `SandboxCreateArgs`. virtx's [Hello world](https://virtx.sh/docs/hello-world/) covers which server to run, on your machine or elsewhere. ### Troubleshooting virtx's errors carry a `source` (`server`, `job`, `transport` or `client`) and, from the server, an HTTP `status`. Tell them apart by those, not by the message ([Errors](https://virtx.sh/docs/reference/api/#errors)). | What you see | Why, and what to do | | --- | --- | | `` `` exited with `` from `build_image(...).complete()` | A step of the recipe failed. The job's log, printed above it by step (`STEP 1/2: …`), shows the command's output. | | `: not found, or private and pulled without credentials` | The image name is wrong, or the image is private. | | `no image here is tagged : pull it first` (status `404`) | Pull or build the image before making a sandbox from it. | | `status` `400`, such as `abins: this server has no program called …` | An option is out of range or unknown. The message names it. | | `status` `409` | The name is taken, the volume is in use, or the sandbox's VM has exited. | | `this server was built without a GPU` (status `422`) | This server can't give a GPU. Use a release build of virtx's server. | | Vulkan in a GPU sandbox finds no device | The host has no Vulkan driver. Install the GPU maker's driver on Linux or Windows; on macOS, virtx brings its own. | | A command in the sandbox can't resolve or reach a host | The sandbox was made with `network` off, which leaves it no network device. Turn it on, or fetch the data in your program and write it in. `web_search` and `web_fetch` work either way. | | The agent's file isn't in `/artifacts` | The agent wrote it somewhere else. Name the folder in the instruction, as the examples do, and check the agent's last message for the path it used. | | The first sandbox fails to boot, with `boot_failed` | See [Installation](https://ailoy.co/docs/guides/installation/#troubleshooting). | ### Next - [Running an agent](https://ailoy.co/docs/guides/running/): run a turn whole or streamed, and many turns. - [Tools](https://ailoy.co/docs/guides/tools/): what the agent can do in its sandbox. --- ## Running an agent https://ailoy.co/docs/guides/running/ Run a turn whole or streamed, stop it, carry a conversation over many turns, and what happens when a turn fails. A turn starts with your query and ends when the model answers without asking for a tool. In between, the model may ask for tools any number of times, and their results go back to it. [How an agent works](https://ailoy.co/docs/concepts/#a-turn) walks through it. ### run and run_stream `agent.run(query)` yields one `MessageOutput` for each message of the turn as it completes: the assistant's tool calls, each tool result, and the final answer. The query is a string or a [message](https://ailoy.co/docs/guides/message-format/#sending-a-message). | Field | Description | | --- | --- | | `message` | The complete message. | | `finish_reason` | Why the model stopped: `stop`, `length`, `tool_call` or `refusal` (with a `reason`). | | `usage` | Input and output token counts, when the provider reports them. | `agent.run_stream(query)` (`runStream` in Node.js) yields `MessageDeltaOutput`s instead: - Each `delta` holds a piece of a message, such as a few tokens of text or thinking, and each tool result comes as one delta. - Concatenated, the deltas between two `finish_reason`s make up the message `run` would yield. In Rust, the `Delta` trait's `accumulate` and `finish` do this for you. Use `run` when you act on whole messages, and `run_stream` to show the model's words as it writes them. **Python** ```python async for output in agent.run_stream("Explain what a microVM is."): for part in output["delta"]["contents"]: if part["type"] == "text": print(part["text"], end="", flush=True) ``` **Node.js** ```js for await (const { delta } of agent.runStream('Explain what a microVM is.')) { for (const part of delta.contents) { if (part.type === 'text') process.stdout.write(part.text) } } ``` **Rust** ```rust let query = Message::new(Role::User).with_contents([Part::text("Explain what a microVM is.")]); let mut stream = agent.run_stream(query); while let Some(output) = stream.next().await { for part in &output?.delta.contents { if let PartDelta::Text { text } = part { print!("{text}"); } } } ``` ### Iterating a turn Nothing runs until the turn is iterated: `agent.run(...)` returns a value to loop over, and each step of the loop moves the turn on. - To stop a turn partway, break out of the loop. In Python, `aclose()` on the run does the same; in Rust, drop the stream. - As the next turn begins, each tool call the model made that has no result yet gets a result saying so, which keeps the conversation in a form the model's API accepts. ### Many turns Every query, assistant message and tool result is added to the agent's history, so the next `run` continues where the last one left off. Read it with `agent.history`. In Python and Node.js, reading it while a turn is being iterated raises. To continue a conversation in a new agent, as after your program restarts, pass the saved messages to the builder: **Python** ```python agent = await AgentBuilder("anthropic/claude-haiku-5-5").history(saved_messages).build() ``` **Node.js** ```js const agent = await new AgentBuilder('anthropic/claude-haiku-5-5').history(savedMessages).build() ``` **Rust** ```rust let agent = AgentBuilder::new("anthropic/claude-haiku-5-5") .history(saved_messages) .build() .await?; ``` Messages are plain JSON, so you can store them wherever you like and load them back unchanged. An agent that worked in a sandbox also needs its files to carry on: [Picking up later](https://ailoy.co/docs/guides/sandbox/#picking-up-later). ### When a turn fails A turn ends with an error rather than a message in these cases, and the agent stays usable: - **The model fails before its first message of the turn**, as when its API is down or a key is wrong. The query is taken back out of the history, so the same query can be run again. - **The model's output limit cuts its reply short.** The cut reply is yielded and stays in the history, then the turn ends with an error, so the next query can ask for the rest. - **The model's API refuses an image in a tool result.** The image is replaced by a note saying so and the request is sent again, once for each batch of tool results; a second refusal ends the turn. A tool that fails does not end the turn: an unknown tool, a missing sandbox, an exception in your function or a failed command becomes that call's result, and the model can try something else. - In Python, ailoy's own errors are `AiloyError`, and a sandbox's failures are virtx's `VirtxError`, with the server's `status`. - In Node.js, an error from the agent has `code` `AILOY_ERROR`, or `VIRTX_ERROR` for a sandbox's failure. A call on virtx's own package, such as `createSandbox`, throws its `VirtxError` instead, with `source` and `status`. ### Usage Each `MessageOutput` from the model carries `usage`, its input and output token counts, when the provider reports them. A long run's input grows with every tool result; [Context manager](https://ailoy.co/docs/guides/context-manager/) keeps it under a limit. ### Next - [Context manager](https://ailoy.co/docs/guides/context-manager/): keep a long run under the model's context limit. - [Message format](https://ailoy.co/docs/guides/message-format/): the messages `run` yields. --- ## Context manager https://ailoy.co/docs/guides/context-manager/ Replace old tool results past a token limit, and old screenshots past a cap. The agent sends its whole history to the model on every call, so a long run sends more with each step: every tool call adds its result: a file it read, a page it fetched or a command's output. The context manager keeps it down in two ways: it replaces old tool results with a placeholder once the model's input grows past a limit, and it replaces old screenshots once the history holds too many. ### Turning it on Every setting has a default, and an agent without a context manager behaves as if it had one with every default: the image cap is on and the token limit is off. | Setting | Default | What it is | | --- | --- | --- | | `max_input_tokens` (`maxInputTokens`) | 0 | The input the model reports, in tokens, past which old tool results are replaced. `0` turns truncation off. | | `preserve_recent_turns` (`preserveRecentTurns`) | 3 | How many of the latest user turns are left as they are. | | `max_images` (`maxImages`) | 30 | Images in tool results the history may hold at the start of a turn. `0` turns the cap off. | | `preserve_recent_images` (`preserveRecentImages`) | 10 | Images in tool results left once the cap is passed. | **Python** ```python agent = await ( AgentBuilder("anthropic/claude-haiku-5-5") .sandbox(sandbox) .context_manager(max_input_tokens=50_000, preserve_recent_turns=2) .build() ) ``` **Node.js** ```js const agent = await new AgentBuilder('anthropic/claude-haiku-5-5') .sandbox(sandbox) .contextManager({ maxInputTokens: 50000, preserveRecentTurns: 2 }) .build() ``` **Rust** ```rust use ailoy::agent::ContextManager; let agent = AgentBuilder::new("anthropic/claude-haiku-5-5") .sandbox(sandbox) .context_manager(ContextManager { max_input_tokens: 50_000, preserve_recent_turns: 2, ..Default::default() }) .build() .await?; ``` ### Tool results past the token limit As each turn begins, once the user's message is in the history, the agent looks at the last input token count the model reported. When that is more than `max_input_tokens`, it truncates the history: - A turn is a user message and everything after it up to the next user message. The last `preserve_recent_turns` turns, including the one just begun, are left as they are. If the history has fewer turns than that, nothing changes. `1` and `0` both leave only the turn just begun. - In the turns before those, each tool result's contents become the text `[context truncated]`. The result keeps the id of the call it answers, since APIs such as Anthropic's refuse a tool call that has no result. - The system message, the user's messages and the model's own messages, tool calls included, stay whole. No message is removed. The placeholders replace the results in the agent's history, so `agent.history` shows them too, and they stay in it. The count comes from a call already made, and the history is truncated only as a turn begins. A turn that goes past the limit runs to its end with the history unchanged, and the next turn begins truncated. The requests of a turn send back the thinking the model has produced in it. From Claude 5.1 on, the API can refuse a thinking block once anything before it has changed ([Keeping the prefix unchanged](https://platform.claude.com/docs/en/build-with-claude/preserved-thinking#prefix-check)), so the history stays as it is until the turn ends. A reply without `usage` leaves the last count in place, so a model that never reports usage, such as a model of your own whose replies leave it out, never triggers truncation. And since only tool results are replaced, a history whose messages alone are past the limit keeps growing. ### Images past the cap At the start of each turn, when the tool results hold more than `max_images` images, the oldest become the text `[image from an earlier turn removed]` until `preserve_recent_images` remain. - Only images in tool results count and only they are replaced: a screenshot, an image read with `imgread`, an image an MCP tool returned. Images you attach to a message are never replaced. - Within a turn nothing is replaced, so a turn of many screenshots sends them all until the next turn starts. - The cap counts across every turn, the last `preserve_recent_turns` included. As with the token limit, the placeholders stay in `agent.history`. Apart from the cap, and for every model, an embedded image past 2576 pixels on its longer edge, attached or returned by a tool, is shrunk to that edge before it enters the history. The shrunk image is turned upright by its EXIF orientation and keeps its color profile, and comes back as: | Image | Comes back as | | --- | --- | | Any but a WebP | Its own format | | A WebP with transparent pixels | PNG | | An opaque lossless WebP | PNG, or JPEG if that PNG would pass 5 MB in base64 | | Any other WebP | JPEG | | One that would still come out past 5 MB in base64, an animated one, or a GIF of any size | Left as it is | ### Next - [Model providers](https://ailoy.co/docs/guides/model-providers/): naming a model and choosing how it runs. - [Tools](https://ailoy.co/docs/guides/tools/): built-in tools, your own functions, MCP and the browser. --- ## Model providers https://ailoy.co/docs/guides/model-providers/ Name a model and choose how it runs: a CLI login, the maker's API, Bedrock, OpenRouter or a server you run yourself. ### Naming a model Name the model as `/` when you build the agent. The name is the one its maker gives it: the official API id for Claude, GPT and Gemini, the Hugging Face repo id for open-weight models, and the API id for a model with no repo, such as EXAONE's `k-exaone_v2.5`. The same name works whichever way the model runs. | Models | Org | Example | | --- | --- | --- | | Claude | `anthropic` | `anthropic/claude-haiku-5-5` | | GPT | `openai` | `openai/gpt-6-luna` | | Gemini | `google` | `google/gemini-3.1-pro` | | DeepSeek | `deepseek-ai` | `deepseek-ai/DeepSeek-V3.2` | | Kimi | `moonshotai` | `moonshotai/Kimi-K2-Thinking` | | GLM | `zai-org` | `zai-org/GLM-4.6` | | Qwen | `Qwen` | `Qwen/Qwen3-235B-A22B-Instruct-2507` | | EXAONE | `LGAI-EXAONE` | `LGAI-EXAONE/k-exaone_v2.5` | **Python** ```python agent = await AgentBuilder("anthropic/claude-haiku-5-5").build() ``` **Node.js** ```js const agent = await new AgentBuilder('anthropic/claude-haiku-5-5').build() ``` **Rust** ```rust let agent = AgentBuilder::new("anthropic/claude-haiku-5-5").build().await?; ``` For a CLI, the org alone (`anthropic`) runs the CLI's default model. ### Backends Each org's models run on one **backend**: | Backend | Runs the model through | Needs | | --- | --- | --- | | `cli` | The org's CLI: Claude Code (`claude`), Codex (`codex`) or Gemini CLI (`gemini`) | The CLI on `PATH`, logged in | | `api` | The org's own API | `ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, `GEMINI_API_KEY`, `DEEPSEEK_API_KEY`, `KIMI_API_KEY` (or `MOONSHOT_API_KEY`), `ZAI_API_KEY`, `DASHSCOPE_API_KEY` (Qwen) or `EXAONE_API_KEY` | | `bedrock` | Amazon Bedrock | `AWS_BEARER_TOKEN_BEDROCK`; the region from `AWS_REGION`, then `AWS_DEFAULT_REGION`, else `us-east-1` | | `openrouter` | OpenRouter | `OPENROUTER_API_KEY` | | `self-hosted` | A server you run yourself, through the OpenAI-compatible Chat Completions API it serves: vLLM, llama-server, Ollama, LM Studio or SGLang | `SELF_HOSTED_BASE_URL`, and `SELF_HOSTED_API_KEY` if the server wants one | By default, Claude, GPT and Gemini run through their CLIs, and the other orgs through their own APIs. Keys are read from the environment when a model is built, so set them before that. `cli` and `api` know the orgs in [Naming a model](#naming-a-model). The other backends build a model for any org, `meta-llama` or `mistralai` as well. Such an org has no backend until you set one with `set_lang_model_provider`; building its model before that fails. Which backends serve which org: | Org | `cli` | `api` | `bedrock` | `openrouter` | `self-hosted` | | --- | :-: | :-: | :-: | :-: | :-: | | `anthropic` | ✓ | ✓ | ✓ | ✓ | ✓ | | `openai` | ✓ | ✓ | ✓ | ✓ | ✓ | | `google` | ✓ | ✓ | | ✓ | ✓ | | `deepseek-ai`, `moonshotai`, `zai-org`, `Qwen`, `LGAI-EXAONE` | | ✓ | ✓ | ✓ | ✓ | | any other org | | | ✓ | ✓ | ✓ | Bedrock and OpenRouter name models their own way. Ailoy looks your model up in their catalogs, so you still write `anthropic/claude-haiku-5-5`, and the catalog decides which Bedrock or OpenRouter id it runs as. A server you run yourself is asked what it serves too; [A server of your own](#a-server-of-your-own) says how the id is found, and how to name it yourself when the server calls the model something else. ### Choosing a backend Set an org's backend with `set_lang_model_provider` (`setLangModelProvider` in Node.js) before building an agent. It applies to every model of that org built afterwards. **Python** ```python import ailoy ailoy.set_lang_model_provider("anthropic", "api") agent = await AgentBuilder("anthropic/claude-haiku-5-5").build() ``` **Node.js** ```js const { setLangModelProvider } = require('@brekkylab/ailoy') setLangModelProvider('anthropic', 'api') const agent = await new AgentBuilder('anthropic/claude-haiku-5-5').build() ``` **Rust** ```rust use ailoy::model::{Backend, set_lang_model_provider}; set_lang_model_provider("anthropic", Backend::Api); let agent = AgentBuilder::new("anthropic/claude-haiku-5-5").build().await?; ``` `remove_lang_model_provider` (`removeLangModelProvider`) takes the org's provider away, after which its models can't be built. ### A server of your own `self-hosted` reads its server from the environment, one for the whole process. To name the server per org, give `set_lang_model_provider` the backend together with the server's URL, and an API key if the server wants one. Two servers, say vLLM for code and Ollama for chat, are two orgs: **Python** ```python ailoy.set_lang_model_provider("Qwen", {"backend": "self-hosted", "base_url": "http://gpu-box:8000/v1", "api_key": "..."}) ailoy.set_lang_model_provider("meta-llama", {"backend": "self-hosted", "base_url": "http://localhost:11434/v1", "models": {"Llama-3.3-70B-Instruct": "llama3.3:70b"}}) coder = await AgentBuilder("Qwen/Qwen3-Coder-30B-A3B-Instruct").build() chat = await AgentBuilder("meta-llama/Llama-3.3-70B-Instruct").build() ``` **Node.js** ```js setLangModelProvider('Qwen', { backend: 'self-hosted', base_url: 'http://gpu-box:8000/v1', api_key: '...' }) setLangModelProvider('meta-llama', { backend: 'self-hosted', base_url: 'http://localhost:11434/v1', models: { 'Llama-3.3-70B-Instruct': 'llama3.3:70b' } }) const coder = await new AgentBuilder('Qwen/Qwen3-Coder-30B-A3B-Instruct').build() const chat = await new AgentBuilder('meta-llama/Llama-3.3-70B-Instruct').build() ``` **Rust** ```rust use ailoy::model::{LangModelServer, set_lang_model_provider}; set_lang_model_provider("Qwen", LangModelServer::new("http://gpu-box:8000/v1")?.with_api_key("...")); set_lang_model_provider("meta-llama", LangModelServer::new("http://localhost:11434/v1")?.with_model("Llama-3.3-70B-Instruct", "llama3.3:70b")); let coder = AgentBuilder::new("Qwen/Qwen3-Coder-30B-A3B-Instruct").build().await?; let chat = AgentBuilder::new("meta-llama/Llama-3.3-70B-Instruct").build().await?; ``` The model keeps its name whatever the server calls it. When a model is built, Ailoy finds the id to send in three steps and takes the first that gives one: `models` (`with_model` in Rust), which maps a name to the id the server serves it as; the server's own list at `/models`, where an id equal to `/` or to `` alone counts, ignoring case; and the desc as you wrote it. So vLLM, which serves Hugging Face repo ids, needs nothing; LM Studio lists `qwen/qwen3-0.6b` and is sent that for `Qwen/Qwen3-0.6B`; and Ollama's `llama3.3:70b` is nothing like `Llama-3.3-70B-Instruct`, so it is mapped, as above. `get_lang_model_provider` answers `self-hosted`. Another endpoint that serves the OpenAI-compatible Chat Completions API, such as a LiteLLM gateway or Together's API, runs on `self-hosted` the same way: its URL as `base_url` and its key as `api_key`. ### Model options Two options go to every backend: | Option | Builder method | Description | | --- | --- | --- | | `thinking_effort` | `thinking_effort` (`thinkingEffort`) | How much the model thinks before it answers: `low`, `medium` or `high`. Unset, the model's default. | | `output_schema` | `output_schema` (`outputSchema`) | A JSON schema the model's answers must match. | **Python** ```python agent = await ( AgentBuilder("openai/gpt-6-luna") .thinking_effort("high") .output_schema({"type": "object", "properties": {"answer": {"type": "string"}}, "required": ["answer"]}) .build() ) ``` **Node.js** ```js const agent = await new AgentBuilder('openai/gpt-6-luna') .thinkingEffort('high') .outputSchema({ type: 'object', properties: { answer: { type: 'string' } }, required: ['answer'] }) .build() ``` **Rust** ```rust use ailoy::{model::ThinkingEffort, to_value}; let agent = AgentBuilder::new("openai/gpt-6-luna") .thinking_effort(ThinkingEffort::High) .output_schema(to_value!({"type": "object", "properties": {"answer": {"type": "string"}}, "required": ["answer"]})) .build() .await?; ``` On `self-hosted`, and for EXAONE on `api`, `thinking_effort` is sent two ways, since servers read different ones: as `reasoning_effort` (`low`, `medium` or `high`), the field OpenAI's Chat Completions grades thinking by, and as the chat template's `enable_thinking` (and `thinking`) in `chat_template_kwargs`, which turns thinking on rather than grading it. `output_schema` is sent as a `json_schema` `response_format`. vLLM reads `chat_template_kwargs` and `response_format`, and its documentation says it hands `reasoning_effort` to the chat template, turning `enable_thinking` on with it. What the other servers do with them, measured on 2026-11-09 with Qwen3-0.6B on each local server and `k-exaone_v2.5` on EXAONE's API, a schema with `additionalProperties: false` telling enforcement from obedience: | Server | `reasoning_effort` | `chat_template_kwargs` | `response_format` | Thinking comes back as | | --- | --- | --- | --- | --- | | llama-server (llama.cpp build 11146) | Not read: `"bogus"` is accepted too | Read: `enable_thinking: false` switched the thinking off | Enforced | `reasoning_content` | | Ollama 0.40.12 | Read, as `"bogus"` is refused, but `low`, `medium` and `high` left Qwen3's thinking as it was | Ignored | Enforced | `reasoning` | | LM Studio 0.4.26 | Read, as `"bogus"` is refused, but `low`, `medium` and `high` left Qwen3's thinking as it was | Ignored | Enforced, with no thinking while the reply is structured | `reasoning_content` | | EXAONE API (`k-exaone_v2.5`) | Read, as `"bogus"` is refused, `medium` included; on one counting problem the thinking did not follow it, `low` taking 991 to 1728 reasoning tokens over six runs and `high` 1054 to 2131 over four | `enable_thinking: false` left the model thinking, with the thinking and its `` in the reply | Enforced | `reasoning_content` | So with Qwen3, `thinking_effort` changes nothing on llama-server, Ollama or LM Studio: the model thinks as its template defaults. EXAONE always thinks, and with `thinking_effort` unset it runs at its own default effort, which its documentation gives as `max`. SGLang has not been measured. ### Running a model without an agent `LangModel` builds a model the way an agent does, and runs it on a conversation you give it: no tools are called and no history is kept. `infer` returns the whole reply as a `MessageOutput`, and `infer_stream` (`inferStream`) yields `MessageDeltaOutput`s as the model writes. **Python** ```python from ailoy import LangModel model = await LangModel.create("anthropic/claude-haiku-5-5") messages = [{"role": "user", "contents": [{"type": "text", "text": "Hi"}]}] output = await model.infer(messages) async for delta in model.infer_stream(messages, options={"thinking_effort": "low"}): ... ``` **Node.js** ```js const { LangModel } = require('@brekkylab/ailoy') const model = await LangModel.create('anthropic/claude-haiku-5-5') const messages = [{ role: 'user', contents: [{ type: 'text', text: 'Hi' }] }] const output = await model.infer(messages) for await (const delta of model.inferStream(messages, [], { thinking_effort: 'low' })) { // ... } ``` **Rust** ```rust use ailoy::{ message::{Message, Part, Role}, model::{LangModelOptions, create_lang_model}, }; let model = create_lang_model("anthropic/claude-haiku-5-5").await?; let messages = [Message::new(Role::User).with_contents([Part::text("Hi")])]; let output = model.infer(&messages, &[], &LangModelOptions::default()).await?; let mut deltas = model.infer_stream(&messages, &[], &LangModelOptions::default()); ``` Tools, if you pass them, are only described to the model: its tool calls come back in the reply for you to run. ### Bringing your own model An org can also be served by your own code. Instead of a backend name, give `set_lang_model_provider` a **factory**: it's called with the org and the name after the slash (`None`/`null` when the model is named by the org alone) and returns the model. The model has - `infer(messages, tools, options)`, returning a `MessageOutput` (or, in Python and Node.js, an awaitable or promise of one), and optionally - `infer_stream(messages, tools, options)` (`inferStream`), yielding `MessageDeltaOutput`s. Without it, streaming gives `infer`'s reply as one delta. The factory may also return a `LangModel`, to serve the org with a model from another org. **Python** ```python class Echo: def __init__(self, name): self.name = name async def infer(self, messages, tools, options): text = messages[-1]["contents"][0]["text"] return { "message": {"role": "assistant", "contents": [{"type": "text", "text": text}]}, "finish_reason": {"type": "stop"}, } ailoy.set_lang_model_provider("mine", lambda org, name: Echo(name)) agent = await AgentBuilder("mine/echo").build() ``` **Node.js** ```js class Echo { constructor(name) { this.name = name } async infer(messages, tools, options) { const text = messages[messages.length - 1].contents[0].text return { message: { role: 'assistant', contents: [{ type: 'text', text }] }, finish_reason: { type: 'stop' }, } } } setLangModelProvider('mine', (org, name) => new Echo(name)) const agent = await new AgentBuilder('mine/echo').build() ``` **Rust** ```rust use std::sync::Arc; use ailoy::{ message::{FinishReason, Message, MessageDeltaOutput, MessageOutput, Role}, model::{InferLangModel, LangModelOptions, LangModelProvider, set_lang_model_provider}, tool::ToolDesc, }; use futures::{future::BoxFuture, stream::{self, BoxStream}, StreamExt as _}; struct Echo; impl InferLangModel for Echo { fn infer( &self, messages: &[Message], _tools: &[ToolDesc], _options: &LangModelOptions, ) -> BoxFuture<'static, anyhow::Result> { let contents = messages.last().map(|m| m.contents.clone()).unwrap_or_default(); Box::pin(async move { Ok(MessageOutput { message: Message::new(Role::Assistant).with_contents(contents), finish_reason: FinishReason::Stop {}, usage: None, }) }) } fn infer_stream( &self, messages: &[Message], tools: &[ToolDesc], options: &LangModelOptions, ) -> BoxStream<'static, anyhow::Result> { let output = self.infer(messages, tools, options); stream::once(async move { output.await.map(MessageDeltaOutput::from) }).boxed() } } set_lang_model_provider("mine", LangModelProvider::custom(|_org, _name| Ok(Arc::new(Echo)))); let agent = AgentBuilder::new("mine/echo").build().await?; ``` In Python and Node.js the factory itself must return the model directly, not an awaitable or promise of it. The model's methods are called with the messages, tools and options as dicts or objects, the same shapes the [message format](https://ailoy.co/docs/guides/message-format/) describes. ### Troubleshooting | What you see | Why, and what to do | | --- | --- | | `failed to start the claude CLI` (or `codex`, `gemini`), on the first turn | The CLI isn't installed, or isn't on the `PATH` of your program. Install it ([With a CLI login](https://ailoy.co/docs/guides/installation/#with-a-cli-login-default)), or switch the org to `api`. | | The CLI's own error on the first turn, such as Claude Code's "Not logged in" | Log in: `claude auth login`, `codex login`, or run `gemini` and sign in. Codex is read from its `auth.json`, so a login kept in the system keyring (`cli_auth_credentials_store`) isn't found. | | `ANTHROPIC_API_KEY is not set` (or another `…_API_KEY`), at `build()` | Set the variable before building the agent; a blank one counts as unset. [Backends](#backends) lists each org's variable. | | `'' has no CLI`, or `'' has no API of its own` | Only `anthropic`, `openai` and `google` have a CLI, and `api` knows only the orgs in [Naming a model](#naming-a-model). Use `bedrock`, `openrouter` or `self-hosted` for any other. | | `no provider set for lang model org ''` | The org has no default backend. Set one with `set_lang_model_provider` first. | | `AWS_BEARER_TOKEN_BEDROCK is not set` | Bedrock is reached with a bearer token, not AWS access keys or a profile. Set the token. | | `Bedrock request failed with status …` on the first turn | The region is wrong, as `us-east-1` is used when neither `AWS_REGION` nor `AWS_DEFAULT_REGION` is set, or Bedrock doesn't serve the model there. Ailoy builds an id for any model, so a model Bedrock lacks, such as Gemini, fails only when it is called. | | `SELF_HOSTED_BASE_URL is not set` | Set it, or give the server per org with `set_lang_model_provider` ([A server of your own](#a-server-of-your-own)). | | `chat completions request failed with status 404: …` | The `base_url` is missing its `/v1`. Ailoy adds `/chat/completions` to the URL as given. | | A connection error naming `/chat/completions` on the first turn | The server isn't running, or the host or port is wrong. `build()` still succeeds and only logs `listing the models at /models failed`. | --- ## Message format https://ailoy.co/docs/guides/message-format/ The one message format Ailoy uses for every provider. Everything that goes into and comes out of an agent is a **message**. Ailoy uses one format for every provider, and converts it to the provider's own format when it calls the model. A message has a **role** and a list of **parts**: ```json { "role": "user", "contents": [ { "type": "text", "text": "Can you explain how photosynthesis works?" } ] } ``` In Python and Node.js a message is a plain dict or object of this shape. In Rust it is `ailoy::message::Message`. ### Role | Role | Who writes it | | --- | --- | | `system` | Instructions that set the model's behaviour. Always the first message. | | `user` | The end user. | | `assistant` | The model. | | `tool` | A tool, with the result of a call the model asked for. | You don't usually write the system message yourself. The agent builds it from `.instruction(...)` and its [skills](https://ailoy.co/docs/guides/skills/), those of `skill(...)` and of its sandbox's abins, and puts it at the front of the history, unless the history you give it already has one. ### Fields | Field | Description | | --- | --- | | `role` | One of the roles above. | | `contents` | What was said, as a list of parts. | | `thinking` | The model's reasoning trace, kept apart from `contents`. Only on assistant messages from reasoning models. | | `tool_calls` | The tools the model wants to call, as `function` parts. Only on assistant messages. | | `id` | On a `tool` message, the id of the call it answers. | | `signature` | A provider-issued signature for `thinking`, sent back as is on the next turn. | Reasoning and tool calls are stored in their own fields rather than in `contents`, so the answer the user sees is never mixed with them. ### Part A part is one unit of content. A message made of text, an image and more text is three parts. | `type` | Shape | Used for | | --- | --- | --- | | `text` | `{ "text": "..." }` | Plain text. | | `image` | `{ "image": { "type": "url", "url": "..." } }` or `{ "image": { "type": "embedded", "mime_type": "image/png", "data": ... } }` | An image, by URL or as bytes. | | `function` | `{ "id": "...", "function": { "name": "...", "arguments": { ... } } }` | A tool call, inside `tool_calls`. | | `value` | `{ "value": ... }` | Any JSON value, such as a tool result. | > **Tip:** > Not every provider accepts image URLs (Gemini doesn't). Embedded bytes work everywhere that takes images. ### Sending a message `agent.run` takes either a string, which becomes one user text part, or a full message. Pass a message when you need more than text, such as an image: **Python** ```python from pathlib import Path query = { "role": "user", "contents": [ {"type": "image", "image": {"type": "embedded", "mime_type": "image/jpeg", "data": Path("dog.jpg").read_bytes()}}, {"type": "text", "text": "What do you see in this image?"}, ], } async for output in agent.run(query): ... ``` **Node.js** ```js const fs = require('fs') const query = { role: 'user', contents: [ { type: 'image', image: { type: 'embedded', mime_type: 'image/jpeg', data: fs.readFileSync('dog.jpg') } }, { type: 'text', text: 'What do you see in this image?' }, ], } for await (const output of agent.run(query)) { // ... } ``` **Rust** ```rust use ailoy::message::{Message, Part, Role}; let query = Message::new(Role::User).with_contents([ Part::image_embedded("image/jpeg", std::fs::read("dog.jpg")?.into())?, Part::text("What do you see in this image?"), ]); let mut stream = agent.run(query); ``` ### Tool calls and results When the model decides to call a tool, its assistant message carries the call in `tool_calls`: ```json { "role": "assistant", "contents": [{ "type": "text", "text": "Let me check the weather." }], "tool_calls": [ { "type": "function", "id": "call_01HZX2", "function": { "name": "get_weather", "arguments": { "city": "Seoul" } } } ] } ``` The agent runs the tool and adds a `tool` message whose `id` matches the call: ```json { "role": "tool", "id": "call_01HZX2", "contents": [{ "type": "value", "value": 12.3 }] } ``` If the tool fails, the error still comes back as a `tool` message, so the model can see it and recover. The agent then calls the model again, and repeats until the model answers without calling a tool. ### What `run` yields `agent.run` yields each message of a turn as a `MessageOutput`, and `agent.run_stream` yields `MessageDeltaOutput`s, pieces of those messages: [Running an agent](https://ailoy.co/docs/guides/running/#run-and-run_stream). ### History An agent keeps every message of the conversation in its history, as plain JSON you can store and give back to a new agent: [Many turns](https://ailoy.co/docs/guides/running/#many-turns). --- ## Tools https://ailoy.co/docs/guides/tools/ The built-in tools, functions of your own, and the tools of MCP servers and the browser. An agent calls the tools you give it on the `AgentBuilder`: the built-in ones on this page, functions of your own, the tools of an [MCP server](https://ailoy.co/docs/guides/using-mcp/) or of the [browser](https://ailoy.co/docs/guides/using-browser/), and [the one `memory(...)` adds](#memory). ### Built-in tools #### A shell and files An agent given a sandbox with `sandbox(...)` gets a shell and tools to read and change files in it, with nothing else to call. Which tools come with the shell depends on the model's org: | Org | Tools | | --- | --- | | `openai` | `shell`, `apply_patch`, `imgread` | | `google` | `shell`, `read_file`, `write`, `edit`, `imgread` | | `deepseek-ai`, `moonshotai`, `zai-org`, `Qwen`, `LGAI-EXAONE` | `shell`, `read`, `write`, `edit` | | Any other, `anthropic` included | `shell`, `read`, `write`, `edit`, `imgread` | | Tool | What it does | | --- | --- | | `shell` | Runs a command, with an optional timeout in seconds. | | `read` | Reads up to 2,000 numbered lines of a text file, or `limit` lines from line `offset`. | | `read_file` | Reads up to 2,000 lines of a text file, or the lines from `start_line` to `end_line`. | | `write` | Writes a text file, replacing one already at that path. | | `edit` | Replaces an exact string that occurs once in a text file, or, with `replace_all`, every occurrence of it. | | `apply_patch` | Adds, deletes, updates and moves files, from a patch in the format Codex uses. | | `imgread` | Reads a PNG, JPEG, GIF or WebP image of up to 5 MB and gives it to the model as an image. | `imgread` is left out for `deepseek-ai`, `moonshotai`, `zai-org`, `Qwen` and `LGAI-EXAONE` because their backends pass a tool result to the model as text, so the model would get a label in place of the image. The seven tools in the table come with `sandbox(...)` and run in that sandbox, as in [Giving an agent a sandbox](https://ailoy.co/docs/guides/sandbox/); an agent without one does not get them. The agent does not start, stop or remove its sandbox. virtx stops an idle sandbox's VM and boots it again over what it wrote when it is next needed, so a later call finds the files as the last one left them. #### The web `web_search_tool` and `web_fetch_tool` (`webSearchTool`, `webFetchTool`) do not come with the sandbox. The two tools run in your program's process, not in the sandbox, so they work without one. - `web_search` sends the query to several search engines at once and merges what they find, one result per URL, best first. It answers with up to 10 results, or up to 30 when the model asks for more. `web_search_tool` takes the engines to use: `Bing`, `Brave`, `DuckDuckGo`, `Google`, `Mojeek`, `Naver`, `Startpage`, `Yahoo` and `Yandex`. None, or an empty list, uses them all. - `web_fetch` fetches one URL. An HTML page comes back as its visible text (the default), as Markdown, or as the HTML itself; any other body, such as JSON, comes back as it is. A long body comes in pieces, and the model asks for the next one with `offset`; only the body's first 2 MiB are read. It makes at most one request a second to a host, and only to addresses on the public internet: loopback, the local network and cloud metadata addresses are refused. **Python** ```python agent = await ( AgentBuilder("anthropic/claude-haiku-5-5") .web_search_tool(["DuckDuckGo", "Brave"]) .web_fetch_tool() .build() ) ``` **Node.js** ```js const agent = await new AgentBuilder('anthropic/claude-haiku-5-5') .webSearchTool(['DuckDuckGo', 'Brave']) .webFetchTool() .build() ``` **Rust** ```rust use ailoy::tool::WebSearchEngineKind; let agent = AgentBuilder::new("anthropic/claude-haiku-5-5") .web_search_tool(vec![WebSearchEngineKind::DuckDuckGo, WebSearchEngineKind::Brave]) .web_fetch_tool() .build() .await?; ``` ### Your own functions A function of your program becomes a tool once it is registered with a **tool description**: the name the model calls it by, what it does, and a JSON schema for its arguments. The agent gets the description from `tool(...)`, or a list of them from `tools(...)`. In Python and Node.js, registering returns it; in Rust you build it with `ToolDescBuilder` and register the function under its name. This gives the agent `order_status`, which looks an order up by its id: **Python** ```python import asyncio from ailoy import AgentBuilder, register_tool ORDERS = {"A-1001": {"status": "shipped", "eta": "2026-10-24"}} def order_status(order_id: str) -> dict: if order_id not in ORDERS: raise KeyError(f"no order {order_id}") return ORDERS[order_id] async def main() -> None: desc = register_tool( { "name": "order_status", "description": "Look up an order's status and expected delivery date by its id.", "parameters": { "type": "object", "properties": {"order_id": {"type": "string", "description": "The order id, such as A-1001"}}, "required": ["order_id"], }, }, order_status, ) agent = await AgentBuilder("anthropic/claude-haiku-5-5").tool(desc).build() async for output in agent.run("When does order A-1001 arrive?"): for part in output["message"]["contents"]: if part["type"] == "text": print(part["text"]) asyncio.run(main()) ``` **Node.js** ```js const { AgentBuilder, registerTool } = require('@brekkylab/ailoy') async function main() { const orders = { 'A-1001': { status: 'shipped', eta: '2026-10-24' } } const desc = registerTool( { name: 'order_status', description: "Look up an order's status and expected delivery date by its id.", parameters: { type: 'object', properties: { order_id: { type: 'string', description: 'The order id, such as A-1001' } }, required: ['order_id'], }, }, ({ order_id }) => { if (!(order_id in orders)) throw new Error(`no order ${order_id}`) return orders[order_id] }, ) const agent = await new AgentBuilder('anthropic/claude-haiku-5-5').tool(desc).build() try { for await (const { message } of agent.run('When does order A-1001 arrive?')) { for (const part of message.contents) { if (part.type === 'text') console.log(part.text) } } } finally { await agent.close() } } main() ``` **Rust** ```rust use ailoy::{ agent::AgentBuilder, datatype::Value, message::{Message, Part, Role}, to_value, tool_func, tool::{ToolDescBuilder, set_tool_provider}, }; use futures::StreamExt as _; #[tokio::main] async fn main() -> anyhow::Result<()> { let desc = ToolDescBuilder::new("order_status") .description("Look up an order's status and expected delivery date by its id.") .parameters(to_value!({ "type": "object", "properties": {"order_id": {"type": "string", "description": "The order id, such as A-1001"}}, "required": ["order_id"] })) .build(); set_tool_provider( "order_status", tool_func!(|args: Value| -> Value { match args.pointer("/order_id").and_then(Value::as_str) { Some("A-1001") => to_value!({"status": "shipped", "eta": "2026-10-24"}), Some(id) => Value::string(format!("error: no order {id}")), None => Value::string("error: no order_id"), } }), ); let mut agent = AgentBuilder::new("anthropic/claude-haiku-5-5") .tool(desc) .build() .await?; let query = Message::new(Role::User).with_contents([Part::text("When does order A-1001 arrive?")]); let mut stream = agent.run(query); while let Some(output) = stream.next().await { let message = output?.message; if message.role == Role::Assistant { for text in message.contents.iter().filter_map(Part::as_text) { println!("{text}"); } } } Ok(()) } ``` How the function is called: - **Python**: the arguments come as keyword arguments, named as in the schema, and the function may be `async`. - **Node.js**: they come as one object, and the function may return a promise. - **Rust** registers a `ToolFunc` with `set_tool_provider`, under the name in the description. `tool_func!` builds one from a closure that takes the arguments as a `Value`; with `async` before the closure, its body can `.await`. The function returns what a message can hold: null, a boolean, a number, a string, or a list or object of those. In Python and Node.js an exception, or a rejected promise, does not end the run: the model gets it as the result, such as `error: KeyError: 'no order B-9'` from the Python function above, and can try something else. Tool calls the model makes in one step run at the same time, the seven built-in tools above among them: a sandbox runs many processes at once. A function of yours may be called again before its last call has returned. A Python or Node.js function runs in your program, not in the sandbox. To run a command or read a file there, it calls the virtx `Sandbox` you made, such as `sandbox.exec(...)` or `sandbox.read_file(...)`. In Rust, a closure that also takes `sandbox: &Sandbox` gets the agent's sandbox, as the built-in tools do, and `ailoy::tool::{exec, read, write}` run a command and read and write a file in it. Tools are registered by name for the whole process, the built-in ones included. Registering a name again, `shell` among them, replaces its function for every agent built after that. `set_tool_provider(name, func)` (`setToolProvider` in Node.js) replaces only the function, for a tool whose description a spec already has. The exception is `web_search` in an agent given a non-empty list of engines, which builds its own. `remove_tool_provider` (`removeToolProvider`) takes a name out. ### Memory `memory(dir)` gives the agent notes on the user that outlast a session. They are kept on this host, in `MEMORY.md` in the folder `dir`, so they need no sandbox. The folder, and those on the way to it, are made when the agent is built; the file is made by the first note. The notes go at the end of the system message as they were when the agent was built, and the agent changes them with the `memory` tool: it adds a fact as an entry of its own, replaces an entry when its fact changes, or removes one. The changes in one call are made in order, all or none. Each entry is led by this host's date when it was last written, as `[2026-11-17] Drinks barley tea`. A change shows in the next agent built on the folder, not in the one that made it. The entries hold at most 3,000 characters unless `limit` says otherwise. A change that would make them larger is refused, and the agent shortens or removes entries to make room. A person can edit the file too: its entries are paragraphs, a blank line apart. **Python** ```python from ailoy import Agent, AgentBuilder agent = await AgentBuilder("anthropic/claude-haiku-5-5").memory("./memory/user1", limit=2000).build() # The same folder for an agent from a spec. agent = await Agent.from_spec( {"model": "anthropic/claude-haiku-5-5", "memory": {"dir": "./memory/user1", "limit": 2000}} ) ``` **Node.js** ```js const agent = await new AgentBuilder('anthropic/claude-haiku-5-5') .memory('./memory/user1', { limit: 2000 }) .build() // The same folder for an agent from a spec. const again = await Agent.fromSpec({ model: 'anthropic/claude-haiku-5-5', memory: { dir: './memory/user1', limit: 2000 }, }) ``` **Rust** ```rust use ailoy::agent::Memory; let agent = AgentBuilder::new("anthropic/claude-haiku-5-5") .memory(Memory::new("./memory/user1").with_limit(2000)) .build() .await?; ``` An agent built with a history that already holds a system message keeps that message as it is: it gets the `memory` tool, but its notes are not added. A spec that lists a `memory` tool of its own beside a memory fails to build. ### How much of a result the model reads The agent keeps at most 30,000 characters of each part of a tool result, for built-in tools and your own alike: - A longer part keeps its first and last 15,000 characters around a note of how many were cut, so a file read whole may reach the model with its middle missing. - A Python or Node.js function's result, a string included, becomes a value part. A value part is measured in characters of its JSON, and once that passes 30,000, the model gets the JSON text as a string with its middle cut. - `web_fetch` and `shell` size their results to fit: a long page comes in pieces that each reach the model whole, and `shell` cuts a long stdout or stderr itself, keeping its start and end around a note of how many characters it lost. --- ## Using MCP https://ailoy.co/docs/guides/using-mcp/ Give an agent the tools of any MCP server. An agent can use the tools of any [MCP](https://modelcontextprotocol.io) server. Register the server, and you get back a description of each of its tools. Pass those to the `AgentBuilder` with `tools(...)`. Each tool is registered as `{prefix}__{name}`, so tools from different servers don't clash. For example, the `fetch` tool of a server registered under `fetch` becomes `fetch__fetch`. ### Stdio servers `register_mcp_stdio` starts the server as a local process and talks to it over stdin and stdout. This runs [`mcp-server-fetch`](https://github.com/modelcontextprotocol/servers/tree/main/src/fetch) with `uvx`: **Python** ```python import asyncio from ailoy import AgentBuilder, register_mcp_stdio async def main() -> None: tools = await register_mcp_stdio("fetch", "uvx", ["mcp-server-fetch"]) agent = await ( AgentBuilder("anthropic/claude-haiku-5-5") .tools(tools) .build() ) async for output in agent.run("Summarize https://modelcontextprotocol.io in three sentences."): for part in output["message"]["contents"]: if part["type"] == "text": print(part["text"]) asyncio.run(main()) ``` **Node.js** ```js const { AgentBuilder, registerMcpStdio } = require('@brekkylab/ailoy') async function main() { const tools = await registerMcpStdio('fetch', 'uvx', ['mcp-server-fetch']) const agent = await new AgentBuilder('anthropic/claude-haiku-5-5') .tools(tools) .build() try { for await (const { message } of agent.run('Summarize https://modelcontextprotocol.io in three sentences.')) { for (const part of message.contents) { if (part.type === 'text') console.log(part.text) } } } finally { await agent.close() } } main() ``` **Rust** ```rust use ailoy::{ agent::AgentBuilder, message::{Message, Part, Role}, tool::register_mcp_stdio, }; use futures::StreamExt as _; #[tokio::main] async fn main() -> anyhow::Result<()> { let tools = register_mcp_stdio("fetch", "uvx", ["mcp-server-fetch"]).await?; let mut agent = AgentBuilder::new("anthropic/claude-haiku-5-5") .tools(tools) .build() .await?; let query = Message::new(Role::User) .with_contents([Part::text("Summarize https://modelcontextprotocol.io in three sentences.")]); let mut stream = agent.run(query); while let Some(output) = stream.next().await { let message = output?.message; if message.role == Role::Assistant { for text in message.contents.iter().filter_map(Part::as_text) { println!("{text}"); } } } Ok(()) } ``` > **Caution:** > A stdio server runs on the host, not in the agent's sandbox, with the same access as your program. Register only servers you trust. ### Streamable HTTP servers `register_mcp_streamable_http` connects to a remote server by its URL. This registers [DeepWiki](https://deepwiki.com)'s server, which answers questions about GitHub repositories: **Python** ```python from ailoy import register_mcp_streamable_http tools = await register_mcp_streamable_http("deepwiki", "https://mcp.deepwiki.com/mcp") ``` **Node.js** ```js const { registerMcpStreamableHttp } = require('@brekkylab/ailoy') const tools = await registerMcpStreamableHttp('deepwiki', 'https://mcp.deepwiki.com/mcp') ``` **Rust** ```rust use ailoy::tool::register_mcp_streamable_http; let tools = register_mcp_streamable_http("deepwiki", "https://mcp.deepwiki.com/mcp").await?; ``` Pass `tools` to `AgentBuilder.tools(...)` as above. ### Unregistering `unregister_mcp` (`unregisterMcp` in Node.js) removes a server's tools by their prefix and closes the connection to the server. **Python** ```python from ailoy import unregister_mcp unregister_mcp("fetch") ``` **Node.js** ```js const { unregisterMcp } = require('@brekkylab/ailoy') unregisterMcp('fetch') ``` **Rust** ```rust ailoy::tool::unregister_mcp("fetch"); ``` ### Troubleshooting | What you see | Why, and what to do | | --- | --- | | An OS error such as `No such file or directory (os error 2)` or `program not found` from `register_mcp_stdio` | The command, such as `uvx`, isn't installed or isn't on your program's `PATH`. Install it (`uvx` comes with [uv](https://docs.astral.sh/uv/)), or give its full path. | | `connection closed: initialize response` | The server started and exited before answering. Its error output isn't shown, so run the same command in a terminal to see why. | | A tool's name isn't the one the server gives it | Tools are named `__`, and any character outside letters, digits, `_` and `-` becomes `_`: prefix `my.server` and tool `odd/name` give `my_server__odd_name`. A name over 64 characters logs a warning, since some model APIs refuse it. | --- ## Using a browser https://ailoy.co/docs/guides/using-browser/ Let an agent drive a browser over CDP. An agent can drive a browser with its `browser_*` tools: your own, or one of its own. Give it one with `browser(...)` on the `AgentBuilder`. The tools reach the browser from your program over the Chrome DevTools Protocol (CDP), not from the agent's sandbox, so an agent needs no sandbox to browse. By default the browser is your own (`Browser::user()` in Rust): the Chromium-based browser that turned remote debugging on last, unless you name one. It needs remote debugging on; in Chrome 144 or later, open `chrome://inspect/#remote-debugging` and turn it on. (For a browser of the agent's own, see [A browser of the agent's own](#a-browser-of-the-agents-own).) Then: **Python** ```python import asyncio from ailoy import AgentBuilder async def main() -> None: agent = await AgentBuilder("anthropic/claude-sonnet-5-5").browser().build() async for output in agent.run("Open https://example.com and tell me its title."): for part in output["message"]["contents"]: if part["type"] == "text": print(part["text"]) await agent.close() asyncio.run(main()) ``` **Node.js** ```js const { AgentBuilder } = require('@brekkylab/ailoy') async function main() { const agent = await new AgentBuilder('anthropic/claude-sonnet-5-5').browser().build() try { for await (const { message } of agent.run('Open https://example.com and tell me its title.')) { for (const part of message.contents) { if (part.type === 'text') console.log(part.text) } } } finally { await agent.close() } } main() ``` **Rust** ```rust use ailoy::{agent::AgentBuilder, browser::Browser}; let mut agent = AgentBuilder::new("anthropic/claude-sonnet-5-5") .browser(Browser::user()) .build() .await?; ``` Nothing connects until the agent first uses a browser tool. Then the browser asks you whether to allow it. While it is allowed, Chrome shows that it is being controlled by automated software. The agent opens a window of its own and works there. The browser asks only once for the agent's whole life, because Ailoy keeps one connection to it open. To connect sooner, say while you are at your screen, call `start_browser()` (`startBrowser()` in Node) between turns. It does nothing once connected. A decline, or remote debugging being off, comes back as an error. `start_url` (`startUrl` in Node, `Browser::start_url` in Rust) is the page the agent's window opens on. - If you decline, the agent hears so and does not try again in that turn. When your next message asks it to, its next browser tool asks you again. - If the browser closes, or you turn remote debugging off, the agent connects again on its next browser tool. The browser asks again, and if the agent's window is gone it gets a new one. The agent is told when this happens. - If remote debugging is off, the agent is told how to turn it on, and you can pass that on. Ailoy finds the browser by the `DevToolsActivePort` file a Chromium-based browser writes in its user data directory while remote debugging is on. By default it looks at Chrome, Chrome Beta, Dev and Canary, Chromium, Edge and Brave, and takes whichever turned remote debugging on last. To name one, pass `user_browser` (`userBrowser` in Node, `Browser::user_browser` in Rust): `"chrome"`, `"chrome-beta"`, `"chrome-dev"`, `"chrome-canary"`, `"chromium"`, `"edge"` or `"brave"`, or any other by its user data directory (a path in Python, `{ userDataDir }` in Node, `UserBrowser::Custom` in Rust). > **Caution:** > The agent uses your real browser, signed in wherever you are. Its tools cannot reach your other tabs, but in its own window it can do anything you could. The browser tools' descriptions tell it to ask you before anything that cannot be undone, such as paying, sending or deleting. That is an instruction, though, not a limit, so use your own browser only with an agent and a task you trust. ### A browser of the agent's own With `isolated` (`isolated: true` in Node, `Browser::isolated()` in Rust), the agent gets a browser apart from yours: Ailoy starts it on first use and closes it when the agent closes. It needs no remote debugging turned on and asks you nothing. ```python agent = await AgentBuilder("anthropic/claude-sonnet-5-5").browser(isolated=True).build() ``` - It is `executable` if you name one, else a Chromium-based browser installed here: Chrome, Chromium, Edge or Brave, the first found. With none, starting it fails. - It runs on a fresh profile that is deleted at the end, so it is signed in nowhere. `profile` keeps a user data directory instead, so sign-ins last from one run to the next. - It opens a window, where you can sign in when the agent tells you to. `headless` runs it without one, as on a server; then the agent can only tell you what a site needs. - If it closes, the next browser tool starts it again on the same profile, and the agent is told its tabs are gone. `user_browser` is for your own browser only, and `headless`, `executable` and `profile` for the agent's own; mixing them fails when the agent is built. ### The tools Rather than being handed the page at every step, the agent reads it with `browser_snapshot` when it needs to. | Tool | What it does | |---|---| | `browser_navigate` | Opens a URL in the current tab, or in a new one with `new_tab`. | | `browser_back` | Goes back one page. | | `browser_snapshot` | The page as text: first a line on the page as a whole (links, refs, iframes, how much lies above and below, whether it still loads), then its accessibility tree in document order, frames included (those of other sites too). What can be acted on has a ref such as `[ref=e3]`; what is hidden or covered is left out, a box that scrolls says how far, and a select lists its options. `interactive` keeps only what can be acted on, `depth` limits the tree, `selector` keeps one element and what is inside it, `urls` shows where links go. | | `browser_click` | Clicks an element by ref, at its middle, by script when something covers it; or at `x` and `y` in the last screenshot. A ``, an ARIA combobox, menu or listbox, or a Semantic UI dropdown. | | `browser_select_dropdown` | Picks a dropdown's option by its text or value, case ignored. | | `browser_search_page` | Searches the page's text, like grep, with the text around each match and the element it is in. | | `browser_find_elements` | Queries elements by CSS selector, with their text, the attributes asked for and how many children they have. | | `browser_evaluate` | Runs JavaScript in the page and returns its value; an image it returns as a data URL is shown as one. | | `browser_screenshot` | A picture of the current tab, at most 1280 pixels wide; `browser_click`'s coordinates are its pixels. Old screenshots are capped as in [Images past the cap](https://ailoy.co/docs/guides/context-manager/#images-past-the-cap). | | `browser_wait` | Waits for text to appear, or for some seconds. | | `browser_dialog` | Accepts or dismisses a confirm, or answers a prompt. An alert is accepted on its own, and the agent is told. | | `browser_tabs` | Lists the agent's tabs, by id. | | `browser_switch_tab`, `browser_close_tab` | Switches to or closes one of them. | With a sandbox, four more tools keep or take a file there. `browser_save_screenshot` and `browser_save_as_pdf` save the current tab in the sandbox as a PNG or a PDF; the PDF is named after the page unless the agent gives a name, with paper, orientation, scale and margins as asked. `browser_upload_file` puts a sandbox file into a file input, the one by ref or the nearest one. `browser_save_download` copies a file the agent's tabs downloaded (up to 512 MiB) into the sandbox. Downloads themselves go where your browser puts them. A ref names the same element while the page shows the same document, and one that appeared since the last snapshot is marked `[new]`; after a navigation the agent takes a new snapshot. Each action reports the page's title and address afterwards, and a tab the page opens becomes the agent's current one. The tools reach only the agent's own tabs: the ones it opened, and those its pages opened. ### Sites that check for bots Some sites turn away traffic that looks automated, with a robot check or a block. By default the description of `browser_navigate` tells the agent to use sites as a person would: start from a site's home page or search and go through its links and forms rather than typed-in query URLs, act at a person's pace, and never retry in a loop. When a robot check appears anyway, it stops and tells you rather than trying to get around it. To leave this out, pass `careful=False` (`careful: false` in Node, `Browser::careful(false)` in Rust). Ailoy adds nothing to the agent's system prompt for the browser: what the agent knows of it is in the tools' descriptions. ### When a site needs you When a site needs something only you can do, such as signing in, a CAPTCHA or a second factor, the agent never asks for your password: it tells you in its reply what to do and ends its turn. Do it in its window, then tell it to go on. It does the same before anything that cannot be undone (see the caution above). --- ## Skills https://ailoy.co/docs/guides/skills/ Give an agent folders of instructions for one kind of task, in the Agent Skills format. > **Needs a sandbox:** > The agent reads its skills through its sandbox, so an agent with skills needs one ([Giving an agent a sandbox](https://ailoy.co/docs/guides/sandbox/)). A skill is a folder of instructions for one kind of task, with the files those instructions use, in the [Agent Skills](https://agentskills.io/specification) format. The agent is told which skills it has and what each is for, and to read a skill's instructions when a task matches it. ### What a skill folder holds A `SKILL.md`, and anything it refers to: scripts, references, data. `SKILL.md` opens with YAML frontmatter giving the skill's `name` and a `description` of what it does and when to use it, and the instructions follow. This is the start of the one in [`laya/shared`](https://github.com/brekkylab/ailoy-examples/tree/main/laya/shared) in ailoy-examples, whose instructions tell the agent to run `run_laya.py` from the same folder: ````markdown --- name: laya description: Answer typed questions about a text with Laya, a machine learning model for decisions. Use it to classify, score or answer yes or no about a message, an email or a ticket, with calibrated probabilities. --- # Laya Laya is a machine learning model for decisions. Given a text, such as a message, an email or a ticket, it answers typed questions about it with calibrated probabilities. It picks one of several options, rates on an ordered scale, or answers yes or no, and it generates no text. You put what is to be decided to it as questions, and write the reply yourself from its answers. ## Running it Run `run_laya.py` from this directory with the mode and the request as its two arguments. ```sh python3 run_laya.py bf16 '{"state": "...", "questions": {...}}' ``` ```` Ailoy reads `name` and `description` and nothing else from the frontmatter, each as one line: keep each on a single line, without YAML's `>` or `|`. ### Giving the agent a skill `skill(dir)` takes the folder's path in the agent's sandbox, not on your machine. Put the folder in the sandbox, with whatever its instructions expect to find there: Laya's instructions read its model from `/models`, which the [laya example](https://github.com/brekkylab/ailoy-examples/tree/main/laya) puts on a volume of its own. A volume, as below, keeps the skill on the virtx server between runs; baking it into the image works too ([Mounting volumes](https://virtx.sh/docs/guides/mounting-volumes/), [Images](https://virtx.sh/docs/guides/images/)). Call `skill` once for each skill. **Python** ```python skill = await client.create_volume("skill-laya") for path in Path("skills/laya").iterdir(): await skill.write_file(path.name, path.read_bytes()) sandbox = await client.create_sandbox( "python:3.12-slim-trixie", volumes=[SandboxVolume(volume=skill, path="/skills/laya", readonly=True)], ) agent = await ( AgentBuilder("anthropic/claude-haiku-5-5") .sandbox(sandbox) .skill("/skills/laya") .build() ) ``` **Node.js** ```js const skill = await client.createVolume('skill-laya') for (const name of readdirSync('skills/laya')) { await skill.writeFile(name, readFileSync(join('skills/laya', name))) } const sandbox = await client.createSandbox('python:3.12-slim-trixie', { volumes: [{ volume: skill, path: '/skills/laya', readonly: true }], }) const agent = await new AgentBuilder('anthropic/claude-haiku-5-5') .sandbox(sandbox) .skill('/skills/laya') .build() ``` **Rust** ```rust let skill = client.create_volume(Some("skill-laya")).await?; for entry in std::fs::read_dir("skills/laya")? { let entry = entry?; skill .write_file(entry.file_name().to_string_lossy(), std::fs::read(entry.path())?, None) .await?; } let sandbox = client .create_sandbox( &SandboxCreateArgs::new("python:3.12-slim-trixie").readonly_volume(skill.name(), "/skills/laya"), ) .await?; let agent = AgentBuilder::new("anthropic/claude-haiku-5-5") .sandbox(sandbox) .skill("/skills/laya") .build() .await?; ``` When the agent writes the system message itself, `build()` reads the frontmatter of each `SKILL.md` through the sandbox, and fails if the `SKILL.md` of a `skill(dir)` is missing or has no `name` or `description`. The system message gets a list of the skills after the instruction: each one's name, description and location, and a line telling the model to read a skill's `SKILL.md` in full before using it. The rest of `SKILL.md` stays out of the system message; the agent reads it with its own tools. So an agent with skills needs a sandbox, which brings a tool that reads files, such as `read`. For `anthropic` models the list is an XML block: ```text # Skills The following skills provide specialized instructions for specific tasks. When a task matches a skill's description, read the SKILL.md at its location in full before proceeding. When a skill refers to a relative path, resolve it against the skill's directory, the one that holds its SKILL.md. laya Answer typed questions about a text with Laya, a machine learning model for decisions. Use it to classify, score or answer yes or no about a message, an email or a ticket, with calibrated probabilities. /skills/laya/SKILL.md ``` For any other org, the same preamble is followed by a Markdown list, one line per skill: ```text - `laya` at /skills/laya/SKILL.md. Answer typed questions about a text with Laya, a machine learning model for decisions. Use it to classify, score or answer yes or no about a message, an email or a ticket, with calibrated probabilities. ``` Skills are added only to the system message the agent writes itself. A `history(...)` that brings a system message keeps it: the skills are not read or added. ### Skills from the sandbox's abins A sandbox can be made with some of virtx's own programs, its abins, at `/abin`: `index` indexes document files and searches them, `docread` reads a Word, PDF or text file a window at a time, and `display` runs GUI programs on a screen watched over VNC. Each comes with a `SKILL.md` at `/abin/skills/{name}/`, and the agent lists it among its skills without a `skill(...)` call: **Python** ```python sandbox = await client.create_sandbox("python:3.12-slim-trixie", abins=["index", "docread"]) ``` **Node.js** ```js const sandbox = await client.createSandbox('python:3.12-slim-trixie', { abins: ['index', 'docread'] }) ``` **Rust** ```rust let sandbox = client .create_sandbox(&SandboxCreateArgs::new("python:3.12-slim-trixie").abin("index").abin("docread")) .await?; ``` An abin with no `SKILL.md` is left out of the list rather than failing `build()`. [Setting up sandboxes](https://virtx.sh/docs/guides/setting-sandboxes/) covers the `abins` option. ### Troubleshooting | What you see | Why, and what to do | | --- | --- | | `reading the skill /SKILL.md` at `build()` (a `VirtxError` with status `404` in Python and Node.js) | The `SKILL.md` of a `skill(dir)` isn't in the sandbox. `dir` is a path in the sandbox, not on your machine: check that the volume holding it is mounted there. | | ``the frontmatter has no `name` ``, or ``no `description` `` | Add the field to the frontmatter, on one line. | | ``a SKILL.md opens with a `---` line`` | The file must start with the frontmatter, between two `---` lines. | | `an agent with skills needs a sandbox to read them from` | Give the agent a sandbox with `sandbox(...)`. | | A skill's description in the system message is just `>` or `\|` | YAML's multi-line values aren't read, and no error is raised: put the description on one line. | --- ## API reference https://ailoy.co/docs/reference/ The Python, Node.js and Rust API reference. > **Note:** > This section is a placeholder. Its pages are being written.