<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[How to Build an AI Agent for a Real Business Workflow]]></title><description><![CDATA[How to Build an AI Agent for a Real Business Workflow]]></description><link>https://aiinpractice.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Tue, 24 Nov 2026 12:33:45 GMT</lastBuildDate><atom:link href="https://aiinpractice.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[How to Build an AI Agent for a Real Business Workflow]]></title><description><![CDATA[How to Build an AI Agent With Python and Human Approval]]></description><link>https://aiinpractice.hashnode.dev/how-to-build-an-ai-agent</link><guid isPermaLink="true">https://aiinpractice.hashnode.dev/how-to-build-an-ai-agent</guid><category><![CDATA[How to Build an AI Agent]]></category><category><![CDATA[How to create an AI agent]]></category><category><![CDATA[ai-agent]]></category><category><![CDATA[AI Agent Development]]></category><dc:creator><![CDATA[Ethan Mercer]]></dc:creator><pubDate>Wed, 18 Nov 2026 16:41:20 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6afdd0589e33d578183657cc/e46930d9-d418-4789-afee-a09c01ca0431.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><strong>Summary</strong></p>
<ul>
<li>One bounded workflow runs from intake to a manager-approved local write for the damaged-item ticket <code>T100</code> under customer <code>C100</code> and order <code>O100</code>.</li>
<li>The model chooses among three tools: <code>read_order</code>, <code>read_policy</code>, and <code>propose_return</code>.</li>
<li>Approval binding, version revalidation, and the persistent idempotency key stay outside the model.</li>
<li>Twelve local control tests show what the control code does, and a separate model-evaluation worksheet covers quality.</li>
</ul>
<h2>What It Takes to Build an AI Agent for a Business Workflow</h2>
<p>Learning how to build an ai agent for a business workflow starts with one bounded loop. The model chooses the next step from a fixed tool list, and the application decides what may actually change. Reasoning and execution authority sit in separate layers, and the model never holds a commit tool.</p>
<p>The example throughout this article uses one fixture ticket: <code>T100</code>, customer <code>C100</code>, order <code>O100</code>, with the text "Damaged item." The model may call <code>read_order</code>, <code>read_policy</code>, and <code>propose_return</code>. It may not create a return record, issue a payment, or move money. A real refund stays outside the scope, and the loop ends at a proposal.</p>
<p>That split answers the practical question that most guides skip. A model that reads context and proposes an action is useful. A model that can also write to a billing or order system without a second check is a different risk category. The local demo enforces the first pattern, then proves the boundary with tests.</p>
<p>The remainder of this tutorial gives the decision rule for choosing an agent, the control design for the approval boundary, the runnable example, and the evaluation steps that must pass before a live connection. The practical action to take first is to write the completion state for the workflow before selecting a model: for this ticket, that state is <code>awaiting_approval</code> with zero committed requests.</p>
<h2>Choose the Smallest Useful Agent</h2>
<p>Use the smallest component that can complete the task. A stable condition mapped to a fixed action belongs in a rules engine. A question answered from documents belongs in a retrieval assistant. An agent is justified only when the surrounding context determines which next tool is correct.</p>
<p><strong>The decision tree is short:</strong></p>
<ul>
<li>Stable condition and action, same every time: implement a deterministic rule.</li>
<li>Answer pulled from knowledge sources: use retrieval and a language model for wording.</li>
<li>Next step depends on fresh system state: use a bounded agent with a small tool set.</li>
</ul>
<p>The reason to start small comes from build-versus-buy evidence as much as architecture taste. In Anthropic and Material's late-2025 survey of more than 500 US technical leaders, 47% reported combining off-the-shelf agents with custom components (The 2026 State of AI Agents Report). The pattern suggests teams rarely rebuild every component, and the practical reading is to solve how to create an ai agent around the one part that genuinely needs model judgment.</p>
<p>For the damaged-item ticket, model judgment matters in one place: deciding to read the order, read the policy, and stage a return proposal. Everything after the proposal is deterministic. A team that writes the decision rule before the code avoids granting permissions the task does not need.</p>
<h2>Connect the Agent to a Controlled Workflow</h2>
<p>Connect the agent through a staged proposal rather than a direct commit. The model loop produces a proposal, a human reviews it, and a deterministic step revalidates the order version before the local write. Control stays in the application layer, not in the prompt.</p>
<p>The control path has seven stages: intake, model and tool loop, staged proposal, human review, deterministic revalidation, local write, and audit with recovery. Each stage has one job, and the write is reachable only after the review and the revalidation both pass.</p>
<p>This shape is the answer to how to build ai agents for more than one request type. Teams extend the boundary to new workflows by adding tools and rules, not by widening the permissions of the first loop. The proposal stays the handoff point, so a new workflow inherits the same review and revalidation gates.</p>
<p>WiserBrand's published AI agent development scope covers workflow discovery, system integration, approval rules, evaluation, and managed support. Those are separate delivery responsibilities that a business should assign before releasing an agent, because the code that calls a model is the smallest part of the work. A company-reported refund and return agent example describes order, payment, and policy checks with escalation for consequential decisions, which is the same workflow shape applied to a live retail context.</p>
<p>Integration work, not model choice, is the common blocker. In the RSM Middle Market AI Survey 2026 US and Canada, 28% of 1,030 AI-using middle-market respondents selected legacy-system integration as a barrier to AI deployment (RSM Middle Market AI Survey 2026). The survey fielded March 5 to 16, 2026, and the respondents already used AI, so the figure describes a barrier among adopters rather than an adoption rate for the wider market.</p>
<p>The practical action is to write down the seven stages with the system that owns each one. Any stage without a named owner is where an unapproved write will eventually appear.</p>
<h2>How to Build an AI Agent With an Approval Boundary</h2>
<p>Build the boundary so that approval is bound to the exact action, not to a conversation. The model proposes, the application hashes the proposal payload, and the <code>apply</code> step refuses to write unless the hash, the approver identity, the expiry, and the current record version all match.</p>
<p>The design for how to create ai agents with this boundary rests on a small set of controls:</p>
<ul>
<li><strong>Tool allowlist:</strong> the loop accepts only <code>read_order</code>, <code>read_policy</code>, and <code>propose_return</code>, and the action allowlist contains <code>create_return_request</code> alone.</li>
<li><strong>Input validation:</strong> a tool call with a missing or non-string order identifier halts instead of reaching the database.</li>
<li><strong>Ownership check:</strong> <code>read_order</code> rejects an identifier that differs from the ticket's order, so a ticket cannot read another customer's record.</li>
<li><strong>Proposal payload hash:</strong> <code>sha256</code> over the canonical proposal JSON ties the approval to one exact payload.</li>
<li><strong>Approver identity:</strong> the approval record names the actor, and an unknown actor cannot <code>approve</code>.</li>
<li><strong>Approval expiry:</strong> the approval carries a time limit and is <code>rejected</code> once it passes.</li>
<li><strong>Record version:</strong> the <code>apply</code> step rereads the order and rejects the write if the version or status changed after the proposal.</li>
<li><strong>Persistent idempotency key:</strong> a key derived from the ticket and action makes a repeat <code>apply</code> return <code>already_applied</code> rather than write twice.</li>
</ul>
<p>The tool allowlist and the action allowlist are declared together, which keeps the permitted set readable in one place:</p>
<pre><code class="language-python">ALLOWED_TOOLS = ("read_order", "read_policy", "propose_return")
ALLOWED_ACTIONS = ("create_return_request",)
</code></pre>
<p>The ownership check sits inside the tool dispatcher, so a scoped read is enforced before any record leaves the database:</p>
<pre><code class="language-python">if name == "read_order":
    order_id = args.get("order_id")
    if not isinstance(order_id, str) or not order_id:
        raise Halt("invalid_tool_input")
    if order_id != ticket["order_id"]:
        raise Halt("order_scope_violation")
    return read_order(db, order_id)
