D4S.AgentMetrics 1.0.0

dotnet add package D4S.AgentMetrics --version 1.0.0
                    
NuGet\Install-Package D4S.AgentMetrics -Version 1.0.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="D4S.AgentMetrics" Version="1.0.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="D4S.AgentMetrics" Version="1.0.0" />
                    
Directory.Packages.props
<PackageReference Include="D4S.AgentMetrics" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add D4S.AgentMetrics --version 1.0.0
                    
#r "nuget: D4S.AgentMetrics, 1.0.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package D4S.AgentMetrics@1.0.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=D4S.AgentMetrics&version=1.0.0
                    
Install as a Cake Addin
#tool nuget:?package=D4S.AgentMetrics&version=1.0.0
                    
Install as a Cake Tool

D4S.AgentMetrics

Internal NuGet package for Dev4Side AI agents built on .NET 10.

It handles, transparently:

  • Handshake — verifies at startup that the agent is registered and active in the D4S back-end.
  • Metric definition registration — sends all metric descriptors (default + custom) to the back-end.
  • Business metric tracking — exposes IMetricWriter.TrackAsync with an in-memory queue.
  • Periodic flush — drains the queue and POSTs the event batch to the back-end.
  • Heartbeat — sends periodic liveness pings to the back-end.

Internal use only. This package is not intended for public distribution.


Prerequisites

The agent must already be registered in the D4S back-end before starting.
Agent creation is handled manually or via the marketplace onboarding process — this package only verifies that the registration exists.
If the agent is missing or inactive the handshake fails and the application will not start.


Installation

dotnet add package D4S.AgentMetrics

Quick start

// Program.cs — minimal required configuration
builder.Services.AddAgentMetrics(options =>
{
    options.AgentId   = "my-agent";
    options.DisplayName = "My Agent";
    options.TenantId  = configuration["Metrics:TenantId"];
    options.BaseUrl   = configuration["Metrics:BaseUrl"];
    options.D4SApiUrl = configuration["Metrics:D4SApiUrl"];
    options.D4SApiKey = configuration["Metrics:D4SApiKey"];
});

// Add the automatic request-tracking middleware
app.UseAgentMetricsTracking();

Configuration

Option Type Default Description
AgentId string — (required) Unique agent identifier as registered in the D4S back-end.
DisplayName string — (required) Human-readable agent name shown in the dashboard.
TenantId string — (required) Tenant that owns this agent.
BaseUrl string — (required) Public URL of the agent itself.
D4SApiUrl string — (required) Base URL of the central D4S back-end.
D4SApiKey string — (required) API key sent as X-Api-Key on every back-end call.
FlushInterval TimeSpan 00:00:10 How often the metric queue is flushed.
HeartbeatInterval TimeSpan 00:02:00 How often a heartbeat ping is sent.

Default profile metrics

These eight metrics are always included automatically — no extra code required.
UseProfile(AgentProfile.Default) is optional but recommended for clarity.

Key Label Aggregation Tracked by
total_interactions Interazioni totali Count Middleware (automatic)
avg_response_time_ms Tempo medio risposta (ms) Average Middleware (automatic)
error_rate Tasso di errore Percentage Middleware (automatic, HTTP 5xx)
prompt_tokens_total Token prompt totali Sum ITrackedChatClient (automatic)
completion_tokens_total Token completion totali Sum ITrackedChatClient (automatic)
total_tokens_total Token totali Sum ITrackedChatClient (automatic)
avg_tokens_per_interaction Token medi per interazione Average ITrackedChatClient (automatic)
avg_confidence_score Confidence medio Average Manual (TrackAsync)

Tracking custom metrics

// Register custom metrics in AddAgentMetrics:
options.AddRanking("top_exams", "Esami più richiesti", dimensionName: "exam_name", topN: 5);
options.AddScalar("avg_confidence_score", "Confidence medio", aggregate: AggregationType.Average);

// Then inject IMetricWriter wherever you need it:
public class MyService
{
    private readonly IMetricWriter _metrics;
    public MyService(IMetricWriter metrics) => _metrics = metrics;

    public async Task HandleAsync(string examName, double confidence)
    {
        // Pure count (value = null)
        await _metrics.TrackAsync("total_interactions");

        // Ranking: increment counter for a dimension value
        await _metrics.TrackAsync("top_exams", dimension: examName);

        // Scalar with a numeric value
        await _metrics.TrackAsync("avg_confidence_score", value: (decimal)confidence);
    }
}

AI token tracking

Wrap your Azure AI Foundry ChatCompletionsClient to record token usage automatically:

// Registration
builder.Services.AddTrackedChatClient(
    new ChatCompletionsClient(endpoint, new AzureKeyCredential(apiKey)),
    model: "gpt-4o");

// Usage — tokens are tracked on every successful call
public class MyAiService
{
    private readonly ITrackedChatClient _ai;
    public MyAiService(ITrackedChatClient ai) => _ai = ai;

    public async Task<string> AnswerAsync(string question)
    {
        var result = await _ai.CompleteAsync(question);
        return result.Choices[0].Message.Content;
    }
}

Development order

For contributors, the recommended implementation sequence is:

  1. Models & contracts (MetricType, AggregationType, MetricDescriptor, IMetricWriter, ITrackedChatClient)
  2. Configuration (AgentMetricsOptions, AgentProfile)
  3. Default profile (DefaultAgentProfile)
  4. D4SApiClient — HTTP wrapper for all back-end calls
  5. AgentHandshakeService — startup verification
  6. MetricWriter — in-memory queue implementation
  7. MetricFlushService — periodic flush background service
  8. MetricHeartbeatService — periodic heartbeat background service
  9. MetricTrackingMiddleware — automatic HTTP request tracking
  10. TrackedChatClient — Azure AI Foundry token-usage wrapper
  11. ServiceCollectionExtensions — wires everything together

Internal use notice

This package is developed and maintained by Dev4Side for internal use only.
It is not published on NuGet.org and is not intended for external consumption.

Product Compatible and additional computed target framework versions.
.NET net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.0.0 57 6/8/2026