Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Chapter 16. Streaming Output and Progress

What does the UI look like for a handler function that takes ten seconds to run? The answer from the previous fifteen chapters is “nothing moves, then everything appears at once after ten seconds”. During those ten seconds the user does not know whether the click registered or how much longer it will take, and most people click again.

In these ten seconds, results come out as they are computed, progress is reported as it advances, and timed actions fire on their own. Finally you connect a real model service and join the “pieces that come back one at a time” into text that appears on the UI a segment at a time.

The sample adds a fourteenth block to the workbench. The streaming module: one streaming run, one run with progress, a timer, and an input box for asking the model.

16.1 Async Handler Functions and Streaming Output

An ordinary handler function is “in once, out once”. A streaming handler function is “in once, out many times”, written by returning an async sequence.

async IAsyncEnumerable<string> StreamRun()
{
    var text = "";

    for (var i = 1; i <= 6; i++)
    {
        await Task.Delay(400);
        text += $"Segment {i}.";
        yield return text;
    }
}

Six yield returns are six frames. Figure 16-1 places the three approaches on three timelines. A one-shot return is “empty at the front, everything in the last cell”, streaming output is “each cell has one more segment than the last”, and progress reporting is “the content does not move, only the percentage updates”.

Figure 16-1 Three approaches, three timelines

The binding is the same as for an ordinary handler function: one button, one output. You do not need to declare “this is streaming”. When the return type is IAsyncEnumerable<T>, the framework knows to send it out frame by frame.

Figure 16-2 shows the stream halfway through: the panel holds “Segment 1. Segment 2.” and a thin progress bar is running along the top.

Figure 16-2 Halfway through the stream: the panel holds the segments produced so far, with a thin progress bar along the top

Figure 16-3 shows the stream finished: six segments joined together, with no duplicates.

Figure 16-3 Stream finished: the last frame is the complete result, six segments with no duplicates

Notice the text variable: each round appends a segment, then yield return text. What you output is the whole string, not just the segment you added. This is the part of streaming most often written wrong, and the next section is devoted to it.

The sample pauses 400 milliseconds between segments so you can see it “growing” with the naked eye. In real work that pause comes from the computation itself — reading a line, computing a step, querying a record all take time anyway. Do not add Task.Delay just to “look like it is streaming”; what users want is real progress, not animation.

The code before yield return is “what has to be done before this frame”. Inside the loop it runs once per frame; outside the loop it runs only once (say preparing data, or connecting to the database once). This distinction matters for streaming. Put something that “should happen only once” inside the loop and six frames do it six times, doubling how long the user waits.

The value of streaming is not just “looking fast”. It makes the “waiting” visible. When the user sees the first segment, they know the program is working and that their click was not wasted. Those ten seconds change from “blank” to “segments appearing one after another”, which feels completely different.

One number captures this: time to the first segment. Without streaming, the user waits for “everything to finish”, ten seconds; with streaming, the user waits for “the first segment”, 400 milliseconds in the sample. The total time is not reduced at all, but the time to “a reaction” drops from ten seconds to 0.4 seconds. People judge “is it stuck” by this number, not by the total duration. Chat applications almost all stream, because “the start” comes earlier.

Streaming also has a side effect that is easy to miss. It turns one request into a series of responses. Originally it was one HTTP request and one response; now it is one request and dozens of pushes. The connection has to stay open, and every push along the way can fail. This is why streaming code has one more layer of “what to do when something goes wrong” than an ordinary handler function; Chapter 17 picks this up.

16.2 Output Semantics, Intervals, and Multi-Component Output

Each frame outputs the “current complete value”, not “the part added in this frame”.

What happens if you write it to “output only the increment”? The output component replaces its whole value each time it receives a frame, so if you output “Segment 2”, the screen is left with only “Segment 2”; output “Segment 3” and only “Segment 3” remains. Each frame overwrites the previous one, so the text appears to jump. To have the text keep growing, every frame has to output everything.

This mistake is common because intuitively “streaming” means “sending one segment at a time”. What is sent one segment at a time is the protocol layer (the server writes back one fragment at a time), while the UI layer wants “what the whole text is right now”. Between the two layers there is one accumulation. Join the fragments together, then output the joined whole. The text += delta in the sample’s Ask is exactly this accumulation.