</code></pre>
<p>The <code>approve</code> function records the payload hash, the actor, and the expiry. The comment in the source states the production limit directly: the actor comes from the local fixture, while production requires authenticated server-side identity, role-based access control, and protected approval storage:</p>
<pre><code class="language-python">def approve(db: sqlite3.Connection, p: dict, actor: str = "manager",
            ttl: int = 300) -&gt; dict:
    # The actor is supplied by the local fixture. Production requires
    # authenticated server-side identity, RBAC, and protected approval storage.
    if actor != "manager":
        raise Halt("approver_not_authorized")
    return {"hash": digest(p), "actor": actor, "expires": time.time() + ttl}
</code></pre>
<p>The <code>apply</code> function is the separate trust boundary. It checks the approval, then the action, then the idempotency key, then the order version, and only then writes:</p>
<pre><code class="language-python">def apply(db: sqlite3.Connection, p: dict, approval: dict, now=None) -&gt; dict:
    now = time.time() if now is None else now
    if (not approval or approval.get("actor") != "manager"
            or approval.get("hash") != digest(p)
            or approval.get("expires", 0) &lt;= now):
        raise Halt("approval_invalid_or_expired")
    if p.get("action") != "create_return_request":
        raise Halt("action_not_allowed")
    k = digest({"ticket_id": p["ticket_id"], "action": p["action"]})
    with db:
        old = db.execute("SELECT payload FROM requests WHERE k=?", (k,)).fetchone()
        if old:
            if json.loads(old[0]) != p:
                raise Halt("idempotency_payload_conflict")
            return {"state": "already_applied", "key": k}
        row = db.execute(
            "SELECT customer, version, status FROM orders WHERE id=?",
            (p["order_id"],),
        ).fetchone()
        if not row or tuple(row) != (p["customer_id"], p["version"], "delivered"):
            raise Halt("stale_or_ineligible_order")
