跳到正文
DEV Community· Tayyab Hafiz·· 55 分鐘前AI 評分57

如何在 .NET 按 Agent 步驟追蹤 LLM 成本,並避免把價格寫入程式碼

Track LLM cost per agent step in .NET without putting prices in your code

AI 導讀

文章示範如何在 .NET 服務中使用 System.Diagnostics.Metrics、OpenTelemetry 和 Azure Monitor,按 Agent 步驟記錄 LLM token 用量,並在查詢時套用價格估算成本,避免把價格寫入程式碼。

正文

This article was drafted with AI help and reviewed by the author.

The model bill for an agent arrives as one number. It doesn't tell you which step got expensive.

An agent in a .NET service usually makes several model calls per user request. A router. A retrieval rewrite. One or two tool decisions. The final answer. Any one of them can quietly double its prompt after a change, and the monthly total just goes up.

So you want cost per step, per model, per day. And for the outliers, cost per conversation.

This post sets that up with System.Diagnostics.Metrics, OpenTelemetry and Azure Monitor. One design rule runs through it. Record tokens in code. Turn tokens into money at query time.

The C# compiled with TreatWarningsAsErrors against net8.0 and Azure.Monitor.OpenTelemetry.AspNetCore 1.6.0. The two KQL queries passed the Kusto.Language parser against a minimal Application Insights schema. Nothing was run against a live Application Insights resource, and every price below is a placeholder.

Why prices stay out of the code

It's tempting to compute dollars right after the call and emit a cost_usd metric. Three things go wrong.

  1. Prices change. When a provider cuts a price, every historical point you emitted is now wrong, and you can't recompute it.
  2. Discounts are messy. Cached input, batch pricing and different context-length tiers all change the rate. Getting that right in a hot path is fiddly. Getting it right in a query is a table edit.
  3. You lose the raw signal. Tokens are what changed when a prompt grew. Dollars hide whether it was input, output or cache misses.

Tokens are facts. Prices are a lookup. Keep them apart.

Three places for one number

Every model call produces the same usage numbers. They go to three places, each for a different question.

| Signal | Tags or fields | Answers | | --- | --- | --- | | Metrics | step, model, provider | "What did each step cost per day?" | | Span attributes | on the current trace | "Why was this request slow or expensive?" | | One structured log | conversation id, step, model, tokens | "What did this conversation cost? What's p95?" |

The split exists because of cardinality. A metric tagged with a conversation id creates a new time series for every conversation. The .NET OpenTelemetry SDK limits how many tag combinations it keeps per metric, and storage backends charge for series too. Conversation ids belong in logs.

The contract

Your model client, whatever SDK it wraps, returns usage in one shape.

```csharp public sealed record ChatRequest(string ConversationId, string Step, string Prompt);

public sealed record ChatResult( string Text, string Provider, string Model, long InputTokens, long CachedInputTokens, long OutputTokens);

public interface IChatModel { Task<ChatResult> CompleteAsync(ChatRequest request, CancellationToken ct); } ```

InputTokens includes cached tokens. That matches how OpenAI reports input_tokens with a cached_tokens subset. If your provider reports cached tokens separately, add them together in the client before returning.

The metrics

The OpenTelemetry GenAI semantic conventions define token counters for this. They currently name them gen_ai.client.inference.usage.input_tokens, gen_ai.client.inference.usage.output_tokens and gen_ai.client.inference.usage.cache_read.input_tokens, with attributes such as gen_ai.operation.name, gen_ai.provider.name, gen_ai.request.model and gen_ai.token.modality. They're marked as development, and they have changed before. Older material uses a single gen_ai.client.token.usage histogram instead.

Using the current names costs nothing and makes your data line up with libraries that adopt them later.

```csharp using System.Diagnostics; using System.Diagnostics.Metrics;

public sealed class LlmUsageMetrics { public const string MeterName = "Agent.LlmUsage";

// Names follow the OpenTelemetry GenAI token metrics, which are still in development. // Keep them in this one class so a rename is a one-file change. private readonly Counter<long> input; private readonly Counter<long> cachedInput; private readonly Counter<long> _output;

public LlmUsageMetrics(IMeterFactory meterFactory) { var meter = meterFactory.Create(MeterName); input = meter.CreateCounter<long>( "genai.client.inference.usage.inputtokens", "{token}", "Input tokens, including cached tokens"); cachedInput = meter.CreateCounter<long>( "genai.client.inference.usage.cacheread.inputtokens", "{token}", "Input tokens served from the provider cache"); output = meter.CreateCounter<long>( "genai.client.inference.usage.outputtokens", "{token}", "Output tokens"); }

public void Record(string step, ChatResult result) { // Low-cardinality tags only. Never a conversation, user or tenant id. var tags = new TagList { { "genai.operation.name", "chat" }, { "genai.provider.name", result.Provider }, { "genai.request.model", result.Model }, { "genai.token.modality", "text" }, { "app.agent.step", step }, };

// The conventions ask for strictly positive measurements. if (result.InputTokens > 0) input.Add(result.InputTokens, tags); if (result.CachedInputTokens > 0) cachedInput.Add(result.CachedInputTokens, tags); if (result.OutputTokens > 0) _output.Add(result.OutputTokens, tags); } } ```

