AI Agents
This guide shows how the starter's pieces fit together for AI agents: one supervised sharded actor
per agent that keeps the conversation, pipeToSelf for model calls, a per-node rate
limiter, a human approval step with ask and a timeout, and snapshots that survive a restart.
All Java code on this page is included from the runnable example in
example/agent.
The Kotlin tabs show the same code in Kotlin, written with the actor-kotlin module; they
are not part of the example.
The example uses a fake model, so it needs no API key and no network:
./gradlew :example:agent:bootRun # runs one demo conversation and logs it
./gradlew :example:agent:test # the tests named at the end of this page
Why actors fit agents
An agent is a long conversation with state, slow external calls, and side effects. Actors give you:
- One owner per conversation. An agent's actor handles one message at a time, so its history needs no locks, even with thousands of agents on one node.
- Location transparency. With sharding, the cluster keeps exactly one instance of each agent id and routes messages to it, wherever it lives.
- No blocked threads. A model call can take seconds. The actor sends the call, keeps answering other messages, and handles the reply as a new message.
- Supervision. If the agent's code throws, a supervisor restarts it from its last snapshot.
The model behind an interface
The agent only knows this interface. The example ships a scripted fake; a real provider is another bean that implements it.
/**
* The only thing an agent knows about the model. Swap the fake for a real provider by adding
* another bean that implements this interface; the agent code does not change.
*/
public interface LlmClient {
/**
* Sends the conversation so far and returns the model's next step. Must not block the
* caller: the agent pipes the result back to itself.
*/
CompletionStage<LlmReply> complete(List<ChatMessage> conversation);
}
/**
* The only thing an agent knows about the model. Swap the fake for a real provider by adding
* another bean that implements this interface; the agent code does not change.
*/
interface LlmClient {
/**
* Sends the conversation so far and returns the model's next step. Must not block the
* caller: the agent pipes the result back to itself.
*/
fun complete(conversation: List<ChatMessage>): CompletionStage<LlmReply>
}
The fake model used by the example:
/**
* A scripted model, so the example runs without an API key or network.
*
* <ul>
* <li>"weather in <city>" asks for the {@code weather} tool;
* <li>"refund <order>" asks for the {@code refund} tool, which needs a human approval;
* <li>"my name is <name>" is remembered, and "what is my name?" answers from the conversation;
* <li>a tool result is turned into the final answer;
* <li>anything else is echoed.
* </ul>
*/
@Component
public class FakeLlmClient implements LlmClient {
private final AgentProperties properties;
public FakeLlmClient(AgentProperties properties) {
this.properties = properties;
}
@Override
public CompletionStage<LlmReply> complete(List<ChatMessage> conversation) {
long latencyMillis = properties.getFakeLlmLatency().toMillis();
return CompletableFuture.supplyAsync(
() -> reply(conversation), CompletableFuture.delayedExecutor(latencyMillis, TimeUnit.MILLISECONDS));
}
static LlmReply reply(List<ChatMessage> conversation) {
ChatMessage last = conversation.get(conversation.size() - 1);
if (last.role() == ChatMessage.Role.TOOL_RESULT) {
return LlmReply.answer("Tool " + last.toolName() + " says: " + last.content());
}
String text = last.content().trim();
String lower = text.toLowerCase(Locale.ROOT);
int weather = lower.indexOf("weather in ");
if (weather >= 0) {
String city = text.substring(weather + "weather in ".length()).replaceAll("[?.!]+$", "");
return LlmReply.callTool("weather", city);
}
if (lower.startsWith("refund ")) {
return LlmReply.callTool("refund", text.substring("refund ".length()));
}
if (lower.startsWith("what is my name")) {
for (int i = conversation.size() - 1; i >= 0; i--) {
ChatMessage message = conversation.get(i);
if (message.role() == ChatMessage.Role.USER
&& message.content().toLowerCase(Locale.ROOT).startsWith("my name is ")) {
return LlmReply.answer("Your name is " + message.content().substring("my name is ".length()));
}
}
return LlmReply.answer("You did not tell me your name.");
}
if (lower.startsWith("my name is ")) {
return LlmReply.answer("Nice to meet you, " + text.substring("my name is ".length()));
}
return LlmReply.answer("You said: " + text);
}
}
/**
* A scripted model, so the example runs without an API key or network.
*
* - "weather in <city>" asks for the `weather` tool;
* - "refund <order>" asks for the `refund` tool, which needs a human approval;
* - "my name is <name>" is remembered, and "what is my name?" answers from the conversation;
* - a tool result is turned into the final answer;
* - anything else is echoed.
*/
@Component
class FakeLlmClient(private val properties: AgentProperties) : LlmClient {
override fun complete(conversation: List<ChatMessage>): CompletionStage<LlmReply> =
CompletableFuture.supplyAsync(
{ reply(conversation) },
CompletableFuture.delayedExecutor(properties.fakeLlmLatency.toMillis(), TimeUnit.MILLISECONDS),
)
companion object {
fun reply(conversation: List<ChatMessage>): LlmReply {
val last = conversation.last()
if (last.role == ChatMessage.Role.TOOL_RESULT) {
return LlmReply.answer("Tool ${last.toolName} says: ${last.content}")
}
val text = last.content.trim()
val lower = text.lowercase()
val weather = lower.indexOf("weather in ")
return when {
weather >= 0 -> {
val city = text.substring(weather + "weather in ".length).replace(Regex("[?.!]+$"), "")
LlmReply.callTool("weather", city)
}
lower.startsWith("refund ") -> LlmReply.callTool("refund", text.substring("refund ".length))
lower.startsWith("what is my name") -> {
val name = conversation.lastOrNull {
it.role == ChatMessage.Role.USER && it.content.lowercase().startsWith("my name is ")
}
if (name != null) LlmReply.answer("Your name is " + name.content.substring("my name is ".length))
else LlmReply.answer("You did not tell me your name.")
}
lower.startsWith("my name is ") -> LlmReply.answer("Nice to meet you, " + text.substring("my name is ".length))
else -> LlmReply.answer("You said: $text")
}
}
}
}
Tools are beans too. A tool that changes the world asks for a human approval first:
One sharded actor per agent
Each agent id is a sharded entity. Its behavior is the agent's logic, AgentBrain, under a restart
supervisor.
/**
* One sharded entity per agent id: the cluster keeps exactly one instance of each agent, on
* some node, and routes every message for that id to it.
*
* <p>The agent's logic is {@link AgentBrain}, run under a restart supervisor. If it crashes, the
* supervisor restarts it and it reloads its conversation from the snapshot store.
*/
@Component
public class AgentActor implements SpringShardedActor<AgentActor.Command> {
public static final ShardedEntityType<Command> TYPE_KEY = ShardedEntityType.of(Command.class, "Agent");
/** Commands may cross nodes, so they are JSON serializable. */
public interface Command extends JsonSerializable {}
/** A user message. The reply is the agent's final answer for this turn. */
public static final class Chat extends AskCommand<AgentAnswer> implements Command {
public final String text;
@JsonCreator
public Chat(@JsonProperty("text") String text) {
this.text = text;
}
}
/** Reads the agent's state. Answered at once, even while an LLM call is pending. */
public static final class GetConversation extends AskCommand<ConversationView> implements Command {}
/** Makes the agent throw, to show supervision. */
public static final class SimulateCrash implements Command {
@JsonCreator
public SimulateCrash() {}
}
private final AgentBrain.Dependencies dependencies;
public AgentActor(
AgentRuntime runtime,
LlmClient llm,
ToolRegistry tools,
AgentSnapshotStore snapshots,
AgentProperties properties) {
this.dependencies = new AgentBrain.Dependencies(
llm,
tools,
snapshots,
runtime.rateLimiter(),
runtime.approvals(),
properties.getApprovalTimeout(),
properties.getMaxToolSteps());
}
@Override
public ShardedEntityType<Command> entityType() {
return TYPE_KEY;
}
@Override
public SpringActorBehavior<Command> create(SpringShardedActorContext<Command> ctx) {
return AgentBrain.behavior(SpringActorBehavior.builder(Command.class, ctx), ctx.getEntityId(), dependencies);
}
}
/**
* One sharded entity per agent id: the cluster keeps exactly one instance of each agent, on
* some node, and routes every message for that id to it.
*
* The agent's logic is [AgentBrain], run under a restart supervisor. If it crashes, the
* supervisor restarts it and it reloads its conversation from the snapshot store.
*/
@Component
class AgentActor(
runtime: AgentRuntime,
llm: LlmClient,
tools: ToolRegistry,
snapshots: AgentSnapshotStore,
properties: AgentProperties,
) : SpringShardedActor<AgentActor.Command> {
companion object {
val TYPE_KEY: ShardedEntityType<Command> = ShardedEntityType.of(Command::class.java, "Agent")
}
/** Commands may cross nodes, so they are JSON serializable. */
interface Command : JsonSerializable
/** A user message. The reply is the agent's final answer for this turn. */
class Chat @JsonCreator constructor(@JsonProperty("text") val text: String) : AskCommand<AgentAnswer>(), Command
/** Reads the agent's state. Answered at once, even while an LLM call is pending. */
class GetConversation : AskCommand<ConversationView>(), Command
/** Makes the agent throw, to show supervision. */
class SimulateCrash @JsonCreator constructor() : Command
private val dependencies = AgentBrain.Dependencies(
llm,
tools,
snapshots,
runtime.rateLimiter,
runtime.approvals,
properties.approvalTimeout,
properties.maxToolSteps,
)
override fun entityType(): ShardedEntityType<Command> = TYPE_KEY
override fun create(ctx: SpringShardedActorContext<Command>): SpringActorBehavior<Command> =
AgentBrain.behavior(actorBehavior<Command>(ctx), ctx.entityId, dependencies)
}
Callers address agents by id and never need to know which node hosts them:
/** Talks to agents by id. The agent may live on any node of the cluster. */
@Service
public class AgentService {
private final SpringActorSystem actorSystem;
public AgentService(SpringActorSystem actorSystem) {
this.actorSystem = actorSystem;
}
public CompletionStage<AgentAnswer> chat(String agentId, String text, Duration timeout) {
return agent(agentId)
.ask(new AgentActor.Chat(text))
.withTimeout(timeout)
.execute();
}
public CompletionStage<ConversationView> conversation(String agentId, Duration timeout) {
return agent(agentId)
.ask(new AgentActor.GetConversation())
.withTimeout(timeout)
.execute();
}
public void simulateCrash(String agentId) {
agent(agentId).tell(new AgentActor.SimulateCrash());
}
private SpringShardedActorHandle<AgentActor.Command> agent(String agentId) {
return actorSystem.sharded(AgentActor.class).withId(agentId).get();
}
}
/** Talks to agents by id. The agent may live on any node of the cluster. */
@Service
class AgentService(private val actorSystem: SpringActorSystem) {
suspend fun chat(agentId: String, text: String, timeout: Duration): AgentAnswer =
agent(agentId).ask(AgentActor.Chat(text)).withTimeout(timeout).await()
suspend fun conversation(agentId: String, timeout: Duration): ConversationView =
agent(agentId).ask(AgentActor.GetConversation()).withTimeout(timeout).await()
fun simulateCrash(agentId: String) {
agent(agentId).tell(AgentActor.SimulateCrash())
}
private fun agent(agentId: String): SpringShardedActorHandle<AgentActor.Command> =
actorSystem.sharded<AgentActor, _>().withId(agentId).get()
}
Single node by default
The example sets spring.actor.cluster.join-self: true, so one node forms its own cluster.
For more nodes, remove it and list spring.actor.cluster.seed-nodes as in the
Sharded Actors guide.
The agent loop without blocking
A turn is: user message, rate-limit permit, model call, then either a final answer or a tool
call followed by another model call. The model call returns a CompletionStage;
pipeToSelf turns its result into a message, so the actor never waits on it.
private void requestPermit() {
status = Status.PERMIT;
deps.rateLimiter().tell(RateLimiterActor.Acquire.replyingTo(permits));
}
private SpringActorBehavior<AgentActor.Command> onPermit(PermitGranted granted) {
if (status != Status.PERMIT) {
return SpringActorBehavior.same();
}
status = Status.LLM;
ctx.getLog().debug("Agent {} calls the LLM", agentId);
// The future completes on another thread; pipeToSelf turns it into a message, so
// the actor never waits and never touches its state from that thread.
ctx.pipeToSelf(deps.llm().complete(List.copyOf(conversation)), LlmResponded::new);
return SpringActorBehavior.same();
}
private SpringActorBehavior<AgentActor.Command> onLlmResponded(LlmResponded responded) {
if (status != Status.LLM) {
return SpringActorBehavior.same(); // a reply for an earlier incarnation
}
if (responded.error() != null) {
finishTurn("Sorry, the model call failed: " + responded.error().getMessage());
return SpringActorBehavior.same();
}
LlmReply reply = responded.reply();
if (!reply.isToolCall()) {
finishTurn(reply.text());
return SpringActorBehavior.same();
}
if (++toolSteps > deps.maxToolSteps()) {
finishTurn("Stopped after " + deps.maxToolSteps() + " tool calls.");
return SpringActorBehavior.same();
}
append(ChatMessage.toolCall(reply.toolName(), reply.toolArgument()));
Optional<Tool> tool = deps.tools().find(reply.toolName());
if (tool.isEmpty()) {
toolResult(reply, "unknown tool");
} else if (tool.get().requiresApproval()) {
askForApproval(reply);
} else {
runTool(tool.get(), reply);
}
return SpringActorBehavior.same();
}
private fun requestPermit() {
status = Status.PERMIT
deps.rateLimiter.tell(RateLimiterActor.Acquire.replyingTo(permits))
}
private fun onPermit(): SpringActorBehavior<AgentActor.Command> {
if (status != Status.PERMIT) {
return SpringActorBehavior.same()
}
status = Status.LLM
ctx.log.debug("Agent {} calls the LLM", agentId)
// The future completes on another thread; pipeToSelf turns it into a message, so
// the actor never waits and never touches its state from that thread.
ctx.pipeToSelf(deps.llm.complete(conversation.toList())) { reply, error -> LlmResponded(reply, error) }
return SpringActorBehavior.same()
}
private fun onLlmResponded(responded: LlmResponded): SpringActorBehavior<AgentActor.Command> {
if (status != Status.LLM) {
return SpringActorBehavior.same() // a reply for an earlier incarnation
}
val reply = responded.reply
if (responded.error != null || reply == null) {
finishTurn("Sorry, the model call failed: ${responded.error?.message}")
return SpringActorBehavior.same()
}
val toolName = reply.toolName
val toolArgument = reply.toolArgument
if (toolName == null || toolArgument == null) {
finishTurn(reply.text.orEmpty())
return SpringActorBehavior.same()
}
if (++toolSteps > deps.maxToolSteps) {
finishTurn("Stopped after ${deps.maxToolSteps} tool calls.")
return SpringActorBehavior.same()
}
append(ChatMessage.toolCall(toolName, toolArgument))
val tool = deps.tools.find(toolName).orElse(null)
when {
tool == null -> toolResult(reply, "unknown tool")
tool.requiresApproval() -> askForApproval(reply)
else -> runTool(tool, reply)
}
return SpringActorBehavior.same()
}
While a call is pending the agent still answers GetConversation at once, and a new Chat
waits in a queue until the current turn ends.
A rate limiter per node
Model providers limit calls per second. Each node spawns one rate limiter actor and every agent
on that node asks it for a permit before each call. It keeps a sliding one-second window, so no
one-second span ever holds more than agent.calls-per-second calls.
/**
* One per node: hands out permits for LLM calls, at most {@code agent.calls-per-second} in any
* one-second window. Requests over the limit wait in a queue; a timer wakes the actor when the
* oldest permit leaves the window.
*
* <p>The starter has no rate limiter, so this is a plain actor with a timer from its behavior context.
*/
@Component
public class RateLimiterActor implements SpringActor<RateLimiterActor.Command> {
public interface Command {}
/** Ask for one permit. The reply comes when the call may start. */
public static final class Acquire extends AskCommand<Permit> implements Command {
@Nullable private final SpringActorRef<Permit> adapter;
public Acquire() {
this(null);
}
private Acquire(@Nullable SpringActorRef<Permit> adapter) {
this.adapter = adapter;
}
/** For actors that want the permit as a message instead of a future. */
public static Acquire replyingTo(SpringActorRef<Permit> replyTo) {
return new Acquire(replyTo);
}
void grant(Permit permit) {
if (adapter != null) {
adapter.tell(permit);
} else {
reply(permit);
}
}
}
/** @param grantedAtNanos {@link System#nanoTime()} when the permit was granted */
public record Permit(long grantedAtNanos) {}
private enum WakeUp implements Command {
INSTANCE
}
private static final Duration WINDOW = Duration.ofSeconds(1);
private final int callsPerSecond;
public RateLimiterActor(AgentProperties properties) {
this.callsPerSecond = properties.getCallsPerSecond();
}
@Override
public SpringActorBehavior<Command> create(SpringActorContext actorContext) {
return SpringActorBehavior.builder(Command.class, actorContext)
.withState(ctx -> new SlidingWindow(ctx, callsPerSecond, WINDOW.toNanos()))
.onMessage(Acquire.class, SlidingWindow::onAcquire)
.onMessage(WakeUp.class, (window, wakeUp) -> window.drain())
.build();
}
private static final class SlidingWindow {
private final SpringBehaviorContext<Command> ctx;
private final int limit;
private final long windowNanos;
private final Deque<Long> granted = new ArrayDeque<>();
private final Deque<Acquire> waiting = new ArrayDeque<>();
SlidingWindow(SpringBehaviorContext<Command> ctx, int limit, long windowNanos) {
this.ctx = ctx;
this.limit = limit;
this.windowNanos = windowNanos;
}
SpringActorBehavior<Command> onAcquire(Acquire acquire) {
waiting.addLast(acquire);
return drain();
}
SpringActorBehavior<Command> drain() {
long now = System.nanoTime();
while (!granted.isEmpty() && now - granted.peekFirst() >= windowNanos) {
granted.removeFirst();
}
while (!waiting.isEmpty() && granted.size() < limit) {
granted.addLast(now);
waiting.removeFirst().grant(new Permit(now));
}
if (!waiting.isEmpty()) {
long untilFree = windowNanos - (now - granted.peekFirst());
ctx.startSingleTimer(WakeUp.INSTANCE, WakeUp.INSTANCE, Duration.ofNanos(untilFree));
}
return SpringActorBehavior.same();
}
}
}
/**
* One per node: hands out permits for LLM calls, at most `agent.calls-per-second` in any
* one-second window. Requests over the limit wait in a queue; a timer wakes the actor when the
* oldest permit leaves the window.
*
* The starter has no rate limiter, so this is a plain actor with a timer from its behavior context.
*/
@Component
class RateLimiterActor(properties: AgentProperties) : SpringActor<RateLimiterActor.Command> {
interface Command
/** Ask for one permit. The reply comes when the call may start. */
class Acquire private constructor(private val adapter: SpringActorRef<Permit>?) : AskCommand<Permit>(), Command {
constructor() : this(null)
internal fun grant(permit: Permit) {
if (adapter != null) adapter.tell(permit) else reply(permit)
}
companion object {
/** For actors that want the permit as a message instead of a future. */
fun replyingTo(replyTo: SpringActorRef<Permit>) = Acquire(replyTo)
}
}
/** @param grantedAtNanos [System.nanoTime] when the permit was granted */
data class Permit(val grantedAtNanos: Long)
private data object WakeUp : Command
private val callsPerSecond = properties.callsPerSecond
override fun create(actorContext: SpringActorContext): SpringActorBehavior<Command> =
actorBehavior<Command>(actorContext)
.withState { ctx -> SlidingWindow(ctx, callsPerSecond, 1.seconds.inWholeNanoseconds) }
.onMessage(Acquire::class.java) { window, acquire -> window.onAcquire(acquire) }
.onMessage(WakeUp::class.java) { window, _ -> window.drain() }
.build()
private class SlidingWindow(
private val ctx: SpringBehaviorContext<Command>,
private val limit: Int,
private val windowNanos: Long,
) {
private val granted = ArrayDeque<Long>()
private val waiting = ArrayDeque<Acquire>()
fun onAcquire(acquire: Acquire): SpringActorBehavior<Command> {
waiting.addLast(acquire)
return drain()
}
fun drain(): SpringActorBehavior<Command> {
val now = System.nanoTime()
while (granted.isNotEmpty() && now - granted.first() >= windowNanos) {
granted.removeFirst()
}
while (waiting.isNotEmpty() && granted.size < limit) {
granted.addLast(now)
waiting.removeFirst().grant(Permit(now))
}
if (waiting.isNotEmpty()) {
val untilFree = windowNanos - (now - granted.first())
ctx.startSingleTimer(WakeUp, WakeUp, Duration.ofNanos(untilFree))
}
return SpringActorBehavior.same()
}
}
}
The node-local actors are spawned once, when Spring starts:
/**
* Node-local actors that every agent on this node shares: the LLM rate limiter and the approval
* gateway. Each node spawns its own, so the rate limit is per node.
*/
@Component
public class AgentRuntime {
private final SpringActorHandle<RateLimiterActor.Command> rateLimiter;
private final SpringActorHandle<ApprovalActor.Command> approvals;
// The actor beans are parameters so Spring registers them before they are spawned here.
public AgentRuntime(SpringActorSystem actorSystem, RateLimiterActor rateLimiterActor, ApprovalActor approvalActor) {
this.rateLimiter = actorSystem
.actor(RateLimiterActor.class)
.withId("llm-rate-limiter")
.spawnAndWait();
this.approvals =
actorSystem.actor(ApprovalActor.class).withId("approvals").spawnAndWait();
}
/**
* Node-local actors that every agent on this node shares: the LLM rate limiter and the approval
* gateway. Each node spawns its own, so the rate limit is per node.
*/
@Component
class AgentRuntime(
actorSystem: SpringActorSystem,
// The actor beans are parameters so Spring registers them before they are spawned here.
rateLimiterActor: RateLimiterActor,
approvalActor: ApprovalActor,
) {
val rateLimiter: SpringActorHandle<RateLimiterActor.Command> =
actorSystem.actor<RateLimiterActor, _>().withId("llm-rate-limiter").spawnAndWait()
val approvals: SpringActorHandle<ApprovalActor.Command> =
actorSystem.actor<ApprovalActor, _>().withId("approvals").spawnAndWait()
}
Per node, not per cluster
With three nodes the cluster can make three times agent.calls-per-second calls. For a
cluster-wide limit, run the limiter as a cluster singleton (asClusterSingleton()) instead.
A human approval step
When the model asks for a tool that needs approval, the agent asks the node's approval gateway with a timeout. The gateway holds the request until a human answers; if nobody answers in time, the ask fails and the agent tells the model the tool was not run.
private void askForApproval(LlmReply call) {
status = Status.APPROVAL;
PendingApproval request =
new PendingApproval(agentId + "-" + UUID.randomUUID(), agentId, call.toolName(), call.toolArgument());
Duration timeout = deps.approvalTimeout();
ctx.pipeToSelf(
deps.approvals()
.ask(new ApprovalActor.RequestApproval(request, timeout))
.withTimeout(timeout)
.execute(),
(ApprovalDecision decision, Throwable error) -> {
if (error != null) {
return new ApprovalResolved(call, false, "no human answer within " + timeout);
}
return new ApprovalResolved(
call, decision.approved(), decision.approved() ? "approved" : "rejected by a human");
});
}
private SpringActorBehavior<AgentActor.Command> onApprovalResolved(ApprovalResolved resolved) {
if (status != Status.APPROVAL) {
return SpringActorBehavior.same();
}
LlmReply call = resolved.call();
Optional<Tool> tool = deps.tools().find(call.toolName());
if (resolved.approved() && tool.isPresent()) {
runTool(tool.get(), call);
} else {
toolResult(call, "not run: " + resolved.reason());
}
return SpringActorBehavior.same();
}
private fun askForApproval(call: LlmReply) {
status = Status.APPROVAL
val request = PendingApproval("$agentId-${UUID.randomUUID()}", agentId, call.toolName!!, call.toolArgument!!)
val timeout = deps.approvalTimeout
ctx.pipeToSelf(
deps.approvals
.ask(ApprovalActor.RequestApproval(request, timeout))
.withTimeout(timeout)
.execute(),
) { decision, error ->
if (error != null || decision == null) {
ApprovalResolved(call, false, "no human answer within $timeout")
} else {
ApprovalResolved(call, decision.approved, if (decision.approved) "approved" else "rejected by a human")
}
}
}
private fun onApprovalResolved(resolved: ApprovalResolved): SpringActorBehavior<AgentActor.Command> {
if (status != Status.APPROVAL) {
return SpringActorBehavior.same()
}
val call = resolved.call
val tool = deps.tools.find(call.toolName!!).orElse(null)
if (resolved.approved && tool != null) {
runTool(tool, call)
} else {
toolResult(call, "not run: ${resolved.reason}")
}
return SpringActorBehavior.same()
}
The human side, for a controller, a chat bot or a test:
/** The human side of the approval step, for a controller, a Slack bot or a test. */
@Service
public class ApprovalService {
private static final Duration TIMEOUT = Duration.ofSeconds(3);
private final AgentRuntime runtime;
public ApprovalService(AgentRuntime runtime) {
this.runtime = runtime;
}
public CompletionStage<List<PendingApproval>> pending() {
return runtime.approvals()
.ask(new ApprovalActor.ListPending())
.withTimeout(TIMEOUT)
.execute();
}
/** Completes with false if the request is unknown or its timeout has passed. */
public CompletionStage<Boolean> decide(String requestId, boolean approved) {
return runtime.approvals()
.ask(new ApprovalActor.Decide(requestId, approved))
.withTimeout(TIMEOUT)
.execute();
}
}
/** The human side of the approval step, for a controller, a Slack bot or a test. */
@Service
class ApprovalService(private val runtime: AgentRuntime) {
suspend fun pending(): List<PendingApproval> =
runtime.approvals.ask(ApprovalActor.ListPending()).withTimeout(TIMEOUT).await()
/** Returns false if the request is unknown or its timeout has passed. */
suspend fun decide(requestId: String, approved: Boolean): Boolean =
runtime.approvals.ask(ApprovalActor.Decide(requestId, approved)).withTimeout(TIMEOUT).await()
private companion object {
val TIMEOUT: Duration = Duration.ofSeconds(3)
}
}
Supervision and restarts
The agent's logic runs under a restart supervisor (withSupervisionStrategy). A restart creates the
state again with withState, and the state loads the last snapshot:
/**
* Restart on failure, at most 10 times a minute. A restart creates the state again, so the
* brain reloads its conversation from the last snapshot. After the limit the entity stops,
* and sharding starts a fresh one on the next message.
*/
public static SpringActorBehavior<AgentActor.Command> behavior(
SpringActorBehavior.Builder<AgentActor.Command, SpringBehaviorContext<AgentActor.Command>> builder,
String agentId,
Dependencies dependencies) {
return builder.withSupervisionStrategy(SupervisionStrategy.restart().withLimit(10, Duration.ofMinutes(1)))
.withState(ctx -> new AgentBrain(ctx, agentId, dependencies))
.onMessage(AgentActor.Chat.class, AgentBrain::onChat)
.onMessage(AgentActor.GetConversation.class, AgentBrain::onGetConversation)
.onMessage(AgentActor.SimulateCrash.class, AgentBrain::onSimulateCrash)
.onMessage(PermitGranted.class, AgentBrain::onPermit)
.onMessage(LlmResponded.class, AgentBrain::onLlmResponded)
.onMessage(ApprovalResolved.class, AgentBrain::onApprovalResolved)
.build();
}
private AgentBrain(SpringBehaviorContext<AgentActor.Command> ctx, String agentId, Dependencies dependencies) {
this.ctx = ctx;
this.agentId = agentId;
this.deps = dependencies;
this.permits = ctx.messageAdapter(RateLimiterActor.Permit.class, PermitGranted::new);
dependencies.snapshots().load(agentId).ifPresent(snapshot -> conversation.addAll(snapshot.conversation()));
}
companion object {
/**
* Restart on failure, at most 10 times a minute. A restart creates the state again, so the
* brain reloads its conversation from the last snapshot. After the limit the entity stops,
* and sharding starts a fresh one on the next message.
*/
fun behavior(
builder: SpringActorBehavior.Builder<AgentActor.Command, SpringBehaviorContext<AgentActor.Command>>,
agentId: String,
dependencies: Dependencies,
): SpringActorBehavior<AgentActor.Command> =
builder.withSupervisionStrategy(SupervisionStrategy.restart().withLimit(10, 1.minutes.toJavaDuration()))
.withState { ctx -> AgentBrain(ctx, agentId, dependencies) }
.onMessage(AgentActor.Chat::class.java) { brain, msg -> brain.onChat(msg) }
.onMessage(AgentActor.GetConversation::class.java) { brain, msg -> brain.onGetConversation(msg) }
.onMessage(AgentActor.SimulateCrash::class.java) { brain, _ -> brain.onSimulateCrash() }
.onMessage(PermitGranted::class.java) { brain, _ -> brain.onPermit() }
.onMessage(LlmResponded::class.java) { brain, msg -> brain.onLlmResponded(msg) }
.onMessage(ApprovalResolved::class.java) { brain, msg -> brain.onApprovalResolved(msg) }
.build()
}
private val permits: SpringActorRef<RateLimiterActor.Permit> =
ctx.messageAdapter(RateLimiterActor.Permit::class.java) { PermitGranted(it) }
private val conversation = mutableListOf<ChatMessage>()
init {
deps.snapshots.load(agentId).ifPresent { conversation.addAll(it.conversation) }
}
Every change to the conversation is saved before the agent moves on, so a new actor system finds the agent where it left off:
The store is an interface. The example writes one JSON file per agent; for a database, implement
it with a JPA entity and repository like ActorSnapshot and ActorSnapshotRepository in the
persistence example (see also
State in a Database).
/**
* Saves and loads agent snapshots. The example writes JSON files; a JPA implementation with an
* {@code ActorSnapshot} entity and repository, as in example/persistence, plugs in the same way.
*/
public interface AgentSnapshotStore {
Optional<AgentSnapshot> load(String agentId);
void save(AgentSnapshot snapshot);
}
/**
* Saves and loads agent snapshots. The example writes JSON files; a JPA implementation with an
* `ActorSnapshot` entity and repository, as in example/persistence, plugs in the same way.
*/
interface AgentSnapshotStore {
fun load(agentId: String): Optional<AgentSnapshot>
fun save(snapshot: AgentSnapshot)
}
Configuration
| Property | Default | What |
|---|---|---|
agent.calls-per-second |
20 |
Model calls one node may start per second |
agent.approval-timeout |
30s |
How long an agent waits for a human |
agent.max-tool-steps |
5 |
Tool calls per turn before the agent stops |
agent.snapshot-dir |
${java.io.tmpdir}/agent-snapshots |
Where snapshots are written |
agent.fake-llm-latency |
0 (200ms in application.yml) |
Delay of each fake model reply |
agent.demo |
true |
Run one demo conversation on start-up |
What the tests show
| Test | Shows |
|---|---|
AgentConversationTest |
user message, model reply, tool call, tool result, final answer |
ConcurrentAgentsTest |
100 agents at once, each with its own id and its own history |
RateLimiterTest |
no one-second window holds more permits than the limit |
SlowLlmTest |
the agent answers other messages while a model call is pending |
SupervisionTest |
a crashed agent restarts and reloads its conversation |
ActorSystemRestartTest |
the conversation survives a restart of the whole actor system |
HumanApprovalTest |
approve, reject, and a timeout when nobody answers |
What the starter does not provide yet
The example builds these itself:
- Rate limiting. There is no rate limiter in the starter; the example's is an actor.