AI Extension

Overview

EasyAdminBlazor.AI is an optional extension of the framework. It adds an AI assistant to the admin panel: conversation, business tools gated by the current user's menu and button permissions, and per-call Token and cost auditing. The framework only does rate limiting and model resolution; whether to allow a call, and all quota / entitlement decisions, are left to the host business layer.

It only takes effect when installed. Without it, admin pages, service registration and menus are unchanged. The extension does not modify core behavior — it only plugs into extension points provided by the core package.

Capability Description
Conversation Streaming output, Markdown rendering, live progress (thinking / answering / running a tool), image input when the model supports it, quick replies
Multiple models OpenAI-compatible endpoints, a default model per scene (daily chat / complex analysis / document recognition), API keys encrypted at rest
Business tools Business extensions mark methods with [AiTool]; the framework checks permissions at call time and routes write operations through a confirmation card
Rate limiting & metering The framework only provides a per-user per-minute rate limit; whether to enforce quota / entitlement is decided by the host via IAiAccessGuard; usage and cost logged per call
Audit Call log and tool log cross-drill; AI write operations and page changes land in the same operation log
Error memory Failed tool executions are remembered so later conversations warn the model not to repeat the mistake

Installation

This extension is not published to the public NuGet feed; it is included for paid source-code licensees. For source integration use a ProjectReference:

<ProjectReference Include="..\Extensions\EasyAdminBlazor.AI\EasyAdminBlazor.AI.csproj" />

The host performs framework registration; the extension never calls AddEasyAdminBlazor in return:

builder.AddEasyAdminBlazor(new EasyAdminBlazorOptions { /* ... */ })
       .AddEasyAdminBlazorAI(opt =>
       {
           opt.RateLimitPerMinute = 60;       // Per-user calls per minute; 0 = unlimited
       });

AiOptions is also bound to the "Ai" section of appsettings; the configure delegate runs afterwards and overrides the configuration file. With Enabled = false, the initializer does not take over menus and the service layer rejects calls.

On startup, AiInitializer creates tables and provisions menus idempotently. Exceptions are caught and logged as warnings; they never block site startup.

Admin Pages

AiInitializer registers the top-level group "AI" (Admin/Ai, sort order 800) and five pages:

Page Path Permission code Purpose
AI Chat Admin/Ai/Chat 10031 Talk to the model and invoke tools the user is allowed to use
AI Models Admin/Ai/Model 10032 Configure models, scene defaults, pricing and capability flags; add/edit/remove buttons
Call Log Admin/Ai/CallLog 10034 Token breakdown, status and duration for every model call
Tool Log Admin/Ai/ToolLog 10035 Tool calls and rejections, including pending / rejected confirmations
Usage Admin/Ai/Usage 10036 Aggregated view

The framework ships with no quota table and no quota management page, and makes no assumptions about the host's recharge or grant workflow. Whether to restrict calls, and where the allowance comes from, are decided by the host via IAiAccessGuard. The framework only exposes the IAiQuotaSource hook for the host to feed order data in, used to show "remaining quota" on the chat page (see below).

Model Configuration

One AiModel row = one model endpoint:

  • Code / Name / Provider: the provider is a dictionary code; openai-compatible uses the built-in OpenAiChatClientFactory.
  • Base URL / API Key / Model name: the API key is stored encrypted, masked in the edit form; leaving it blank keeps the old value.
  • Scene: chat / analysis / document, etc. Default models are resolved per scene; AiOptions.DefaultScene defaults to chat.
  • Capability flags: SupportsTools (no tools attached when false), SupportsStreaming, SupportsVision, DisableThinking.
  • Pricing: four tiers — input / output / cached input / reasoning, per million Tokens, plus a cost currency. Reasoning Tokens are already included in output; blank means "same price as output", 0 means free.
  • Tenant: empty / main is host-wide shared, otherwise tenant-private. Under SaaS, models are centrally managed by the host and tenants cannot define their own.

DisableThinking is for models like DeepSeek that enable thinking by default when tools are present: thinking Tokens are billed as output but may be missing from usage, so local statistics would not match the vendor bill. Checking it sends reasoning_effort=none.

Business Tools

The tool attribute lives in the core package. Business extensions only reference the core package to mark methods; without the AI extension the attribute has no effect:

[AiTool(
    Name = "shipment_pending",
    Description = "List pending shipments",
    PermissionPath = "Admin/Shipment",
    PermissionButton = "edit",
    RequiresConfirmation = false)]
public async Task<object> ListPendingAsync([Description("Customer code, optional")] string? customerCode) { ... }
Argument Purpose
Name / Description Tool name and description; defaults to the method name and its [Description]
PermissionPath Maps to SysMenu.Path, may contain {parameter} placeholders resolved from call arguments; checked with read-only AdminContext.HasPath
PermissionButton Button code under that menu (add/edit/remove); only applies when PermissionPath is set
RequiresConfirmation Set true for write operations; a confirmation card appears first (every time / deletes only / never)