This is where this semantics differs from “appending”. The output component has no “append” operation, only “replace with this value”. Streaming just makes that “replace” happen many times.

If there is more than one output component, each frame has to give a value to every output. For example, streaming text and a counter at the same time: yield return (text, count), matched up in order against the outputs list. Every frame must supply all outputs. Give only some and the rest are taken as “no value”, which shows on the UI as those components flashing empty. To keep an output’s previous frame, use gr.Skip().

The typical use of multi-output streaming is “main result + side information”. The body text grows while a count rises and a status changes beside it. Output all three together every frame and the UI stays in sync; output only the body and let another event update the count, and the two fall out of step. The user sees the text reach the third segment while the count is still at one.

The order has to match too. The order in outputs decides how the return value is split. Return a three-tuple and the first goes to the first output, the second to the second. Get it backwards and nothing throws — the text simply lands in the counter box. This kind of mistake is obvious on the UI, but when debugging you should think “order” first, not “wrong value”.

streamEvery is this section’s second parameter: the minimum number of seconds between two frames. Omit it and every frame is sent; write 0.5 and output produced faster than half a second is not sent to the front end frame by frame. Its purpose is “do not flood the front end”. A handler function that produces a frame every millisecond is too much for the browser to render and for the network to carry; add a lower bound and the frame count falls into a controllable range.

When should you set it? Look at frame density. Text streaming (a model emitting characters) is usually one frame every few tens of milliseconds and needs no attention; streaming where each frame is heavy, like images or audio, must set it. Without it, bandwidth and CPU are spent on “sending frames” and less time is left for the actual computation.

streamEvery is in seconds; 0.5 means half a second. Writing 0 is the same as omitting it — “send every frame”. It affects only the rhythm of “sending”, not the rhythm of “computing”. The handler function still yields as many times as it should; the frames are just sent more sparsely.

It and triggerMode: AlwaysLast solve problems at different layers. streamEvery governs the rhythm of sending: frames are still produced, just not sent one by one. AlwaysLast governs the choice of what to queue: new ones displace old ones, and old frames never even reach the handler function. The former suits “every frame carries information” (text), the latter “only the latest matters” (camera images).

One more point that is easy to forget: streamEvery is a binding-level parameter, not an application-level one. Within the same application a text stream can leave it unset while an image stream sets 0.5, each following its own density. You do not have to slow down every stream for the sake of one heavy one.

There is also an implicit convention: the last frame must be complete. The framework does not know when your business logic is done; it only knows the sequence has ended. The last frame when the sequence ends is the final result. So do not yield an extra “summary” outside the loop unless you really want it to overwrite everything before it.

Exceptions in streaming need thinking through too. If the sequence throws halfway, the UI shows “stopped midway + an error”. It does not automatically go back to empty, nor does it retract content that has already appeared. The user at least sees the part that was computed. To “clear on failure”, record the failure in catch, then after leaving try first yield an empty string and rethrow the exception (you cannot yield inside catch; Section 16.6 covers this restriction); to “keep on failure”, just let it stop there. Both are fine, but you have to have thought about it.

16.3 Progress: Reporting, Step Reporting, and Display

Streaming solves “having something to look at”; progress solves “how much longer”. It produces no content, it only reports a number.

In terms of writing, the handler function gains one parameter.

async Task<string> WithProgress(Progress progress)
{
    for (var i = 1; i <= 6; i++)
    {
        await Task.Delay(350);
        progress.Report(i / 6.0, $"Step {i}: computing a bit");
    }

    return "**Progress** all six steps done, the last frame is the complete result.";
}

Progress is not written into inputs. Parameters injected by the framework do not take up an input slot. Progress, CancellationToken, and event data are all in this category. What if you declare it as an input? The framework will look for a value in a component to fill it and error if it cannot find one; even if it finds one, what you get is not a progress object.

Why must it be injected? Because progress does not belong to any component. It is the state of “this run”, following the call, not the page. If you made it an input component, you would get things like “last round’s progress being read by the next round”; as an injected parameter, every call gets a fresh object belonging only to that run.

This also explains “why you do not place a component on the page for the progress bar”: it is a channel. The handler function writes into it, the front end reads from it. You can write as many times as you like; what is read is always the last one.

