Skip to content

Checking your reading list…

Retry

Stay curious. Build better.

Appearance

Choose how BestHub looks on this device.

Changes apply immediately.

Search articles

Open Discover with these filters

Suggested searches

Java AI Agents: 8 Core Concepts from Interview to Production

This article explains eight core concepts for building AI agents in Java—ReAct loops, tool calling, memory, planning, reflection, multi-agent systems, MCP, and workflow vs. agent trade-offs—with production-ready code examples, pitfall analyses, and interview-focused insights.

Overview

The author shares hard-won lessons from building a production "intelligent customer service Agent" in Java. The key insight: an Agent is not just a smarter prompt; it is an LLM placed inside a stateful loop that can observe, reason, act, and self-correct.

Agent = LLM (brain) + Memory + Tools + Planning + Reflection, wired together by a ReAct loop; complex tasks are delegated to multiple agents; MCP standardizes tool integration; workflows are "fixed-process" Agent precursors.

Anchor distinction: Workflow = human defines process, model fills blanks; Agent = model decides next step autonomously.

Mnemonic for interviews: Loop handles the present, planning handles the future, memory handles the past, reflection handles quality, MCP handles external integration, multi-agent handles scale, workflow handles determinism.

1. ReAct Loop: The Agent's Heartbeat

What It Is

ReAct = Reasoning + Acting. The model alternates Thought → Action (tool call) → Observation until reaching a final answer. Unlike plain multi-turn chat, ReAct has an explicit "think-act-observe" closed loop, enabling the model to actively call external tools and adjust decisions based on results .

Java Implementation: Guardrails Over Loop Mechanics

The real challenge isn't writing the loop—it's that the loop lacks hard boundaries . The author's team suffered a runaway loop where the model hopped between two tools all night, exploding the token bill. They added three defenses: maxIterations hard limit

Per-turn token budget

Tool-call fingerprint deduplication (same tool + same params N times → circuit break)

/**
 * ReAct loop skeleton with circuit breakers
 * Highlights: explicit termination + round budget + action deduplication + exception fallback
 */
public class ReActAgent {
    private static final int MAX_ROUNDS = 8;          // round budget prevents infinite loops
    private final ChatModel chatModel;
    private final ToolRegistry toolRegistry;
    private final ChatMemory memory;

    public String run(String userQuery) {
        memory.add(UserMessage.from(userQuery));
        Set<String> actionFingerprint = new HashSet<>(); // deduplicate identical actions

        for (int round = 1; round <= MAX_ROUNDS; round++) {
            // 1. Thought + Action: model decides, may return tool call
            AgentResponse resp = chatModel.chat(memory.messages());

            if (resp.isToolExecutionRequired()) {
                // Fingerprint deduplication: break "repeat same query" loop
                if (!actionFingerprint.add(resp.toolCall().fingerprint())) {
                    memory.add(SystemMessage.from(
                        "⚠️ You have repeated this action, try a different approach or give final answer"));
                    continue;
                }
                // 2. Action: execute tool. On failure, feed error back to model for self-correction
                String obs;
                try {
                    obs = toolRegistry.execute(resp.toolCall()).toJson();
                } catch (Exception e) {
                    obs = "Tool execution failed: " + e.getMessage() + ", try another approach";
                }
                memory.add(ObservationMessage.from(truncate(obs, 2000))); // truncate to prevent token explosion
                continue; // back to Thought
            }

            // 3. Termination: model gives final answer
            return resp.finalAnswer();
        }
        // Fallback: force convergence after max rounds, hand off to human
        return "⚠️ Max rounds reached, current conclusion: " + memory.lastAssistantAnswer();
    }
}
Interview talking points: round budget prevents infinite loops; tool exceptions converted to natural language feedback (model reroutes instead of crash); observation truncation written back to memory; duplicate-action fingerprint circuit breaker—these four are critical for production ReAct stability.

In Spring AI 2.0 the loop is abstracted as ToolCallingAdvisor —a recursive advisor that re-enters the chain while the AssistantMessage contains toolCalls. But "has a loop" ≠ "loop is safe"; business-level guardrails must be written by you.

