Skip to content

Checking your reading list…

Retry verification

Stay curious. Build better.

Appearance

Choose how BestHub looks on this device.

Changes apply immediately.

Search articles

Open Discover with these filters

Suggested searches

Agent Production Playbook: Architecture, Tooling, Memory & Evaluation

Agent Production Playbook: Architecture, Tooling, Memory & Evaluation

This comprehensive guide covers agent architecture selection (ReAct vs Plan-and-Execute), tool calling design patterns, memory and state management, performance optimization techniques, evaluation metrics, and Agent-RAG integration strategies for reliable production deployment.

1. Agent Core Architecture

1.1 ReAct vs Plan-and-Execute: Differences & Selection

ReAct (Reason + Act) operates in a think-act-observe loop: the model thinks one step, selects a tool, executes, observes the result, then thinks again. Its strengths are flexibility for open-ended, uncertain, multi-branch tasks; no need to pre-define a full plan; and dynamic adaptation to unexpected results. Weaknesses include unbounded step counts risking infinite loops, higher token usage and latency per step, and drift over long chains. Typical scenarios: knowledge-base research, troubleshooting, complex customer consultations, unknown problem diagnosis.

Plan-and-Execute separates planning from execution: first generate a complete ordered task plan, then execute steps serially with the model only invoking tools per step. Variants support replanning on failure. Advantages: controllable, observable, auditable plans; stable steps suit standardized processes; easy to add approvals, timeouts, circuit breakers; more predictable cost. Drawbacks: a flawed initial plan derails everything; poor adaptation to dynamic changes; plan granularity is hard to balance. Typical scenarios: ticket processing, data report generation, fixed approval flows, standardized business operations, ERP/MES document handling.

Selection heuristic:

Uncertain path, incomplete information, need to explore and decide dynamically → ReAct.

Relatively fixed business process, standard steps, strong governance, human plan review → Plan-and-Execute (with optional replanning).

Most common industrial hybrid: top-level Plan, with ReAct inside individual steps.

1.2 Roles of Model, Tool, and State in an Agent

Model (LLM): Decision layer. Understands goals, reasons, selects next action, parses tool results, generates final answer. It holds no real business capability—only decides.

Tool: Capability layer. Encapsulates external capabilities: database queries, APIs, file I/O, computation, RAG retrieval, messaging. The model cannot directly operate external systems; tools are deterministic execution units.

State: Context carrier. Stores current task progress, acquired information, tool results, completed steps, error flags, approval flags. The model itself does not persist state; the framework manages and passes state to the model.

In short: the model decides what to do, the tool does it, the state records how far we've gotten.

1.3 Why Complex Tasks Need Workflow Constraints Beyond Prompts

Prompts are soft guidance but have fundamental limits:

LLM randomness causes drift over long chains.

Prompts cannot enforce execution order, retry policies, permissions, timeouts, or approvals.

Complex tasks require boundaries, idempotency, transaction guarantees—models lack native transaction ability.

Token limits prevent stuffing all business rules into the prompt.

Signals that you must add workflow constraints:

High-risk operations (data deletion, order placement, refunds, config changes).

Steps with strong sequential dependencies, branching logic, loop bounds.

Need for audit logs, human intervention, timeout circuit breaking.

Requirement for stable, reproducible results—no random behavior.

Task chain longer than 3–5 tool calls.

Prompts are “soft guidance”; workflows are “hard guardrails.” Production-grade agents always combine Prompt + process constraints .

1.4 Single Agent vs Multi-Agent: How to Choose?

Single Agent: One entity plans, calls tools, completes all subtasks. Suits single-goal tasks with tightly coupled subtasks, no role separation needed, simple queries, lightweight data lookups. Benefits: simple architecture, no communication overhead, easy debugging.

Multi-Agent: Role separation (Planner, Retriever, Executor, Verifier, Reviewer) communicating via messages. Suits tasks naturally decomposable into independent responsibilities, requiring responsibility isolation, different models/permissions per subtask, independent verification to prevent hallucination.

More agents ≠ better: introduces communication costs, message loss, coordination ambiguity; blurred boundaries cause blame-shifting and circular contention; debugging difficulty grows exponentially.

Selection principle: If a single agent can handle it, don't introduce multi-agent. Only split when responsibility isolation, permission isolation, or verification isolation bring clear benefits.

1.5 Preventing Tool Call Loops and Deadlocks

Root cause: model repeatedly receives similar results and keeps choosing the same tool. Four-layer defense:

Hard step limit: global maximum tool-call rounds; terminate when reached.

History action deduplication: record (tool name + parameter hash); block repeated actions within a short window.

Result convergence check: compare current tool output with previous round's information delta; stop if no new information.

Model-side prompt constraint: add “stop when information is insufficient; do not repeatedly call the same tool.”

Fallback: throw “unable to complete” and escalate to human.

1.6 Human Confirmation for High-Risk Operations

Layered interception, recommended approach:

Tag high-risk tools at registration (deletion, fund changes, config pushes).

High-risk actions not executed directly; agent generates a pending approval ticket and pauses.