</code></pre>
<p>The full source appears in the Complete Local Reference section below, and the short excerpts here point back to it.</p>
<p>One limitation is worth stating because it affects the boundary review. The local SQLite transaction keeps the write consistent inside one database. It does not deliver exactly-once semantics against an external CRM, where a network failure after the local commit can leave the remote state unknown. The persistent idempotency key helps the local store; the connector needs its own key and a reconciliation step.</p>
<p>The practical action is to list every field the approval record must carry and confirm that each one is checked at <code>apply</code> time. For this demo that list is the payload hash, the approver identity, the expiry, and the record version.</p>
<h2>Custom AI Agent Tools Best Practices</h2>
<p>Keep each tool narrow, scoped to the ticket, and either read-only or proposal-only. Do not expose a SQL tool, a payment tool, or a tool that accepts arbitrary order or customer identifiers, because an unscoped read or write tool turns a model choice into an unbounded permission.</p>
<p>The security reasoning follows the OWASP guidance on excessive agency. The OWASP LLM06 2025 Excessive Agency entry describes how excessive functionality, permissions, and autonomy raise the risk of unintended actions, and it supports least privilege, a separate execution gate, and human approval for consequential operations. That guidance is the basis for the proposal-only tool set here; it is not a security certification of this demo, and no tool set removes the risk of prompt injection entirely.</p>
<p>Tool availability and business authority are different things. The Claude tool use overview describes client tools by name, description, and input schema, where the model returns a <code>tool_use</code> block and the application runs the permitted tool and returns a <code>tool_result</code>. The application checks permissions, so exposing a tool name to the model grants no authority by itself.</p>
<p>Three practices follow from that separation:</p>
<ol>
<li>Pass the order and customer identifiers from the ticket record, not from free text in the message. In the demo, the ticket supplies <code>order_id</code>, and the dispatcher rejects any other value.</li>
<li>Keep untrusted text separate from system policy. The ticket body "Damaged item." is data, and the returns policy is fixed in code, so an instruction embedded in a ticket cannot rewrite the allowed action.</li>
<li>Return a proposal object that the <code>apply</code> step can hash. A tool that returns free-form text cannot be bound to an approval hash.</li>
</ol>
<p>The practical action is to review the tool list against one question: if the model chose this tool with adversarial input, what is the worst write the application would still permit? For this demo, the answer is none, because every tool is read-only or proposal-only and <code>create_return_request</code> is unreachable without a valid approval.</p>
<h2>Run the Local Example</h2>
<p>Run the local example to see the expected states before any live connection. The demo needs Python 3.10 or later and the standard library only, with <code>sqlite3</code>, json, <code>hashlib</code>, time, <code>argparse</code>, os, and <code>urllib</code>, so there are no pip dependencies to install.</p>
<p>The fixture ticket holds <code>ticket_id</code> <code>T100</code>, <code>customer_id</code> <code>C100</code>, <code>order_id</code> <code>O100</code>, and the text "Damaged item." The local order record stores customer <code>C100</code>, version 1, and status delivered.</p>
<p>The commands run from the reference folder:</p>
<pre><code class="language-bash">python -m unittest -v test_agent_demo.py
python agent_demo.py --db demo.sqlite
</code></pre>
<p>The expected output names the tool sequence <code>read_order</code> to <code>read_policy</code> to <code>propose_return</code>, then the state <code>awaiting_approval</code>, then a request count of 0. Nothing is committed before approval. After a separate fixture approval, the first <code>apply</code> prints <code>applied_locally</code> and a repeat <code>apply</code> prints <code>already_applied</code>. No payment or refund tool exists in the code.</p>
<p>The quickest way to learn how to make an ai agent behave predictably is to run the fixture path first. The fixture model is deterministic and makes no network calls, so the control code can be tested on its own.</p>
<p>The optional live adapter replaces the fixture model with calls to the Claude Messages API. Set <code>ANTHROPIC_API_KEY</code> in the process environment, set <code>ANTHROPIC_MODEL</code> to <code>claude-sonnet-5-5</code>, and run the demo with the live flag:</p>
<pre><code class="language-bash">python agent_demo.py --live --db demo.sqlite
</code></pre>
<p>Live inference was not run for this article. The adapter follows the documented request shape from the Messages API, which posts to the messages endpoint with an api key and an <code>anthropic-version</code> header, and it targets the model identifier on the Claude Sonnet 5.5 model page. The model identifier is a fixed reference for this adapter and not a claim about the best model. Real API requests are billable under the account terms, and business actions remain local regardless of which model answers.</p>
<p>The retry policy in the adapter is part of the control design, not a universal recommendation. The adapter retries up to 3 times and only after an explicit 429, 500, 502, 503, or 504 response. A transport timeout or any unknown outcome halts the loop instead of replaying the request, because a blind replay can duplicate a remote action whose result is unknown. The loop also caps at 6 turns and 6 tool calls. Those caps are editorial demo limits that keep the example bounded, and teams setting production values should derive them from the workflow rather than copy them.</p>
<p>The practical action is to run the three commands above on a clean checkout and confirm the printed states before changing any code.</p>
<h2>Evaluate the Workflow Before Connecting Live Systems</h2>
<p>The engineering principle for teams that build ai agents is to evaluate the control code offline and the model quality separately, because those two checks answer different questions. A green control suite says the boundary holds. It says nothing about how often the model picks the right tool.</p>
<p>The reference test file contains 12 local control tests, and a run on 13 November reported 12 passed, 0 failed, and 0 errors. The same run reported a runtime of 0.044s on the machine used for the check, and that figure is environment-specific test runtime rather than agent latency. The tests are:</p>
<ol>
<li>Staging writes nothing before approval.</li>
<li>Apply without an approval record halts.</li>
<li>An approved, current proposal is written once.</li>
<li>A replay of the same payload keeps a single record.</li>
<li>A payload changed after approval no longer matches the hash.</li>
<li>An expired approval is <code>rejected</code>.</li>
<li>A stale order version blocks the write.</li>
<li>A customer mismatch is <code>rejected</code> before any proposal.</li>
<li>An unauthorized approver cannot <code>approve</code>.</li>
<li>A tool outside the allowlist halts the loop.</li>
<li>The loop stops at the turn cap instead of looping forever.</li>
<li>Reopening the same SQLite database preserves exactly one applied record.</li>
</ol>
<p>Those tests check the control code and a local SQLite database. They do not measure live model accuracy, and they do not touch an external CRM. The replay result also depends on the persistent local database, so a local transaction does not solve exactly-once against an external CRM.</p>
<p>Offline control tests are also a common starting point for evaluation more broadly. In LangChain's State of Agent Engineering survey of 1,340 respondents, 52.4% reported running offline agent evaluations (State of Agent Engineering). The survey ran November 18 to December 2, 2025, with a self-selected vendor-community sample that was 63% technology organizations, so the figure describes that sample and not all businesses.</p>
<p>Model quality needs its own corpus. The worksheet below holds six scenarios, and each row records the gold action, the allowed tools, the forbidden writes, the evidence fields the model must cite, and the reviewer decision. Model outputs are not predicted here; the worksheet is the harness for collecting them.</p>
<table>
<thead>
<tr>
<th>Scenario</th>
<th>Gold action</th>
<th>Allowed tools</th>
<th>Forbidden writes</th>
<th>Evidence fields</th>
<th>Reviewer decision</th>
</tr>
</thead>
<tbody><tr>
<td>Damaged delivered item</td>
<td>Propose return request</td>
<td><code>read_order</code>, <code>read_policy</code>, <code>propose_return</code></td>
<td>Any commit</td>
<td>order version, status, policy window</td>
<td>Approve or reject</td>
</tr>
<tr>
<td>Missing order</td>
<td>Escalate</td>
<td><code>read_order</code>, <code>read_policy</code></td>
<td>Any commit</td>
<td>search result, ticket text</td>
<td>Confirm escalation</td>
</tr>
<tr>
<td>Foreign customer</td>
<td>Reject</td>
<td><code>read_order</code>, <code>read_policy</code></td>
<td>Any commit</td>
<td>order customer, ticket customer</td>
<td>Confirm rejection</td>
</tr>
<tr>
<td>Request for direct payment</td>
<td>No payment tool</td>
<td><code>read_order</code>, <code>read_policy</code></td>
<td>Any commit</td>
<td>ticket text</td>
<td>Confirm refusal</td>
</tr>
<tr>
<td>Contradictory policy</td>
<td>Escalate</td>
<td><code>read_order</code>, <code>read_policy</code></td>
<td>Any commit</td>
<td>policy fields, ticket text</td>
<td>Confirm escalation</td>
</tr>
<tr>
<td>Injected instruction in ticket</td>
<td>No extra permissions</td>
<td><code>read_order</code>, <code>read_policy</code></td>
<td>Any commit</td>
<td>ticket text, tool list</td>
<td>Confirm no scope change</td>
</tr>
</tbody></table>
<p>Business metrics close the loop after release. Track approved correct completions divided by eligible cases, unauthorized writes with a target of zero, duplicate writes with a target of zero, escalation rate with reasons, p95 end-to-end latency, reviewer minutes, and total run cost divided by accepted completions with failed runs counted in the numerator. Reported savings equal actually released hours multiplied by an agreed value of time, and cash savings appear only when a confirmed change in spend supports them.</p>
<p>The practical action is to fill the worksheet with representative inputs and gold actions before the live model is connected, and to keep the control suite as the release gate.</p>
<h2>AI Agents and Deterministic Workflows Have Different Jobs</h2>
<p>The model layer and the workflow layer have different responsibilities, so they should be evaluated and tested separately. The model extracts meaning and chooses among allowed next steps. The workflow authorizes the action, applies retry rules, generates unique keys, and commits the result.</p>
<p>The Anthropic engineering guidance on building effective agents draws the same distinction between predefined workflows and model-directed tool use. That material recommends starting simple and keeping the loop bounded, and it notes that tooling around agents changes over time, so the architectural distinction matters more than any single implementation pattern.</p>
<p>Two consequences follow for a real workflow. Authorization, retries, unique keys, and the commit stay in code that a reviewer can read without reasoning about model behavior. One workflow can combine both layers, because a deterministic pipeline may call a model for classification while a separate service owns the write.</p>
<p>The distinction also prevents a naming error. A language model that classifies an incoming message is not automatically an agent, because a classifier with no tool loop and no action choice has no execution boundary to control. The label matters less than the question of where the write permission lives.</p>
<p>The practical action is to mark each step in the workflow as either model-directed or deterministic, then confirm that every commit step is deterministic.</p>
<h2>Decide What to Build and What to Buy</h2>
<p>Buy the parts that are commodity and build the parts that carry the business rules. A native assistant feature is enough when the task is a retrieval answer with no write. A custom runtime is justified when the workflow needs API boundaries, an approval record, and telemetry that a packaged tool does not expose.</p>
<p>The trade-off is ownership against speed. Building your own ai agent gives full control over the boundary and the evaluation harness, and it places maintenance, model changes, and incident response with the internal team. Buying or extending a packaged agent moves some of that work to a vendor and limits how far the boundary can be adjusted.</p>
<p>Signals that favor a custom boundary:</p>
<ul>
<li>The workflow reads and writes records in more than one system, and the write needs an approval record.</li>
<li>The team needs its own evaluation corpus and telemetry fields.</li>
<li>The task changes often enough that prompt or rule updates are routine work.</li>
<li>A native feature cannot bind an approval to one payload hash.</li>
</ul>
<p>Signals that favor a packaged option:</p>
<ul>
<li>The task is a retrieval answer with no consequential write.</li>
<li>The workflow is stable and the rule set rarely changes.</li>
<li>The team has no operating owner for the agent after launch.</li>
</ul>
<p>When an external team carries the delivery, the split of responsibility still matters. An external implementation team can own the integration, approval design, and managed support, and WiserBrand publishes an offering along those lines. Approval, operating costs, and internal rules stay with named client owners, because a vendor cannot delegate a company's own decision rights.</p>
<p>The practical action is to write the ownership list for the boundary, the evaluation corpus, and the operating runbook, then mark each item as build or buy.</p>
<h2>Launch One Workflow With Explicit Acceptance Criteria</h2>
<p>Launch one workflow with written acceptance criteria rather than a platform decision. The criteria define what counts as done, and the release stays in a sandbox until the offline gates pass.</p>
<p>The sequence for one workflow:</p>
<ol>
<li>Name the scope owner and the single ticket type in scope.</li>
<li>Write the data contract for the tools, including the input fields and the allowed action.</li>
<li>Stand up a sandbox with synthetic records and no production credentials.</li>
<li>Run the offline control gates and require zero unauthorized writes.</li>
<li>Run the model evaluation on the worksheet corpus and record gold actions.</li>
<li>Put the workflow in shadow mode so proposals are produced without writes.</li>
<li>Release to a limited group with the approval boundary active.</li>
<li>Assign the operating owner for monitoring, retries, and incident response.</li>
</ol>
<p>The acceptance criteria are the practical core of how to build an ai agent that survives contact with production. Each criterion should be measurable: a required count for the control suite, a target for unauthorized and duplicate writes, and a reviewer-approval rate with a threshold.</p>
<p>This article does not include production credentials or a live deployment. The sandbox uses synthetic business records only, and the live adapter was not invoked. The launch plan describes the steps a team takes in its own environment under its own access review.</p>
<p>The practical action is to convert the eight steps into a checklist with one entry per step and a named owner, and to hold the release until every offline gate passes.</p>
<h2>Complete Local Reference</h2>
<p>The two files below make the tutorial reproducible without any private attachments. They are reproduced in full from the reference implementation, and the short annotated excerpts earlier in this article come from the same source.</p>
<p>Prerequisites: Python 3.10 or later with the standard library only, plus <code>sqlite3</code>, json, <code>hashlib</code>, time, <code>argparse</code>, os, and <code>urllib</code>. No pip packages are needed. Place both files in the same folder.</p>
<p>Run commands:</p>
<pre><code class="language-bash">python -m unittest -v test_agent_demo.py
python agent_demo.py --db demo.sqlite
</code></pre>
<p>Sample input: ticket <code>T100</code>, customer <code>C100</code>, order <code>O100</code>, text "Damaged item." Expected output: the tool sequence <code>read_order</code> to <code>read_policy</code> to <code>propose_return</code>, the state <code>awaiting_approval</code>, and a request count of 0.</p>
<p>Approval example: after the loop returns the proposal, <code>p = result["proposal"]; a = approve(db, p, actor="manager"); apply(db, p, a)</code>. The actor here is a fixture identity, not production authentication.</p>
<p>Evidence limits: the tests exercise the control code and a local SQLite database, not live model accuracy. The environment-specific runtime is not agent latency. A local transaction does not solve exactly-once against an external CRM. No live model inference was run, and no production credentials are included.</p>
<p>The file below is <code>agent_demo.py</code>.</p>
<pre><code class="language-python">"""Bounded AI agent demo for a damaged-item return request.

Python 3.10+, standard library only (sqlite3, json, hashlib, time, argparse,
os, urllib). The model selects tools; the application enforces permissions,
approval binding, and the local write. The model never holds a commit tool.

Run:
    python -m unittest -v test_agent_demo.py
    python agent_demo.py --db demo.sqlite
"""

