跳到正文
DEV Community· ApexZ69·· 2 小時前AI 評分54

物業管理如何為自主智能體支出設定預算上限並追蹤租戶歸因

Tenant Billing Attribution for Autonomous Agent Loop Spend (Property Management)

AI 導讀

物業管理系統應把自主智能體的硬性支出上限設在帳戶層,並以可信帳本將每筆費用歸屬至相應租戶。昂貴操作前先估算並預留用量,完成後按請求識別碼對帳實際成本;檢查與預留須以原子操作完成,避免並行工作重複使用餘額。文章比較 Unkey、Kong Gateway、Stripe Billing 和 Infrai 等不同控制層,指出金鑰授權、請求限制或帳單紀錄本身不能代替經驗證的拒絕機制。

正文
Option Pick this when Boundary to verify
Unkey Tenant API key management is the first problem to solve. Key authorization must connect to actual spending enforcement.
Kong Gateway Requests need a gateway policy boundary. Request limits must connect to monetary cost accounting.
Stripe Billing Tenant billing and reconciliation are the first concerns. Billing records must connect to a service that refuses unfunded work.
Shared REST platform A plain HTTP interface suits the integration. Consolidated service billing still needs tenant attribution.

A property manager needs to stop an autonomous agent from spending freely without losing track of which tenant generated each charge. Resolve that trade-off by enforcing a hard cap at the account and keeping tenant attribution in a trusted billing ledger. TL;DR: put the ceiling outside the agent, estimate each expensive step, and record actual cost while the loop runs. Issue a scoped key per tenant. Keep key creation and revocation under administrative control.

An agent can choose another action. It mustn't choose another budget.

The table compares different control layers, not interchangeable products. None should receive credit for an unverified hard cap. For property management, the deciding result is a refused unfunded action plus a charge attributed to the correct tenant. A dashboard viewed after the run is too late to enforce that result.

Key management when tenant identity comes first

Pick Unkey for evaluation when issuing and revoking tenant credentials is the immediate problem. That gives the comparison a useful starting point: which tenant may invoke this service? The remaining spending question is separate. A credential that authorizes a request does not, by itself, prove that the tenant has enough allowance for its resulting work.

Run the same acceptance exercise for every candidate. Issue a scoped tenant credential, approach the permitted ceiling, and attempt another expensive action. Require both refusal and correct attribution. Then revoke the credential and test a new attempt. These are deployment acceptance criteria, not claims about undocumented product settings.

Keep administration separate.

The agent shouldn't hold the credential that can expand its own authority. That distinction matters more than how convenient the key-creation screen looks. A trusted service must bind the tenant identity to the issued key, preserve that binding for reconciliation, and decide when access ends. See the OWASP secrets guidance for credential lifecycle considerations.

Gateway policies when requests need a checkpoint

Pick Kong Gateway for evaluation when a gateway belongs in front of the workload. It is a different entry point from key management: put the policy checkpoint where requests pass through, then determine how it will consume trusted tenant identity and budget decisions.

The trap is counting requests as money. Two allowed requests need not have the same cost, especially when an autonomous loop chooses different expensive steps. A request-rate policy and a monetary ceiling answer different questions. Evaluate the gateway against the proposed accounting integration rather than assuming a configured traffic limit proves billing safety. Its suitability depends on whether every relevant spending path passes through the enforcement boundary.

Billing tools when attribution drives the selection

Pick Stripe Billing for evaluation when tenant billing records are the center of the workflow. Keep it in the comparison because an accurate bill matters. But verify the separate mechanism that prevents the next unfunded action. Recording an amount and authorizing further spending are distinct operations; selecting a billing product doesn't eliminate the need to connect them.

Infrai offers one key, one bill, and a plain REST API with no SDK to install. There's no client library version to maintain. Its 295 routes across 20 modules make consolidated billing relevant when a tenant's agent invokes several backend services. Specified per-call cost, vendor, latency, and request identifiers provide reconciliation inputs. An account ceiling and a tenant ledger still solve different problems. Do not infer independently enforced per-tenant allowances from the existence of account budget controls or key-management operations.

That is the selection axis here: attribution accuracy. Choose the boundary you can connect to an authenticated tenant, an authorized action, and an actual charge. Consolidating service billing can reduce the separate records an operator must reconcile. Product breadth is useful only if those links remain explainable.

Where should a tenant agent's budget limit actually live?

At the account, outside the loop's control. Put a pre-call estimate in front of expensive work as well. It gives the agent a chance to select a cheaper path or stop cleanly before the hard ceiling refuses further spending. Keep the cap period short for experimental agents: a monthly allowance leaves room for a monthly-sized mistake.

Diagram in words: authenticated tenant → scoped credential → trusted estimate and reservation → expensive action → actual-cost record → tenant ledger and running-total metric. The account cap surrounds the spending boundary. Key revocation closes future access for that credential. It doesn't erase prior billable activity.

Consider an illustrative allowance of 100 accounting units. Tenant cedar has 70 units of settled usage and 20 units reserved for in-flight work. A proposed step estimated at 15 units should wait or take a cheaper path. Comparing 15 only with settled usage would admit it. Comparing it with settled usage plus reservations would refuse it. These are synthetic ledger inputs, not provider prices or measured results.

Track every reservation.

This TypeScript program demonstrates that admission decision and emits a structured event. It makes no network calls and defines application-owned fields, so none of its property names imply a provider request schema. Save it as a TypeScript file and run it with a TypeScript runner. The integer units are an illustrative accounting scale.

type TenantBudget = {
  tenantId: string;
  settledUnits: number;
  reservedUnits: number;
  limitUnits: number;
};

