AiTokenTracker 0.4.2

dotnet add package AiTokenTracker --version 0.4.2
                    
NuGet\Install-Package AiTokenTracker -Version 0.4.2
                    
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="AiTokenTracker" Version="0.4.2" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="AiTokenTracker" Version="0.4.2" />
                    
Directory.Packages.props
<PackageReference Include="AiTokenTracker" />
                    
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 AiTokenTracker --version 0.4.2
                    
#r "nuget: AiTokenTracker, 0.4.2"
                    
#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 AiTokenTracker@0.4.2
                    
#: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=AiTokenTracker&version=0.4.2
                    
Install as a Cake Addin
#tool nuget:?package=AiTokenTracker&version=0.4.2
                    
Install as a Cake Tool

AiTokenTracker .NET SDK

AiTokenTracker captures outbound LLM traffic and sends it to your ingest API for centralized token/cost parsing.

This SDK supports two integration paths so teams can adopt with minimal refactoring:

  1. HttpClient Handler Integration (preferred)
    • Use .AddAiTokenTracker() on IHttpClientFactory clients.
    • Captures full request/response envelopes.
  2. SDK Wrapper Integration
    • Use IAiTokenTrackerSdkClient when provider SDK calls bypass your HttpClient pipeline.
    • Captures full request/response payloads from DTOs.

Installation

dotnet add package AiTokenTracker --version <latest>

Quick Start

Register once in DI:

using AiTokenTracker;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddAiTokenTracker(options =>
{
    options.AuthToken = "your-subscription-or-api-key";
});

Then for preferred full-fidelity capture on HTTP clients you own:

builder.Services
    .AddHttpClient("OpenAiHttp")
    .AddAiTokenTracker();

Integration Modes

1) HttpClient Handler Integration (Preferred)

Best when your outbound LLM calls go through IHttpClientFactory.

builder.Services.AddHttpClient("LlmClient")
    .AddAiTokenTracker();

Any classified LLM request sent by this client is captured with full body.

Scoped Custom Filters For Automatic Capture

You can attach custom filters to automatic handler capture by opening an interception scope in the current async flow:

var scope = AiTokenTrackerInterceptionScope.Create(new Dictionary<string, string>
{
    ["Workflow"] = "AutoPublish",
    ["JobId"] = "job-42"
});

try
{
    using HttpClient llmClient = httpClientFactory.CreateClient("LlmClient");
    using HttpResponseMessage response = await llmClient.PostAsync("/v1/responses", content, cancellationToken);
}
finally
{
    scope.Close();
}

You can also use using:

using var scope = AiTokenTrackerInterceptionScope.Create(new Dictionary<string, string>
{
    ["Workflow"] = "AutoPublish"
});
await llmClient.PostAsync("/v1/responses", content, cancellationToken);

Use one scope per logical request/workflow. Create(...) opens the scope automatically.

2) SDK Wrapper Integration (For SDKs that bypass HttpClientFactory)

If a provider SDK hides transport internals, wrap calls with IAiTokenTrackerSdkClient. providerHint is optional and should be passed when known.

public sealed class TrackedOpenAiClient
{
    private readonly OpenAIClient _inner;
    private readonly IAiTokenTrackerSdkClient _tracker;

    public TrackedOpenAiClient(OpenAIClient inner, IAiTokenTrackerSdkClient tracker)
    {
        _inner = inner;
        _tracker = tracker;
    }

    public async Task<Response> CreateResponseAsync(string model, string userPrompt, CancellationToken cancellationToken)
    {
        var responseClient = _inner.GetOpenAIResponseClient(model);

        var requestPayload = new
        {
            userInputText = userPrompt
        };

        IAiTokenTrackerCallScope scope = _tracker.BeginLlmCall(
            request: requestPayload,
            providerHint: "openai");

        try
        {
            var response = await responseClient.CreateResponseAsync(userPrompt, cancellationToken: cancellationToken);
            _ = scope.CompleteAsync(response.Value, 200, cancellationToken: CancellationToken.None);
            return response.Value;
        }
        catch (Exception ex)
        {
            _ = scope.FailAsync(ex, cancellationToken: CancellationToken.None);
            throw;
        }
    }
}

This pattern guarantees capture even when provider SDKs do not run through your tracked HttpClient handlers.

Services Registered

AddAiTokenTracker(...) registers:

  • AiTokenTrackerDelegatingHandler
  • IAiTokenTrackerIngestionClient
  • IAiTokenTrackerSdkClient
  • ILlmRequestClassifier default implementation (DefaultLlmRequestClassifier)
  • Named ingest client: AiTokenTracker.IngestionClient

Configuration

AiTokenTrackerOptions:

  • AuthToken (string, required)

Custom Provider Classification

The SDK includes DefaultLlmRequestClassifier heuristics (OpenAI/Anthropic/Gemini/Unify/common paths).

To customize, implement ILlmRequestClassifier:

public interface ILlmRequestClassifier
{
    bool TryClassify(HttpRequestMessage request, out string? providerHint);
}

Register your classifier in DI. It will run alongside defaults.


Choosing a Strategy

Use this guideline:

  • If call path uses HttpClientFactory: use Handler Integration.
  • If call path uses provider SDK abstraction: use Wrapper Integration.

Recommended rollout for large codebases:

  1. Enable SDK globally.
  2. Add .AddAiTokenTracker() to known LLM HttpClient registrations.
  3. Add wrapper integration only at central SDK service boundaries.

Troubleshooting

No ingest events received

Check:

  1. AuthToken is configured and non-empty.
  2. Request is classified as LLM traffic.
  3. If using provider SDKs, confirm wrapper integration is applied where the call is made.

Calls are visible but token fields are zero

That usually means payload shape was not full-fidelity or not parseable by server analyzers. Ensure handler/wrapper path is providing request/response bodies.

Duplicate events

If both handler and wrapper are applied to the exact same call path, you can ingest duplicates. Use one primary integration path per call flow.


Notes

  • The SDK intentionally sends envelopes asynchronously to avoid blocking LLM call latency.
Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  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
0.4.2 212 6/11/2026
0.4.0 123 5/27/2026
0.3.9 137 5/20/2026
0.3.8 138 5/20/2026
0.3.7 135 5/20/2026
0.3.6 134 5/20/2026
0.3.5 132 5/12/2026
0.3.4 137 5/12/2026
0.3.3 138 5/12/2026
0.2.0 142 3/24/2026
0.1.0 145 3/24/2026