aziztoba.github.iogithub

Abdulaziz Toba — AI Engineer

120// illustrative · streaming an inference response
121using System.Diagnostics;
122using System.Runtime.CompilerServices;
123
124public sealed class InferenceStream
125{
126 private readonly IModelClient model;
127 private readonly IMetricSink metrics;
128
129 public async IAsyncEnumerable<string> Generate(
130 Conversation conversation,
131 [EnumeratorCancellation] CancellationToken cancellation)
132 {
133 var timer = Stopwatch.StartNew();
134 var firstToken = true;
135 var outputTokens = 0;
136
137 await foreach (var token in model.StreamAsync(
138 conversation.Messages, cancellation))
139 {
140 cancellation.ThrowIfCancellationRequested();
141
142 if (firstToken)
143 {
144 metrics.Observe("time_to_first_token", timer.Elapsed);
145 firstToken = false;
146 }
147
148 outputTokens++;
149 yield return token.Text;
150 }
151
152 metrics.Observe("generated_tokens", outputTokens);
153 metrics.Observe("generation_duration", timer.Elapsed);
154 }
155}
156
157// latency and throughput tell different stories.
158// measure both. keep the context. respect the budget.
159public record Conversation(IReadOnlyList<Message> Messages);
160public record Message(string Role, string Content);
161public record Token(string Text);
162// end of illustrative buffer
NORMAL~/Projects/inference/stream.cs136:1 5%