Report(fraction, description) takes two parameters: how far along (0 to 1), and a line of text for a person to read. The small label in Figure 16-4 reads “Step 4, computing a bit · 66.7%”. The first half is the description, the second half the percentage the framework computes from fraction.

Figure 16-4 Progress: description plus percentage, following whichever step the handler function has reached

What do you pass for fraction? “The proportion already done.” Six steps with the fourth finished is 4/6 ≈ 0.67. Pass null to mean “progress unknown”. By the contract, no progress bar is drawn then, only the description is kept. Some tasks cannot compute a proportion (say waiting on an external interface); using null is more honest than inventing a number.

Two other methods report “which one / how many in total”, with the fraction computed by the framework itself.

  • ReportSteps(index, total, description, unit): you tell it which one you are on and how many there are in total;
  • Track(values, description). You pass a collection to it and it reports as it iterates; the denominator is the number of elements.

Replace the progress.Report(...) line in the sample and you have these two forms.

    // The total is known: report "which one / how many in total"; the framework computes the fraction.
    progress.ReportSteps(4, 6, "Sub-step 4", unit: "step");

    // A collection to iterate: pass it to Track and it reports as you go.
    foreach (var name in progress.Track(new[] { "Read", "Compute", "Write back" }, "Three segments"))
    {
        await Task.Delay(200);
    }

The unit of ReportSteps is “what one step is called”; if you omit it the unit is steps. Track is less work. You do not count yourself or compute a fraction — just pass the collection to Track. It reports “which element you are on”; when the elements are done it is 100%, and however many items the collection has, that many cells appear on the UI.

Track has a boundary. The tracker stays attached until the collection is exhausted. Nest another Track inside and one push carries two trackers, of which the client shows the later one. The outer one’s progress then stops moving. To nest, use ReportSteps on the outer layer and count yourself.

Update(steps) gets its name from “advance a few steps”, but you cannot see it on the UI. After the call nothing has changed, and the index in later pushes is not affected either. To accumulate, keep a variable yourself and pass it to ReportSteps. One extra variable is better than one more progress bar that does not move.

Which of the three methods to pick? A rule of thumb: when the loop count is known and even, use ReportSteps; when processing a collection, use Track; when progress cannot be computed, use Report(null, "...") and let the description run along without drawing a progress bar.

Where progress is shown is decided by the binding’s showProgress. The sample writes ProgressDisplay.Full, so that small label appears in the top-right of the panel; omit it and you get the default compact style, just a thin line. You can also specify showProgressOn to display progress on a different component — say the progress bar in the status area and the result in the result area.

Can progress and streaming be used together? Yes, but keep them distinct: streaming replaces content, progress reports a number. With both on, the UI has text growing segment by segment and also a progress line — the most comfortable form. The user both sees things coming out and knows how much is left.

There is a detail when using them together. Every streaming frame refreshes the output component, and progress also refreshes that component’s corner badge; the two do not fight (one changes content, the other the badge). But if showProgressOn points to another component, progress is displayed there instead. This parameter is very useful when building a UI that separates “result area + status area”.

There is another common mistake: reporting progress inside a streaming handler function, but reporting “which frame”. Frame count and business progress are often not the same thing — one frame might be one segment of text, or a whole result. Report progress by business steps, not by frame count.

The last point: progress must be real. Report is called by the handler function itself; the framework does not compute it for you. Write a fake timer that advances it at a constant rate and the user will think “that is smooth”, then get fooled once on a step that hangs. After that one time, they never look at the progress bar again.

16.4 Timer and Timed Triggers

Some things are meant to happen when the time comes: polling a status, refreshing a dashboard, fetching data every few seconds. Timer is made for this.

var clock = gr.Timer(2, active: false);

Two parameters: the interval in seconds and whether it starts running immediately. It draws nothing. You cannot see it on the page; what it does is make the front end fire a tick event every two seconds.

tick binds a handler function just like an ordinary event. In the sample look at “start” and “stop” along with it.

    pane.Clock.Tick(OnTick, null, [pane.Tick], apiName: "Timer");

    flow.Start.Click(StartClock, null, [pane.Clock, pane.Tick], apiName: "Start timer");
    flow.Stop.Click(StopClock, null, [pane.Clock, pane.Tick], apiName: "Stop timer");

