Use URLSession’s asynchronous byte API to read the streaming response from a loopback model endpoint, then decode each chat delta and append its text. Keep a separate state for completion or interruption so callers can distinguish a full reply from text received before a disconnect.
Define a small client contract
Start with macOS, a Swift toolchain, and a localhost server that already supports OpenAI-compatible Chat Completions streaming. The example uses a direct llama.cpp server with one model already selected. Record its port and exact served model ID. Keep the endpoint on loopback during the exercise. One application process streams one text reply. The snippet does not need to handle tool calls, upload images, or discover models. llama.cpp server API documentation
Write down what the caller should observe. You want a successful HTTP response, one or more text fragments, and the stream’s completion marker. If a server emits a fragment and disconnects early, report a failure and retain the partial text only if your interface labels it. A view that leaves the partial words on screen can be useful to a writer. Saving those same words as a completed record would be misleading. Define that distinction before you connect any editor or export action.
The example accepts the common single-line JSON data records used by the selected streaming API. Server-sent events as a broader format permit several data lines per event. A different server may need a full event parser. Verify that your own endpoint sends the simple records used below. Check the documented response shape, then use a harmless fixture to check your parser. Server-sent events format in the HTML standard
Choose a request that is easy to confirm
Use a short synthetic prompt such as Reply with MARINA 27 only. Compare the final assembled text with that expected result. A server can send the single word all at once or deliver it as several fragments. The application should treat both as successful if the final value and stream end are correct. The number of chunks reveals very little about how many original tokenizer tokens were generated. Avoid presenting chunk counts or network timings as model measurements.
Observe what the server returns before adding visual behavior. A response header announces which body type to expect. An ordinary JSON response is easier to handle separately than pretending it is a stream. A non-success status may contain an error body. Check the status and content type before decoding deltas. This keeps a missing model, a permission error, and a bad record distinguishable during diagnosis.
Implement a narrow Swift command-line client
Save this example as ChatStream.swift. Replace the model argument with the exact ID served by your running endpoint. If the local server uses authentication, pass its dedicated token through your own local environment. Keep the token out of the source and test output.
import Foundation
struct Chunk: Decodable {
struct Choice: Decodable {
struct Delta: Decodable { let content: String? }
let index: Int
let delta: Delta
}
let choices: [Choice]
}
enum ChatFailure: Error {
case badStatus(Int)
case wrongContentType
case invalidPayload
case incomplete
}
final class DeclineRedirects: NSObject, URLSessionTaskDelegate {
func urlSession(
_ session: URLSession,
task: URLSessionTask,
willPerformHTTPRedirection response: HTTPURLResponse,
newRequest request: URLRequest,
completionHandler: @escaping @Sendable (URLRequest?) -> Void
) {
completionHandler(nil)
}
}
func appendChat(
request: URLRequest,
append: (String) -> Void
) async throws {
let session = URLSession(configuration: .ephemeral, delegate: DeclineRedirects(), delegateQueue: nil)
defer { session.finishTasksAndInvalidate() }
let (bytes, metadata) = try await session.bytes(for: request)
guard let http = metadata as? HTTPURLResponse else {
throw ChatFailure.badStatus(0)
}
guard (200...299).contains(http.statusCode) else {
throw ChatFailure.badStatus(http.statusCode)
}
guard http.mimeType?.lowercased() == "text/event-stream" else {
throw ChatFailure.wrongContentType
}
let decoder = JSONDecoder()
for try await line in bytes.lines {
try Task.checkCancellation()
guard line.hasPrefix("data:") else { continue }
let payload = String(line.dropFirst(5)).trimmingCharacters(in: .whitespaces)
if payload == "[DONE]" { return }
guard let chunk = try? decoder.decode(Chunk.self, from: Data(payload.utf8)) else {
throw ChatFailure.invalidPayload
}
if let delta = chunk.choices.first(where: { $0.index == 0 })?.delta.content,
!delta.isEmpty {
append(delta)
}
}
throw ChatFailure.incomplete
}
@main
struct ChatStream {
static func main() async throws {
let args = CommandLine.arguments
guard args.count == 2, let url = URL(string: "http://127.0.0.1:8080/v1/chat/completions") else {
print("Usage: chat-stream MODEL_ID")
return
}
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.timeoutInterval = 30
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("text/event-stream", forHTTPHeaderField: "Accept")
if let token = ProcessInfo.processInfo.environment["LOCAL_CHAT_TOKEN"] {
request.setValue("Bearer " + token, forHTTPHeaderField: "Authorization")
}
request.httpBody = try JSONSerialization.data(withJSONObject: [
"model": args[1],
"stream": true,
"messages": [["role": "user", "content": "Reply with MARINA 27 only."]]
])
var reply = ""
try await appendChat(request: request) { part in
reply += part
FileHandle.standardOutput.write(Data(part.utf8))
}
print()
if reply.trimmingCharacters(in: .whitespacesAndNewlines) != "MARINA 27" {
throw ChatFailure.invalidPayload
}
}
}
Compile the single file with swiftc -parse-as-library ChatStream.swift -o chat-stream. Run the produced binary with the model ID as its only argument. Adjust the port in the source before compiling if your listener differs. For an Xcode command-line target, add the code to the intended target and ensure there is only one entry point. Apple’s documentation for URLSession asynchronous response bytes
Understand the fragment loop
The networking call returns before the entire streaming body arrives. Reading the lines lets your application inspect records as the server sends them. The payload after the data field is either the service’s end marker or a JSON object. The code decodes the object and uses the content string for the first requested choice. It ignores chunks with no text, such as certain usage or role records. That is useful because a successful stream may include changes in state before the answer begins.
Append text exactly as received. Trimming each fragment could remove a space between words. The library trims only the framing around the data payload and applies trimming to a separate copy of the final assembled text when comparing the sample. The final reply may contain Unicode characters, punctuation and newlines. Give JSON decoding the complete data record so split bytes at the network layer do not become separate words in your application.
If the API streams a different terminal signal, locate it in the provider documentation before adapting the loop. Some services send a distinct done event or a finish reason field. This client expects the explicit marker shown for the chosen protocol. Keep a source identifier beside the parser so the next developer knows which wire behavior was intentional. Do not classify a disconnected connection as completed only because its last delta looked like the end of a sentence.
Keep transport, framing and reply state observable
The redirect delegate declines HTTP redirects. If the server responds with a redirect, the status check should report that problem rather than following a target that could be outside the intended local connection. Keep the initial address explicit as well. A host picker that later allows a remote address needs a separate decision about privacy, credentials and transport. The current example is deliberately a loopback exercise with a fixed path. Apple’s URLSession redirect handling
Define your error states where the rest of the app can use them. A client can separate unable to connect, unsuccessful status, unexpected content type, invalid data record, cancelled reading, and completion marker missing. Those states lead to different operator actions. A failed transport leaves no proof that the model received the prompt. A bad data record shows the connection worked and the application encountered a body it could not use. A completed record with an unexpected phrase invites a look at model behavior or prompt wording. Keep that distinction when mapping errors to a friendly message.
When an application adds tool calls to the same protocol later, update the response model and the acceptance tests. The current code decodes text content for the first choice. A tool call can appear without text and may spread its arguments across several records. Treat that as a new feature with its own validation before processing any returned tool data. For a text-only window, it is sufficient to recognize that no accepted final answer was assembled. A decoder that silently starts acting on an unexpected field can produce unwanted behavior.
Consider how the code will handle more than one output choice. The example reads choice index zero and does not request several. If your endpoint can emit alternatives, give each choice its own buffer and select which one the view shows. A repeated index can be normal because several fragments belong to one reply. It does not indicate a second reply by itself. Test with a fixture where the first alternative contains MARINA and another contains BIRCH. The visible record should never alternate between those two unrelated texts.
Build a reproducible parser check
Before connecting the first real prompt, write down three representative records. A first data line can carry a choice with content MARINA. A second data line can carry ** 27** starting with a space, and the third line can carry [DONE]. Run the same decoding path on those strings if you have separated it into a small function. The output should be MARINA 27 and finish cleanly. A second fixture ending just after the second JSON record should preserve the visible text while reporting an incomplete stream. That second case tests your end handling even though the text happens to match the expected phrase.
Add a valid empty-content record before the two text lines. This represents the fact that a server can report the assistant role without supplying visible text yet. The answer should still match. For a malformed JSON fixture in the middle of a stream, make the parser report an error rather than silently continuing past text that might have been lost. A developer deciding where to put a retry can then distinguish a syntax or protocol problem from a network interruption.
Add fixture tests around the edges of a response
Use a local test service or injectable sequence of lines when building automated checks. Begin with cases that need no actual model. Supply a role-only record, a record containing a trailing space inside the JSON string, and a record containing regular text. Put the marker at the end. Make sure the final text preserves the space in the content even though the outer line may have optional whitespace. This tests that framing and payload normalization happen at different levels.
Then supply text with an escaped newline inside one content string. The network representation remains a single JSON line while the appended text spans two displayed lines. Check the visible reply has both lines and that the parser did not interpret the embedded newline as a separate event. For a Unicode case, place a non-ASCII word in the content and ensure it displays as intended. Your fixture should exercise UTF-8 decoding without asserting how many packets a real server sends.
Add one request that returns a synthetic HTTP error and one returning ordinary application JSON. The streaming parser should reject both before appending any content. If you later display an error message from the server, handle it in that response type and avoid mixing it with a partially formed assistant reply. An acceptance test can check that the view still has its previous complete transcript after the failed attempt.
Finally, test a timeout midway through reading. Make the fixture send one valid record and then stop sending data without a completion marker. Check that the view retains or discards the first fragment according to the interface you designed. When a manual retry is available, it should begin from a fresh request and empty buffer. Otherwise a legitimate new reply can appear duplicated because the old partial value stayed in the same field.
Test the receiving interface with multiple fragments. In a GUI, let the first read complete before sending the second, or use a local fixture with a pause between them. Watch whether the visible text grows and whether the finished label appears only after the marker. A single synthetic answer is enough to define the acceptance criteria. If the actual running model responds with a longer sentence than requested, the client can still be working even though the known-output exercise needs a different prompt or candidate.
Integrate cancellation safely in a view
If this client feeds a SwiftUI view, own one Task per live reply and cancel the old task before starting a new one from the same input. Adapt the callback to send UI updates through the state holder expected by the view, typically a main-actor state object. Track which request owns the visible reply so an old request cannot append after the user has pressed Cancel and opened a new one. A short request identifier is sufficient for that purpose.
Test cancellation with a controlled fixture or a text request long enough for you to press Stop. Confirm that no more characters from the cancelled request appear in the next reply. Display a clear Stopped state and keep any partial text separately. A device can stop listening before the remote execution has fully unwound. If your server exposes request state, check it separately from UI cancellation. Closing the client stream ends its reading. It does not prove that the runtime released a slot immediately.
Avoid buffering the whole answer inside a networking callback before showing it. With a long reply, buffering changes the behavior of the interface even while the server streams. If character-level update frequency makes the view jump, collect a few fragments per UI refresh while keeping the order. Test both the final text and the visual first update. Use a harmless fixed input so you can repeat the choice after a UI change.
Locate failure by its observed stage
If the request cannot connect at all, verify the server’s loopback port and whether the client process runs on the same machine. If the server says the route exists but returns a non-success status, check model ID, request shape and local authentication. If the body is ordinary JSON, inspect whether the request set stream to true and whether the server supports the endpoint. An error from only the decoder after several valid chunks can indicate a wire variant or malformed payload. Keep a minimal sample with sensitive text removed so you can compare it with the documented shape.
Record what a working integration depends on
Write down the client target you built, the server version, the actual API path, and the name of the completion marker. An app update can change a connection without changing a model, and a server can change its streaming details without changing the model weights. Keep a synthetic request and the expected output in the project. It is easier to repeat a short test at each upgrade than to debug a detailed user transcript whose expected first reply is uncertain.
If the terminal test works while the graphical app fails, compare their environment and request setup. A sandboxed app may have different network permissions. A project may also provide its own system instructions or redirect code. Start by testing the same known endpoint and payload with the app’s current settings. Avoid increasing timeouts as the first response to a path mismatch. A short predefined input helps determine whether the app is receiving a valid request before you tune UI updates.
Keep logs focused on request IDs, response status, byte parsing outcomes, and timing needed for diagnosis. If content logging is useful in a test, use only the synthetic fixture and keep it away from logs containing private inputs. A reviewer should be able to decide if the transport worked without obtaining a prompt or local authorization value. If you have several local clients using the same endpoint, compare logs during a quiet moment so the known request is easy to identify.
Exercise a regenerated response across two application sessions
For a writing app that saves a transcript, decide exactly when a local reply becomes part of the stored document. In the exercise, send a new request for MARINA 27, let it finish, then save only after the confirmed terminal marker. Open a second session and verify the final text still appears in the correct conversation. Run the same flow with a partial fixture that stops after MARINA. Restart the app and check its policy for that partial result. There should be a visible difference between a draft the user chose to retain and a successfully completed assistant response.
Use two rapid requests to verify that your model selection stays attached to the correct traffic. For example, have your first temporary fixture send MARINA and pause. Cancel its task. Send a second request for BIRCH 19 and verify the second displayed response uses its own selected endpoint and call identity. If any of the first response appears after the second start, review which task owns the buffer and which actor updates the view. Cancellation and ownership solve different parts of the problem. A request can still race with a UI transition after the user has decided to stop it.
Some output contains leading whitespace or a newline before the first content. Decide how the user should see it. The transport parser should preserve the actual content because a client cannot tell whether a leading newline matters to a code snippet or Markdown document. If your display strips blank prefixes for a preview, keep the raw assembled reply available for a copy operation when exact formatting matters. Verify that the first visible text and copied result follow the contract you chose.
If you build a lightweight automated fixture, make the checks explicit. Keep one test for successful parsing from valid records, one for the completion flag, one for a cancelled request, and one for a reader that receives a new reply immediately after cancellation. Where possible, use an injectable byte or line source so those tests can run on a Mac whose local model endpoint is closed. A passing parsing fixture establishes the application behavior under the given response. A passing local server call adds evidence about the actual server’s wire compatibility.
Maintain the smallest example you need to reproduce a failure. Save the response status and a synthetic record containing the unexpected field, then note the app and server versions. When someone tries a new compatibility implementation, they can run the same tests with the protocol documented for it. Keep one combined acceptance log for changes that affect the reader’s ability to identify a complete reply.
After changing the endpoint, send one practice request that receives an ordinary redirect and confirm that your client rejects it before following any alternate location. A refused redirect can be a simple configuration error, such as a route supplied without a required path segment. Fix the configured route rather than accepting the alternate destination automatically. Keep a status message that helps the person operating the app inspect the original address safely. The status can report the rejected response code without displaying credentials or the full text submitted by the user.
In a reusable component, pass a text fragment to the view only once for each decoded record. Test that a view rerender alone does not append a prior fragment again.
Once the program works with the known phrase and the truncated fixture, add one real application feature at a time. For example, accept user input while preserving the explicit server and model fields. Repeat the known phrase from the view, cancel the next fixture, and confirm the following reply has its own buffer. The feature is ready for the application’s next stage when partial text cannot be mistaken for a finalized answer and the completion behavior can be reproduced independently of the selected model.