Counter-intuitive fact for testers: same task, same code, same model can produce completely different trajectories —one run converges in 3 rounds, another in 5. Therefore Agent tests cannot assert "must call A then B"; they can only assert final answer correctness and guardrail activation .

2. Tool Calling: The Agent's Hands and Feet

What It Is

The model only "speaks"; Function Calling makes it emit structured intent (tool name + parameter JSON) , which our Java process actually executes (query DB, call API, run code) and feeds the result back. The security boundary lives entirely on our side.

The most elegant Java approach uses Spring AI / LangChain4j @Tool annotation to auto-generate JSON Schema:

@Component
public class OrderTools {
    @Tool(description = """
        Query order status. Only invoke when user provides explicit order ID.
        Parameter orderId format: ORD- prefix + 8 digits.
        If user only says "my order" without an ID, ask for it—do not guess.
        """)
    public OrderStatus queryOrder(@P("Order ID, e.g. ORD-12345678") String orderId) {
        Assert.isTrue(orderId.matches("ORD-\\d{8}"), "Invalid order ID format"); // pre-validation blocks hallucinated params
        return orderService.get(orderId);
    }
}

Model's structured call looks like:

{
  "toolCall": "queryOrder",
  "arguments": { "orderId": "ORD-12345678" }
}

Four Production Hard Lessons

Description is the model's "manual"—write it like API docs. Tool count grows; description quality directly determines call accuracy—include when to call, when not to, parameter format, and when to ask for clarification.

Parameter validation must happen in Java layer ( @Valid / assertions). Don't trust model-generated JSON. Models invent city names, enum values, unauthorized IDs.

Write tools (place order, refund, delete) require mandatory idempotency keys + human confirmation gates. Retry-caused duplicate orders will cost you a week of post-mortem.

Tool results must be condensed before feeding back. Raw payloads blow context window; paginate, trim fields, or use "reference-style return" (only return ID, fetch details on demand).

Architectural detail often missed: build a ToolRegistry as single source of truth —reflection scans annotations to generate schema, so LLM's tool descriptions and executor's metadata come from the same place, avoiding manual drift. On validation failure, feed structured error back to model; its self-correction success rate rises noticeably. Remember: error messages are also part of the prompt.

Newer models support multiple toolCall in one response; use CompletableFuture for parallel execution, but ensure toolCallId alignment when writing results back.

3. Memory: The Agent's Recall, Easiest to Turn into "Fake Memory"

Layered Architecture

Many recite "short-term Redis, long-term vector store", but real systems need at least three layers, often four:

Current-turn context : This turn's messages + tool results; in-memory message list; single turn

Short-term memory : Conversation context; sliding window + token truncation; within session

Long-term memory : User preferences, historical facts; vector store retrieval (RAG); cross-session

Task state / episodic memory : Intermediate state, failure lessons, success traces; DB / Redis structured storage; single task / cross-task

Two Hidden Pitfalls

Pitfall 1: Spring AI's default short-term memory is JVM-internal ConcurrentHashMap , window 20 messages, lost on process restart. Production must replace the repository—basic hygiene.

Pitfall 2: A single tool call can exceed the window size. MessageWindowChatMemory truncates from UserMessage boundaries to avoid splitting a turn, but when tool calling bloats beyond the window, non-system messages may be wiped entirely—the model instantly "loses the plot".

Solution: sliding window + summarization compression : when over limit, distill earliest messages into a summary and inject it, rather than discarding.

/**
 * Layered memory: short-term window + long-term vector recall
 * Highlights: auto-summarize on overflow, async fact persistence, prevent unbounded context growth
 */
public class LayeredMemory {
    private final List<Message> shortTerm = new ArrayList<>();
    private final VectorStore longTerm;                 // long-term vector store (PGVector/Milvus)
    private static final int WINDOW = 10;               // keep latest 10 messages
    private final ChatModel summaryModel;

