Skip to content

Write an application

An application is an agent definition and a mini-app that runs it. This guide writes the definition, checks it with the conformance kit, and runs it. Its worked examples are the kit's two toys, in autonmi.conformance.toy: a scripted application and a tool-calling one, both conforming.

1. The definition

Both toys' agents double a few numbers as simulations and report their sum. The scripted toy, Toy, asks the model how many simulations to run and runs them at once; the tool-calling toy, ToolToy, lets the model call an MCP tool, a task tool and an inline tool:

"""Two toy applications that conform: the kit's worked examples, and its checks in CI.

Agent `a<i>` doubles `wanted(i)` numbers, from `i` on, as simulations on its population's engine,
and reports their sum. Agents with an even index suspend while a simulation runs.
- `Toy` is scripted: its step asks the model how many simulations to run (the stub answers 3 or 4,
  by agent) and runs them at once (`SimulateAll`, a fan-out with a barrier).
- `ToolToy` is tool-calling: its model looks the agent's first number up on an MCP server
  (`lookup`), calls `double` once per number, then `report`. Each `double` writes its value to the
  population's store, as a tensor, under the key it returns; `report` reads the values back by the
  keys the model passes on. Its stub plays that model from the messages alone, so that a fake model
  server can serve it too.

    python -m autonmi.conformance autonmi.conformance.toy:definition --stable result
    python -m autonmi.conformance autonmi.conformance.toy:tool_definition --stable result
    python -m autonmi.conformance.toy PORT     # the tool-calling toy's MCP server
"""

from __future__ import annotations

import asyncio
import json
import os
import re
import subprocess
import sys
import time
from collections import Counter
from pathlib import Path

from flowgentic.fleet import Reply, ToolCall, Usage
from flowgentic.host import current_agent
from flowgentic.tools import mcp_tool, task_tool
from pydantic import BaseModel, Field

from autonmi.agent import AgentSpec, Check, PopulationContext, ToolAgent
from autonmi.mcp import free_ports, stop_servers, wait_port
from autonmi.scripted import Done, Report, ScriptedAgent, Simulate, SimulateAll
from autonmi.store import awaited, open_store

__all__ = [
    "LOOKUP",
    "DoubleArgs",
    "LookupArgs",
    "ToolStub",
    "ToolToy",
    "Toy",
    "ToyStub",
    "definition",
    "double",
    "double_into_store",
    "expected",
    "serve",
    "suspends",
    "tool_definition",
    "tool_definition_without_lookups",
    "tool_results",
    "wanted",
]


class DoubleArgs(BaseModel):  # noqa: D101 - a docstring would join the tool's schema, which the model reads
    x: float


def double(x: float) -> dict:
    """Double `x`: the toys' simulation, slow enough that an agent finds it running and suspends.

    Returns:
        `x`, its double `y`, and the id of the process that ran it.
    """
    time.sleep(0.02)
    return {"x": x, "y": 2 * x, "pid": os.getpid()}


def double_into_store(x: float, store_spec: str, key: str) -> dict:
    """Write `double`'s value to the store as a tensor, under `key`: the tool-calling toy's simulation."""
    value = double(x)
    open_store(store_spec).put_tensor(key, [value["x"], value["y"]])
    return {"key": key}


def suspends(agent_id: str, args: dict) -> bool:
    """Return whether a simulation suspends its agent: those of agents with an even index do."""
    return int(agent_id[1:]) % 2 == 0


def wanted(i: int) -> int:
    """Return how many simulations agent `a<i>` runs."""
    return 3 + i % 2


def expected(i: int) -> dict:
    """Return agent `a<i>`'s result in the scripted toy; the tool-calling toy's is its `total`."""
    k = wanted(i)
    return {"k": k, "total": sum(2 * (i + j) for j in range(k)), "order": [i + j for j in range(k)]}


# --- the scripted toy -------------------------------------------------------------------------------