app.agent.step is our own attribute. Keep its values a small fixed set, like router, rewrite, tool_select and answer. Never put free text in it.

IMeterFactory comes from DI in .NET 8 and plays well with testing. The meter name must match what you register with OpenTelemetry, which is why it's a constant.

The decorator

Wrap the real client so no call site can forget to record.

```csharp using System.Diagnostics;

public sealed partial class InstrumentedChatModel : IChatModel { private readonly IChatModel inner; private readonly LlmUsageMetrics metrics; private readonly ILogger<InstrumentedChatModel> _logger;

public InstrumentedChatModel( IChatModel inner, LlmUsageMetrics metrics, ILogger<InstrumentedChatModel> logger) { inner = inner; metrics = metrics; _logger = logger; }

public async Task<ChatResult> CompleteAsync(ChatRequest request, CancellationToken ct) { var result = await _inner.CompleteAsync(request, ct);

// 1. Aggregates by step and model, cheap to keep for months. _metrics.Record(request.Step, result);

// 2. The current span, so a slow or costly request shows its tokens in the trace. Activity.Current?.SetTag("genai.usage.inputtokens", result.InputTokens); Activity.Current?.SetTag("genai.usage.outputtokens", result.OutputTokens);

// 3. One structured log per call. This is where the conversation id lives. LogUsage( request.ConversationId, request.Step, result.Model, result.InputTokens, result.CachedInputTokens, result.OutputTokens);

return result; }

[LoggerMessage( EventId = 4100, Level = LogLevel.Information, Message = "LLM usage {ConversationId} {Step} {Model} in={InputTokens} cached={CachedInputTokens} out={OutputTokens}")] private partial void LogUsage( string conversationId, string step, string model, long inputTokens, long cachedInputTokens, long outputTokens); } ```

The LoggerMessage source generator keeps the log cheap and gives each parameter a stable name. Those names become the field names you'll query.

The span tags use the gen_ai.usage.* attribute names from the same conventions. In Application Insights they show up on the dependency or request that was active at the time, which is handy when someone asks why one request took 40 seconds.

Wiring

```csharp using Azure.Monitor.OpenTelemetry.AspNetCore; using OpenTelemetry.Metrics;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddOpenTelemetry() .UseAzureMonitor() .WithMetrics(metrics => metrics.AddMeter(LlmUsageMetrics.MeterName));

builder.Services.AddSingleton<LlmUsageMetrics>(); builder.Services.AddSingleton<ProviderChatModel>(); builder.Services.AddSingleton<IChatModel>(sp => new InstrumentedChatModel( sp.GetRequiredService<ProviderChatModel>(), sp.GetRequiredService<LlmUsageMetrics>(), sp.GetRequiredService<ILogger<InstrumentedChatModel>>()));

var app = builder.Build(); app.Run(); ```

The Azure Monitor distro picks up the connection string from APPLICATIONINSIGHTS_CONNECTION_STRING. In AKS that's an environment variable on the deployment, ideally fed from a secret store, not baked into the image.

Daily cost by step, in KQL

Application Insights stores OpenTelemetry metrics in the customMetrics table. Attributes land in customDimensions. For counters the useful column is valueSum.

``kusto // Example prices in USD per 1M tokens. Not real rates. Copy yours from the provider. let prices = datatable(model: string, inputPerM: real, cachedPerM: real, outputPerM: real) [ "example-small", 0.10, 0.01, 0.40, "example-large", 2.00, 0.20, 8.00 ]; customMetrics | where timestamp > ago(30d) | where name startswith "gen_ai.client.inference.usage." | extend model = tostring(customDimensions["gen_ai.request.model"]), step = tostring(customDimensions["app.agent.step"]) | summarize input = sumif(valueSum, name == "gen_ai.client.inference.usage.input_tokens"), cached = sumif(valueSum, name == "gen_ai.client.inference.usage.cache_read.input_tokens"), output = sumif(valueSum, name == "gen_ai.client.inference.usage.output_tokens") by day = bin(timestamp, 1d), step, model | join kind=leftouter prices on model | extend estCostUsd = ((input - cached) * inputPerM + cached * cachedPerM + output * outputPerM) / 1e6 | project day, step, model, input, cached, output, estCostUsd | order by day desc, estCostUsd desc ``