    public void add(Message msg) {
        shortTerm.add(msg);
        // Long-term: persist factual info async to vector store with source & timestamp
        if (msg.isFact()) {
            longTerm.add(Embedding.from(msg.content()));
        }
        // Overflow: compress earliest messages into summary to free window
        if (shortTerm.size() > WINDOW) {
            String summary = summaryModel.summarize(
                shortTerm.subList(0, shortTerm.size() - WINDOW),
                "Retain: user goal, confirmed facts, tools called & conclusions, pending items");
            shortTerm.subList(0, shortTerm.size() - WINDOW).clear();
            shortTerm.add(0, SystemMessage.from("[Historical Summary] " + summary));
        }
    }
}
Key insight: writing long-term memory is harder than retrieval. Not every dialogue deserves vector storage. We use "explicit write decision"—only persist user preferences, confirmed conclusions, corrected facts, with memoryKey for idempotency and overwrite (e.g., preference.theme ). Retrieval uses hybrid scoring : semantic similarity + keyword + entity match + time decay, not pure vector top-K.

Final warning on memory pollution: once a wrong conclusion is stored as long-term fact, it keeps "coming back". Memory must carry "confidence + source + timestamp" tags; user-corrected info gets highest priority , conflicts resolved by latest, periodic stale cleanup.

4. Planning & Reflection: From "Wing It" to "Observable"

Task Planning: Think Before Acting

ReAct is reactive —each step only sees the immediate. For long tasks requiring "research then execute, execute then verify, fail then replan", explicit Planning is needed. Three typical strategies:

Static Planning : Decompose all steps upfront, execute sequentially; best for fixed-step short/medium tasks

Plan-and-Execute : Produce full plan (DAG), execute stepwise, support replan on failure; best for long tasks, need audit, need parallelism

ReWOO : Planning phase emits all tool calls upfront, removing Observations from planning context; best for token-cost-sensitive scenarios

Engineering takeaway: plan must be serializable (stored in DB) , each step with explicit deliverable, supporting failed replan, human plan edit, checkpoint resume; independent sub-tasks run in parallel. Common pattern: model outputs JSON plan → Java parses to task DAG → schedule by dependency.

// Planning artifact: structured task list
public record Plan(List<TaskStep> steps) {}
public record TaskStep(String id, String goal, String dependsOn, Status status) {}
enum Status { PENDING, RUNNING, DONE, FAILED, SKIPPED }

Reflection: Not "Are You Sure?"

Cold water first: simply asking "are you sure?" barely works—the model will say "I'm sure". Performative reflection symptom: "I reflected, I think it's right"—then it's still wrong.

Effective reflection is evidence-based verification . Our pipeline:

Goal → LlmPlanner → DagScheduler (with cycle detection) → StepExecutor → ToolSelector → LlmReflector

. Reflector outputs four branches:

/**
 * Reflection review: rules first + model fallback, retry if below threshold
 * Highlights: deterministic checks never delegated to LLM self-eval; explicit score threshold + attempt cap
 */
public class Reflector {
    private static final double PASS_SCORE = 0.8;
    private static final int MAX_REFLECT = 2;

    public ReflectResult review(String goal, AgentResult draft, List<ToolCall> calls, int times) {
        if (times >= MAX_REFLECT) return ReflectResult.pass(draft); // fallback allow

        // 1. Rule/programmatic checks first: anything code can verify, never ask LLM
        if (calls.stream().anyMatch(ToolCall::failed))
            return ReflectResult.retry("Failed tool call detected");
        if (!citationChecker.allSupported(draft.answer()))
            return ReflectResult.retry("Conclusion lacks retrieval evidence");

        // 2. Model only does semantic review, must output structured issue list
        Score score = chatModel.score(goal, draft.answer(), List.of(
            "Missing user sub-questions",
            "Numbers/dates consistent with tool results",
            "Out-of-scope or unauthorized"));
        if (score.value() >= PASS_SCORE) return ReflectResult.pass(draft);

        // 3. Save lesson to episodic memory for next few-shot injection
        episodicMemory.saveFailure(goal, score.issues());
        return ReflectResult.retry(score.issues().toString());
    }
}
Key insight: anything deterministically verifiable must never be delegated to LLM self-evaluation—this is the cheapest reliability boost. Review must return concrete issue list, not "try again"; four branches CONTINUE / RETRY_STEP / REPLAN / ABORT make every step's disposition explicitly traceable.