Present to human: goal, parameters, impact scope, risk explanation.

Human chooses: approve execution / modify parameters then execute / reject and terminate.

All confirmations leave audit logs. Advanced: rule-based whitelist for low-risk same-type operations to auto-approve.

2. Tool Calling in Production

2.1 Function Calling vs Model-Generated JSON

Function Calling (native model tool calling)

Pros: native format alignment, high parsing success; built-in validation; mainstream models have specialized optimization; less extraneous text.

Cons: depends on model capability; schema changes require model version adaptation; some open-source small models have weak function calling.

Best for: production main paths, multi-tool selection, complex parameters, stability priority.

Model-Generated JSON (prompt-constrained JSON output)

Pros: works with any LLM, no native function calling needed; high control flexibility.

Cons: more prone to format errors, comments, truncation, extra text; requires extra JSON cleaning + retry; heavy prompt burden.

Best for: open-source weak models, custom protocols, simple structured output, rapid POC.

Production priority: Function Calling; JSON output only as fallback.

2.2 Tool Schema Design & Parameter Ambiguity Issues

Schema design guidelines:

Parameters explicit, strongly typed, with detailed descriptions.

Enumerate all allowed values—avoid “related values.”

Strictly distinguish required vs optional.

Avoid over-generalized huge parameters.

Keep tool granularity moderate—don't pack all operations into one tool.

Ambiguous parameters cause: model hallucinates parameters, passes wrong fields, exceeds ranges; returns unexpected results; hidden bad cases hard to reproduce; even accidental business data corruption.

2.3 Disambiguating Similar Tools

Example similar tools: query_order_by_id / query_order_by_customer. Techniques:

Tool descriptions clearly differentiate applicable conditions—no near-duplicate descriptions.

Semantic tool naming.

System prompt explicitly: first judge which tool matches the query condition.

Add a pre-classifier (small model / rule-based) to route, bypassing model selection.

Validation layer: check if tool input parameters match tool semantics (e.g., ID-based query tool must not receive a customer name).

2.4 Tool Call Failure: Retry, Circuit Breaker, Fallback

Retry: only for transient errors (network blips, 5xx); exponential backoff; limit retry count; business idempotency is a prerequisite! Non-idempotent operations must not auto-retry.

Circuit Breaker: when a tool fails continuously beyond a threshold in a short window, open breaker, reject calls for a period to avoid cascade; alert.

Fallback: on breaker/persistent failure, switch to alternative tool, simplified query, preset response, or human handoff—instead of letting the agent hang.

2.5 Persistent Tool Timeouts: Wait, Switch, or Terminate?

Pre-classify tiers:

Lightweight queries: short timeout + 1 retry; on timeout switch to alternative query method.

Heavy compute / third-party: single timeout, no infinite wait; mark unavailable after timeout.

Core path with no fallback: terminate task, return “dependency service timeout, task cannot complete,” notify human.

Never block indefinitely.

2.6 Preventing Accidental High-Risk Tool Calls

Three-layer defense (all required):

Permission layer: agent identity bound to tool whitelist; high-risk tools excluded by default.

Tag interception layer: framework intercepts tools tagged high-risk, forces human confirmation.

Semantic validation layer: validate input parameter risk scope (e.g., batch delete row count limit), block if exceeded.

Never trust the model to judge risk on its own.

3. Memory and State Management

3.1 What to Store in Agent State? Why Not Full Conversation?

State stores: task ID, goal, executed action list (tool + params + result summary), intermediate conclusions, error flags, approval status, plan steps, retrieved key information.

Why not store raw conversation:

Raw dialogue is verbose—lots of model chatter, repetitive text; high storage cost.

Passing it to the model later explodes token usage.

Much raw content has no value for subsequent decisions.

Privacy and audit: raw dialogue and structured state are separate concerns.

Principle: State is a structured task progress snapshot, not a chat log copy.

3.2 Short-Term vs Long-Term Memory

Short-term (working memory): valid only within current task lifecycle. Holds acquired info, execution history, intermediate results; follows the task, archived/cleaned on completion; usually injected directly into the current prompt context.

Long-term memory: persists across tasks. User preferences, historical business records, knowledge-base summaries, past successful cases; stored in vector DB / database; retrieved on demand at task start, not loaded entirely by default.

3.3 Handling Token Overflow from Long Conversations

Common combined approaches:

Summarization compression: compress earlier history into structured summaries.

Sliding window: keep last N raw interactions, summarize older content.

Structured state replaces raw dialogue: feed only action summaries to the model, not full conversation.

Chunking + external retrieval: offload history to vector store, recall on demand.

Switch to larger-context model, or split into subtasks.

3.4 Why Not Dump All History into a Vector Store?

Vector retrieval is similarity matching , not exact state:

Recall is uncontrolled—easily surfaces irrelevant old dialogue, adding noise.

No temporal or state-transition markers; can't tell which info is stale for the current task.

Historical dialogue contains hallucinations and erroneous intermediate conclusions; storing them pollutes the vector store continuously.