class ToyStub:
    """A Flowgentic transport: answers how many simulations to run, by the agent it is called for."""

    model = "toy-stub"

    async def complete(self, messages, tools=None, **kwargs):
        """Answer how many simulations the calling agent runs, as `wanted` gives it."""
        agent = current_agent()
        if agent is None:
            raise RuntimeError("the stub was called outside an agent")
        return Reply(content=str(wanted(int(agent[1:]))), usage=Usage(prompt_tokens=8, completion_tokens=1))


class Toy:
    """The scripted toy's agent definition."""

    name = "toy"

    def __init__(self, agents: int) -> None:
        self.knobs = {"agents": agents}

    def agents(self):
        """Yield agent `a<i>`, with the input `{"i": i}`, for each of the knobs' agents."""
        for i in range(self.knobs["agents"]):
            yield AgentSpec(f"a{i}", {"i": i})

    def stub(self, replica: int) -> ToyStub:
        """Return the scripted toy's stub."""
        return ToyStub()

    def services(self, run_dir: Path, servers: int = 1):
        """Start no MCP servers: the scripted toy has none."""
        return [], []

    def build(self, pop: PopulationContext):
        """Return the population's scripted agent; its results and completed tasks go in `pop.state`."""
        results = pop.state.setdefault("results", {})
        completed = pop.state.setdefault("completed", Counter())  # the agents' tasks that completed

        def on_task(record) -> None:
            if record.ok:
                completed[record.info.agent_id] += 1

        tool = task_tool(double, name="double", args_schema=DoubleArgs, suspend=suspends)
        question = [{"role": "user", "content": "How many simulations?"}]

        async def step(s: dict, event, ask):
            if s["phase"] == "start":
                k = int(await ask(question))
                calls = tuple(Simulate({"x": s["i"] + j}, call_id=f"c{j}") for j in range(k))
                return {**s, "phase": "sum", "k": k}, SimulateAll(calls)
            if s["phase"] == "sum":
                result = {"k": s["k"], "total": sum(v["y"] for v in event), "order": [v["x"] for v in event]}
                return {**s, "phase": "done", "result": result}, Report(result)
            return s, Done(s["result"])

        return ScriptedAgent(
            start=lambda agent_id, spec: {"phase": "start", "i": spec["i"]},
            step=step,
            simulate=tool,
            report=lambda agent_id, result: results.__setitem__(agent_id, result),
            model_calls_limit=1,
            on_task=on_task,
        )

    def rows(self, pop: PopulationContext) -> list[dict]:
        """Return a row per agent of the population: `agent_id`, `finished`, `simulations` and `result`."""
        results = pop.state.get("results", {})
        completed = pop.state.get("completed", {})
        return [
            {
                "agent_id": a,
                "finished": a in results,
                "simulations": completed.get(a, 0),
                "result": results.get(a),
            }
            for a in pop.agent_ids
        ]

    def verify(self, rows: list[dict], store) -> list[Check]:
        """Check that every agent's result is the one `expected` gives."""
        wrong = [r["agent_id"] for r in rows if r["result"] != expected(int(r["agent_id"][1:]))]
        return [Check("every_sum_is_right", not wrong, {"wrong": wrong[:10]})]


# --- the tool-calling toy ---------------------------------------------------------------------------


class LookupArgs(BaseModel):  # noqa: D101 - a docstring would join the tool's schema, which the model reads
    agent: str = Field(description="the agent's id, such as a7")


LOOKUP = mcp_tool("lookup", description="Look up an agent's first number.", args_schema=LookupArgs, idempotent=True)
_AGENT = re.compile(r"agent (a\d+)")


def tool_results(messages: list[dict]) -> list[tuple[str, dict]]:
    """Return every tool result of a conversation, in order, as (the tool's name, its value).

    A result that is not JSON, such as a tool's error, raises: the stub then fails its agent's call.
    """
    names: dict[str, str] = {}
    out = []
    for m in messages:
        if m.get("role") == "assistant":
            for call in m.get("tool_calls") or ():
                names[call["id"]] = call["function"]["name"]
        elif m.get("role") == "tool":
            out.append((names[m["tool_call_id"]], json.loads(m["content"])))
    return out


