Technical Architecture and Security Boundaries for AI Financial Assistants Connected to Bank Accounts

    This article explains the technical architecture required when connecting an AI financial assistant to personal bank accounts. It focuses on read-only bank authorization, deterministic data normalization and expense classification, a calculation layer that separates numeric computation from language modeling, prompt injection protections, compliance boundaries, and evaluation metrics. The core argument is that the main challenge is not making a language model sound conversational, but constraining risk through architecture: limited data access, trustworthy computation, explainable results, and auditable workflows.

    1. The Core Requirement: Restricted Data, Deterministic Computation, and Natural Language Explanation

    When an AI assistant is connected to personal bank accounts, the questions users typically ask fall into four categories:

    1. Spending aggregation: Where did the money go this month, and how much was spent on rent, utilities, shopping, dining, and other categories?
    2. Upcoming payment scheduling: Before the next salary date, which bills are still due?
    3. Financial decision support: Is a vacation expense currently affordable?
    4. Savings trend estimation: How much can the user approximately save each month?

    These questions may look like casual conversation, but from an engineering perspective they are composed of three distinct parts:

    • Restricted data access
    • Deterministic numerical computation
    • Natural-language explanation and follow-up generated by a large language model

    Mixing these three layers together without clear boundaries is the most common source of failure in this type of feature. The architecture should therefore be explained layer by layer, following the data flow.

    2. Layer 1: Read-Only Authorization Channel

    The key design principle is connection, not login. The user should not enter bank credentials inside the assistant interface. Instead, authorization is completed through a standard open banking aggregation mechanism: the user is redirected to the bank-side authorization page, confirms the requested permission scope, and the assistant receives a token after the callback. After that, data requests are proxied by the aggregation platform.

    This produces several clear engineering constraints:

    • Least privilege: Request only read permissions, such as account list, balance, credit limit, and transaction history. Do not request transfer, payment, investment, or modification permissions.
    • Token lifecycle management: Use a short-lived access token plus a rotatable refresh token, with support for immediate revocation.
    • Limited data visibility: Restrict visible data to the bank name, account name, account type, last four digits of the account number, balance, credit limit, and historical transactions, commonly covering about two years. Do not expand beyond this scope.
    • Read-only as an architectural guarantee: Enforce a method whitelist at the gateway layer rather than relying on business code to remember not to perform writes.

    The following is a simplified example of a read-only proxy gateway policy:

    1. READ_ONLY_ENDPOINTS = {"/accounts", "/balances", "/transactions"}
    2. def outbound_request(method: str, path: str, token: str):
    3. # 1) Reject write operations at the gateway layer
    4. if method != "GET" or path not in READ_ONLY_ENDPOINTS:
    5. raise Forbidden("read-only gateway: write operations are not permitted")
    6. # 2) Load the token from secure storage and do not log it
    7. headers = {"Authorization": f"Bearer {load_token_securely(token)}"}
    8. # 3) Mask the response before passing it downstream
    9. return desensitize(do_request(method, path, headers))

    The desensitize() step is often overlooked, but it determines what can appear in downstream logs, caches, and prompts. The default policy should be:

    • Keep only the last four digits of the account number.
    • Keep the merchant description but mark it as untrusted external text.
    • Never persist tokens or refresh credentials in application logs.

    3. Layer 2: Data Normalization and Expense Classification

    Transaction data received from the aggregation platform is raw data. Merchant descriptions vary in length, currency symbols and amounts are inconsistent, refunds and fees use different sign conventions, and delayed settlement may create duplicate records for the same transaction. Sending this directly to a model will produce unstable answers.

    A deterministic normalization pipeline is therefore required first.

    Deduplication and Idempotency

    Use a unique key based on account ID + transaction fingerprint and write with upsert semantics rather than append-only insertion. The transaction fingerprint can be generated from a hash of the date, amount, and normalized merchant result. Duplicate entries caused by delayed settlement should be resolved by fingerprint matching, not by model judgment.

    Field Normalization

    Normalize the following fields:

    • Amounts should be represented as signed decimals.
    • Time zones and date granularity should be unified.
    • Currency and precision should be standardized.
    • Transaction time and posting time should be distinguished.

    For cash flow forecasting, transaction time and posting time cannot be treated as the same field.

    Expense Classification

    A layered fallback strategy is recommended:

    1. CATEGORIES = (
    2. "housing",
    3. "utilities",
    4. "groceries",
    5. "dining",
    6. "shopping",
    7. "transport",
    8. "health",
    9. "subscriptions",
    10. "income",
    11. "transfer",
    12. "other",
    13. )
    14. def classify(tx, user_rules, merchant_map, mcc_map, model):
    15. # 1) User-defined rules have the highest priority
    16. if tx.fingerprint in user_rules:
    17. return user_rules[tx.fingerprint]
    18. # 2) Use the normalized merchant mapping
    19. key = normalize_merchant(tx.raw_description)
    20. if key in merchant_map:
    21. return merchant_map[key]
    22. # 3) Fall back to industry category codes
    23. if tx.mcc in mcc_map:
    24. return mcc_map[tx.mcc]
    25. # 4) Use a text classification model, but do not force low-confidence guesses
    26. pred = model.predict(f"{tx.raw_description} {tx.city or ''}")
    27. return pred.label if pred.confidence >= 0.75 else "other"

    Two design choices are important:

    • User rules take priority: This gives users explainability and the ability to correct results, which significantly reduces trust costs.
    • Low-confidence results fall back to other: This prevents incorrect classifications from contaminating monthly summaries. Misclassifying one dining transaction has limited impact, but misclassifying rent as dining would distort many conclusions.

    Recurring Expense Detection

    Subscriptions and fixed bills do not need to be semantically understood by a model. They can be identified using statistical features:

    • The normalized merchant is the same.
    • The amount fluctuates within a narrow range.
    • The interval is approximately 28 to 35 days, or occurs on a fixed monthly date.
    • The transaction has appeared at least three times historically.

    Such transactions can be classified as recurring expenses, and the next expected debit date can be predicted. This is the core basis for answering questions such as how many bills are due before the next salary.

    Internal Transfer Exclusion

    Credit card repayments and transfers between a user’s own accounts may appear as expenses in raw transaction data. If they are not identified, they can inflate both spending and income and distort balance calculations. Rules should mark and exclude these entries based on conditions such as:

    • The counterparty is an account owned by the same user.
    • An equal and opposite entry appears on the income side within a short period.

    4. Layer 3: Deterministic Computation and the Model’s Responsibility Boundary

    This is the layer where mistakes are most likely. The large language model should not be responsible for arithmetic. All amount aggregation, balance inference, and savings forecasting must be performed by the deterministic calculation layer. The model’s role is limited to retrieving data, organizing information, and explaining results.

    The recommended tools are all read-only:

    Tool Responsibility Key Constraint
    list_accounts Return account name, type, last four digits, balance, and credit limit Do not return the full account number
    query_transactions Filter transactions by time and optional category Must include a time window and limit the number of returned records
    spending_summary Aggregate spending by category and period, including period-over-period comparison Aggregation is performed server-side
    upcoming_bills Output scheduled future bills based on recurring expense detection Include confidence and inference basis
    cashflow_forecast Combine balance and bill schedule to output a retainable amount range Output a range rather than a single value

    Tool descriptions must explicitly state that the operation is read-only, and parameter validation must be enforced:

    1. {
    2. "name": "query_transactions",
    3. "description": "Query read-only transaction records for authorized accounts. This tool supports reading only and has no fund operation capabilities.",
    4. "parameters": {
    5. "type": "object",
    6. "properties": {
    7. "start_date": {
    8. "type": "string",
    9. "format": "date"
    10. },
    11. "end_date": {
    12. "type": "string",
    13. "format": "date"
    14. },
    15. "account_ids": {
    16. "type": "array",
    17. "maxItems": 10,
    18. "items": {
    19. "type": "string"
    20. }
    21. },
    22. "categories": {
    23. "type": "array",
    24. "items": {
    25. "type": "string"
    26. }
    27. },
    28. "limit": {
    29. "type": "integer",
    30. "maximum": 500,
    31. "default": 200
    32. }
    33. },
    34. "required": [
    35. "start_date",
    36. "end_date"
    37. ]
    38. }
    39. }

    Context Budget

    Two years of transaction data can contain thousands of records, so it is not practical to place everything into the model context. The correct approach is:

    1. Aggregate first.
    2. Retrieve selectively.
    3. Drill down only when needed.

    By default, only monthly summaries and anomalous transactions should be provided to the model. When the user asks about a specific category, retrieve details for that category. Use retrieval-based data access only when long merchant descriptions truly need to be understood. This approach controls cost and reduces exposure of irrelevant data.

    How to Calculate Affordability

    The question “Can I afford this?” should not be answered by model intuition. It should be defined deterministically:

    1. Disposable balance =
    2. current available balance
    3. + unused credit limit
    4. - scheduled fixed expenses before the next income date
    5. - pending bills

    For income dates or expense posting times that are uncertain, the system should return a range rather than a single value. The model’s task is to explain the range and key assumptions in natural language. For example, it may state that the conclusion assumes salary arrives on the usual date and that no additional large expenses occur.

    5. Prompt Injection and Authorization Risk

    Transaction notes, transfer memos, and merchant descriptions are untrusted external text. They may contain content that resembles instructions. Key protections include:

    • Clearly separate instruction regions from data regions. External text should always be rendered as data and must not be treated as instructions.
    • Limit tool calls with maximum rounds and timeouts to avoid being induced into looping calls.
    • Validate all tool call parameters again at the gateway. Do not trust model output directly.
    • Apply structured output constraints. Do not allow the model to assemble amount values on its own.
    • Maintain a full audit trail: user question, tools called, parameters, and response summaries. Account fields in audit logs must still be masked.

    6. Compliance and Product Boundaries

    The red lines for personal finance scenarios should be reflected in both product design and system implementation:

    • No investment advice: The system should not generate buy or sell recommendations and should not provide asset allocation advice. This boundary should be built into response templates.
    • Revocable authorization: Users should be able to disconnect accounts at any time, revoke tokens, and trigger cleanup of cached data.
    • Minimal data retention: Raw transaction data should be fetched on demand. After aggregation jobs are complete, detailed records should not be retained for long periods. Clear retention periods and deletion mechanisms are required.
    • Encryption and isolation: Tokens and sensitive fields should be encrypted. Keys should be managed by a dedicated key management service. In multi-tenant environments, logical isolation should be applied per user. Cache keys must include user identifiers to avoid cross-user cache hits.
    • Explainability: Every classification and prediction should be traceable to a specific rule or historical data source. Users should be able to correct results with one click, and corrections should be fed back into the rule system.

    7. Implementation Checklist and Evaluation Dimensions

    The recommended minimum engineering implementation order is:

    1. Authorization integration
    2. Read-only gateway
    3. Normalization and deduplication
    4. Classification pipeline
    5. Aggregation and prediction calculation layer
    6. Tool encapsulation
    7. Session orchestration and context budgeting
    8. Auditing and data masking
    9. Evaluation set construction

    This sequence should not be skipped. If the calculation layer is not solid before the model is introduced, the result will only be fluent responses with incorrect numbers.

    Evaluation should cover four categories of metrics:

    1. Numerical correctness: Consistency with offline calculation results for aggregated amounts, balances, and bill schedules. This should be close to 100%. “Approximately correct” is not acceptable.
    2. Classification quality: Classification accuracy and the proportion of other. A high other ratio indicates insufficient rule coverage or model coverage.
    3. Security and compliance: Unauthorized tool call blocking rate, injection test pass rate, and number of cross-user data leakage cases. Cross-user leakage must be zero.
    4. Experience: Useful first-answer rate, number of clarification follow-ups, and end-to-end latency.

    In terms of deployment, this type of system mainly requires general cloud capabilities:

    • Gateway and load balancing services handle authorization callbacks and outbound proxying.
    • Message queues smooth out batch fetching for aggregation jobs.
    • Object storage holds desensitized intermediate results for offline analysis.
    • Logging services support the audit chain.
    • Monitoring and alerting cover authorization failure rates and numerical consistency anomalies.

    In cloud environments such as Baidu AI Cloud, these capabilities can be composed from general-purpose product categories and do not require proprietary interfaces.

    8. Conclusion

    The technical difficulty of connecting bank accounts to an AI assistant is not making the model talk. It is using architecture to constrain risk: read-only authorization channels, deterministic computation layers, trustworthy data boundaries, and auditable end-to-end workflows.

    The value of the model should be concentrated in the final step: translating structured numbers into language that users can understand, question, and use for decisions. If the model is instead responsible for data retrieval, arithmetic, and permission judgment, the feature may launch quickly, but it will only become a machine that outputs incorrect answers with high confidence.