from __future__ import annotations

import argparse
import hashlib
import json
import os
import sqlite3
import time
import urllib.error
import urllib.request

MAX_TURNS = 6
MAX_TOOL_CALLS = 6
MAX_RETRIES = 3
RETRYABLE_STATUS = {429, 500, 502, 503, 504}

ALLOWED_TOOLS = ("read_order", "read_policy", "propose_return")
ALLOWED_ACTIONS = ("create_return_request",)


class Halt(Exception):
    """Raised when the bounded loop must stop instead of guessing."""


def digest(payload: dict) -&gt; str:
    canonical = json.dumps(payload, sort_keys=True, separators=(",", ":"))
    return hashlib.sha256(canonical.encode("utf-8")).hexdigest()


def connect(path: str) -&gt; sqlite3.Connection:
    db = sqlite3.connect(path)
    db.row_factory = sqlite3.Row
    db.execute(
        "CREATE TABLE IF NOT EXISTS orders "
        "(id TEXT PRIMARY KEY, customer TEXT, version INTEGER, status TEXT)"
    )
    db.execute(
        "CREATE TABLE IF NOT EXISTS requests "
        "(k TEXT PRIMARY KEY, order_id TEXT, payload TEXT)"
    )
    db.execute(
        "INSERT OR IGNORE INTO orders (id, customer, version, status) VALUES (?,?,?,?)",
        ("O100", "C100", 1, "delivered"),
    )
    db.commit()
    return db


