Send a chat request with streaming enabled to a running llama-server and use curl’s no-buffer option to inspect events as they arrive. Each streamed chat choice can contain a fragment of the answer. Join the visible content in order and check how the stream ended before using the result. A partial reply can contain useful words while still failing a client’s completion check.

This walkthrough assumes the server and Terminal are on the same Mac, and that the server already has a text chat model. The exercise uses a fictional timetable sentence. You will first inspect the transport and then replay a saved stream through a small local checker. This lets you reproduce a client parsing failure without repeatedly generating new output.

Establish a normal response from the running listener

Find the loopback address and port of the process you intend to use. The examples use port 8080. Verify the service’s models route before asking for a completion and copy the returned model ID exactly. If you require a bearer token on your listener, add that header with the local token when making requests. The examples show an ordinary same-Mac development listener that accepts calls without it.

curl -sS --connect-timeout 2 http://127.0.0.1:8080/v1/models

In a scratch directory, save the following request as chat-request.json and replace the placeholder. The completion should return the three words Morning Repair Session. The two events in the prompt provide a named distractor, so you can tell whether the model picked the right event. The output is short enough to inspect visually. Use a straightforward instruction model for this transport exercise. The llama.cpp reference describes synchronous and streaming support for the same chat route. llama.cpp Chat Completions API.

{
  "model": "REPLACE_WITH_API_ID",
  "messages": [
    {
      "role": "user",
      "content": "Schedule: the 09:15 slot is Morning Repair Session. The 13:20 slot is Afternoon Print Exchange. Reply only with the 09:15 event title."
    }
  ],
  "max_tokens": 80,
  "stream": false
}

Send it and read the body. The full chat response is a single JSON object. Visible text appears in the first choice’s message content. An error that occurs here belongs to the server, model ID, or request path before the streaming behavior enters the exercise. Confirm that the field contains sensible text and that a finish reason is visible.

curl -sS --max-time 120 \
  -H 'Content-Type: application/json' \
  --data-binary @chat-request.json \
  http://127.0.0.1:8080/v1/chat/completions

Inspect the same request as a stream

Make a copy of the request named chat-stream-request.json and change stream to true. Leave the prompt and model fields as they were. Use curl’s -N switch to disable its output buffering. The pipeline shows the body and copies it to a new local file. Server headers go to a separate file so they are available for debugging without being included in the data passed to the checker. curl no-buffer option.

set -o pipefail
curl -sS -N --max-time 120 \
  -D chat-stream-headers.txt \
  -H 'Content-Type: application/json' \
  --data-binary @chat-stream-request.json \
  http://127.0.0.1:8080/v1/chat/completions | tee chat-stream.sse

Look in the saved headers for a successful response and an event-stream content type. In the body, you should see data lines with JSON chunks. The choice can have a delta which contains a piece of visible text. The first chunk can establish a role without supplying text. A later frame may carry the finish reason without content. The stream ends with a special data value, so a parser needs to recognize that value before it tries to decode the line as JSON. The server’s documentation discusses the streaming protocol and the implementation supplies the event handling. llama.cpp server implementation notes.

The model can break text into pieces of several different lengths. For example, one event may contain an entire word while a later event contains a leading space and part of the next word. Join content fragments as delivered. An extra space inserted after each frame can change the result. Removing whitespace from each fragment before joining can merge separate words. Trimming around the final combined content is appropriate for this exercise.

Reassemble the saved synthetic stream

Save the following Python 3 checker as check-stream.py in the same directory. It handles the one-data-line frames emitted by this server route for the exercise. A general event-stream client should use an SSE parser that also handles multi-line data events and intermediary framing. The checker gathers the selected choice’s string fragments, keeps its finish reason, and expects the terminal marker. It also rejects a response where a stream error arrives after output has already begun.

import json

fragments = []
finish_reason = None
terminated = False

with open("chat-stream.sse", encoding="utf-8") as stream:
    for line in stream:
        if not line.startswith("data:"):
            continue
        payload = line.removeprefix("data:").strip()
        if payload == "[DONE]":
            terminated = True
            break
        frame = json.loads(payload)
        if "error" in frame:
            raise ValueError(f"Stream error: {frame['error']}")
        for choice in frame.get("choices", []):
            if choice.get("index") != 0:
                continue
            content = choice.get("delta", {}).get("content")
            if isinstance(content, str):
                fragments.append(content)
            if choice.get("finish_reason") is not None:
                finish_reason = choice["finish_reason"]

if not terminated:
    raise ValueError("Stream ended before its terminal marker")
if finish_reason != "stop":
    raise ValueError(f"Unexpected finish reason: {finish_reason!r}")
answer = "".join(fragments).strip()
if answer != "Morning Repair Session":
    raise ValueError(f"Unexpected title: {answer!r}")
print(f"Verified streaming answer: {answer}")