class ToolStub:
    """A Flowgentic transport that plays the tool-calling toy's model.

    It calls `lookup` when it is offered, `double` once per number, `report`, then answers with no
    tool call.
    """

    model = "tool-toy-stub"

    def next_call(self, messages: list[dict], tools: list[dict] | None) -> tuple[str, dict] | None:
        """Return the next tool call, as its name and arguments; None once the agent has reported."""
        agent = _AGENT.findall(next(m["content"] for m in messages if m.get("role") == "user"))[0]
        results = tool_results(messages)
        called = [name for name, _ in results]
        if "report" in called:
            return None
        if "lookup" not in called and "lookup" in {t["function"]["name"] for t in tools or ()}:
            return "lookup", {"agent": agent}
        first = next((v["x"] for name, v in results if name == "lookup"), int(agent[1:]))
        keys = [v["key"] for name, v in results if name == "double"]
        if len(keys) < wanted(int(agent[1:])):
            return "double", {"x": first + len(keys)}
        return "report", {"keys": keys}

    async def complete(self, messages, tools=None, **kwargs) -> Reply:
        """Answer with the next tool call, or with no tool call once the agent has reported."""
        call = self.next_call(list(messages), tools)
        calls = () if call is None else (ToolCall(id=f"call-{len(messages)}", name=call[0], args=call[1]),)
        return Reply(
            content="" if calls else "Reported.",
            tool_calls=calls,
            usage=Usage(prompt_tokens=8 * len(messages), completion_tokens=8),
            finish_reason="tool_calls" if calls else "stop",
            model=self.model,
        )


class ToolToy(Toy):
    """The tool-calling toy's agent definition: the scripted toy's rows, with the model choosing each step.

    `lookups`: whether its agents look their first number up, on MCP servers that `services` starts.
    """

    name = "tool-toy"

    def __init__(self, agents: int, lookups: bool = True) -> None:
        self.knobs = {"agents": agents, "lookups": lookups}

    def agents(self):
        """Yield agent `a<i>`, whose input asks it to double its numbers and report their sum."""
        for i in range(self.knobs["agents"]):
            yield AgentSpec(f"a{i}", f"You are agent a{i}. Double your numbers one by one, then report their sum.")

    def stub(self, replica: int) -> ToolStub:
        """Return the tool-calling toy's stub."""
        return ToolStub()

    def services(self, run_dir: Path, servers: int = 1) -> tuple[list, list[str]]:
        """Start `servers` MCP servers on 127.0.0.1, with lookups; none without.

        Each logs to `mcp-server-<i>.log` in `run_dir`. Returns their processes and URLs, once all listen.
        """
        if not self.knobs["lookups"]:
            return [], []
        run_dir.mkdir(parents=True, exist_ok=True)
        procs: list[subprocess.Popen] = []
        ports = free_ports(servers)
        try:
            for i, port in enumerate(ports):
                with open(run_dir / f"mcp-server-{i}.log", "w") as log:
                    command = [sys.executable, "-m", "autonmi.conformance.toy", str(port)]
                    procs.append(subprocess.Popen(command, stdout=log, stderr=subprocess.STDOUT))
            for port in ports:
                wait_port(port, 60)
        except BaseException:
            stop_servers(procs)
            raise
        return procs, [f"http://127.0.0.1:{port}/mcp" for port in ports]

    def build(self, pop: PopulationContext) -> ToolAgent:
        """Return the population's tool-calling agent: its tools are `double`, `report`, and `lookup` with lookups."""
        results = pop.state.setdefault("results", {})
        completed = pop.state.setdefault("completed", Counter())

        def on_task(record) -> None:
            if record.ok:
                completed[record.info.agent_id] += 1

        def prepare(agent_id: str, call_id: str, args: dict) -> dict:
            return {"x": args["x"], "store_spec": pop.store_spec, "key": f"double/{agent_id}/{call_id}"}

        async def report(keys: list[str]) -> dict:
            """Report the sum of the doubles that `double` wrote under these keys."""
            # an async tool runs on the population's event loop: it awaits the store, off the loop
            agent = current_agent()
            values = await asyncio.gather(*(awaited(pop.store, "get_tensor", k) for k in keys))
            total = sum(float(v[1]) for v in values)
            results[agent] = total
            await awaited(pop.store, "put", f"report/{agent}", total)
            return {"total": total}

        double_tool = task_tool(
            double_into_store,
            name="double",
            description="Double a number.",
            args_schema=DoubleArgs,
            prepare=prepare,
            suspend=suspends,
        )
        tools = [double_tool, report]
        if self.knobs["lookups"]:
            tools.insert(0, LOOKUP)
        return ToolAgent(
            system_prompt="Double numbers with `double`, then report their sum with `report`.",
            tools=tools,
            max_model_calls=10,
            on_task=on_task,
        )

    def verify(self, rows: list[dict], store) -> list[Check]:
        """Check that every agent put in the store the sum that `expected` gives."""

        def right(agent_id: str) -> bool:
            return store.get(f"report/{agent_id}", None) == expected(int(agent_id[1:]))["total"]

        wrong = [r["agent_id"] for r in rows if not right(r["agent_id"])]
        return [Check("every_sum_is_right", not wrong, {"wrong": wrong[:10]})]