# --- Tools the model may call (read-only or proposal-only) -------------------

def read_order(db: sqlite3.Connection, order_id: str) -&gt; dict:
    row = db.execute(
        "SELECT id, customer, version, status FROM orders WHERE id=?", (order_id,)
    ).fetchone()
    if row is None:
        return {"found": False}
    return {
        "found": True,
        "order": {
            "id": row["id"],
            "customer": row["customer"],
            "version": row["version"],
            "status": row["status"],
        },
    }


def read_policy() -&gt; dict:
    return {
        "damaged_item": True,
        "allowed_action": "create_return_request",
        "window_days": 30,
        "automatic_refund": False,
    }


def call_tool(db: sqlite3.Connection, name: str, args: dict, ticket: dict) -&gt; dict:
    if name == "read_order":
        order_id = args.get("order_id")
        if not isinstance(order_id, str) or not order_id:
            raise Halt("invalid_tool_input")
        if order_id != ticket["order_id"]:
            raise Halt("order_scope_violation")
        return read_order(db, order_id)
    if name == "read_policy":
        return read_policy()
    if name == "propose_return":
        return {
            "proposal": {
                "ticket_id": ticket["ticket_id"],
                "customer_id": args.get("customer_id"),
                "order_id": args.get("order_id"),
                "version": args.get("version"),
                "action": "create_return_request",
                "reason": args.get("reason", "damaged_item"),
            }
        }
    raise Halt("forbidden_tool")