Three bindings. tick does the work, the other two change “whether to run”. Both buttons treat the timer itself as an output, because what they change is its Active.

The handler function looks like this.

string OnTick()
{
    ticks++;

    return $"**Timer** {ticks} ticks, the latest at {DateTimeOffset.Now:HH:mm:ss}.";
}

Figure 16-5 shows the result of “start → wait six and a half seconds → stop”: the timer panel reads “stopped, 3 ticks in total”. Three ticks is exactly the number those six and a half seconds should produce; after stopping, another four seconds passed and the number did not change.

Figure 16-5 The timer: one tick every two seconds after starting, and no more after stopping

Stopping deserves its own explanation. Write Active back to false, then put the timer into the return value.

(Gradio.Net.Timer, string) StopClock()
{
    pane.Clock.Active = false;

    return (pane.Clock, $"**Timer** stopped, {ticks} ticks in total.");
}

Why return the component itself? Because Active is a property written into the page configuration, and the front end watches it. When the configuration becomes false, the front end clears that clock. Change only the field on the C# object without returning it and the front end never sees the change, so the clock keeps running.

The timer has one boundary that is easy to step into: it runs only while the page is visible. Switch to another tab and the browser stops the timer; switch back and it resumes. This is to save power. But for a requirement like “must sample every two seconds”, it is not reliable enough. That kind of requirement has to be handled on the server (a background task); you cannot count on the front end.

The other side of this boundary is “it does not need the server to remember anything”. The timer is a clock inside the page. The server only writes “every two seconds” and “whether to run” into the configuration; the browser does the rest. So when the page is closed, the clock is gone. There is no such thing as “the server is still counting for you”.

When should you use a timer? Three kinds of scenario: polling (asking “is it done yet” every few seconds), refreshing (numbers on a dashboard updating themselves), and rhythm (automatically switching an image every so often).

tick goes through the queue. With the page open and the timer firing every two seconds, the queue always has events; if the tick handler function is slow, the queue piles up and other people’s requests are blocked outside (Chapter 15). So it has to be light. Read a number, update a piece of text — do not do heavy work inside it.

If you really need heavy work, let tick do only one read. Read a status, a file, or a counter, and continue only if it changed. The essence of polling is “most of the time nothing has changed”; make that “no change” pass light and polling pays off.

Polling is the most common use, and it is written in three steps: the timer fires every two seconds, tick asks “is it done yet” once, and when it is done you stop the timer. The third step is easy to forget. Forget it and the page keeps asking until the user closes the page. So the tick handler function usually has a check. When the work is done, write Active back to false and return the timer — the same set of actions as the stop button at the start of this section.

The timer also interacts with the queue: its tick is queued by default. If the previous tick has not finished when the next one arrives, two ticks sit in the queue, which shows up as “running slower and slower”. To avoid it, bind tick with concurrencyLimit: 1 and triggerMode: AlwaysLast (Chapters 5 and 15). A new tick displaces the old ones that have not run, so only the latest one is ever processed.

16.5 Streaming Input from Media Components

Chapter 11 covered Image’s streaming: true; here we add where it fits into “streaming”.

Turn it on and the camera sends frames to the server one at a time, each frame triggering one stream event. Audio and video work the same way. In other words, streaming for media components is an input stream. Data flows from the browser to the server, and the handler function is called repeatedly.

This is the opposite direction from the streaming in earlier sections of this chapter. An output stream is “one call, many returns”; an input stream is “many calls, one value each”. The two share a word but have completely different code structures.

  • Output stream: one handler function, returns IAsyncEnumerable;
  • Input stream: one handler function, receives one frame, returns once, called many times.

What is an input stream good for? Real-time filters, real-time recognition, transcribing while recording. What is it bad for? Anything that “needs to see the whole segment”. Transcribing a piece of audio or editing a piece of video has to wait until recording is done. The criterion is simple: can this task produce a result from this one frame alone. If yes, use an input stream; if not, wait until recording finishes.