def serve(port: int) -> None:
    """Serve the tool-calling toy's `lookup` over MCP's Streamable HTTP, on 127.0.0.1:`port`."""
    import uvicorn
    from mcp.server.mcpserver import MCPServer

    server = MCPServer("autonmi-toy", log_level="WARNING")

    @server.tool()
    async def lookup(agent: str) -> dict:
        """Return an agent's first number."""
        return {"x": int(agent.removeprefix("a"))}

    # Stateless, with JSON replies: any client of a tool service's pool can send any call. The
    # keep-alive outlasts uvicorn's 5 s, at which the server can close a connection a client reuses.
    app = server.streamable_http_app(stateless_http=True, json_response=True, host="127.0.0.1")
    uvicorn.run(app, host="127.0.0.1", port=port, log_level="warning", timeout_keep_alive=600)


# --- the kit's factories ------------------------------------------------------------------------------


def definition(agents: int, run_dir: Path) -> Toy:
    """Return the scripted toy for `agents` agents."""
    return Toy(agents)


def tool_definition(agents: int, run_dir: Path) -> ToolToy:
    """Return the tool-calling toy for `agents` agents, with its MCP servers."""
    return ToolToy(agents)


def tool_definition_without_lookups(agents: int, run_dir: Path) -> ToolToy:
    """Return the tool-calling toy without lookups: no MCP server, so no tool service."""
    return ToolToy(agents, lookups=False)


if __name__ == "__main__":
    serve(int(sys.argv[1]))

What to copy from it, with the clauses of the contract it keeps:

  • Everything at a module's top level: the definition's class, its factory, the task function, its argument schema and the stub. Under Dragon each population's process receives the definition pickled, and imports these by name (C3).
  • agents() yields the same AgentSpecs, with unique string ids, in the same order, every time (C4).
  • build(pop) only sets up: it declares the task tool (flowgentic.tools.task_tool, with suspend saying which calls suspend their agent) and returns the agent. Per-population state, here the results and the completed tasks, lives in pop.state (C5).
  • The scripted agent's state is a plain dict, and only what step returns changes it (C8).
  • The stub is a Flowgentic transport whose reply depends only on the agent (flowgentic.host.current_agent()) and its messages (C6).
  • rows(pop) gives one row per id in pop.agent_ids, finished or not, with agent_id, finished, and here simulations, counted from the task records as each task ends, so that an agent that fails has its count too; no field AUTONMI adds (C13 to C16).
  • verify returns checks; it does not raise (C17).

A tool-calling application returns a ToolAgent from build instead, as ToolToy does:

  • Its tools are a list: an MCP tool (flowgentic.tools.mcp_tool), answered by the MCP servers that services(run_dir, servers) starts; task tools, run on the population's engine; and inline functions, run in the agent's process.
  • A task reaches the population's store by its spec: prepare adds pop.store_spec and a key to the task's arguments, and the task opens the store with autonmi.store.open_store. Under Dragon the task runs in another process, and the store is RaDEX.
  • Its stub answers from the messages alone, so that a fake model server can serve it too.