The price table lives in the query. When prices change, you edit the table and the whole history recomputes. You can also move it into a Log Analytics function or an external table so dashboards and alerts share one copy.

The leftouter join is deliberate. A model that isn't in the price table shows an empty cost instead of disappearing. That's the row you want to notice after someone switches models.

Before trusting the query, run customMetrics | where name startswith "gen_ai" | take 10 and check the dimension names in your workspace match.

Cost per conversation, and the sampling trap

``kusto let prices = datatable(model: string, inputPerM: real, cachedPerM: real, outputPerM: real) [ "example-small", 0.10, 0.01, 0.40, "example-large", 2.00, 0.20, 8.00 ]; traces | where timestamp > ago(1d) | extend conversationId = tostring(customDimensions["ConversationId"]), model = tostring(customDimensions["Model"]), input = tolong(customDimensions["InputTokens"]), cached = tolong(customDimensions["CachedInputTokens"]), output = tolong(customDimensions["OutputTokens"]) | where isnotempty(conversationId) and isnotnull(input) | join kind=leftouter prices on model | extend costUsd = ((input - cached) * inputPerM + cached * cachedPerM + output * outputPerM) / 1e6 | summarize calls = count(), costUsd = sum(costUsd) by conversationId | summarize conversations = count(), p50 = percentile(costUsd, 50), p95 = percentile(costUsd, 95), worst = max(costUsd) ``

This reads the structured usage logs from the traces table and gives you the distribution across conversations. Alert on p95 or on the worst conversation, not only on the daily total. A runaway loop in one conversation can hide inside a normal-looking day.

There's a catch, and it's easy to miss.

Microsoft's docs say metrics are never sampled. Traces are. The .NET Azure Monitor distro defaults to rate-limited sampling of five traces per second, and by default it also drops logs that belong to a trace that was sampled out.

So on a busy service, the per-conversation query sees a sample. That's fine for percentiles, mostly. It's wrong for totals. Take totals from the metrics query, never from summing logs.

If you need every usage log, turn off trace-based log sampling:

``csharp builder.Services.AddOpenTelemetry() .UseAzureMonitor(options => options.EnableTraceBasedLogsSampler = false); ``

That applies to all logs with trace context, not only these. Check what it does to your ingestion volume first.

Alerts worth having

  • Daily estimated cost per step above a threshold. A log search alert on the first query, filtered to yesterday.
  • Input tokens per call per step jumped. Divide input tokens by call count per step and compare with last week. This catches the prompt that grew after a deploy, before the money adds up.
  • p95 conversation cost above a threshold. Catches loops and pathological inputs.
  • A model with no price. Rows where estCostUsd is empty.

Keep provider-side spend limits too. Telemetry tells you what happened. It doesn't stop it.

Limitations

  • These are estimates. The provider's invoice is the source of truth, including discounts, minimums and taxes. Reconcile monthly.
  • Cache writes, batch discounts and tiered context pricing aren't modelled in the price table. Add columns if your provider charges them.
  • Metrics export on an interval. A process that dies before export loses its last interval of counts.
  • The semantic convention names are in development. Pin them in one class and recheck when you upgrade instrumentation libraries.
  • Microsoft's docs now also describe a newer Microsoft OpenTelemetry distro with a slightly different setup call. The concepts here carry over. Check which package your team standardizes on.
  • Usage only exists when the call returns. A request cancelled mid-stream may still be billed by the provider without reaching your decorator.

Takeaways

  • Record tokens, not dollars. Apply prices at query time.
  • Metrics carry step, model and provider. Logs carry conversation ids.
  • Use the GenAI token metric names, and keep them in one place.
  • Totals come from metrics, because metrics aren't sampled. Distributions come from logs.
  • Alert on tokens per call per step, so a growing prompt shows up before the bill does.

Telemetry covers the model line. Hosting, voice minutes and the time someone spends keeping an agent healthy are separate lines, and this piece on AI agent cost per month lays them out side by side.

References

來源:DEV Community · dev.to