The two are often used together. Take a “transcribe while recording” feature: the audio component has streaming input on, transcribing each small piece as it arrives (input stream), and the resulting text is appended to the panel segment by segment (output stream). With the two streams stacked, what the user sees is “words appearing as they speak”. This is the most elegant use of streaming and also the hardest to tune. The two sides have different rhythms — input fast, output slow — so there has to be buffering in between.

The cost of an input stream is on the queue. One event per frame, thirty frames a second is thirty events. All the limits from Chapter 15 apply here: the concurrency limit decides how many frames are processed at once, the queue limit decides how many pile up. So before turning on an input stream, think clearly about “how long one frame takes to process”; when you cannot keep up, dropping old frames is more sensible than queuing them.

Dropping frames means setting this kind of binding to triggerMode: AlwaysLast. When a new frame arrives, old ones that have not run are displaced. For live images this is right: what the user wants is “now”, not “every frame from three seconds ago”.

One more thing to think through: each frame of streaming input is a complete new value, not an “increment”. What the camera sends is this frame’s image, not “the difference from the previous frame”. So the handler function processes a whole image from scratch every time; there is no “continuing from last time”. To remember state across frames (say “how many times this face has appeared”), use the state from Chapter 14, and watch out for concurrency. When two frames are processed at the same time, the state gets trampled.

16.6 Connecting to an OpenAI-Compatible Service

The previous five sections all made up their own data. This section connects to something real: an OpenAI-compatible service and a real streaming conversation.

Configuration first. The address, key, and model name are not written into the code; they are read from environment variables.

    public static string? Missing
    {
        get
        {
            var missing = new List<string>();

            if (string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("OPENAI_BASE_URL"))) missing.Add("OPENAI_BASE_URL");
            if (string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("OPENAI_API_KEY"))) missing.Add("OPENAI_API_KEY");
            if (string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("OPENAI_MODEL"))) missing.Add("OPENAI_MODEL");

            return missing.Count == 0 ? null : string.Join(", ", missing);
        }
    }

Three variables: OPENAI_BASE_URL (up to and including /v1), OPENAI_API_KEY, and OPENAI_MODEL.

The model name also comes from an environment variable, because the model name is the decision of “which model this deployment uses”; it belongs to the runtime environment, not the code. The same code uses a cheap small model on the development machine and a large one in production — what changes is the environment variable, not the source. This is the same idea as UploadFolder in Chapter 12: environment-related things live in the environment.

When the environment variables are read matters too. The sample reads them on every request, not once at startup into storage. Environment variables cannot be changed after the process starts, so both approaches give the same experience for “changing configuration”: both require a restart. The only difference is a few extra string lookups per request, which is negligible. If you really care about that overhead, store them in a static field and write clearly that “changing configuration requires a restart”.

When configuration is missing, the sample says plainly which items are missing instead of making up an answer.

Figure 16-6 Configuration missing: the panel lists the missing variable names and gives no answer

This is deliberate. A clever-looking answer whose content is made up would cover up “never actually connected” until something fails in a real environment.

For the same reason, the sample does not write the address, key, or model name into any log. Tempted to print them while debugging? Print “configuration complete” and “which item is missing” instead. Once a value has been printed, it stays in some log file on some machine and can never be taken back.

With configuration complete, asking one question is one HTTP request. Here you use await foreach.

async IAsyncEnumerable<string> Ask(string question)
{
    var text = "";

    await foreach (var delta in ChatBook.AskAsync(question))
    {
        text += delta;
        yield return text;
    }

    if (text.Length == 0)
    {
        yield return "**Model** returned no content this time.";
    }
}

What ChatBook.AskAsync produces are fragments (a few characters each); here you append each to text and output the whole text. The division between the two layers is clear. The client handles “produce a fragment as soon as one is read”, the UI layer handles “join it into a complete value”. The “output the complete value every frame” rule from Section 16.2 is put into practice right here.

Why not have the client produce the complete value directly? Because it should not know what the UI wants. The client does one thing: pull the characters out of the SSE one by one. What happens after that (joining into complete text, counting characters, filtering sensitive words) is the caller’s business. That is the value of layering. Switch to a different UI (say the command line) and the client does not have to change.

That if (text.Length == 0) has to stay too. Sometimes the model returns an empty stream (the service is fine but there is not a single character); then await foreach never enters the loop and text is still empty. The UI shows nothing and the user thinks it is stuck. Adding a line “returned no content this time” at least tells them the model said nothing, not that the program broke.