Cost guardrail: reflection itself consumes LLM calls; unlimited reflection = unlimited spend . Set maxReflections (default 2) + global token budget; on overflow force closure with "completed parts + reasons for incompleteness" instead of letting Agent pretend it finished.

5. Multi-Agent: When to Split, When Not To

Single Agent with too many tools → prompt bloat, decision chaos. Splitting seems natural, but selection principle is pragmatic:

"Multi-agent" isn't to make architecture look fancy; it's when a single Agent's tool set and context grow so large they interfere with each other—then split by responsibility. Before splitting, try single Agent + tool routing. After split, each Agent's context and tool set are isolated—far more controllable than "one super Agent carrying 80 tools".

Signals to split: context cross-pollution, tool set too large causing mis-selection, need different models/permissions, need parallel speedup. Signals NOT to split: simple task, strong sequential dependency, communication cost > benefit (honestly, most "multi-agent" systems are just dressed-up workflows). Keep count to 3–5; more explodes coordination cost.

Common collaboration topologies: (diagram omitted)

Four engineering must-haves:

Choose centralized orchestration (one Orchestrator schedules others) for control; decentralized (free agent chat) is flexible but prone to runaway. Spring AI Alibaba provides SequentialAgent, ParallelAgent, RoutingAgent primitives—essentially directed graph + state machine .

Each Agent owns independent System Prompt, tool set, memory space , with separate sessionId / ChatMemory to prevent context leakage—e.g., Agent A's retrieved customer info leaking into Agent B's context is a nightmare to debug.

Communicate via structured messages (carrying taskId / traceId / idempotency key), state in shared storage (blackboard pattern), not by passing "hearsay" through chat history. Aggregation layer passes conclusions only, not raw transcripts.

Cycle detection + global timeout to avoid A-waits-B, B-waits-A deadlock.

Java's native advantage: Java 21 virtual threads . Run multiple agents concurrently with Executors.newVirtualThreadPerTaskExecutor() —lightweight, natural context isolation, far less hassle than Python's asyncio.

6. MCP Protocol: The "USB-C" of Tool Integration

What It Is

MCP (Model Context Protocol) is Anthropic's open protocol based on JSON-RPC 2.0 , standardizing how "tools / data / prompts" are provided. Previously each tool needed custom integration: M apps × N tools = M×N explosion. With MCP it becomes M+N— Server implements once, plugs in everywhere , fully decoupling tools from Agents. Analogy: MCP does for tools what JDBC did for database drivers.

Three core concept groups:

Three primitives: Tools (model-callable actions), Resources (readable data), Prompts (server-side prompt templates).

Transport: local process uses stdio; cross-service uses Streamable HTTP / SSE (with auth & observability).

Lifecycle: initialize handshake → tools/list discovery → tools/call execution, supports dynamic tool list changes.

Java integration via Spring AI official MCP starter, config-only:

spring:
  ai:
    mcp:
      client:
        enabled: true
        stdio:
          connections:
            weather:
              command: java -jar mcp-weather-server.jar

After wiring, MCP Server's tools automatically become ToolCallback beans injected into ChatClient , turning Agent capabilities from "hardcoded" to "plugin hot-swap". Client usage sketch:

// MCP client: discover → validate → invoke
McpSession s = McpClient.connect("stdio", "npx @demo/mcp-server");
s.initialize(ClientInfo.of("my-agent", "1.0"));

List<Tool> tools = s.listTools();                     // 1. dynamic discovery, no hardcoding
JsonNode args = JsonUtils.parse("{\"path\":\"/app/pom.xml\"}");
schemaValidator.validate(tool.inputSchema(), args);     // 2. validate against server-provided schema