With Python 3.9 or later, run the checker on the captured file. The expected line ends with Morning Repair Session. If the model produces added wording, the connection and stream may be working, while the exercise’s exact format check fails. If the final reason indicates length, keep the body as evidence and repeat with a larger output budget. For a text-only app, the finish status should influence whether a result is ready for reuse or needs review.

After one success, change the 09:15 event to Tool Inventory Walk while leaving the later event unchanged. Update the expected answer in a fresh copy of the checker, capture a fresh response, and repeat. This test distinguishes the current fixture from an old saved transcript. Then make a local copy of the good capture and delete its terminal marker before running the checker on that copy. The checker should report an early ending even though all the visible words may still be present.

Diagnose which part of the stream failed

A JSON error in the saved content can occur before a stream starts. Check the status and content type first. If the server returns a normal JSON error body, a frame parser has no data events to read. A missing model ID or a request rejected by the backend can cause this. Save the actual response body so you can read its details before investigating Terminal buffering.

A stream that arrives as a single visible burst can still be a valid stream. A short reply may have been generated quickly or grouped by a runtime or intermediate output layer. Use the saved body to see whether it consists of event frames. Compare a direct Terminal run with any pipeline, log viewer, or app that consumes it. The curl option controls curl’s output buffering, while other programs can make independent buffering decisions.

An early disconnect needs different handling from an intact reply that ends because its token allowance was used. In a user interface, show partial text as in-progress while frames arrive, then check the terminal marker and per-choice finish reason before treating the result as complete. If the connection ends early, preserve enough information to explain the interruption and let the user intentionally try again. A script that submits a new prompt automatically after a partial answer can confuse its own logs about which output belongs to which request.

Keep the saved synthetic stream and checker for the next client update. You can replay the file locally to compare a normal completion, a missing marker, and an unexpected title. These fixtures isolate parser behavior from model sampling and make it straightforward to check that the next version applies the same completion rules to the same data.

Try a few known event sequences offline

One short fixture can confirm exactly how joining works. Keep a copy of the normal stream, then inspect the frames that correspond to the first choice. Mark which are role-only, which include visible content, and which indicate completion. Count the nonempty content fragments if you are debugging a client. Their precise number can vary. The comparison that matters is the complete text after concatenation and the final reason. If you test a new parser against the saved file, it should produce the same complete text regardless of when the file was captured.

Make another copy and change one fragment that contains a meaningful word. For example, replace Repair with Painting in the appropriate part or replace the assembled title with a known manually split version. Leave the finish reason and marker intact. The checker should report unexpected content. This distinguishes a technically complete stream from a result that fails the particular fixture. Then restore the words and change the final finish reason from the successful value to length. The checker should report the finish problem even though the assembled title is correct. Save the untouched response separately so you can verify that the earlier result still passes.

A client consuming the same endpoint may encounter a usage-only event with an empty choices array. The checker iterates over whatever choices each frame contains, so such a frame adds no visible text. If an application asks for multiple choices, track the fragment list separately for each index. Two outputs can arrive interleaved in one response. Joining their text in arrival order without grouping would produce a line that belongs to neither choice. Use one choice in this exercise so you can inspect each delta’s effect visually.

If you collect streams for troubleshooting, keep each new request next to its own body, headers, and prompt fixture. This is particularly valuable when an application cancels a request and immediately opens a second stream. A transcript file opened in append mode could contain the terminal marker from a previous run and give false confidence about the latest one. The example captures a single request to a new body file each time. When you adapt it, decide how to give each request a new capture name and how to tell whether its generation finished independently of the UI.

For shell pipelines that are hard to observe interactively, first rerun curl directly without another process consuming it. Then add the capture or downstream program back and compare. If the direct output behaves as expected, inspect that consumer’s line handling before changing the model. Event framing, visible reply quality, and terminal rendering can fail independently, and the saved test gives you an input for checking each stage.

Distinguish an HTTP read from an SSE event

An HTTP client can deliver the body in arbitrary pieces. A single read may end after a partial JSON word, or one read may contain several complete events. The transport’s read boundary gives a programming convenience. SSE uses its own framing rules, and chat JSON uses another level inside an event. In the saved replay, file iteration gives the simple checker one line at a time. A live parser that consumes byte buffers needs a way to recognize complete lines and events independently of the size of the incoming piece. WHATWG event stream format and parsing.

Work through one visible example. A JSON frame could carry the text fragment Morning with no following space. The next frame could carry a leading space and the letters Repair. The third could carry another leading space and Session. Joining those three content values as delivered produces the expected title. The stream itself includes other characters, such as field labels, JSON punctuation, and empty separator lines. All of those belong to the surrounding layers and should never appear inside the answer text.