Figure 16-7 is one answer from the real service, to the question “explain in one sentence what streaming output is”; a complete sentence appears in the panel.

Figure 16-7 One answer from a real service, with fragments joined into one complete sentence

A timeout is mandatory. The sample sets 60 seconds on HttpClient; without it, a stuck service leaves the handler function hanging, the queue slot occupied, and every later request waiting in line. 60 seconds is a compromise. A normal answer finishes in a few seconds; one that shows no sign after 60 seconds can safely be declared dead.

Service errors need to be explained too. On a non-2xx response the sample returns a line “the service returned 500, no answer this time” instead of throwing, because throwing inside streaming shows up on the UI as “a red block” the user cannot understand; returning a line at least tells them what happened.

Three kinds of failure have to be reported separately: no configuration (which variables are missing), cannot connect (wrong address, service not started, waited too long), and service rejection (wrong key, model does not exist, rate limited). The user actions for the three are completely different. For the first, set the environment variables; for the second, check whether the service is up; for the third, check the key and quota. Report all of them as “something went wrong” and the user can only try each one in turn.

The first is handled by that Missing check earlier; the other two are caught in code like this.

        // You cannot yield inside a catch, so record the failure first and yield it after the try block.
        string? failure = null;
        HttpResponseMessage? response = null;
        try
        {
            response = await Client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken);
        }
        catch (HttpRequestException)
        {
            failure = "(Could not connect to the service, no answer this time.)";
        }
        catch (TaskCanceledException)
        {
            failure = "(Timed out, no answer this time.)";
        }

There is a C# restriction to know here: yield return cannot be written inside catch (nor inside a try that has a catch). So “catch an exception then output a line” in streaming code needs a workaround. Record the failure in a variable first, then yield after leaving try. This workaround is not pretty, but it is the only way to let the stream keep going.

There is one more case: the connection breaks halfway through reading. The connection is established and headers received, then nothing after some frame. In that case await foreach throws and the sample does not catch it. The UI shows an error and the content already produced stays where it is. This is the same thing as “keep completed results on failure” in Chapter 17, which covers it in detail.

Multi-turn conversation is simple at this layer too. messages is an array and you put history messages into it one by one. The sample puts only one, because this chapter’s conversation is a single question; for multiple turns, convert the ChatMessage list from Chapter 13 into an array of {role, content}. The two structures are almost identical — when converting you only need to drop the blocks and keep the text.

One more thing to know about real services: the answer may contain Markdown. What a model emits is often text with **, lists, and code blocks; a Markdown output component is exactly right for it, while a Textbox shows those symbols literally. The sample uses Markdown, so the sentence in Figure 16-7 is rendered.

16.7 Request Structure, Streaming Fragments, and the End Marker

This section lays the protocol out. Knowing it is what lets you switch to another service or write your own compatibility layer.

The request is a POST to <base>/chat/completions, with Authorization: Bearer <key> in the headers and JSON in the body.

{"model":"<model name>","stream":true,"messages":[{"role":"user","content":"<question>"}]}

This is how it is assembled in code.

        using var request = new HttpRequestMessage(HttpMethod.Post, $"{endpoint}/chat/completions");
        request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", key);
        request.Content = new StringContent(
            JsonSerializer.Serialize(new
            {
                model,
                stream = true,
                messages = new[] { new { role = "user", content = question } },
            }),
            Encoding.UTF8,
            "application/json");

stream: true is the key: without it the server computes everything and returns in one shot; with it the server writes back as it computes. messages is an array, each entry with role and content. Multi-turn conversation just means putting a few more entries into this array (the message structure from Chapter 13 becomes the request body here).

There are a few other fields commonly included. temperature controls “how random” (0 most stable, 1 most divergent), max_tokens controls “the most it may generate”, and the system role can carry one overall instruction. The sample includes none of them. What this chapter verifies is “how to wire up the stream”, not “how to tune parameters”. In a real application you will run into these sooner or later.

Only two request headers are required: Authorization and Content-Type. The former carries the key, the latter is application/json. Some services also want Accept: text/event-stream, but that header is of limited use. The response type is decided by stream: true, not by Accept.