JsonNode result = s.callTool("read_file", args);       // 3. execute
// 4. Critical safety: treat result as "untrusted data", sanitize + truncate + isolate injection
String safe = sanitizer.sanitize(result.toString(), 8000);

Two Engineering Realities

First, MCP isn't a silver bullet; tool description explosion remains. Dozens of MCP tools stuffed into context → token cost spikes, model mis-selects (empirical: >30 tools accuracy drops sharply). Our fix: two-level routing —lightweight "tool retriever" semantically recalls top-K relevant tools for the task, only those schemas injected into main loop. MCP handles "standardized access"; routing handles "signal-to-noise".

Second, biggest risk isn't the protocol—it's indirect Prompt Injection. Third-party Server responses can be interpreted as instructions by the model. Must enforce: data/instruction separation markers + tool whitelist & permission tiers + full-call audit + human confirmation for high-risk ops ; remote Servers add network isolation, heartbeat reconnect, timeout fallback (degrade to local @Tool).

7. Workflow vs Agent: The Architecture Soul-Search

Interviewers love this; production teams often choose wrong. Comparison:

Who defines flow: Workflow = human hardcodes nodes & transitions (DAG/state machine); Agent = model dynamically decides next step

Flexibility: Workflow = low, fixed paths; Agent = high, adapts on the fly

Determinism / Control: Workflow = high, predictable, testable, auditable; Agent = low, non-deterministic behavior

Cost / Latency: Workflow = low & predictable; Agent = high, grows linearly with steps

Fit Scenarios: Workflow = approvals, reports, ETL, fixed Q&A Agent = research, creation, troubleshooting, deep analysis

Failure Diagnosis: Workflow = inspect node; Agent = need full trace

Decision flowchart: (diagram omitted)

Databricks quote I agree with: "Use workflows wherever possible; Agent is the last resort." Agent's cost isn't "maybe slower"; it's errors accumulate while output still looks plausible, trajectories non-reproducible, cost/latency unbounded upfront, attack surface expands with tool set .

Real-world production answer is almost always hybrid: outer workflow guarantees SLA, retry, audit, canary; only at nodes requiring genuine judgment embed a controlled Agent loop, wrapped with tool whitelist, round limit, human approval—three hard constraints.

8. Pitfall Cheat Sheet: Pain Points & Fixes

Condensed from project battle scars, usable for interviews and implementation:

ReAct infinite loop / non-convergence : Repeatedly calls same tool, midnight token bill explosion → MAX_STEPS hard cap + token budget circuit breaker + action fingerprint deduplication + "no progress → degrade to human"

Tool hallucination : Invents tool names/params/enums, JSON parse errors → Schema single source of truth + pre-execution validation + structured error feedback + few-shot examples + tool top-K retrieval

Context explosion : Tool returns huge JSON, window blows in few turns → Sliding window + summarization compression + tool result trimming/pagination + reference-style return + token-budget eviction

Side-effects & idempotency : Retries cause duplicate orders / duplicate DB writes → Write tools enforce idempotency key (traceId derived) + dry-run preview + human confirmation for high-risk + transactional compensation

Error cascade : One upstream mistake poisons all downstream → Per-step "validation gate" (rules first) + fail-fast replan + critical intermediate artifacts persisted for rollback

Memory pollution : Wrong conclusion stored long-term, keeps resurfacing → Memory tagged with source/time/confidence, user corrections prioritized, periodic conflict detection & expiry

Short-term memory fragmentation : Single tool call exceeds window, context wiped → Four-layer memory + truncate from UserMessage boundary + externalize ChatMemory repository

Reflection theater : Review only says "looks good", gets worse each iteration → Reflection must hook external verifiers (DB re-query / rules / unit tests), forbid LLM self-eval loop, cap at 1–2 rounds

Multi-agent runaway : Agents blame each other, state inconsistency, circular deps → Centralized Orchestrator + blackboard + structured messages + independent sessionId + cycle detection