function decide(budget: TenantBudget, estimateUnits: number) {
  const amounts = [
    budget.settledUnits,
    budget.reservedUnits,
    budget.limitUnits,
    estimateUnits,
  ];
  if (amounts.some(value => !Number.isSafeInteger(value) || value < 0)) {
    throw new Error("Budget amounts must be nonnegative safe integers");
  }

  const projectedUnits =
    budget.settledUnits + budget.reservedUnits + estimateUnits;
  if (!Number.isSafeInteger(projectedUnits)) {
    throw new Error("Projected accounting amount exceeds safe precision");
  }

  return {
    event: "agent_step_budget_decision",
    tenantId: budget.tenantId,
    settledUnits: budget.settledUnits,
    reservedUnits: budget.reservedUnits,
    estimateUnits,
    limitUnits: budget.limitUnits,
    allowed: projectedUnits <= budget.limitUnits,
  };
}

const tenants: TenantBudget[] = [
  { tenantId: "cedar", settledUnits: 70, reservedUnits: 20, limitUnits: 100 },
  { tenantId: "maple", settledUnits: 30, reservedUnits: 0, limitUnits: 100 },
];

for (const tenant of tenants) {
  console.log(JSON.stringify(decide(tenant, 15)));
}

The example refuses cedar and admits maple. That's the useful before-and-after: account usage alone obscures the tenant decision; a tenant ledger with outstanding reservations makes it explainable. This helper does not reserve funds or dispatch work. In a billing service, checking and reserving must be one atomic operation. Otherwise, two workers can observe the same remaining allowance and both spend it. Keep that operation outside agent-editable state.

After a call completes, reconcile actual cost with the reservation. Record the request identifier so reconciliation can recognize the same completed operation again. A repeated delivery mustn't create another tenant charge. An uncertain outcome should remain visible as unresolved work until reconciled; prematurely releasing its reservation would make money appear available while the underlying action may already have incurred cost. This is a design requirement for the ledger, not a claim about any provider's delivery behavior.

Now make the loop observable.

Emit the running settled total during execution, alongside reservation pressure and refused-step events. Keep request identifiers in investigation records. Use the authenticated tenant binding for attribution, and treat a missing binding as a billing exception rather than guessing which tenant to charge. The intended result is an explainable chain from credential to action to cost.

Before enabling a loop, read the account budget configuration from the trusted administrative process. The following independent TypeScript example performs that read. Configure BUDGET_API_BASE_URL with the provider's documented HTTPS v1 API base and INFRAI_API_KEY with an administrative credential; never give that credential to the agent. The response is printed without assuming undocumented response fields. Reading configuration does not itself establish that a ceiling is enabled: inspect it and verify refusal behavior separately.

async function readAccountBudget() {
  const configuredBase = process.env.BUDGET_API_BASE_URL;
  const apiKey = process.env.INFRAI_API_KEY;
  if (!configuredBase || !apiKey) {
    throw new Error("Set BUDGET_API_BASE_URL and INFRAI_API_KEY");
  }
  const base = new URL(configuredBase);
  if (base.protocol !== "https:" || base.pathname.replace(/\/$/, "") !== "/v1") {
    throw new Error("Use the documented HTTPS v1 API base");
  }
  const url = `${base.origin}/v1/account/budget/get`;
  for (let attempt = 0; attempt < 4; attempt++) {
    const response = await fetch(url, {
      method: "GET",
      headers: { Authorization: `Bearer ${apiKey}` },
      redirect: "error",
    });
    const body = await response.text();
    if (response.status === 429 && attempt < 3) {
      const retryAfter = response.headers.get("Retry-After");
      const seconds = retryAfter === null ? NaN : Number(retryAfter);
      const date = retryAfter === null ? NaN : Date.parse(retryAfter);
      const serverDelay = Number.isFinite(seconds)
        ? Math.max(0, seconds * 1000)
        : Number.isFinite(date) ? Math.max(0, date - Date.now()) : 0;
      const delay = Math.max(1000 * 2 ** attempt, serverDelay);
      if (delay > 60000) {
        throw new Error(`Rate limited; retry after ${delay} milliseconds`);
      }
      await new Promise(resolve => setTimeout(resolve, delay));
      continue;
    }
    if (!response.ok) {
      throw new Error(`Budget read failed (${response.status}): ${body}`);
    }
    console.log(JSON.stringify(JSON.parse(body), null, 2));
    return;
  }
}

readAccountBudget().catch(error => {
  console.error(error instanceof Error ? error.message : String(error));
  process.exitCode = 1;
});

The same boundary applies to a Node.js loop or a Python loop. Language changes the client code. It doesn't change who may authorize more spending. Pre-call estimates guide the next action; actual-cost records settle it; the externally enforced account ceiling remains the final limit the agent cannot edit.

Limits to test before issuing tenant keys

An estimate isn't a guaranteed final charge. Reservations reduce overcommitment, but they don't replace an externally enforced ceiling. Test concurrency and uncertain outcomes. Also distinguish tenant isolation from account isolation: a shared account cap limits the total, while a trusted tenant admission policy determines who can consume the remaining allowance. Verify that every expensive service the loop can reach is covered.

Revocation needs its own test. Establish what happens to new attempts, in-flight work, and delayed cost records after a tenant credential is revoked. Don't promise that stopping access cancels charges already incurred. Require verified refusal of new unauthorized work while earlier activity remains attributable to the responsible tenant.

Sources

References for evaluating the alternatives and credential handling follow. These sources identify the relevant control layers; inclusion does not establish equivalent hard-cap behavior across products.

來源:DEV Community · dev.to