Without stream, the response is one whole piece of JSON, with the body text in choices[0].message.content.

{"choices":[{"index":0,"message":{"role":"assistant","content":"Streaming output means..."},"finish_reason":"stop"}],"usage":{"total_tokens":133}}

With stream, message becomes delta, only one segment is given at a time, and the whole response turns into a series of “server-sent events” (SSE). The field names of the two responses differ by one word. message is “one complete item”, delta is “the increment for this segment”. Get it wrong and what you read is always empty.

A streaming response comes back frame by frame as “server-sent events” (SSE); the server never gives one whole piece of JSON at once. Each line looks like this.

data: {"choices":[{"delta":{"content":"Streaming"},"index":0,"finish_reason":null}]}

Taken apart: data: is the prefix, followed by a piece of JSON; choices[0].delta.content is the text of this segment. Some services also include delta.reasoning_content. That is the model’s “thinking”, not the body text; the sample’s parser takes only content, so the thinking is naturally skipped.

A real stream looks like this (most of the middle frames are omitted).

: keepalive

data: {"choices":[{"delta":{"role":"assistant","content":""},"index":0,"finish_reason":null}]}

data: {"choices":[{"delta":{"content":"Streaming"},"index":0,"finish_reason":null}]}

data: {"choices":[{"delta":{"content":"output"},"index":0,"finish_reason":null}]}

data: {"choices":[],"usage":{"prompt_tokens":6,"completion_tokens":127,"total_tokens":133}}

data: [DONE]

The first frame is often “empty”: content is an empty string and there is only role. It is telling you “output has started”. The last two frames have no body text either — one is usage statistics, one is the end marker. Only the ones in between are the actual characters.

There are four kinds of line to recognize in the stream.

  • Blank lines, used as separators, skipped;
  • Lines starting with a colon (say : keepalive), comments the server uses to keep the connection alive, skipped;
  • data: [DONE], the end marker, stop when you read it;
  • A data: whose choices is an empty array. Some services append a usage statistic (token counts) at the end; it has no body text, so skip it.

Only when all four are handled is the parsing complete. Miss one and the symptom is “the stream never ends” or “a strange extra piece of text at the end”.

The finish_reason field has three values: stop for normal completion, length for truncation (hit max_tokens), and content_filter for being blocked by a content policy. The sample does not read it. When the stream ends it simply ends; but to build something like “if the answer was truncated, should we continue generating”, you have to read it.

One more point. The same id appears in every frame of this whole round. It is “the number of this round of conversation”. To pick out “which frames belong to the same request” among a bunch of concurrent streams, it is what you rely on. The sample does not use it, because the sample opens only one stream at a time; with real multi-way concurrency (say two users asking at once), it is the key.

The name delta in a frame is easy to misunderstand. It is called “increment”, and indeed each frame’s delta.content is only “the characters added in this frame”. In other words, the protocol layer is incremental, the UI layer wants a complete value. That accumulation between the two layers is exactly what this chapter has been talking about all along. The name is not wrong; it just describes the protocol, not the UI.

Errors come in two kinds. One is at the HTTP layer: the status code is not 2xx and the response body usually has a {"error": {...}} saying whether the key is wrong, the model does not exist, or it was rate limited. The other is inside the stream: the connection was established and broke midway, in which case await foreach throws. The sample does not catch this one, so the exception goes straight to the UI; to catch it, wrap await foreach in a try and turn it into a line a person can understand.

HTTP-layer error codes should be matched up: 401 is a wrong key, 404 a wrong model name or path, 429 rate limiting (come back later), 500 the service itself failing. These four cover the vast majority of cases; see the code and you know what to change. The sample reports only the code, not the original text, because that text can be long and may carry the server’s internal information.

There is also an “error” that reports no error: empty content is returned. The service ends normally without a single frame of body text, the UI shows nothing, and the user thinks it is broken. The sample checks for exactly this and returns a line “returned no content this time”. In streaming, “empty” and “never ran” look exactly the same, so you need that line to tell them apart.

When writing your own compatibility layer, there is one more rule: each frame must be complete JSON. SSE is split by lines, so a frame cannot span lines (unless you use multi-line data:, which is a different form with poor compatibility). So the server must not serialize with indentation. Indented JSON becomes several lines and falls apart when the client reads line by line. The JsonSerializer.Serialize the sample uses does not indent by default, which is exactly right.

