Meters AI usage in CrestApps.Core 2.0: tracks tokens, audio, images, and costs per provider request. Use when pricing, attributing, or debugging AI usage records.
Ships in crestapps-core. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
Every client IAIClientFactory returns meters its own requests by wrapping the provider's client and reading the provider-agnostic UsageDetails on each response. That covers every provider, including custom IAIClientProvider implementations, with no provider code.
services.AddCoreAIUsageTracking() or .AddUsageTracking() on the AI suite builder. Without it, and without an IAICompletionUsageObserver of your own, nothing is metered and IAICompletionUsageService is not registered.UseFunctionInvocation() yields one record per round trip and a cached response yields none.UseUsageLabels(...) on the client pipeline, or an AIUsageScope around a call into a service that creates the client for you. Labels never reach the provider.AIUsageMetering.Meter(...).using CrestApps.Core.AI;
builder.Services.AddCoreAIUsageTracking();
// or, on the AI suite builder
builder.Services.AddCrestAppsCore(crestApps => crestApps
.AddAISuite(ai => ai.AddUsageTracking()));
Metering follows registration: a client is wrapped only when an IAICompletionUsageObserver is registered (checked through IServiceProviderIsService, so nothing is constructed to find out). AddCoreAIUsageTracking() registers the default IAICompletionUsageService, which is itself an observer. A host can register its own observer instead of, or alongside, it.
Each record goes to every registered IAICompletionUsageObserver. The default IAICompletionUsageService saves through IAICompletionUsageStore. The YesSql chat-session stores (AddCoreAIChatSessionStoresYesSql(), which calls AddCoreAICompletionUsageStoresYesSql()) and the EntityCore chat-session stores (AddCoreAIChatSessionStoresEntityCore()) register a store. A record whose scope was already disposed when the response finished is dropped rather than failing the answer. The YesSql and EntityCore usage stores write and commit each record at once in their own session or context (bounded to 30 seconds), so a record never opens a transaction the caller then holds across its next model call, and it is kept when the caller's work rolls back.
During a text turn of AIChatHubCore (SendMessage, RunAgent, the AG-UI endpoint), DefaultAICompletionUsageService gives each call's tokens to AIChatSessionTokenUsageCollector.Current instead of updating the session metrics after every call; the hub adds them once when the turn ends, completed, failed or stopped. Voice, realtime and background calls update the metrics as before.
| Property | Meaning |
|---|---|
OperationType | AIUsageOperationTypes.Chat, Embedding, Image, SpeechToText, TextToSpeech, Realtime or RealtimeTranscription |
ClientName, ConnectionName, DeploymentName, ModelName | Where the request went; ModelName is what the provider reported, else the deployment |
InputTokenCount, OutputTokenCount, TotalTokenCount | Tokens in and out |
CachedInputTokenCount, ReasoningTokenCount | Discounted cached input; reasoning output tokens |
InputAudioTokenCount, OutputAudioTokenCount | Audio tokens, billed at their own rate |
CacheWriteInputTokenCount, CachedInputAudioTokenCount | Tokens written to the prompt cache (Anthropic bills a premium); cached audio input |
InputImageTokenCount, OutputImageTokenCount | Image tokens in and out |
AcceptedPredictionTokenCount, RejectedPredictionTokenCount | Predicted-output tokens; rejected ones are still billed |
WebSearchCount, WebFetchCount | Server-side web searches and fetches |
AdditionalCounts | Any other count the provider reported, by its own name |
AudioDurationMs, CharacterCount, ImageCount | Duration-, character- and image-billed units; AudioDurationMs also holds generated TTS length when known |
AudioStartMs, AudioInputBytes, AudioOutputBytes, SegmentCount | Start of recognized speech, audio sizes, transcription segments |
AudioSampleRate, AudioFormat, VoiceId, Language, TargetLanguage, Speed, Pitch | What an STT or TTS request asked for |
ContextType, Purpose | Category of feature and reason for the request |
SessionId, ProfileId, InteractionId, UserId, VisitorId, ResponseLatencyMs, IsStreaming | Attribution and timing |
Input and output token counts include the cached, cache-write, audio and image tokens; those fields say how many were of each kind. A provider that measures a non-token unit better reports it in UsageDetails.AdditionalCounts under AIUsageAdditionalCounts.AudioDurationMs, CharacterCount or ImageCount. The adapters' own names are read too: Anthropic's CacheCreationInputTokens, WebSearchRequests and WebFetchRequests, and OpenAI's audio, image and predicted-output token details. A TTS model that reports only tokens has its output tokens recorded as audio output tokens, and an image model's as image output tokens.
ContextType is the feature category (AIChatSession and ChatInteraction for the built-in chats; any other feature names its own). Purpose is why the request was made. The framework uses AIUsagePurposes: Conversation, Planning, SearchQueryGeneration, Retrieval, Indexing, TitleGeneration, SubAgent, TabularProcessing, DataExtraction, PostSessionProcessing, ImageAnalysis, DocumentAnalysis, ImageGeneration, ChartGeneration, MetadataExtraction, Transcription, SpeechSynthesis, VoiceConversation, Guardrail, PersonalDataRedaction, ConversationSummarization.
When your code creates the client:
using CrestApps.Core.AI.Completions; // UseUsageLabels
using CrestApps.Core.AI.Resilience; // UseDefaultResilience
var chatClient = await clientFactory.CreateChatClientAsync(deployment, builder => builder
.UseDefaultResilience()
.UseUsageLabels(contextType: "Leads", purpose: "LeadScoring"));
UseUsageLabels exists on the chat, embedding, image, speech-to-text, text-to-speech and realtime builders. CreateRealtimeClientAsync takes no pipeline callback, so build on the returned client:
var realtimeClient = (await clientFactory.CreateRealtimeClientAsync(deployment))
.AsBuilder()
.UseUsageLabels(contextType: "Support", purpose: AIUsagePurposes.VoiceConversation)
.Build();
When a service creates the client for you, wrap the call in a scope:
using CrestApps.Core.AI.Completions;
using var usageScope = AIUsageScope.Begin(contextType: "Leads", purpose: "LeadScoring");
var response = await completionService.CompleteAsync(deployment, messages, context, cancellationToken);
Scopes nest and a null label inherits from the enclosing scope. A scope flows with the async context, so it does not reliably survive yield return inside an async iterator; label streaming code with UseUsageLabels or per-request keys instead.
A single request can carry labels in ChatOptions.AdditionalProperties or AICompletionContext.AdditionalProperties under AICompletionContextKeys.UsageContextType and UsagePurpose. Resolution order: the request's value, the client's UseUsageLabels, the current AIUsageScope, the request's AICompletionContextKeys.DefaultUsagePurpose, then the chat session or interaction category.
Wrap the provider client before adding any middleware, so every round trip is recorded:
using CrestApps.Core.AI.Completions;
using CrestApps.Core.AI.Services;
using Microsoft.Extensions.AI;
IChatClient metered = AIUsageMetering.Meter(
providerClient,
clientName: "MyProvider",
connectionName: null,
deploymentName: "model-id",
serviceProvider,
defaultPurpose: AIUsagePurposes.Conversation);
var client = new ChatClientBuilder(metered)
.UseFunctionInvocation()
.Build(serviceProvider);
AIUsageMetering.Meter has overloads for IChatClient and IEmbeddingGenerator<string, Embedding<float>>. The Claude orchestrator uses it for its Anthropic client. The Copilot orchestrator's SDK-managed requests are not metered.
using CrestApps.Core.AI.Completions;
using CrestApps.Core.AI.Models;
using Microsoft.Extensions.Logging;
public sealed class UsageBudgetObserver : IAICompletionUsageObserver
{
private readonly ILogger<UsageBudgetObserver> _logger;
public UsageBudgetObserver(ILogger<UsageBudgetObserver> logger)
{
_logger = logger;
}
public Task UsageRecordedAsync(AICompletionUsageRecord record, CancellationToken cancellationToken = default)
{
if (record.TotalTokenCount > 50_000)
{
_logger.LogWarning(
"Large {OperationType} request on {Deployment} for {Purpose}: {Tokens} tokens.",
record.OperationType,
record.DeploymentName,
record.Purpose,
record.TotalTokenCount);
}
return Task.CompletedTask;
}
}
builder.Services.AddScoped<IAICompletionUsageObserver, UsageBudgetObserver>();
Keep observers fast and non-throwing; they run as each response finishes.
AddCoreAIUsageTracking() also registers an observer that emits each record as OpenTelemetry metrics on the CrestApps.Core meter, for every client kind:
| Instrument | Tags |
|---|---|
crestapps.core.ai.usage.requests | operation, client, deployment, purpose, streaming |
crestapps.core.ai.usage.tokens | The same, plus token.type: input, output, cached, reasoning or audio |
crestapps.core.ai.usage.duration | The same as requests; the response latency in seconds |
input and output already include the cached, reasoning and audio tokens. A total is input plus output; never add up every token.type.EnableOpenTelemetry is on, gen_ai.client.token.usage counts the same chat tokens again. Chart one of the two, never their sum: the usage metrics cover every client kind and carry the purpose, and gen_ai.client.token.usage follows the OpenTelemetry conventions that other tools read.AddCoreAIUsageTracking(), gets no usage metrics.See crestapps-core-observability for collecting them.
using CrestApps.Core.AI.Completions;
using CrestApps.Core.AI.Services;
var records = await usageService.GetAsync(startUtc, endUtc, cancellationToken);
var perModel = AIUsageReport.Build(records, AIUsageReportGrouping.Model);
var perPurpose = AIUsageReport.Build(records, AIUsageReportGrouping.ModelAndPurpose);
var perCategory = AIUsageReport.Build(records, AIUsageReportGrouping.ModelAndCategory);
Every grouping keeps client, model and operation type apart because each combination is priced separately. AIUsageReportRow sums RequestCount, every token, web search, audio, character and image total and AdditionalCounts, and reports AverageResponseLatencyMs. Records written before 2.0 have no operation type and report as chat requests.
AIAudioUsageReport.Build reports speech-to-text and text-to-speech requests only:
var perModel = AIAudioUsageReport.Build(records, AIAudioUsageReportGrouping.Model);
var perVoice = AIAudioUsageReport.Build(records, AIAudioUsageReportGrouping.ModelAndVoice);
var perLanguage = AIAudioUsageReport.Build(records, AIAudioUsageReportGrouping.ModelAndLanguage);
AIAudioUsageReportRow exposes AudioHours, AudioDurationMs, SpeechDurationMs, RequestCount, RequestsWithDurationCount, CharacterCount, AudioInputBytes, AudioOutputBytes, SegmentCount and tokens. TTS length is known only when the provider reports it or the audio is WAV, so a row whose RequestsWithDurationCount is below RequestCount is a minimum.
A deployment can carry its own prices in AIDeploymentPricing (Currency, default USD, and Prices). Each AIDeploymentPrice is an Amount for Per base units of one AIUsageMeters meter:
| Meter | Base unit |
|---|---|
InputTokens, CachedInputTokens, CacheWriteInputTokens, OutputTokens | token |
InputAudioTokens, CachedInputAudioTokens, OutputAudioTokens, InputImageTokens, OutputImageTokens | token |
AudioSeconds | second of audio |
Characters, Images, Requests, WebSearches, WebFetches | one each |
AdditionalCount | the provider count named by CountName |
AboveInputTokens makes a long-context price: a request with more input tokens pays it instead of the lower tier.Increment rounds each request's quantity up, such as 15 for audio billed in 15-second steps.using CrestApps.Core.AI.Completions;
using CrestApps.Core.AI.Models;
deployment.SetPricing("USD",
[
new AIDeploymentPrice { Meter = AIUsageMeters.InputTokens, Amount = 2.5m, Per = 1_000_000 },
new AIDeploymentPrice { Meter = AIUsageMeters.CachedInputTokens, Amount = 1.25m, Per = 1_000_000 },
new AIDeploymentPrice { Meter = AIUsageMeters.OutputTokens, Amount = 10m, Per = 1_000_000 },
]);
var pricing = deployment.GetPricing();
SetPricing drops incomplete prices and removes the pricing when none is left. A configured deployment declares it under Properties:
{
"Name": "gpt-4o",
"Properties": {
"AIDeploymentPricing": {
"Currency": "USD",
"Prices": [
{ "Meter": "InputTokens", "Amount": 2.5, "Per": 1000000 },
{ "Meter": "OutputTokens", "Amount": 10, "Per": 1000000 }
]
}
}
}
Pass pricing to a report and each row gains Currency and EstimatedCost. Requests are priced by DeploymentName; deployments in different currencies, or without a price, land in separate rows:
using CrestApps.Core.AI.Services;
var pricingByDeployment = await deploymentStore.GetPricingByDeploymentAsync(cancellationToken);
var perModel = AIUsageReport.Build(records, AIUsageReportGrouping.Model, pricingByDeployment);
var audio = AIAudioUsageReport.Build(records, AIAudioUsageReportGrouping.Model, pricingByDeployment);
decimal? oneRecord = AIUsageCostEstimator.Estimate(record, AIUsageCostEstimator.GetPricing(pricingByDeployment, record));
decimal? allRecords = AIUsageCostEstimator.Estimate(records, pricingByDeployment);
GetPricingByDeploymentAsync is an IAIDeploymentStore extension declared on AIUsageCostEstimator. To match an actual bill, including discounts and credits, split each meter's billed cost in proportion to the units each group used in the same period; a single blended per-model price misprices groups with a different input and output mix.
AzureOpenAICompletionClient records each tool-calling round trip and keeps cached, reasoning and audio tokens.response.done and on completed input transcriptions, including duration-billed transcription.GeneralAIOptions.EnableAIUsageTracking and GeneralAISettings.EnableAIUsageTracking are [Obsolete] and ignored. Call AddCoreAIUsageTracking() (or .AddUsageTracking()) in any host that had the option on. GeneralAISettings.EnableAIUsageTracking stays readable so a migration can turn a stored true into that registration.AIUsageMetering.Meter returns the client it was given, and IAICompletionUsageService cannot be resolved.YesSqlAICompletionUsageStore passes an IStore, and EntityCoreAICompletionUsageStore an IServiceScopeFactory.AIChatSessionTokenUsageCollector).IAIClientFactory.CreateRealtimeClientAsync returns a metering wrapper. Code that compared the result with a provider instance should call GetService instead.What SKILL.md sets; muted values are Claude Code's defaults
/crestapps-core:crestapps-core-ai-usage-meteringfrom crestapps-core
npx claudepluginhub crestapps/crestapps.agentskills --plugin crestapps-core51 skills in this plugin
/crestapps-core-a2aSkill for Agent-to-Agent (A2A) protocol support in CrestApps.Core on the A2A 1.0 SDK. Covers AddA2AClient and AddCoreAIA2AClient with Entity Framework Core or YesSql connection stores, A2AConnection and A2AConnectionMetadata authentication, AIProfileA2AMetadata, the agent card cache and A2AToolRegistryProvider, the listAvailableAgents, findAgentForTask and findToolsForTask tools, building an A2A host with IAgentHandler, A2AServer, ITaskStore and MapA2A, A2A 1.0 agent cards with supportedInterfaces published at /.well-known/agent-card.json, A2AHostOptions authentication and ExposeAgentsAsSkill, system agents exposed through the host, and upgrading from the 0.3 SDK./crestapps-core-ag-uiSkill for running the CrestApps.Core 2.0 AI chat as an AG-UI agent. Covers the CrestApps.Core.AI.AGUI package (AGUIRunEventWriter, AGUIRunRequest, AGUIJson), AIChatHubCore.RunAgent over SignalR and MapAGUIChat with Server-Sent Events, the RunAgentInput members and streamed events, tool approvals with RequireApproval or an approval tool kind, ApprovalRequiredAIFunction, interrupts and resume, approvals inside agents, page context with crestAppsAGUI.registerContextProvider, shared state with registerStateProvider and update_shared_state, frontend tools, stored tool calls (ChatTurnToolActivity), runs that continue on the next page, AGUIChatOptions.DisconnectedRunTimeout, the protocol and sendPageContext chat options, and the AICompletionContextKeys and ChatResponseHandlerContext members. Use it when showing tool calls in the chat, asking a person before a tool runs, sharing page state with the agent, connecting CopilotKit or another AG-UI client, or troubleshooting approvals and continued runs./crestapps-core-ai-agentsSkill for AI agents in CrestApps.Core 2.0, specialized AIProfile records of type Agent that the primary model invokes as tools. Covers creating agent profiles with AgentMetadata availability (OnDemand or AlwaysAvailable), linking them with AgentInvocationMetadata, how AgentProxyTool runs an agent with tools disabled or through the orchestrator when AllowToolInvocation is set, the AgentInvocationDepth recursion guard, never offering an agent to itself (RunningAgentName), tools of an agent that require an approval and pause the agent, deployment inheritance and the chat slot, code-defined and system agents through IAIProfileProvider including the Tabular Data, PDF, Presentation and Word agents, chat-specific agents that read AIInvocationScope, exposing agents to MCP clients with McpServerOptions Agents and ExposeAllAgents, and SubAgent usage labels. Use it when delegating work to sub-agents, adding a framework-managed agent, publishing an agent over MCP, or troubleshooting an agent the model does not call./crestapps-core-ai-markdownSkill for Markdig-backed Markdown normalization in CrestApps.Core 2.0 AI document, data source and RAG flows. Covers the CrestApps.Core.AI.Markdown package, AddMarkdown on the AI suite builder and AddCoreAIMarkdown on IServiceCollection, MarkdownAITextNormalizer replacing the default IAITextNormalizer, RagTextNormalizer content, chunk and title normalization with HTML stripping and Microsoft.Extensions.DataIngestion.Markdig parsing, the gpt-4o tokenizer chunker with 500 tokens per chunk and 50 tokens of overlap, the plain-text fallback for unsupported inline types, where the normalizer is used (data source indexing, preemptive retrieval, reference titles), and pairing it with document processing. Use it when indexing Markdown-heavy content for retrieval, replacing the text normalizer, or troubleshooting chunk sizes and leftover markup in retrieved text./crestapps-core-ai-memorySkill for AI memory in CrestApps.Core. Covers AddAIMemory, AddCoreAIMemory and AddCoreAIMemoryIndexing, Entity Framework Core and YesSql memory stores, the AIMemory index profile on the Elasticsearch, Azure AI Search and PostgreSQL backends, AIMemoryOptions, the store fallback when no index is usable, background memory indexing, the three kinds of memory (session memory with AIConversationMemory summaries and search_conversation, past conversations with search_past_conversations and list_recent_conversations, durable user memory) switched by MemoryMetadata and ChatInteractionMemoryOptions, preemptive memory retrieval and RunsWhenPreemptiveRagIsDisabled, owner-only chat sessions, the user memory tools, IAIMemorySafetyService validation, and custom IMemoryVectorSearchService implementations./crestapps-core-ai-model-capabilitiesSkill for metadata-driven deployment capabilities in CrestApps.Core 2.0. Covers trained model features such as textGeneration, toolCalling, streaming, reasoning, realtime, textEmbedding, speechToText and textToSpeech, model parameters such as reasoningEffort, declaring them with AIDeploymentMetadata or the Features and Parameters configuration shorthand for Azure App Service settings, registering custom features, parameters and slots with AddAIDeploymentFeature, AddAIDeploymentParameter, AddAIDeploymentSlot and AIDeploymentCapabilityOptions, IAIDeploymentCapabilityService, deployment slots and their resolution chain, AIDeploymentParametersMetadata chat and utility values, IAIDeploymentParameterBinder, UseModelParameters, capability enforcement, the ChatApi Responses routing for reasoning with tools, capability-aware chat UIs, and migrating from AIDeploymentPurpose. Use it when declaring what a model supports, adding a new knob, or fixing stripped tools, missing pickers, or reasoning-effort errors.Other plugins' skills for the same job