Tool classes must be registered as Scoped in DI. There are two registration paths, merged and de-duplicated in AiToolRegistry:

  1. Direct from the host: AddEasyAdminBlazorAI(opt => opt.AddTool<MyTools>())
  2. From a business extension: implement the core package's IAiToolProvider.GetAiToolTypes() — extensions do not reference each other

Other conventions:

  • [Required] on a parameter is the only way to express "business required" (the official factory infers required only from default values); [AiToolInput] controls the confirmation-card control (dictionary / date / enum dropdown).
  • Return objects or lists directly. The registration layer serializes them once — do not call JsonSerializer.Serialize yourself (the default encoder turns Chinese into \uXXXX and inflates tokens).
  • Failed tool executions are recorded as "error memory"; later conversations warn the model not to repeat the mistake. This is global and has no management page.
  • Server-side business logic must still check permissions — PermissionPath only decides whether the model can see and call the tool.

Token Quota

This is the easiest part to misread. In short: the framework does not enforce any quota — it only rate-limits per user per minute; whether to allow a call and whether the allowance is enough are entirely decided by the host via IAiAccessGuard. IAiQuotaSource is merely the host-provided "total granted Tokens" source; the framework does not use it to gate calls, only to show the remaining quota on the chat page.

Where the total allowance comes from

The framework knows nothing about orders, so it defines IAiQuotaSource:

public interface IAiQuotaSource
{
    Task<long> GetTotalGrantedAsync(string tenant, CancellationToken ct = default);
}

The host implements it and returns the tenant's cumulative granted / purchased Tokens (only paid, fulfilled records). For example, FMS sums the Quantity of paid pay_feature_order rows of kind GiftToken (granted at tenant provisioning) and BuyTokenPack (top-up packs); pending, closed and refunded orders do not count.

In the framework, IAiQuotaSource is only used to display "Remaining: N tokens" on the chat page: Chat.razor reads the total and subtracts the accumulated TotalToken of successful ai_call_log rows. It is display-only — failures are logged without blocking the conversation, and nothing is shown when no source is registered. The real allow/deny decision lives in the host's IAiAccessGuard, where the host can read the same source plus the call log to evaluate quota.

AiOptions.FreeTokenGrant / QuotaExhaustedHint are deployment knobs for the host business layer to read: the former is read once when the host creates a grant record, the latter is the message shown when the quota is exhausted. The framework itself never uses them to evaluate quota.

Unlimited quota / monolithic projects

A monolithic project (no multi-tenant extension) needs no quota-table configuration at all — without a host IAiAccessGuard implementation, calls are allowed by default and are only subject to RateLimitPerMinute. To lift the rate limit as well, set AiOptions.RateLimitPerMinute to 0 (default 60). To enforce business rules, implement IAiAccessGuard in the host; no framework-side change is needed.

How usage is counted

Every successful call writes an ai_call_log row (Status = Success, TotalToken recorded) in the current tenant data source — a dedicated database in dedicated mode, or shared-database tables filtered by TenantCode in shared mode. Both the host guard and the chat page's remaining-quota display read it using the "total − cumulative usage" convention; the framework itself never blocks calls based on it.

  • Separate-database mode: tenants are physically separated; callLogRepo points at the current tenant database and no TenantCode column filter is added (legacy convention, so historical rows with a different tag are not silently missed).
  • Shared-database mode: AiCallLog implements ITenantEntity and the ORM has a TenantCode global filter, so the same query is isolated automatically.

AiUsage.From is the single source of truth for metering and costing. Cached input Tokens are part of input; reasoning Tokens are part of output. They are "split out of the parent for a different price", never added on top:

cost = (input−cached)/1e6 × input price + cached/1e6 × cached price
     + (output−reasoning)/1e6 × output price + reasoning/1e6 × (reasoning price ?? output price)

What the framework checks before a call

The framework does only two things before every AI call (AiChatService.EnsureRateAndAccessAsync):

  1. Rate limit RateLimitPerMinute: an in-process sliding window, the per-user calls-per-minute cap; 0 means unlimited. This is the framework's only restriction.
  2. Business allow/deny IAiAccessGuard: the framework gets GetServices<IAiAccessGuard>() and requires all to allow — any one returning false throws AiAccessDeniedException. The default implementation NullAiAccessGuard always allows, so without a host implementation calls are only subject to the rate limit.

The framework knows nothing about plans, orders or Token packs, and ships with no quota table or atomic reservation. The quota and entitlement convention is entirely up to the host's IAiAccessGuard (e.g. role permissions + tenant entitlement + granted Tokens from orders − usage in ai_call_log). Host/platform accounts should always return true.

The call chain