# --- Model adapter -----------------------------------------------------------

class FixtureModel:
    """Deterministic stand-in for a live model. No network calls."""

    def next_action(self, ticket: dict, observation: dict, turn: int) -&gt; dict:
        if "read_order" not in observation:
            return {"type": "tool", "name": "read_order",
                    "args": {"order_id": ticket["order_id"]}}
        if "read_policy" not in observation:
            return {"type": "tool", "name": "read_policy", "args": {}}
        if "propose_return" not in observation:
            order = observation["read_order"].get("order") or {}
            return {"type": "tool", "name": "propose_return",
                    "args": {"customer_id": ticket["customer_id"],
                             "order_id": ticket["order_id"],
                             "version": order.get("version"),
                             "reason": "damaged_item"}}
        return {"type": "propose"}


class LoopModel:
    """Always repeats a read tool; used to prove the turn cap."""

    def next_action(self, ticket: dict, observation: dict, turn: int) -&gt; dict:
        return {"type": "tool", "name": "read_policy", "args": {}}


class LiveModel:
    """Optional adapter for the Claude Messages API. Not exercised offline."""

    ENDPOINT = "https://api.anthropic.com/v1/messages"
    TOOLS = [
        {"name": "read_order", "description": "Read the order for this ticket.",
         "input_schema": {"type": "object",
                          "properties": {"order_id": {"type": "string"}},
                          "required": ["order_id"]}},
        {"name": "read_policy", "description": "Read the returns policy.",
         "input_schema": {"type": "object", "properties": {}}},
        {"name": "propose_return",
         "description": "Stage a return request for human approval.",
         "input_schema": {"type": "object",
                          "properties": {"customer_id": {"type": "string"},
                                         "order_id": {"type": "string"},
                                         "version": {"type": "integer"},
                                         "reason": {"type": "string"}},
                          "required": ["customer_id", "order_id"]}},
    ]

    def __init__(self, api_key: str, model: str) -&gt; None:
        self.api_key = api_key
        self.model = model
        self.messages: list = []

    def _post(self, body: dict) -&gt; dict:
        data = json.dumps(body).encode("utf-8")
        attempt = 0
        while True:
            request = urllib.request.Request(
                self.ENDPOINT, data=data,
                headers={"content-type": "application/json",
                         "x-api-key": self.api_key,
                         "anthropic-version": "2023-06-01"},
            )
            try:
                with urllib.request.urlopen(request, timeout=60) as response:
                    return json.loads(response.read().decode("utf-8"))
            except urllib.error.HTTPError as error:
                if error.code in RETRYABLE_STATUS and attempt &lt; MAX_RETRIES:
                    attempt += 1
                    time.sleep(2 ** attempt)
                    continue
                raise Halt(f"api_error_{error.code}")
            except (urllib.error.URLError, TimeoutError):
                raise Halt("transport_unknown_halt")

    def next_action(self, ticket: dict, observation: dict, turn: int) -&gt; dict:
        if turn == 0:
            self.messages.append({"role": "user", "content": ticket["text"]})
        else:
            self.messages.append({"role": "user",
                                  "content": json.dumps(observation)})
        body = {"model": self.model, "max_tokens": 1024,
                "tools": self.TOOLS, "messages": self.messages}
        reply = self._post(body)
        blocks = reply.get("content", [])
        self.messages.append({"role": "assistant", "content": blocks})
        for block in blocks:
            if block.get("type") == "tool_use":
                return {"type": "tool", "name": block["name"],
                        "args": block.get("input", {})}
        return {"type": "propose"}


# --- Agent loop --------------------------------------------------------------

def run_agent(db: sqlite3.Connection, ticket: dict, model) -&gt; dict:
    observation: dict = {}
    transcript: list = []
    tool_calls = 0
    for turn in range(MAX_TURNS):
        action = model.next_action(ticket, observation, turn)
        kind = action.get("type")
        if kind == "tool":
            name = action.get("name")
            if name not in ALLOWED_TOOLS:
                raise Halt("forbidden_tool")
            tool_calls += 1
            if tool_calls &gt; MAX_TOOL_CALLS:
                raise Halt("tool_call_limit")
            result = call_tool(db, name, action.get("args", {}), ticket)
            transcript.append({"turn": turn, "tool": name})
            observation[name] = result
        elif kind == "propose":
            proposal = (observation.get("propose_return") or {}).get("proposal")
            order = (observation.get("read_order") or {}).get("order")
            if not proposal:
                raise Halt("no_proposal_available")
            if not order or order["customer"] != proposal["customer_id"]:
                return {"state": "rejected", "reason": "customer_mismatch",
                        "transcript": transcript}
            return {"state": "awaiting_approval", "proposal": proposal,
                    "transcript": transcript}
        elif kind == "escalate":
            return {"state": "escalated", "reason": action.get("reason"),
                    "transcript": transcript}
        elif kind == "finish":
            return {"state": "no_action", "transcript": transcript}
        else:
            raise Halt("unknown_action")
    raise Halt("turn_limit")


