Agent host¶
A campaign of agents on an HPC allocation runs thousands of them per Python
process. flowgentic.host.AgentHost runs them: it starts them, keeps the
process responsive while they run, resumes the ones that wait on tasks, and
counts what each is doing. It works with any agent framework through a small
Runner; flowgentic.langgraph.GraphRunner is LangGraph's, and
flowgentic.loop.LoopRunner is Flowgentic's own agent loop,
on OpenAI-format messages, with no LangChain.
from flowgentic.host import Agent, AgentHost
from flowgentic.langgraph import GraphRunner
host = AgentHost(GraphRunner(graph)) # graph: a compiled LangGraph graph
report = await host.run(
Agent(f"agent-{i}", {"messages": [("human", task)]}) for i, task in enumerate(tasks)
)
print(report.finished, report.states["share_by_category"], report.loop_lag)
flowgentic.host needs no extra. GraphRunner needs the langgraph extra.
run takes a fixed set of agents and returns when every one has ended. A
host can also take agents one at a time, as they arrive, between start and
stop: see Agents on demand.
What the host does¶
- It tunes the cyclic collector while it runs. At CPython's defaults the
collector runs every few hundred allocations and scans every young object.
With thousands of agents in a process, each holding its conversation, that
scanning takes most of the process's time. The host raises the collector's
first threshold (
Collector(threshold=100_000); it must be at least 1, since 0 would turn automatic collection off) and moves the objects alive out of the collector's reach (gc.freeze()):runonce its first wave of agents has started, and a started host instart(), before its first agent (Agents on demand). It restores both whenrunreturns orstopends a started host, and also when either is cancelled. Overlapping runs share the collector tuning until the last user releases it, and the first to freeze freezes for them all: arunthat starts while a started host serves freezes nothing of its own, and its report says so (What it reports). When the last host that froze ends, it unfreezes every frozen object, those frozen before it included (CPython 3.12 parks some of its own objects there): CPython cannot unfreeze only part, and reference cycles left frozen would never be freed. An application that keeps objects of its own frozen passesCollector(freeze=False);collector=Noneleaves the collector alone. - It caps the agents live at once. At most
max_live_agents(5,000 by default) are live, suspended ones included. More are accepted, and each starts as soon as a live one ends. The cap bounds how late the event loop runs and how long the collector pauses. Measure both for your own agents withHostReport.loop_lagandHostReport.collector, and set the cap from them. - It staggers a run's first wave. In
runandrun_indexed, the firstmax_live_agentsagents startStagger(batch=100, interval_s=0.5)at a time, so they do not all reach their first model call, or their first suspension, at the same moment. Later agents are not staggered: their starts follow the ends of live agents. A started host starts each agent as it comes (The first wave, below).stagger=takes aStaggerfor every mode, orNonefor none in any; its default,"by_mode", is what this says, andhost.staggerholds what was given. - It resumes agents that wait on tasks. A runner reports a suspended agent with the keys of the tasks it waits on. The host holds only the agent's id and those tasks' futures, awaits the tasks, and resumes the agent; the framework keeps the agent's state in its checkpoint meanwhile.
- It isolates failures. One agent's exception ends that agent, with the
error in its result, and never the others. An exception from
on_donemakes the agentfailedand is kept incallback_error, beside the agent's ownerror. - It stops cleanly when cancelled. When
runis cancelled, each live agent ends ascancelled, notfailed;on_donereceives it, andrunraisesCancelledError. Agents that had not started stayPENDING. A started host'sstop(drain=False)ends its live agents the same way. - It keeps outputs out of memory. Each agent's output goes to
on_done, if given, and is not kept: a finished agent's state can be large.
What it reports¶
run returns a HostReport: each agent's status (done, failed or
interrupted), error, times and suspensions; the count of each status
(outcomes); the agent-seconds spent in each state; the event loop's lag
(time-weighted p99, maximum, share of time over 100 ms); and the collector's
pauses by generation. Its collector["freeze"] gives when the host froze
(at_s, 0 for a started host), how long the freeze took (call_s), and the
objects frozen before (frozen_before) and after (frozen). A host that
found the freeze held by another host froze nothing: its call_s is 0, and
its frozen is its frozen_before, what it found frozen.
The host keeps running values of the lag and the pauses, not every sample, so their memory stays the same however long it runs. Every figure is exact but the lag's time-weighted p99, which comes from a histogram of fixed size (buckets 1 % wide from 0.1 ms up): it is within 1 % of the exact value, or 0.1 ms, whichever is larger, for a p99 under a day, before the report rounds it to 0.1 ms.
AgentStates counts agents in seven states and three categories, the ones a
campaign reports:
| State | Category | The agent is |
|---|---|---|
WORKING |
working | in the agent process: the framework's steps, inline tools |
TOOL_CALL |
working | waiting for a call it made, such as an MCP tool |
MODEL_QUEUED |
waiting | waiting to be admitted to a model server |
MODEL_REQUEST |
making a model request | waiting for a model server's answer |
TOOL_WAIT |
waiting | waiting for a task, queued or running, suspended or not |
PENDING, DONE |
not started, or ended |
Each run requires unique agent IDs and starts its own accounting period; so
does each period of a started host, from start to stop.
The counts can be read from another thread while agents run, for a sampler of
your own: pass your AgentStates as states= and read it while the host runs.
An AgentStates tracks one run at a time, so hosts that run at the same time
each need their own; a second run on one that is in use raises RuntimeError.
Runners¶
A Runner has two methods: start(agent) runs the agent until it ends,
suspends or stops; resume(agent, done) resumes it after its tasks have
ended. Each returns Finished(output), Suspended(waits) or
Interrupted(interrupts). waits pairs a resume id with a task key, and each
key names a future registered in the process with register_pending: the
agent's own registration first, so that two hosts in one process can run
agents with the same ids. A runner that suspends an agent 100 times in a row
on the same tasks, all already ended, makes no progress: the host fails the
agent with a RuntimeError, rather than resume it at once for ever.
LoopRunner(model, tools) runs a tool-calling agent as a loop, with no graph,
and saves a suspended agent's messages to a key-value store; see
Agent loop. The rest of this section is about GraphRunner.
GraphRunner(graph) runs each agent as one thread of a compiled graph, with
the agent's id as thread_id and LangGraph's exit durability by default, so
a checkpoint is saved only when a run ends or suspends. A tool suspends its
agent by calling LangGraph's interrupt({PENDING_KEY: key}) for a task
registered under key. The host releases an agent’s registrations when it
finishes. A future registered outside an agent's task, as by code that submits
tasks before a run, becomes the agent's that first waits on it, and is
released when that agent finishes. One that no agent takes is released when
the run ends, or the last of the runs in progress if several overlap (a
started host's period counts as a run, until stop); one registered when no
run follows stays registered for the life of the process. The tool records the
interrupt with record_interrupt, so the runner frees the run's frames as
soon as it stops. Any other interrupt, such as a question for a human, ends
the agent as interrupted.
A finished agent's thread stays in the graph's checkpointer, so the store
grows with the campaign. With GraphRunner(graph, delete_finished=True), the
runner deletes the thread when the agent finishes, before the host passes the
output to on_done. The store then holds the agents that are running, not
every agent of the campaign: turn it on when the store is a Dragon dictionary,
whose size is fixed when it is created. An interrupted agent keeps its thread
even then, so it can resume once a human answers, and so does a failed or
cancelled one, to debug or retry it. If a thread cannot be deleted, the runner
logs it and counts it in delete_failures, and the agent still finishes.
Turning it on gives up two things. on_done still gets the agent's output,
but the thread's state is gone by then: graph.get_state there finds an empty
thread. And an agent id run again, as a conversation continued in a later host
run, starts a fresh thread, without the earlier turns.
Each resume is a new LangGraph run, which counts its steps against
recursion_limit afresh. So GraphRunner also lets one agent resume at most
recursion_limit times, and fails it with GraphRecursionError after that.
Each resume runs at least one step, so an agent that would finish within the
limit without suspending is never stopped by this. The count lasts until the
agent's run ends, or until the host ends the agent, as when it cancels or fails
an agent that waits between two resumes. GraphRunner refuses a
graph compiled with interrupt_before or interrupt_after: a static
breakpoint stops a run without an interrupt, and the agent would end as
finished, with partial output.
route_tool_calls is the conditional edge after the model node: it sends
each tool call of the last message in the state's messages to the node named
tools, each as its own task (LangGraph's Send).
LangGraph saves each finished call's result with the checkpoint, so when an
agent resumes, only the call that suspended runs again.
from langgraph.graph import START, MessagesState, StateGraph
from langgraph.prebuilt import ToolNode
from flowgentic.langgraph import route_tool_calls
builder = StateGraph(MessagesState)
builder.add_node("model", call_model)
builder.add_node("tools", ToolNode(tools))
builder.add_edge(START, "model")
builder.add_conditional_edges("model", route_tool_calls, ["tools", "__end__"])
builder.add_edge("tools", "model")
graph = builder.compile(checkpointer=checkpointer)
A runner of your own¶
A runner of the application's own, such as one whose code, not a model, picks
each step, uses what Flowgentic's runners use, from flowgentic.host:
current_agent(): the id of the agent the current coroutine works for, orNoneoutside the host's agents. The host sets it in each agent's task, and the tasks started from there inherit it. A worker thread sees it only when started withasyncio.to_threador in a copied context (contextvars.copy_context().run), asLoopRunnerandGraphRunnerrun sync inline tools, so an inline tool reads its agent here under both.loop.run_in_executoralone does not carry it.activity(state): counts the current agent instatefor a block:TOOL_CALL,MODEL_REQUEST,MODEL_QUEUEDorTOOL_WAIT. An agent with no activity open isWORKING, and the host alone makes itPENDINGorDONE, so any other state is aValueError. Activities nest and overlap; the agent's state is the most telling of those open, in that order. A fleet counts its own calls.wait(futures): waits for tasks, such as aToolRuntime's, without raising their errors. A task whose order has not admitted it yet is withdrawn, and never starts, once every wait on it is cancelled, as when the host stops its agent.register_pending, above, for a task the runner suspends its agent on;ToolRuntime.submitregisters its tasks itself.
from flowgentic.host import AgentState, Finished, activity, wait
class Scripted:
"""Each agent runs one simulation, with arguments its code chooses."""
async def start(self, agent):
job = runtime.submit(simulate, agent.id, "sim0", {"x": choose(agent.input)})
with activity(AgentState.TOOL_WAIT):
await wait((job,))
return Finished(job.result())
async def resume(self, agent, done): ...
Telemetry¶
Through the OpenTelemetry API, and only once the application configures an SDK:
- each agent's run is an
invoke_agentspan, with the agent's id ingen_ai.agent.id, and aflowgentic.agent.suspendevent per suspension; a failed agent's span has status ERROR,error.typeand the exception; flowgentic.agentscounts the agents of runs in progress byflowgentic.agent.state, and the counterflowgentic.agent.timeadds up agent-seconds by state andflowgentic.agent.categoryover every run in the process, both read when the SDK collects;flowgentic.host.loop.lagandflowgentic.host.gc.pauserecord the event loop's lag and the collector's pauses, once each however many hosts run.
Telemetry lists every metric, with its unit and buckets, and shows how to configure a meter provider.
Campaigns with millions of agent IDs¶
Use run_indexed when agents can be named by a prefix and an integer. The
host builds each input as a slot opens, keeps detailed state for live agents
only, and returns counts in report.outcomes but no per-agent results in
report.agents. Its on_done callback receives
each individual result. Keep that callback bounded too. The ordinary run
keeps its full per-agent report and validates all application-supplied IDs
before starting work.
host = AgentHost(runner, max_live_agents=256, on_done=save_result)
report = await host.run_indexed(range(start, stop), make_input, id_prefix="campaign-")
Give different processes disjoint index ranges, so that no agent runs in two
processes. Both entry points run agents through the same runner, and the
runner keeps each agent's state as it does in run. The total campaign
population and the number of agents live at once are separate sizing
parameters: each live agent can hold a framework run, pending futures and
external requests, so set max_live_agents from what one process sustains.
To measure host scheduling and peak process RSS on Linux or macOS, run
uv run --locked python benchmarks/agent_host.py --agents 100000.
Add --full-report for the ordinary host path, or --submit for agents given
one at a time to a started host. The runner finishes immediately, uses
generated inputs and performs no model, checkpoint or network calls. The
benchmark's host runs with collector=None, so its CPU time follows where
CPython's full collections fall; it prints the collector's passes in each
generation, and an A/B should compare runs with the same number of full
passes, or try more than one --live.
Agents on demand¶
A server's agents do not come as a list: each starts when a message arrives,
and the server answers the message when its agent ends. A started host takes
them one at a time, with everything run gives but the stagger: the cap, the
collector's settings, suspension, the accounting and on_done.
from flowgentic.host import Agent, AgentHost, QueueFull
host = AgentHost(runner, max_live_agents=5_000, max_queued=20_000)
async def handle(message): # one per message, on the host's event loop
try:
future = host.submit(Agent(f"{message.agent}:{message.task}", message.input))
except QueueFull:
return busy() # "busy, retry later"
result, output = await future # what on_done receives
return answer(output) if result.status == "done" else failed(result)
async with host: # start(); on an error, stop(drain=False)
await serve(handle) # until the server shuts down
report = await host.stop() # waits for the live and waiting agents
start()tunes the collector, starts the probes of the event loop and the collector, and begins an accounting period, asrundoes. It also freezes the objects alive then, after the full collection it runs anyway, so that no request waits for the freeze ("The first wave", below). A host runs one period at a time:start,runorrun_indexedwhile it runs raisesRuntimeError. Afterstop, it can start again, or run a list.async with host:starts the host, and stops it when the block ends:stop()if the block ended normally,stop(drain=False)if it raised. Untilstop, the host keeps the collector's threshold raised, its objects frozen and its probes running, and refuses a secondstart, so start it withasync with, or stop it in afinally. Inside the block,await host.stop()returns the report, and the block's end has nothing left to stop.submit(agent)never blocks. It returns anasyncio.Futurethat resolves to(result, output), whaton_donereceives, when the agent ends:done,failed,interruptedorcancelled. An agent's error is inresult.error, never raised by the future; anon_donethat raises makes the resultfailed, withcallback_error. The agent starts as soon as a slot is free, after the agents submitted before it. It runs in a copy of the caller's context, as a taskasyncio.create_taskmakes there: itsinvoke_agentspan is a child of the span current atsubmit, such as a server's request span. Callsubmiton the host's event loop; from another thread, useasyncio.run_coroutine_threadsafewith a coroutine that calls it.- Ids. An agent's id must be unique among the host's live and waiting
agents:
submitraisesValueErrorotherwise. Once an agent ends, its id is free again, by the time its future resolves, so a server can run one logical agent once per message under one id.LoopRunnerkeys each run's tool calls apart, andGraphRunnercontinues the agent's thread, or starts a fresh one withdelete_finished=True. An id may hold any character: task keys write a/in it as%2F(Repeat safety). max_queuedbounds the agents that wait for a slot:submitraisesQueueFullwhen the host holdsmax_live_agents + max_queuedagents, live or waiting, so a server can refuse work rather than pile it up. Withmax_queued=0, an agent is taken only into a free slot.None, the default, accepts every agent. It does not boundrunorrun_indexed, which take their agents as slots free. WithNone, a burst can queue more agents than the host starts before their callers give up, and a queued agent whose caller timed out still runs when its turn comes, for no one, unless its future was cancelled.asyncio.wait_forandasyncio.timeoutcancel it, so the agent never starts;asyncio.waitwith a timeout,asyncio.shield, or a server that drops a request without cancelling its handler leave it queued. To bound that, setmax_queuedto about the agents the host starts within a caller's timeout, so thatsubmitrefuses the rest withQueueFull, and cancel the future when the caller gives up.- Suspended agents keep their slots. A suspended agent is live, as in
run: while all slots hold agents, live or suspended, new agents wait, and each starts when an agent ends. - The first wave. A started host starts each agent as soon as a slot is
free, with no stagger. A stagger would hold back only the first
max_live_agentsagents sincestart(): withrun'sStagger(batch=100, interval_s=0.5), the last of a first burst of 1,000 agents would start about 4.5 s after the first, and no later burst would be held back at all. What keeps a burst's model calls under the servers' caps is the fleet's admission,TokenAdmissionorRequestAdmission(What the fleet does), which holds every burst's calls, not only the first: a server that meets bursts should set it, since a fleet admits every call at once without it. AStaggergiven to the host still staggers a started host's first wave, as inrun.Stagger(batch=1, interval_s=0)is not the same as none: it yields to the event loop once for each agent of the first wave, and other work then runs between the starts of a burst. A started host does not freeze after its first wave, asrundoes, but instart(): a freeze needs a full collection first, which would run on the event loop inside the first agent's request, andstart()runs one anyway. With the agents-at-scale example's agent process on CPython 3.12, the freeze held the event loop inside the first request for 46 ms withLoopRunnerand 74 ms withGraphRunner(itscall_s); instart()it adds a few microseconds. What the first agents create and keep, such as a framework's lazily built caches, is not frozen: about a thousand objects withGraphRunnerand a few withLoopRunnerin that process, and a full collection there took 0.1 ms either way. The raised threshold holds for every agent. - Cancelling one agent. Cancelling a future cancels its agent: one still
waiting never starts, and one live ends as
cancelled, whichon_donereceives. A handler that awaits the future and is itself cancelled, as when a client goes away, cancels the future too, asawaitdoes; to let the agent run on, awaitasyncio.shield(future). The future is cancelled at once, but the host learns of it one loop turn later: a waiting agent's id and its place undermax_queuedare free after anawait asyncio.sleep(0), and a live agent's once the agent has ended ascancelled, which its future, cancelled already, does not tell. An agent cancelled after the host took it but before its first step, by a cancel or bystop(drain=False), never runs: it ends ascancelled, andon_donedoes not receive it, as for a waiting agent. -
stop(drain=True)refuses new agents (submitraisesRuntimeError), except from the host's own agents, waits for the live and waiting agents to end, ends the host's period, and returns itsHostReport.stop(drain=False)cancels the live agents, which end ascancelled, and withdraws the waiting ones, which never start: each of their futures resolves to acancelledresult whoset_startis0.0, andon_donedoes not receive them.stop(drain=False)while astop()drains cancels what is left, and both return the same report, so a shutdown with a deadline reads:stopping = asyncio.create_task(host.stop()) done, _ = await asyncio.wait({stopping}, timeout=30) if not done: await host.stop(drain=False) # cancel what is left report = await stoppingCancelling
stopends the host as cancellingrundoes.stopends whatstartbegan: whilerunorrun_indexedruns, it raisesRuntimeError, and cancellingrunends a run early. - The report keeps aggregate counts, asrun_indexed's does:agentsis empty, since each result went to its future and toon_done, andoutcomescounts every agent submitted once, those withdrawn before they started ascancelled. While the host runs,host.statescounts the waiting agents asPENDING, and keeps no state of an agent that has ended. - Agents that call agents. An agent may submit another to its own host and await it, as an agent that calls another in the process. Keepmax_live_agentsabove the number of agents that can wait on others at once: an agent waiting on one that cannot start holds its slot. Whilestop()drains, the host still takes the agents its own agents submit, from their tasks, the tasks they start andon_done, so a chain of agents ends as it would have;stop(drain=False)cancels the whole chain. An agent cannot stop the host it runs in, nor can a task it starts, while the agent runs:stopraisesRuntimeErrorthere, since it would wait for the agent's end. - The host's own task. The host starts its agents from a task of its own. If that task is cancelled from outside, as by code that cancels every task, the host starts no more agents: it withdraws the waiting ones, whose futures resolve tocancelledresults, refuses new ones, and logs a warning. The live agents run to their ends, andstopstill ends the host and returns its report.
A host that serves for days keeps, until stop, the task registrations made
outside an agent that no agent took (register_pending, above). Its probes
of the event loop and the collector keep running values and a histogram of
fixed size, about 33 KB, however long it serves. With GraphRunner, the
checkpointer keeps each finished agent's last checkpoint, past stop too,
unless delete_finished=True.