Suppose a live client receives the first half of the letters Repair in one read and the rest in another. Decoding each read as a full JSON record can make that ordinary split look like a syntax error. Store unwritten bytes until enough arrive to identify the complete event or let a conforming library handle the buffer. This becomes visible with accented characters as well. A single letter such as the accented e in Café can span more than one UTF-8 byte. Individually decoding each arbitrary byte buffer can break the character if a boundary falls inside it.

A useful local fixture includes that accented title. Save three events with content values that together produce Café Tool Check. Test the capture with the same checker after changing the expected answer. Then exercise your live client’s parser with the same fixture fed a few bytes at a time. For a buffering implementation, choose splits inside the accented character and between the final marker’s brackets. The exact output string and number of parsed data events should agree with the original capture. Changing the segmentation should affect only when events become complete.

Test complete and incomplete frames separately

SSE uses blank lines to dispatch accumulated fields. Data can occupy multiple lines within one event, and a comment line can carry no message at all. The compact saved-file checker in this guide assumes the server’s ordinary one-data-line records. If you add event parsing to a more general client, verify that it joins consecutive data fields with a newline and waits for the separator. A partial trailing event has not reached the dispatch boundary. WHATWG rules for interpreting event streams.

The small capture below illustrates the separators. It includes a comment, a fragment whose leading space belongs to the JSON string, a finish event, and a final data marker. To use it with the original checker, save it as chat-stream.sse with its blank lines intact. The content fragments combine to Morning Repair Session. A comment ignored by the parser should have no effect on the visible text or completion. Use a scratch directory so the example does not replace a captured server response you still need.

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

: keep-alive

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

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

data: {"choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}

data: [DONE]

A general SSE parser must also handle an event laid out with several data lines. For example, split a valid JSON object across lines between property entries. Prefix each line with the SSE data label and put a blank line after the last fragment. Taken together, those field values form one payload with JSON-safe newline whitespace between its properties. The simple checker earlier will attempt to parse the first line by itself, so this format is a useful negative test for its limited scope. Expect a full SSE parser to dispatch a single event.

For an early-disconnect test of the general parser, remove the final blank separator after the marker. A client adhering to the event dispatch rules should discard the incomplete event and flag the request as incomplete under this chat contract. The compact checker is intended for a normal completed capture and only recognizes the marker line. A client needing stronger guarantees should preserve the frame boundary in its completion check. These tests explain precisely which promise a particular parser makes.

Keep errors and progress out of the final result

A user interface can show incremental text and still need a separate event for committing the final message. Give it an explicit lifecycle. When the chat starts, bind it to one request and mark the content as being received. Append only that request’s choice fragments as events arrive. Finish when the parser sees the expected result and ending. If the server reports an error after several pieces have already arrived, display the partial text with an interrupted status. Do not export it through an action that expects a finished answer until the user has reviewed what happened.

A progress marker or idle comment can help establish that the HTTP connection remains open. It says little about whether the model has returned text. A regular output event can carry a reasoning-related field or another delta property while visible content remains empty. For this plain chat exercise, keep only the string from the normal content property. If another application intentionally displays reasoning or tool data, give those values a separate handling path based on the API it uses. Combining all string fields into the answer yields a different result from reconstructing visible chat content.

A timestamp is useful when a stream seems to pause. Record when the call started, when you saw the first visible content, and when the terminal marker arrived. The presence of these times in a run log helps you see where a diagnostic should begin. The numbers for one hardware and model combination do not establish general performance. To investigate buffering, compare a direct curl output with a downstream viewer using the same short input and observe which layer shows event boundaries. Inspect the captured headers and body before changing model settings.

Make a retry a new, observable request

For a stream that ends early, keep the partial response with its own identifier or path. A fresh attempt might generate slightly different wording. Give it a separate output location, then verify only its own finish reason and marker. An app that starts another request after a user cancellation should close or ignore the earlier subscription for that turn. Otherwise late fragments can arrive after the new output has started and mix messages from both attempts.

Finally, keep three reusable fixtures with an application’s local integration notes. A clean expected stream checks parsing and the final state. A stream with valid content but no terminal marker checks interrupted handling. A stream with a terminal marker and the wrong expected title checks outcome verification independently of the protocol. Use the same local curl request after a server change to see whether the real events still match the assumptions you tested with those fixtures.

Keep headers separate when diagnosing a middle layer

If a local application places a proxy between curl and the model server, make two separate captures. First call the known loopback service directly using the sample request. Then call the application’s authorized local route with the equivalent synthetic input. Store the headers and event bodies under distinct filenames. A successful event-stream header from the proxy indicates the kind of response it claims to send. It still leaves the timing of event delivery and the completion of individual frames to verify.

Compare whether both captures preserve each content fragment, final reason, and terminal event. If the proxy body arrives in one burst but keeps all those things, investigate its buffering behavior with its own documentation. If it returns JSON or omits the terminal event, inspect how it translates the upstream response before exposing it to an interactive UI. Neither difference requires trying a new model first. The direct capture provides a stable baseline for where the change entered.