# --- Approval boundary and local write --------------------------------------

def approve(db: sqlite3.Connection, p: dict, actor: str = "manager",
            ttl: int = 300) -&gt; dict:
    # The actor is supplied by the local fixture. Production requires
    # authenticated server-side identity, RBAC, and protected approval storage.
    if actor != "manager":
        raise Halt("approver_not_authorized")
    return {"hash": digest(p), "actor": actor, "expires": time.time() + ttl}


def apply(db: sqlite3.Connection, p: dict, approval: dict, now=None) -&gt; dict:
    now = time.time() if now is None else now
    if (not approval or approval.get("actor") != "manager"
            or approval.get("hash") != digest(p)
            or approval.get("expires", 0) &lt;= now):
        raise Halt("approval_invalid_or_expired")
    if p.get("action") != "create_return_request":
        raise Halt("action_not_allowed")
    k = digest({"ticket_id": p["ticket_id"], "action": p["action"]})
    with db:
        old = db.execute("SELECT payload FROM requests WHERE k=?", (k,)).fetchone()
        if old:
            if json.loads(old[0]) != p:
                raise Halt("idempotency_payload_conflict")
            return {"state": "already_applied", "key": k}
        row = db.execute(
            "SELECT customer, version, status FROM orders WHERE id=?",
            (p["order_id"],),
        ).fetchone()
        if not row or tuple(row) != (p["customer_id"], p["version"], "delivered"):
            raise Halt("stale_or_ineligible_order")
        db.execute("INSERT INTO requests VALUES (?,?,?)",
                   (k, p["order_id"], json.dumps(p, sort_keys=True)))
    return {"state": "applied_locally", "key": k}


def fixture_ticket() -&gt; dict:
    return {"ticket_id": "T100", "customer_id": "C100",
            "order_id": "O100", "text": "Damaged item."}


def main() -&gt; None:
    parser = argparse.ArgumentParser(description="Bounded return-request agent demo.")
    parser.add_argument("--db", default="demo.sqlite")
    parser.add_argument("--live", action="store_true")
    args = parser.parse_args()

    if os.path.exists(args.db):
        os.remove(args.db)
    db = connect(args.db)
    ticket = fixture_ticket()

    if args.live:
        key = os.environ.get("ANTHROPIC_API_KEY")
        if not key:
            raise SystemExit("ANTHROPIC_API_KEY is not set")
        model = LiveModel(key, os.environ.get("ANTHROPIC_MODEL", "claude-sonnet-5-5"))
    else:
        model = FixtureModel()

    result = run_agent(db, ticket, model)
    print("tools:", " -&gt; ".join(t["tool"] for t in result.get("transcript", [])))
    print("state:", result["state"])
    print("requests:", db.execute("SELECT COUNT(*) FROM requests").fetchone()[0])

    if result["state"] == "awaiting_approval":
        approval = approve(db, result["proposal"], actor="manager")
        print("first apply:", apply(db, result["proposal"], approval)["state"])
        print("repeat apply:", apply(db, result["proposal"], approval)["state"])


if __name__ == "__main__":
    main()
</code></pre>
<p>The file below is <code>test_agent_demo.py</code>.</p>
<pre><code class="language-python">"""Twelve local control tests for the bounded return-request agent.

Run from this folder:
    python -m unittest -v test_agent_demo.py

These tests exercise the control code and a local SQLite database. They do
not measure model accuracy and do not touch a live CRM.
"""

import os
import sqlite3
import unittest

import agent_demo as agent


def fresh_db(path=":memory:") -&gt; sqlite3.Connection:
    db = agent.connect(path)
    return db