EnsureRateAndAccessAsync
  ├─ AiRateLimiter.TryAcquireAsync   rate (in-process sliding window, framework's only restriction)
  └─ IAiAccessGuard.CanUseAiAsync    business allow/deny (host implementation; default NullAiAccessGuard always allows)
AiCallRecorder.BeginAsync           insert placeholder call log
Model call (possibly multiple tool round-trips)
AiCallRecorder.CompleteAsync        fill in Tokens / cost / status / duration

The framework has no quota gate and no reservation/settlement step; IAiQuotaSource is only read when the chat page refreshes the "remaining quota" display. Once the host registers an IAiAccessGuard, the framework's default implementation still participates but always allows — requiring "all to allow" guarantees a host denial cannot be overridden, regardless of registration order.

Wiring in your own orders

// Program.cs — the quota source only feeds the display; the real allow/deny decision is in the guard
builder.Services.AddScoped<IAiQuotaSource, OrderQuotaSource>();
builder.Services.AddScoped<IAiAccessGuard, MyAccessGuard>();

// IAiQuotaSource: sum your own paid orders
public sealed class OrderQuotaSource(IBaseRepository<FeatureOrder> orders) : IAiQuotaSource
{
    public Task<long> GetTotalGrantedAsync(string tenant, CancellationToken ct = default)
        => orders.Select
            .Where(o => o.TenantCode == tenant && o.Status == OrderStatus.Paid)
            .SumAsync(o => o.Quantity, ct);
}

// IAiAccessGuard: the host does its own quota check (illustrative: granted − used)
public sealed class MyAccessGuard(IAiQuotaSource source, IBaseRepository<AiCallLog> logs, AdminContext admin)
    : IAiAccessGuard
{
    public async Task<bool> CanUseAiAsync(CancellationToken ct = default)
    {
        var tenant = admin.TenantCode;
        var granted = await source.GetTotalGrantedAsync(tenant, ct);
        var used = (long)await logs.Select.Where(l => l.Status == AiCallStatus.Success)
                                         .SumAsync(l => l.TotalToken, ct);
        return granted > used;
    }
}

Registering only IAiQuotaSource never blocks a call — it only feeds the remaining-quota display on the chat page. To actually enforce a quota you must implement IAiAccessGuard.

Configuration: AiOptions

Setting Default Description
Enabled true Master switch
RequestTimeoutSeconds 120 Per-request model timeout; each tool round-trip has its own timer
TurnTimeoutSeconds 600 Whole-turn timeout, also the HTTP timeout sent to the vendor
ToolIterationsPerTurn 8 Max tool round-trips per turn; when reached, the user is asked to restate and continue
RateLimitPerMinute 60 Per-user calls per minute; 0 = unlimited
FreeTokenGrant 0 Grant allowance; read once when the host creates a grant record; the framework never uses it to evaluate quota
QuotaExhaustedHint Chinese hint Message when exhausted; {0} is replaced with used Tokens. The framework cannot know whether to suggest a top-up or an admin, so the host configures it
DefaultScene chat Default scene code
InjectUserIdentity true Append user identity to the system prompt; not a permission boundary
OnDemandTools true On-demand tools: attach only the search_tools / invoke_tool meta-tools; the model pulls schemas as needed
AllowPrivateModelEndpoints false Allow model endpoints on localhost / private networks. Do not enable in multi-tenant SaaS — tenant admins could use the server as an internal-network jump host; enable explicitly for self-hosted Ollama

These are deployment/development knobs and are not exposed in the customer-facing parameter page. Customers maintain model connections in the admin panel; quota and order/grant records are the host business layer's responsibility.

Tables

Table Location Purpose
ai_model main DB Model endpoints, scenes, pricing, capability flags
ai_call_log tenant DB Tokens, cost, status and duration of each model call
ai_conversation / ai_message tenant DB Conversation and message history
ai_attachment tenant DB Images and other attachments, private upload + controlled viewing
ai_tool_call_log tenant DB Tool calls and rejections
ai_tool_lesson tenant DB Error memory from failed tool calls

"Tenant DB" in this table means the shared-database rows filtered by TenantCode when shared mode is used, not a separate physical database.

Caveats

  • Quota / entitlement checks are the host's responsibility. The framework only rate-limits; to block by tenant entitlement or quota you must implement IAiAccessGuard, otherwise callers are only subject to the rate limit.
  • Do not add a tenant column filter to ai_call_log queries. Separate databases isolate by database and shared databases use a global filter; a column filter misses historical rows with a different tag and undercounts usage.
  • Tool permission means "can see", not "can do". PermissionPath only controls what the model can discover; server-side business logic must check again.
  • Always set RequiresConfirmation = true for write operations, otherwise the model can change data without the user noticing.
  • A blank API key keeps the old value, it does not clear it.
  • In single-file publishing, static asset versioning falls back to the assembly ManifestModuleId; an empty Assembly.Location will not break page rendering.