2. A factory for the kit

The kit imports a factory by its name, module:function, a function of a number of agents and a run directory that returns the definition set up for its stub model. The toy's is definition(agents, run_dir), at the end of the file above.

3. Run the conformance kit

From Python, in a test:

from autonmi.conformance import conform

report = conform("autonmi.conformance.toy:definition", run_dir="runs/kit-toy", stable=("result",))
assert report.ok, report.text()

From a shell:

python -m autonmi.conformance autonmi.conformance.toy:definition --stable result

stable names row fields that must be the same in every run, beside the kit's own. The kit prints one line per check, failures first. For the toy:

AUTONMI conformance: autonmi.conformance.toy:definition, 24 agents: ok
ok    static               the factory imports by its name
ok    static               the definition has every member the kit needs
ok    static               agents() gives the same unique ids every time
...
skip  dragon               the run under Dragon
      skipped: no Dragon here
ok    two vs one           each agent's end and result are the same as in one
ok    suspended vs one     each agent's end and result are the same as in one
skip  contract             an agent can resume in another process                                                [C12]
      not checked: not required until a population's agents can resume elsewhere

Each step runs in a process of its own that imports the factory by its name, as Dragon's processes do:

Step What it does
static the definition's members; agents() gives the same unique ids on every call; the definition pickles and unpickles in a spawned process; build returns a ToolAgent or a ScriptedAgent; task functions live at a module's top level; the stub is a transport
one the application as a mini-app, one population, with its stub
two the same in two populations
suspended one population; every task tool made to suspend its agent; at most a quarter of the agents live at once
dragon two populations under Dragon, where Dragon is (AUTONMI_DRAGON_TEST=1 on a node)

Each run's directory is then checked: one row per agent with agent_id and finished; no field AUTONMI adds set by the application; under the stub, every agent ends done and finished; simulations equal to the agent's completed tasks; each population's engine ran exactly its agents' tasks; Flowgentic's export complete, its successful calls equal to the rows'; no agent in flight at the end; the run's MiniApp report complete, and Workflow Mini-Apps' offline verifier agreeing; the application's checks and AUTONMI's; a completed task runs again with the same arguments; nothing of an ended agent left in the store; and each agent's end and result the same in every run.

A failure says what was found, the clause of the contract it checks, by its number and its text, and who fixes it: the application, the framework, or either. A definition whose rows leaves an agent out, the test suite's broken_toys:missing_row, fails first with (python -m autonmi.conformance broken_toys:missing_row --agents 8 --runs one, with tests/ on PYTHONPATH):

AUTONMI conformance: broken_toys:missing_row, 8 agents: FAIL (4 of 28 checks)
FAIL  one                  one row per agent, in its population's file                                           [C13, application]
      p000 has 7 rows for 8 agents; missing: a7
      C13: `rows(pop)` returns one row per id in `pop.agent_ids`, whatever the agent's end.
...

The other three failures follow from it, so they say either.

A step that outlasts its time is stopped with every process it started: --timeout (600 s) for the static checks, and 120 s more for each run. python -m autonmi.conformance --help lists the options, such as --agents (24) and --runs.

The kit does not check real models, scale, resuming in another process, a worker that dies, or several nodes; nor the rows of agents that fail or are cancelled, since under the stub every agent ends done.

4. Run it

A mini-app script that runs the toy is in The mini-app. For your application, replace Toy(agents=100) with your definition, and add your own tasks to the workflow after campaign.run().

The tool-calling toy's factory starts its MCP servers, and the kit's runs then use the tool services:

python -m autonmi.conformance autonmi.conformance.toy:tool_definition --stable result

To run any application with the runtime, model-server and telemetry options, give its factory to the example mini-app: python examples/miniapp.py --definition my_app.autonmi:conformance_definition (see the command line).