Building an AI Personal Finance Assistant in Read-Only Mode: Architecture and Practices

    This article walks through how to architect a read-only conversational AI assistant for personal finance Q&A, from decomposing user intents and enforcing write-blocked permissions at the gateway layer, through account binding with credential isolation, deterministic structured queries and rule-based anomaly detection, to APR estimation, structured chart output, compliance controls, and a staged rollout. It is intended for engineers and cloud architects who want a reference design for building safe, auditable, and traceable financial assistants.

    1. Requirements Breakdown: Letting the Conversation Do the Math

    Traditional finance apps present data fragmented across accounts and months. When users want to answer “where did my money go this month,” they often have to switch screens manually, filter rows, and total everything by hand. As the number of accounts grows, the cost of this manual work rises quickly. A recently launched personal finance feature in an AI assistant uses read-only access to financial data together with conversational Q&A, rolled out in phases to a subset of paid subscribers. Stripping away the product wrapper, it is essentially a combination of a read-only data connector + a semantic understanding layer + structured queries + explanation generation. This article follows that abstraction.

    Abstracting the needs from the original scenario, they fall into four categories:

    • Summaries: Aggregate spending by category, merchant, and time window to answer “where did the money go”;
    • Investigation: Detect duplicate charges, hidden fees, and long-unnoticed “silent price increases”;
    • Explanation: When users hit terms like APR (annual percentage rate) or revolving interest, explain the concept first, then calculate the impact;
    • Outputs: Generate weekly spending charts, upcoming bill calendars, and custom dashboards, with support for multi-turn adjustments.

    All four categories share a common prerequisite: the system must be able to read real account and transaction data. This determines that the center of gravity for the entire design is not “generation” but “reading safely, calculating accurately, and explaining traceably.”

    2. First Principles: Read-Only Access Is the Cornerstone of the Security Model

    The easiest way for this kind of feature to go wrong is to quietly expand “read” into “write.” Once an assistant can transfer money, make payments, or place investment orders, the risk level escalates from “wrong information” to “financial loss,” and compliance responsibility changes completely. So the first hard constraint is this: the data connector’s authorization scope must request read-only permissions only — fund transfers, account management, and investment operations are never in scope.

    In engineering terms, this constraint must be enforced at three layers simultaneously, not left to prompt-based model constraints alone:

    1. # Read-only gateway: enforce checks before tool calls reach the data source
    2. ALLOWED_METHODS = {"GET"}
    3. DENY_PATH_PATTERNS = ("transfer", "payment", "withdraw", "order", "invest")
    4. def guard_readonly(request) -> None:
    5. if request.method not in ALLOWED_METHODS:
    6. raise PermissionError("Read-only credentials do not allow write operations")
    7. for pat in DENY_PATH_PATTERNS:
    8. if pat in request.path.lower():
    9. raise PermissionError(f"Blocked path: {pat}")
    • Authorization layer: The minimal permission set requested from the data source contains no write operations;
    • Gateway layer: All outbound requests pass through a unified gateway with dual checks — a method allowlist plus a path denylist;
    • Tool layer: The tool functions exposed to the model provide query semantics only, with no entry points that have side effects.

    The benefit of this layering is that even if the model is induced during some inference to take a risky action (for example, a user asking “help me cancel this subscription”), the call chain is rejected at the gateway and no unauthorized behavior occurs.

    3. Account Binding and Data Access: Isolating Credentials from Business Systems

    The binding flow typically follows the standard delegated authorization model: the user is redirected to the data provider’s page to complete identity authentication, and the app side only obtains a limited token — never the user’s account password. There are a few key engineering points:

    1. Tokens do not land in the business database: Long-term refresh tokens are stored in a key management service; the business database keeps only an account identifier and a mask (such as the last four digits of a card number), so that a single database leak does not compromise the funding account.
    2. Automatic token rotation: Access tokens have short lifetimes; once expired, a background job refreshes them silently, with exponential backoff and alerts configured for refresh failures.
    3. Unified data model: Different data sources return very different structures and must be normalized into a unified transaction view, otherwise downstream aggregation logic cannot be reused.
    1. {
    2. "account_id": "acc_8842",
    3. "posted_at": "2026-11-01T08:12:00Z",
    4. "amount": -12.90,
    5. "currency": "USD",
    6. "merchant_raw": "STREAMING CO *AUTO RENEW",
    7. "merchant_norm": "video subscription",
    8. "category": "subscriptions",
    9. "meta": {"card_mask": "****4417", "recurring_guess": true}
    10. }

    The fields merchant_norm (normalized merchant name) and category are the foundation for all subsequent statistics. It is recommended to recompute them periodically with offline jobs rather than infer them in real time during each Q&A, which reduces latency and improves result stability.

    4. Intent Understanding and Structured Queries: Let the Model Produce Logic, Not Assemble SQL

    The key design principle is: the model is responsible for mapping natural language to constrained structured query parameters, while the actual data access is done by deterministic backend code. This yields three benefits — avoiding SQL injection, guaranteeing reproducible aggregated values, and making auditing easier.

    Example tool contract (using “where did my money go this month” as an example):

    1. {
    2. "tool": "query_transactions",
    3. "readonly": true,
    4. "schema": {
    5. "accounts": {"type": "array", "items": {"type": "string"}, "maxItems": 20},
    6. "time_range": {"type": "object", "properties": {
    7. "from": {"type": "string", "format": "date"},
    8. "to": {"type": "string", "format": "date"}}},
    9. "group_by": {"type": "string", "enum": ["category", "merchant", "week"]},
    10. "filters": {"type": "object", "properties": {
    11. "min_amount": {"type": "number"},
    12. "exclude_refunds": {"type": "boolean", "default": true}}}
    13. }
    14. }

    Complementary boundary checks are equally important:

    1. MAX_LOOKBACK_DAYS = 730 # hard upper bound on the time window, to prevent pulling full history and overwhelming the data source
    2. def validate(query):
    3. span = (query.time_range["to"] - query.time_range["from"]).days
    4. if span > MAX_LOOKBACK_DAYS:
    5. raise ValueError(f"Query range too large ({span} days), please narrow it to within {MAX_LOOKBACK_DAYS} days")
    6. if not query.accounts:
    7. raise ValueError("An explicit account must be specified; full scans without an account scope are forbidden")

    Requiring an explicit account scope is the data minimization principle applied at the query layer: when a user asks “how much did I spend,” the assistant should still restrict the scope to the set of accounts that this user has bound and authorized, with no implicit expansion.

    5. Anomalous Bill Detection: Rules First, Model as Fallback

    Questions like “are there any anomalous charges” are not well suited to relying entirely on the model’s semantic judgment. Numerical consistency must be guaranteed by deterministic rules. Common high-value rules include:

    Rule Detection logic Typical output
    Duplicate charge Same merchant, same amount, interval below threshold “Membership A charged 9.99 twice within 3 days”
    Silent price increase Month-over-month increase above threshold for the same merchant, sustained for two periods “Cloud storage subscription rose from 6 to 9 and has stayed there for 8 months”
    Hidden fee Small amount, high frequency, merchant name contains fee/charge “4 account maintenance fees last month”
    Dormant subscription Consecutive charges ≥ 6 periods with no usage signal “This subscription has charged for 14 consecutive months”
    1. def detect_duplicates(txns, amount_tol=0.01, window_days=5):
    2. """Suspected duplicate charges within the amount tolerance and time window"""
    3. hits = []
    4. for i, a in enumerate(txns):
    5. for b in txns[i + 1:]:
    6. if a.merchant_norm != b.merchant_norm:
    7. continue
    8. if abs(abs(a.amount) - abs(b.amount)) > amount_tol:
    9. continue
    10. if (b.posted_at - a.posted_at).days <= window_days:
    11. hits.append({"merchant": a.merchant_norm,
    12. "amount": abs(a.amount),
    13. "dates": [a.posted_at, b.posted_at]})
    14. return hits

    The model’s role at this layer is “ranking and explaining,” not “judging”: it prioritizes the candidates hit by the rules (by impact amount × persistence) and uses natural language to explain why they are worth attention. This division of labor — “rules produce conclusions, the model produces expression” — significantly reduces numerical hallucination.

    6. Terminology Explanation and Interest Estimation: Explain the Concept First, Then Give Numbers

    When a user asks “what is APR, and how much extra did it cost me this year,” the correct handling is two-stage: first output the conceptual explanation (APR is an annualized cost measure that folds in fees, installment charges, and so on — it differs from the nominal monthly rate × 12), then perform the calculation based on the bill data. The calculation must be an explicit approximation with stated assumptions:

    1. def estimate_apr_interest(balance, apr, days, compound_daily=True):
    2. """
    3. For estimation only; the actual amount follows the statement
    4. balance: average outstanding balance during the period
    5. apr: annual percentage rate (e.g., 0.1999)
    6. days: number of days interest accrues
    7. """
    8. r = apr / 365
    9. if compound_daily:
    10. factor = (1 + r) ** days
    11. return balance * (factor - 1)
    12. return balance * r * days

    Two output norms should be emphasized: first, label assumptions such as “average balance” and “daily compounding assumption,” because real statements differ in their interest calculation cycles, grace periods, and minimum payment rules; second, give a range rather than a single point value — for example, “based on the current balance, the estimated interest for the coming year is roughly between X and Y” — to prevent users from treating the estimate as the statement.

    7. Visualization and Multi-Turn Adjustment: Output Is Structure, Not an Image

    Charts should generate a structured chart spec (data series + dimensions + markers) and let the frontend render it, rather than having the model output a bitmap directly. This way, when the user says “only show the dining category” or “switch from weekly to monthly,” the system only needs to modify the spec parameters, without re-fetching data.

    1. {
    2. "chart": "bar",
    3. "x": {"field": "week", "range": "last_8_weeks"},
    4. "y": {"field": "spend", "agg": "sum"},
    5. "series": [{"field": "category", "filter": {"in": ["dining", "transport"]}}],
    6. "annotations": [{"type": "highlight", "week": "2026-W44", "note": "includes an annual subscription"}]
    7. }

    The bill calendar reuses the next-due date field (next_due_at) derived from the same dataset, sharing the same foundation as anomaly detection, which avoids maintaining two separate logic paths.

    8. Security, Compliance, and Observability

    This part is the dividing line for whether this kind of feature can go to production:

    • Transmission and storage: End-to-end encrypted transmission; sensitive fields encrypted at rest, with the business database keeping only masks and hashes for comparison;
    • Audit trails: Every Q&A records the caller, tool name, parameter summary, volume of data hit, and elapsed time, making it easy to review after the fact “how this number was derived”;
    • Data minimization and retention: Prefer on-demand queries; do not keep an indefinite full mirror; set a retention period and provide a deletion channel;
    • Masked display: The interface masks by default; expanding full information requires secondary verification;
    • Neutrality commitment: No paid placements or recommendations are inserted into financial conclusions, consistent with the “read-only, no self-operated financial products, no investment advice” positioning;
    • Disclaimer and verification prompts: Clearly state that results may be wrong, support one-click drill-down to raw transaction details, and treat bank/statement figures as authoritative for key amounts.

    9. Staged Rollout and Stability

    The recommended pace for phased rollout is: internal whitelist → very small fraction of external users → gradual expansion by subscription tier and region. During the gray-release period, four categories of metrics need close observation:

    Category Example metrics Alert suggestions
    Correctness Consistency deviation between aggregated amounts and the sum of details Block expansion immediately if deviation > 0.01
    Performance End-to-end P95 latency, data source call error rate Automatically degrade to pure query mode if error rate > 1%
    Security Number of unauthorized interceptions, number of anomalous parameter hits A sudden spike triggers manual review
    Experience Follow-up question rate, drill-down detail click rate Used to assess whether explanations are understood

    At the same time, a fast kill switch should be retained: if a systematic numerical deviation is discovered, the Q&A layer can be disabled without code changes while keeping only structured queries, keeping the risk within an acceptable range.

    If a cloud platform such as Baidu AI Cloud is used as the foundation, this capability can be fully assembled from general product categories: on the compute side, use a container platform to host the query gateway and orchestration services with elastic scaling; on the storage side, use object storage to hold archived snapshots and a database service to store the normalized transaction view; on the asynchronous side, use a message queue to decouple “data sync — rule recomputation — index building”; on the governance side, use a logging service for audit trails and monitoring alerts covering error rates and latency; credentials and keys are handed over to a key management service for unified custody and rotation. On the model side, version management is recommended: when tool contracts change, synchronously regress a batch of fixed Q&A cases to ensure upgrades do not silently alter the numerical definitions.

    In summary, the technical difficulty of this kind of personal finance Q&A is not “whether it can chat,” but three points: whether the read-only boundary is enforced in code, whether every number can be drilled down to raw records, and whether errors are honestly disclosed. Do these three things solidly, and a conversational finance assistant can move from demo to usable.