Published

Enterprise AI Agent Architecture: From ReAct Loops to Production Operations

How an enterprise AI agent is built (model, tools, memory, planning) and the rules that keep it safe: tool policies, approval gates, evals, cost caps.

Written by
Ali ÖzdurmuşFounder, Veni AI
Updated
Reading time
6 min read

An AI agent is a system that can decide what to do next, call tools, look at the result and keep going until a task is done. A chatbot answers; an agent acts. That difference is exactly why agents are useful inside a company, and why they need more engineering discipline than a chat window.

This guide covers both halves: how an agent is built, and how teams run agents safely once they touch real systems such as an ERP, a CRM or a shared mailbox.

Chatbot vs. Agent

Chatbot:
User: "Is invoice 2024-118 paid?"
Bot:  "I don't have access to that information."

Agent:
User: "Is invoice 2024-118 paid?"
Agent:
  1. I need the invoice status.
  2. Call erp.get_invoice(id="2024-118")
  3. Read the result: status = "open", due date passed
  4. "Invoice 2024-118 is still open and 12 days overdue."

The Four Building Blocks

1. Model (reasoning)

The LLM interprets the request, decides which step comes next and writes the final answer. Pick the model per task: a smaller, faster model for routing and extraction, a stronger model for multi-step reasoning.

2. Tools (acting)

Tools are how the agent touches the outside world:

  • Database and ERP/CRM queries
  • Internal and third-party APIs
  • Document search (RAG)
  • Sending emails or creating tickets
  • Code execution in a sandbox

3. Memory

  • Short-term: the current conversation and intermediate tool results
  • Long-term: knowledge sources and past decisions, usually stored in a database or vector index

Keep the two apart. Mixing them is a common source of stale or leaked context.

4. Planning

Breaking a goal into steps, deciding the order and knowing when to stop.

The ReAct Pattern

Most agents run a Reason + Act loop:

Thought: What do I need to do?
Action: Which tool should I use?
Action Input: Tool parameters
Observation: Tool result
... (repeat)
Final Answer: Response to the user

A Minimal Agent Loop

Frameworks such as LangGraph or the provider SDKs wrap this loop, but the core is small enough to read in one screen:

python
MAX_STEPS = 8

def run_agent(task: str, tools: dict, llm) -> str:
    messages = [
        {"role": "system", "content": "You are an operations agent. Use tools when you need data."},
        {"role": "user", "content": task},
    ]

    for step in range(MAX_STEPS):
        reply = llm.chat(messages=messages, tools=list(tools.values()))

        if not reply.tool_calls:
            return reply.content  # final answer

        messages.append(reply.as_message())
        for call in reply.tool_calls:
            result = execute_tool(tools, call.name, call.arguments)
            messages.append({"role": "tool", "tool_call_id": call.id, "content": str(result)})

    return "Stopped: step limit reached. A human should review this task."

Two details matter in production: a hard step limit, and a clear message when the agent gives up instead of looping silently.

Defining a Tool

python
get_invoice_tool = {
    "name": "get_invoice",
    "description": (
        "Returns status, amount and due date for one invoice from the ERP. "
        "Use only when the user gives an invoice number."
    ),
    "parameters": {
        "type": "object",
        "properties": {
            "invoice_id": {"type": "string", "description": "Invoice number, e.g. 2024-118"}
        },
        "required": ["invoice_id"],
    },
}

A precise description is the cheapest accuracy improvement you can make: the model chooses tools by reading these texts.

Multi-Agent Systems

When one agent's instructions grow too long, split the work.

Supervisor Pattern

┌─────────────────────────────────────────────────────┐
│                    Supervisor                        │
└───────────────────────┬─────────────────────────────┘
                        │
        ┌───────────────┼───────────────┐
        │               │               │
┌───────▼───────┐ ┌─────▼─────┐ ┌──────▼──────┐
│   Research    │ │  Analysis │ │   Drafting  │
│    Agent      │ │   Agent   │ │    Agent    │
└───────────────┘ └───────────┘ └─────────────┘
python
def supervisor(state):
    task = state["task"]
    if task.type == "lookup":
        return "research_agent"
    if task.type == "report":
        return "drafting_agent"
    return "human_review"

Route by risk as well as by topic: a low-risk lookup can run end to end, while anything that changes a record goes through an approval step.

Plan-and-Execute

For longer tasks, let one call write a plan and separate calls execute each step:

Goal: "Prepare the monthly supplier performance summary"

Plan:
1. Pull delivery records from the ERP
2. Calculate on-time rate per supplier
3. Collect open quality complaints
4. Draft the summary and flag outliers for review

Operating Agents in Production

Getting an agent to work in a demo is the easy part. The question that matters is whether it is safe, measurable and affordable at scale. The patterns below keep showing up in well-run deployments.

Tool Policy Layer

  • Keep an explicit inventory of tools and which agents may call them.
  • Read-only tools by default; write actions need a separate permission.
  • Version the policy and review changes like code.

Human Approval Gates

  • Payments, record deletions, external emails and anything regulated go through a human sign-off.
  • Log who approved what, and when. This is your audit trail.

Memory Design

  • Separate short-term context from long-term knowledge sources.
  • Apply the same access rules to memory that you apply to the source systems.

Error Handling and Retries

python
import time

def call_with_retry(fn, *args, max_retries=3, **kwargs):
    for attempt in range(max_retries):
        try:
            return fn(*args, **kwargs)
        except RateLimitError:
            time.sleep(2 ** attempt)
        except ContextTooLongError:
            kwargs["messages"] = summarize_history(kwargs["messages"])
    raise RuntimeError("Agent step failed after retries")

Cost Limits

python
MAX_COST_PER_TASK = 0.50  # set per workflow, in your billing currency

def check_budget(run):
    cost = run.input_tokens * PRICE_IN + run.output_tokens * PRICE_OUT
    if cost > MAX_COST_PER_TASK:
        raise BudgetExceededError(f"Task cost {cost:.2f} exceeded the limit")

Load PRICE_IN and PRICE_OUT from your provider's current price list rather than hard-coding them.

Measuring Agents

Four metric groups give a usable operational view:

  • Success rate: share of tasks completed correctly, checked against a labeled test set
  • Cost: model and tool spend per task
  • Latency: end-to-end time, including queue delays and approval waits
  • Error classes: wrong tool choice, missing context, data mismatch, permission violation

Track them on one dashboard. A drop in success rate together with a rise in "missing context" errors usually points to retrieval, not to the model.

A Practical Roadmap

  1. Start with one low-risk, high-volume workflow (for example, answering order-status questions from ERP data).
  2. Write the tool policy and approval rules before the first line of agent code.
  3. Build an evaluation set from real, anonymized cases and run it on every release.
  4. Add logging for every tool call: input, output, duration, cost.
  5. Expand to write actions only after the read-only version is stable.

Summary

An agent is a loop around a model, a set of tools and a memory. What makes it fit for a company is everything around that loop: tool policies, approval gates, evaluation and cost control. Start small, measure everything and widen permissions step by step.

At Veni AI we build custom AI agents that work inside a company's own systems, with human review where it matters. If you have a workflow in mind, see what we build or talk to our team.

Keep reading

Have a process that should run on AI?

Describe one process as it runs today, and we'll show you which repetitive steps an AI application or agent could handle.