Build an Autonomous AI Agent Swarm in Java
This tutorial builds an autonomous AI agent swarm in Java, one step at a time. We start with a single agent that calls a tool, then add a second agent, then a reviewer that rejects weak drafts, then a manager agent that plans the work, and finally a hard budget so the swarm can never run away with your token bill.
Everything runs on Spring Boot with SwarmAI, an open-source multi-agent framework built on Spring AI. By default it runs against a local model through Ollama, so you need no API key to follow along.
If you are new to the concept, read What Are Agentic Swarms? first.
Prerequisites
- Java 21 and Maven
- Ollama running locally with a model pulled, for example
ollama pull mistral, or an OpenAI API key - Basic Spring Boot knowledge
The fastest start is to clone the quickstart template from the SwarmAI examples repository. It is a complete Spring Boot application with one agent and one tool. The steps below grow it into a swarm.
Step 1: Add SwarmAI to a Spring Boot project
SwarmAI is published on Maven Central under the ai.intelliswarm group. Add the core and tools modules plus one Spring AI model starter:
<dependency>
<groupId>ai.intelliswarm</groupId>
<artifactId>swarmai-core</artifactId>
<version>${swarmai.version}</version>
</dependency>
<dependency>
<groupId>ai.intelliswarm</groupId>
<artifactId>swarmai-tools</artifactId>
<version>${swarmai.version}</version>
</dependency>
<!-- Local model via Ollama. For OpenAI, use spring-ai-starter-model-openai instead. -->
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-model-ollama</artifactId>
</dependency>
Set swarmai.version to the latest release listed on Maven Central.
Then point Spring AI at your model in application.yml:
spring:
ai:
ollama:
base-url: ${SPRING_AI_OLLAMA_BASE_URL:http://localhost:11434}
chat:
options:
model: ${OLLAMA_MODEL:mistral:latest}
To use OpenAI instead, swap the starter for spring-ai-starter-model-openai, set SPRING_AI_OPENAI_API_KEY, and configure spring.ai.openai.chat.options.model (for example gpt-4o-mini).
Step 2: One agent, one tool, one task
An agent is a role, a goal, a backstory and a set of tools. A task is a unit of work assigned to an agent. A swarm runs tasks with a process type. This is the smallest useful swarm, taken from the quickstart template:
@Bean
CommandLineRunner runDemo(ChatClient.Builder chatClientBuilder,
CalculatorTool calculatorTool) {
return args -> {
Agent analyst = Agent.builder()
.role("Quantitative Analyst")
.goal("Answer word problems with precise arithmetic.")
.backstory("You always use the calculator tool for any arithmetic — " +
"never guess at numbers. Show the expression you evaluated.")
.chatClient(chatClientBuilder.build())
.tools(List.of(calculatorTool))
.maxTurns(3)
.build();
Task problem = Task.builder()
.description("A store sells coffee at $4.75 per bag. A customer buys 13 " +
"bags and uses an 18% loyalty discount. What is the final " +
"price they pay? Use the calculator tool; show the calculation.")
.expectedOutput("The final price in dollars, with the expression you used.")
.agent(analyst)
.build();
SwarmOutput result = Swarm.builder()
.agent(analyst)
.task(problem)
.process(ProcessType.SEQUENTIAL)
.build()
.kickoff(Map.of());
System.out.println(result.getFinalOutput());
};
}
Tools such as CalculatorTool are Spring beans, so you inject them like any other component. maxTurns(3) lets the agent loop: call the tool, read the result, and decide whether it is done.
Run it with mvn spring-boot:run. The agent calls the calculator instead of guessing, which is the first sign of agentic behaviour: the model decides which action to take.
Step 3: Two agents that hand work to each other
Now split the work between a researcher and a writer. The researcher uses the WikipediaTool (no API key needed). The writer's task depends on the research task, so it receives the research output as context:
Agent researcher = Agent.builder()
.role("Research Analyst")
.goal("Find accurate, up-to-date information")
.backstory("Experienced researcher who verifies facts.")
.chatClient(chatClient)
.tool(wikipediaTool)
.permissionMode(PermissionLevel.READ_ONLY)
.build();
Agent writer = Agent.builder()
.role("Content Writer")
.goal("Write clear, engaging reports")
.backstory("Turns research into well-structured articles.")
.chatClient(chatClient)
.build();
Task research = Task.builder()
.id("research").description("Research: {topic}")
.agent(researcher).build();
Task report = Task.builder()
.id("report").description("Write a report from findings")
.agent(writer).dependsOn("research")
.outputFormat(OutputFormat.MARKDOWN).build();
SwarmOutput result = Swarm.builder()
.agents(List.of(researcher, writer))
.tasks(List.of(research, report))
.process(ProcessType.SEQUENTIAL)
.build()
.kickoff(Map.of("topic", "AI agents in enterprise"));
Three details matter here:
{topic}in the task description is filled from the map passed tokickoff, so the same swarm can run on any topic.dependsOn("research")wires the tasks together. SwarmAI orders tasks by their dependencies and passes earlier outputs forward.permissionMode(PermissionLevel.READ_ONLY)limits the researcher to read-only tools. Give each agent only the permissions its role needs.
Step 4: Add a reviewer that sends work back
A single pass is rarely the best an LLM can do. The ITERATIVE process adds a reviewer agent that either approves the output or returns it with feedback. The writer then revises until the reviewer approves or the iteration limit is hit:
SwarmOutput output = Swarm.builder()
.agents(List.of(writer))
.tasks(List.of(draftTask))
.process(ProcessType.ITERATIVE)
.managerAgent(reviewer) // Acts as reviewer
.config("maxIterations", 3) // Max review cycles
.config("qualityCriteria", "Must include data-backed claims")
.build()
.kickoff(inputs);
The reviewer is an ordinary agent, so give it a strict role, for example "Senior Editor who rejects any claim without a source". qualityCriteria tells it exactly what "good" means, and maxIterations guarantees the loop ends.
This writer and critic loop is often the single biggest quality improvement you can make to an LLM workflow, because the critic does not share the author's blind spots.
Step 5: Let a manager agent plan the work
So far you decided the order of work. With the HIERARCHICAL process, a manager agent first writes an execution plan, the worker agents carry it out with the plan as context, and the manager then synthesises the final result:
Agent manager = Agent.builder()
.role("Project Manager")
.goal("Plan the research and make sure the final report answers the question")
.backstory("You break problems into steps, check each result and combine them.")
.chatClient(chatClient)
.build();
SwarmOutput result = Swarm.builder()
.agents(List.of(researcher, writer))
.tasks(List.of(research, report))
.managerAgent(manager)
.process(ProcessType.HIERARCHICAL)
.build()
.kickoff(Map.of("topic", "AI agents in enterprise"));
Notice that the agents and tasks did not change. Only the process type and the manager were added. That is the main design idea in SwarmAI: you pick how much autonomy the swarm gets by choosing a process, not by rewriting your agents. Multi-Agent Orchestration Patterns covers all eight process types, including SELF_IMPROVING and SWARM, which go further and generate new skills at run time.
Step 6: Put a hard limit on cost
Autonomous agents decide how many calls to make, so put a ceiling on them. A BudgetPolicy sets token and dollar limits and what happens when they are reached. HARD_STOP aborts the run, WARN logs and continues:
BudgetPolicy budgetPolicy = BudgetPolicy.builder()
.maxTotalTokens(1_000_000)
.maxCostUsd(10.00)
.onExceeded(BudgetPolicy.BudgetAction.HARD_STOP)
.warningThresholdPercent(75.0)
.build();
SwarmOutput result = Swarm.builder()
.agents(List.of(researcher, writer))
.tasks(List.of(research, report))
.managerAgent(manager)
.process(ProcessType.HIERARCHICAL)
.budgetTracker(new InMemoryBudgetTracker(budgetPolicy))
.budgetPolicy(budgetPolicy)
.build()
.kickoff(Map.of("topic", "AI agents in enterprise"));
Budgets, approval gates and tool permissions are covered in depth in Governing Autonomous AI Agents.
Step 7: Read the results
kickoff returns a SwarmOutput with the final answer, the output of each task and token usage:
if (result.isSuccessful()) {
System.out.println(result.getFinalOutput());
System.out.println("Tokens used: " + result.getTotalTokens());
}
For long-running swarms, kickoffAsync returns a CompletableFuture, and kickoffForEach runs the same swarm over a list of inputs.
Bonus: the same swarm in YAML
If you prefer configuration over code, the swarmai-dsl module loads swarms from YAML. Placeholders use double braces:
swarm:
name: "ResearchReport"
process: SEQUENTIAL
budget:
maxTokens: 300000
maxCostUsd: 5.0
onExceeded: WARN
agents:
researcher:
role: "Senior Researcher"
goal: "Conduct thorough research on {{topic}}"
backstory: "You verify every fact before reporting it."
temperature: 0.2
writer:
role: "Publication Writer"
goal: "Transform research into a clear report on {{topic}}"
backstory: "You write concise, well-structured reports."
temperature: 0.3
tasks:
research:
description: "Research {{topic}} thoroughly with cited sources"
expectedOutput: "Comprehensive research with citations"
agent: researcher
outputFormat: MARKDOWN
report:
description: "Write a report on {{topic}} based on the research"
agent: writer
dependsOn:
- research
outputFormat: MARKDOWN
Load and run it with the auto-configured SwarmLoader:
@Autowired SwarmLoader swarmLoader;
Swarm swarm = swarmLoader.load("workflows/research.yaml",
Map.of("topic", "AI Safety"));
SwarmOutput output = swarm.kickoff(Map.of());
Where to go next
You now have a swarm that researches, writes, reviews its own work, plans with a manager agent and stays inside a budget. From here:
- Explore the built-in tools your agents can use, from Wikipedia and arXiv to Jira, Kafka and S3.
- Browse the examples for complete swarms: competitive analysis, investment memos, customer support and more.
- See how swarms compare with a raw LLM call in the demos.
- Run everything locally with Docker and Ollama.
SwarmAI is open source under the Apache 2.0 licence. If you built something with this tutorial, star SwarmAI on GitHub and tell us about it.