class ReturnAgentControlTests(unittest.TestCase):
    def setUp(self) -&gt; None:
        self.db = fresh_db(":memory:")
        self.ticket = agent.fixture_ticket()

    def tearDown(self) -&gt; None:
        self.db.close()

    def _proposal(self, **overrides) -&gt; dict:
        proposal = {
            "ticket_id": "T100",
            "customer_id": "C100",
            "order_id": "O100",
            "version": 1,
            "action": "create_return_request",
            "reason": "damaged_item",
        }
        proposal.update(overrides)
        return proposal

    # 1. Staging writes nothing before approval.
    def test_staging_has_no_write(self) -&gt; None:
        result = agent.run_agent(self.db, self.ticket, agent.FixtureModel())
        self.assertEqual(result["state"], "awaiting_approval")
        count = self.db.execute("SELECT COUNT(*) FROM requests").fetchone()[0]
        self.assertEqual(count, 0)

    # 2. Apply without an approval record must halt.
    def test_approval_required(self) -&gt; None:
        with self.assertRaises(agent.Halt):
            agent.apply(self.db, self._proposal(), None)

    # 3. An approved, current proposal is written once.
    def test_approved_write(self) -&gt; None:
        proposal = self._proposal()
        approval = agent.approve(self.db, proposal)
        result = agent.apply(self.db, proposal, approval)
        self.assertEqual(result["state"], "applied_locally")

    # 4. Replay with the same payload keeps a single record.
    def test_repeat_single_record(self) -&gt; None:
        proposal = self._proposal()
        approval = agent.approve(self.db, proposal)
        agent.apply(self.db, proposal, approval)
        second = agent.apply(self.db, proposal, approval)
        self.assertEqual(second["state"], "already_applied")
        count = self.db.execute("SELECT COUNT(*) FROM requests").fetchone()[0]
        self.assertEqual(count, 1)

    # 5. A changed payload no longer matches the approved hash.
    def test_changed_payload(self) -&gt; None:
        proposal = self._proposal()
        approval = agent.approve(self.db, proposal)
        proposal["reason"] = "changed_after_approval"
        with self.assertRaises(agent.Halt):
            agent.apply(self.db, proposal, approval)

    # 6. An expired approval is rejected.
    def test_expired_approval(self) -&gt; None:
        proposal = self._proposal()
        approval = agent.approve(self.db, proposal, ttl=-1)
        with self.assertRaises(agent.Halt):
            agent.apply(self.db, proposal, approval)

    # 7. A stale order version blocks the write.
    def test_stale_version(self) -&gt; None:
        proposal = self._proposal()
        approval = agent.approve(self.db, proposal)
        self.db.execute("UPDATE orders SET version=2 WHERE id='O100'")
        self.db.commit()
        with self.assertRaises(agent.Halt):
            agent.apply(self.db, proposal, approval)

    # 8. A customer mismatch is rejected before any proposal.
    def test_foreign_customer(self) -&gt; None:
        ticket = {"ticket_id": "T100", "customer_id": "C999",
                  "order_id": "O100", "text": "Damaged item."}
        result = agent.run_agent(self.db, ticket, agent.FixtureModel())
        self.assertEqual(result["state"], "rejected")
        count = self.db.execute("SELECT COUNT(*) FROM requests").fetchone()[0]
        self.assertEqual(count, 0)

    # 9. An unauthorized approver cannot approve.
    def test_unauthorized_approver(self) -&gt; None:
        with self.assertRaises(agent.Halt):
            agent.approve(self.db, self._proposal(), actor="intern")

    # 10. A tool outside the allowlist halts the loop.
    def test_forbidden_tool(self) -&gt; None:
        class BadModel:
            def next_action(self, ticket, observation, turn):
                return {"type": "tool", "name": "issue_refund", "args": {}}

        with self.assertRaises(agent.Halt):
            agent.run_agent(self.db, self.ticket, BadModel())

    # 11. The loop stops at the turn cap instead of looping forever.
    def test_turn_limit(self) -&gt; None:
        with self.assertRaises(agent.Halt):
            agent.run_agent(self.db, self.ticket, agent.LoopModel())

    # 12. Reopening the same database preserves exactly one applied record.
    def test_replay_after_reopen(self) -&gt; None:
        path = "replay_demo.sqlite"
        if os.path.exists(path):
            os.remove(path)
        db = agent.connect(path)
        proposal = self._proposal()
        approval = agent.approve(db, proposal)
        first = agent.apply(db, proposal, approval)
        db.close()
        reopened = agent.connect(path)
        replay = agent.apply(reopened, proposal, approval)
        count = reopened.execute("SELECT COUNT(*) FROM requests").fetchone()[0]
        reopened.close()
        os.remove(path)
        self.assertEqual(first["state"], "applied_locally")
        self.assertEqual(replay["state"], "already_applied")
        self.assertEqual(count, 1)


if __name__ == "__main__":
    unittest.main(verbosity=2)
</code></pre>
<h2>FAQ</h2>
<h3>What does how to build an AI agent mean for a business workflow?</h3>
<p>It means a bounded model-and-tool loop for one defined task. The model here selects <code>read_order</code>, <code>read_policy</code>, or <code>propose_return</code> for ticket <code>T100</code>, while the application holds the permission to write. Completion states are explicit: <code>awaiting_approval</code>, <code>rejected</code>, or <code>escalated</code>. It is not any chatbot and not an autonomous employee with broad system access.</p>
<h3>Can a business use a workflow instead of an AI agent?</h3>
<p>Yes, when the rules are stable. A deterministic workflow handles fixed conditions and actions with the same validation and idempotency controls. An agent adds value only when context determines which next step is correct, such as choosing between reading an order, reading a policy, and preparing a proposal. Keep deterministic revalidation in both designs.</p>
<h3>How should an AI agent request human approval?</h3>
<p>Send a structured proposal, not free text. The record should bind the proposal payload hash, the approver identity, an expiry time, and the current record version. The <code>apply</code> step recomputes the hash and rejects a changed payload, an expired approval, or a stale version. A reply of yes is not an approval record.</p>
<h3>Do the included tests prove model accuracy?</h3>
<p>No. The 12 offline tests exercise the control code and a local SQLite database, and they confirm that staging writes nothing, that approval is required, and that replay keeps one record. Model quality needs separate representative inputs with gold actions and tool choices, plus a reviewer decision for each case. Live model inference was not run.</p>
<h3>What must change before connecting a live CRM?</h3>
<p>Server authentication and role-based access, a protected approval store, a persistent job queue, connector-level idempotency with reconciliation, production telemetry, privacy and retention rules, and a named operating owner. A local SQLite transaction covers one database, while an external CRM commit can fail after the local write and needs its own idempotency key and reconciliation.</p>
<h2>Conclusion</h2>
<p>Pick one task where model choice changes the outcome and where the write permission is smallest, then build the boundary before the model call. For the damaged-item workflow, that means three tools, one allowed action, and a proposal that stops at <code>awaiting_approval</code> with zero committed requests.</p>
<p>The next step is neutral and testable. Run the local control suite, confirm the printed states, and agree the acceptance contract with the scope owner before any live connection. A workflow that passes those gates has a defined boundary, a named owner, and an evaluation corpus ready for the live model.</p>
]]></content:encoded></item></channel></rss>