MCP security : Third-party Server returns inject instructions, privilege escalation → Instruction/data separation + tool whitelist + least-privilege creds + audit trail + egress isolation

Observability gap : Only know "answer wrong", not which step failed → Full-chain trace (every prompt/tool/latency/token persisted) + replay rerun + traceId end-to-end

Evaluation difficulty : Prompt tweak → unknown if better, trajectories non-reproducible → Offline golden set + trajectory-level assertions (correct tool?) + LLM-as-Judge + canary A/B

Cost & latency : Multi-turn serial, P99 tens of seconds → Model tiered routing (small model routes, large model decides) + sub-task parallelism + ReWOO fewer round-trips + result caching

Architectural trick worth highlighting: turn "loop control" into an interceptor chain (rate limiting, audit, sanitization, retry, circuit breaker). Business Agent only writes prompts and tools; control plane governed centrally. Governance capabilities not scattered across every Agent—future maintenance will thank you.

9. Rapid-Fire Interview Answers

Nearly guaranteed questions in interviews/tech reviews, answers ready to recite:

Q1: ReAct vs plain multi-turn chat?

Multi-turn chat is just context continuation; ReAct has explicit "think-act-observe" loop, model actively calls tools and adjusts decisions based on results, with clear termination and fallback mechanisms.

Q2: ReAct vs Plan-and-Execute selection?

Short tasks, few steps, strong environment feedback → ReAct. Many steps, strong dependencies, need audit & parallelism → Plan-and-Execute. Practice often mixes: coarse plan + ReAct inside sub-tasks, with mid-flight replanning support.

Q3: Why do Agents hallucinate? Engineering mitigations?

Model only generates; facts come from tools & memory. Mitigate by: forcing critical info through tool retrieval, memory with provenance, post-generation reflection verification, core conclusions guarded by code.

Q4: When would you NOT use an Agent?

Fixed process, clear rules, high stability requirements → workflow / rule engine is cheaper. Agent only placed at genuinely uncertain open nodes.

Q5: What problem does MCP solve? stdio vs HTTP?

Turns "tool integration" from per-Agent custom code into protocol-based plug-and-play. Local process → stdio; cross-service → Streamable HTTP (needs auth & observability).

Q6: Multi-agent state sharing?

Shared StateStore / blackboard (Redis/DB) + async message bus, messages carry taskId / traceId / idempotency key , not relying on chat history for telephone-game passing.

Q7: How to evaluate Agents?

Don't judge "answer looks right"; judge trajectory : tool selection accuracy, parameter accuracy, step count, success rate, cost, out-of-bounds rate.

Q8: Java vs Python for Agents—weaknesses & strengths?

Python has richer framework ecosystem (LangChain etc.); Java wins at integrating with existing business systems, permissions, transactions, observability stack. Using Spring AI / LangChain4j, treat Agent as a governable component inside the business system , not an isolated script—that's the differentiator.

Closing Thoughts

The engineering essence of Agents is not "make the model smarter" but wrap a deterministic shell around uncertainty :

ReAct puts insurance on the loop (circuit breaker, deduplication, budget)

Tool routing puts insurance on context (top-K retrieval, strict validation)

Memory layering puts insurance on state (window, summarization, explicit write)

Reflection budget puts insurance on cost (external verification, attempt cap)

Workflow vs Agent choice puts insurance on authority (if you can draw a DAG, don't delegate)

Four sentences sum it up: Keep it from drifting; detect drift fast; recover when detected; replay for post-mortem. Frameworks can wire the loop and tool calls, but guardrails, boundaries, and observability—you must write them yourself.

Pragmatic rollout advice: don't chase "fully autonomous Agent" day one. Start with workflow, embed a tiny Agent at the most uncertain node, add circuit breakers and tracing, stabilize, then gradually expand autonomy.

About this article

For questions about attribution, corrections or content rights, please contactadmin@besthub.devand we will review it promptly.

JavaMemory ManagementAI agentsMCPReActSpring AIMulti-AgentTool Calling

Discussion 0

Questions, practical examples and thoughtful responses.

Open full discussion