Retrieval adds latency and cost. Vector stores suit verified, curated knowledge , not raw, unvalidated agent dialogue streams.

4. Optimization and Troubleshooting

4.1 Quantifying Task Completion Rate: Tool Success Rate ≠ Agent Effectiveness

Core metrics:

Task completion rate (business ground truth: did we achieve user goal? human-labeled / business outcome judged).

Tool call success rate (tool itself returns success).

Tool effectiveness rate: call succeeded but returned info useless for task (ineffective call).

Step count, latency, token consumption, human takeover rate, refusal rate, hallucination rate.

Tool success rate high ≠ agent works well. Model can successfully call a tool but pick the wrong tool, query wrong scope, or reason incorrectly after retrieval. Tool success is a low-level health metric; task completion rate is the core metric.

4.2 Diagnosing Agent Latency: Model, RAG, or Tool?

Instrument each stage:

LLM inference time (planning, tool selection, result parsing).

RAG retrieval time (vector DB, Elasticsearch).

Each external tool call time.

Framework scheduling, serialization time.

Quick diagnosis:

High LLM step time → model inference bottleneck.

High retrieval step time → RAG bottleneck.

Specific external API spike → tool bottleneck.

High scheduling time → state serialization / message queue blocking.

4.3 Core Token Optimization Techniques

Compress history: summaries replace raw dialogue, control context window.

Trim system prompt: remove redundant verbiage.

Summarize tool results: don't feed entire raw tool payloads to the model.

Reduce ineffective tool calls (action deduplication, convergence checks).

Model routing: lightweight routing/classification with small model, complex reasoning with large model.

Cache repeated retrievals and repeated reasoning results.

Enforce max step limit to prevent runaway ReAct loops.

4.4 Bad Case Root Cause Analysis: Isolate Prompt / Model / Tool / Workflow

Fixed investigation order:

Check tool return value: is the tool's data itself wrong? → tool issue.

Tool returned correctly, but model misunderstood or picked wrong tool → model / prompt issue.

Model judgment fine, but workflow rules intercepted / routed incorrectly → workflow issue.

State loss, missing context → state management issue.

Retain for every case: user input, state snapshot, tool input params, tool output, model output, full trace logs.

4.5 Validating Effectiveness After Version Iteration

Build an evaluation set (fixed real business queries with ground truth answers):

Run baseline vs new version on same case batch.

Compare metrics: task completion rate, hallucination rate, tool call count, tokens, human takeover rate.

Statistical hypothesis testing to confirm improvement isn't random noise.

Gradual rollout with online instrumentation, bucketed A/B testing.

5. Agent + RAG in Production

5.1 Agent-RAG vs Traditional RAG: Core Difference

Traditional RAG: single-turn QA paradigm. User asks → retrieve → pass chunks to model for answer; retrieval is one-shot, no follow-up actions. Suits clear questions not needing multi-round queries.

Agent-RAG: retrieval is a multi-callable tool . Model can:

Analyze question, generate retrieval keywords.

After seeing results, find info insufficient, adjust keywords and retrieve again.

Decide when to retrieve vs when not to.

When retrieval falls short, call other tools (database, API) to supplement.

In one sentence: traditional RAG is “retrieve once then answer”; Agent-RAG is “retrieval as one action among many, dynamically multi-round, collaborating with other tools.”

5.2 When to Use Vector vs Keyword Search

Vector search (semantic): user phrasing differs from document wording, synonyms, fuzzy concepts; fits knowledge bases, unstructured docs. Weakness: lower precision, retrieves semantically similar but irrelevant content.

Keyword search (BM25/ES): explicit proper nouns, IDs, ticket numbers, metric names; requires exact match; structured docs, rule docs; high precision recall.

Production optimum: hybrid retrieval with rerank —two-channel recall then re-rank.

5.3 Improving Retrieval Accuracy Beyond Prompt Tuning

Document chunking optimization: split by semantic blocks, not fixed-length brute force.

Document preprocessing: cleaning, structuring, metadata extraction.

Retrieval query rewriting: agent decomposes, expands, generates multiple retrieval queries from user question.

Multi-route retrieval + reranker.

Add metadata filters (doc type, time, business domain).

Negative sample training for reranker.

Summarize retrieval results before feeding to model to reduce noise.

5.4 Ensuring Traceability and Reducing Hallucination

Retrieval results carry source doc IDs, page/paragraph markers; model answers forced to cite source markers.

Add verification agent: independent model cross-checks conclusions against source material.

Restrict model from fabricating non-existent tool fields or documents.

Prefer structured tool outputs over free-text generation.

Force “information insufficient” output for uncertain info—no hallucination.

Full trace log retention: every conclusion linked to its tool/retrieval call.

About this article

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

Published

AI-assisted summary

Report an issue with this article
Memory ManagementReActFunction CallingTool CallingLLM ApplicationsAgent ArchitectureProduction DeploymentAgent EvaluationPlan-and-ExecuteAgent-RAG

Reader feedback

Was this useful?

Useful0

Discussion 0

Questions, practical examples and thoughtful responses.

Open full discussion