Once you have the response, the first thing is to check the status code.

        using var _ = response!;
        if (!response!.IsSuccessStatusCode)
        {
            yield return $"(The service returned {(int)response.StatusCode}, no answer this time.)";
            yield break;
        }

The first line, using var _ = response!;, arranges for the response object to be disposed. var _ is a placeholder name; when the function ends, that response is released. The try in the previous step only “got the response in hand”; the using here adds “give it back when done”.

The ResponseHeadersRead option: the default is “return only after reading the whole response body”, which would make streaming pointless; with it, the call returns as soon as the headers arrive and the body is processed as it is read.

Reading is done one line at a time. There is a detail here: ReadLineAsync waits until “a complete line exists” before returning. If the server has written a segment but not yet the newline, it keeps waiting. For SSE this is exactly what you want: one frame per line, and a frame counts as arrived only when its line is complete.

        string? line;
        while ((line = await reader.ReadLineAsync(cancellationToken)) is not null)
        {
            // Blank lines and comments starting with a colon (some services send keepalives) are not data.
            if (line.Length == 0 || line.StartsWith(':')) continue;
            if (!line.StartsWith("data:", StringComparison.Ordinal)) continue;

            var payload = line[5..].Trim();
            if (payload == "[DONE]") break;

            var delta = Content(payload);
            if (!string.IsNullOrEmpty(delta)) yield return delta;
        }

Buffering at the network layer helps too. ResponseHeadersRead keeps the response body from being buffered as a whole, and StreamReader buffers only a small chunk. With neither layer accumulating, a frame can be “read as soon as it arrives”. The other way round, if any layer in between reads the whole response body into memory before handing it to you, streaming degrades into “wait for everything, then process”. The code looks unchanged on the surface, but the behavior changes completely.

This piece of code is the whole of what “protocol” means here. Switch to another vendor’s compatible service and, as long as it speaks this format, not a single character has to change; if it does not (say a private protocol of your own), this is the section you change.

The cancellationToken in this snippet is currently an empty token (none is passed at the call site); Chapter 17 will wire it up to real cancellation.

16.8 Chapter Summary

Start with a number. The sample’s “streaming run” has six segments at four hundred milliseconds each, two and a half seconds in total. Return the same content in one shot and the user stares at a blank for two and a half seconds; stream it and the first segment is out after four hundred milliseconds. In those two and a half seconds the user sees six times “it grew a bit more” — that is what streaming buys you.

Streaming is written by returning IAsyncEnumerable, with each frame outputting the current complete value. The output component only “replaces with this value”, it does not append. Output only the increment and the text on the UI jumps; to have it grow continuously, every frame must supply everything. With multiple outputs every frame must supply all of them, and gr.Skip() keeps an output’s previous frame; streamEvery adds a minimum interval between frames so the front end is not flooded.

Progress is an injected parameter and does not take an input slot. Report reports a fraction plus a description; ReportSteps and Track report “which one / how many in total” (Update does not push, do not use it); showProgress decides where it is drawn. Progress must be genuinely reported by the handler function — the framework does not compute it for you.

Timer draws nothing; it only makes the front end fire tick on a schedule. To stop it, write Active to false and return the timer. Only when the configuration changes does the front end stop. It runs only while the page is visible, so do not hang heavy work on it, and polling should stop the clock itself when the work is done.

streaming on media components is an input stream: one call per frame, the opposite direction from multi-output streams. Whether you can use it depends on “can this one frame alone produce a result”.

The real-service part has four things: configuration comes from environment variables, missing items are stated plainly, the request carries stream: true, and the response is read line by line as SSE. After data: is JSON, delta.content is the body text, [DONE] is the end, and lines starting with a colon are comments. After reading, join the fragments into a complete value and output it to the UI.

The chapter’s four things each govern one stretch. Streaming makes content appear segment by segment, progress gives the waiting a scale, the timer makes things happen on their own, and the real integration gives all three something to show.

The next chapter covers “what to do when you do not want to wait”: cancelling a running task, and how failure, timeout, and cancellation should each be presented.