AI Orchestration

Understand Vyron, Qwen, and Ollama, then build a native SwiftUI local AI chat interface with model requests, cancellation, errors, and clear privacy boundaries.

~28 min reading~3 min practice estimate
Suggest content

Build Your Own Local AI GUI with Qwen and Ollama

A local AI chat app has three separate jobs. The app presents a conversation and decides what to send. The model supplies learned weights that predict the answer. The runtime loads those weights and performs the computation. In a Vyron-style setup, Vyron is the application layer, Qwen is a model family, and Ollama is one possible local runtime. This lesson builds a small, separate macOS app to make those boundaries visible. It uses synthetic prompts and contains no personal project data.

PartOwnsDoes not do by itself
SwiftUI appInput, model picker, visible messages, error and cancel controlsExecute a model's weights
Qwen checkpointLearned numerical weights and model-specific behaviorListen for HTTP requests or draw a GUI
Ollama runtimeDownload/load compatible models, expose a local API, schedule inference on available hardwareDecide which private files an agent may read

🧠 A model file is data, even though it contains the learned behavior. A runtime is needed to read its format, tokenize input, allocate memory and cache, run the model on CPU/GPU, and turn generated tokens into a response. A different runtime can sometimes serve the same model format; the app-to-runtime contract is what lets you swap implementations.

The local request path

TEXT
You → macOS SwiftUI window → HTTP on 127.0.0.1:11434 → Ollama → Qwen weights
You ← rendered assistant message ← JSON response       ← generated tokens

Text alternative: the GUI sends a chat request to Ollama's loopback API on the same Mac. Ollama loads the selected Qwen checkpoint, computes an answer, and returns a message that the GUI displays. The app owns conversation state; Ollama owns inference. In this example the app sends its current message history with each request. Ollama's chat API accepts a model name and message array at POST /api/chat.

🟨 macOS and iPhone are different machines. In a macOS app, 127.0.0.1 refers to the Mac. In a physical iPhone app, 127.0.0.1 refers to the phone, so it cannot reach Ollama running on the Mac. A phone client needs a deliberately designed bridge to the Mac or another server, with authentication, encrypted transport, and an approved network boundary. Do not expose an unauthenticated Ollama listener to the internet just to make a phone demo work.

Prepare Ollama and a small Qwen model

These steps target macOS 14 or later, Xcode with SwiftUI, and a current Ollama installation. Install and open Ollama from its official quickstart. Ollama's default server listens on 127.0.0.1:11434 according to its FAQ. If the app is already running, do not start a second server on the same port.

Choose a small demonstration model rather than assuming the largest Qwen checkpoint fits. Ollama lists qwen3:4b as a real downloadable tag. It is Qwen3 4B, distinct from the Qwen3.8-27B and Qwen3.8-2.4T-A95B examples in Model Quantization Explained. Its presence here is a teaching choice, not a claim that it is the best model for coding or every Mac.

BASH
ollama pull qwen3:4b
curl http://127.0.0.1:11434/api/tags

The pull needs internet access and free disk space. The tags response should list qwen3:4b. Then test the local chat endpoint with a harmless prompt:

BASH
curl http://127.0.0.1:11434/api/chat \
  -H 'Content-Type: application/json' \
  -d '{"model":"qwen3:4b","messages":[{"role":"user","content":"Say hello in one sentence."}],"stream":false}'

With "stream":false, read the answer from message.content in one JSON response. Without that option, Ollama streams newline-delimited JSON by default. The chat, model-list, and streaming references define these contracts. Local inference through this loopback API needs no cloud API key; the installed model still needs adequate available memory.

Create the macOS project and allow the local connection

  1. In Xcode, create a macOS App with SwiftUI and Swift. Set the deployment target to macOS 14 or later for this example.
  2. Replace the starter app file with the complete LocalAIChatApp.swift example below. Keep only one @main app type in the target.
  3. If App Sandbox is enabled, turn on Outgoing Connections (Client) for the app target. Apple says this entitlement permits a sandboxed app to initiate a connection even to a server on the same machine. Apple App Sandbox network entitlement.
  4. For loopback HTTP, set App Transport Security Settings → Allows Local Networking (NSAppTransportSecurity → NSAllowsLocalNetworking = YES) in the app target's Info settings. Apple's local-networking key documentation covers IP addresses and OS-version behavior. Keep this exception scoped to local networking; do not enable arbitrary loads for every destination.
  5. Run Ollama and confirm the curl request works before launching the GUI. Build and run the macOS app, refresh the model picker, and send a short prompt.

The GUI is a client, so it needs outgoing, not incoming, network permission. If your target uses a custom network policy or older deployment versions, verify its actual ATS behavior rather than copying a broad exception.

A complete SwiftUI chat window

🟦 Single-file teaching example for macOS 14+ and Swift 6. It keeps history in memory for the current window, lists installed models with GET /api/tags, sends POST /api/chat with stream:false, and cancels an in-flight request. It does not implement tools, file access, or cloud fallback.

SWIFT
import SwiftUI
​
private struct ChatPayload: Codable, Sendable {
    let role: String
    let content: String
}
​
private struct ChatLine: Identifiable {
    let id = UUID()
    let role: String
    let content: String
}
​
private struct ChatRequest: Encodable, Sendable {
    let model: String
    let messages: [ChatPayload]
    let stream: Bool
}
​
private struct ChatReply: Decodable, Sendable {
    let message: ChatPayload
}
​
private struct ModelList: Decodable, Sendable {
    let models: [ModelSummary]
}
​
private struct ModelSummary: Decodable, Sendable {
    let name: String
}
​
private enum LocalChatError: LocalizedError {
    case invalidResponse
    case httpStatus(Int)
    case emptyReply
​
    var errorDescription: String? {
        switch self {
        case .invalidResponse:
            return "Ollama returned an invalid response."
        case .httpStatus(let code):
            return "Ollama returned HTTP \(code)."
        case .emptyReply:
            return "The model returned no visible answer."
        }
    }
}
​
private struct OllamaClient: Sendable {
    private let baseURL = URL(string: "http://127.0.0.1:11434")!
​
    func installedModels() async throws -> [String] {
        let url = baseURL.appendingPathComponent("api/tags")
        let (data, response) = try await URLSession.shared.data(from: url)
        try check(response)
        return try JSONDecoder().decode(ModelList.self, from: data)
            .models.map(\.name)
    }
​
    func answer(model: String, messages: [ChatPayload]) async throws -> String {
        let url = baseURL.appendingPathComponent("api/chat")
        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.timeoutInterval = 180
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.httpBody = try JSONEncoder().encode(
            ChatRequest(model: model, messages: messages, stream: false)
        )
​
        let (data, response) = try await URLSession.shared.data(for: request)
        try check(response)
        let reply = try JSONDecoder().decode(ChatReply.self, from: data)
            .message.content.trimmingCharacters(in: .whitespacesAndNewlines)
        guard !reply.isEmpty else { throw LocalChatError.emptyReply }
        return reply
    }
​
    private func check(_ response: URLResponse) throws {
        guard let http = response as? HTTPURLResponse else {
            throw LocalChatError.invalidResponse
        }
        guard (200...299).contains(http.statusCode) else {
            throw LocalChatError.httpStatus(http.statusCode)
        }
    }
}
​
@main
struct LocalAIChatApp: App {
    var body: some Scene {
        WindowGroup {
            ChatView()
                .frame(minWidth: 560, minHeight: 440)
        }
    }
}
​
@MainActor
private struct ChatView: View {
    @State private var draft = ""
    @State private var messages: [ChatLine] = []
    @State private var models: [String] = []
    @State private var selectedModel = ""
    @State private var isSending = false
    @State private var errorText: String?
    @State private var sendTask: Task<Void, Never>?
​
    private let client = OllamaClient()
​
    var body: some View {
        VStack(alignment: .leading, spacing: 12) {
            HStack {
                Picker("Local model", selection: $selectedModel) {
                    ForEach(models, id: \.self) { model in
                        Text(model).tag(model)
                    }
                }
                .disabled(models.isEmpty || isSending)
​
                Button("Refresh Models") {
                    Task { await refreshModels() }
                }
                .disabled(isSending)
​
                Button("Clear Chat") {
                    messages.removeAll()
                    errorText = nil
                }
                .disabled(messages.isEmpty || isSending)
            }
​
            ScrollView {
                LazyVStack(alignment: .leading, spacing: 10) {
                    ForEach(messages) { line in
                        VStack(alignment: .leading, spacing: 4) {
                            Text(line.role == "user" ? "You" : "Assistant")
                                .font(.caption.bold())
                            Text(line.content)
                                .textSelection(.enabled)
                        }
                        .frame(maxWidth: .infinity, alignment: .leading)
                        .padding(10)
                        .background(
                            line.role == "user"
                                ? Color.blue.opacity(0.12)
                                : Color.gray.opacity(0.12),
                            in: RoundedRectangle(cornerRadius: 8)
                        )
                    }
                }
                .frame(maxWidth: .infinity, alignment: .leading)
            }
​
            if let errorText {
                Text(errorText)
                    .foregroundStyle(.red)
                    .accessibilityLabel("Chat error: \(errorText)")
            }
​
            HStack(alignment: .bottom) {
                TextField("Message", text: $draft, axis: .vertical)
                    .lineLimit(1...4)
                    .disabled(selectedModel.isEmpty || isSending)
​
                Button("Send", action: send)
                    .disabled(selectedModel.isEmpty || isSending
                              || draft.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
​
                if isSending {
                    Button("Stop") { sendTask?.cancel() }
                }
            }
        }
        .padding()
        .task { await refreshModels() }
        .onChange(of: selectedModel) { _, _ in messages.removeAll() }
        .onDisappear { sendTask?.cancel() }
    }
​
    private func refreshModels() async {
        do {
            let installed = try await client.installedModels()
            try Task.checkCancellation()
            models = installed
            if !installed.contains(selectedModel) {
                selectedModel = installed.first ?? ""
            }
            errorText = installed.isEmpty
                ? "No model installed. Run ollama pull qwen3:4b."
                : nil
        } catch is CancellationError {
            return
        } catch {
            errorText = "Cannot reach Ollama: \(error.localizedDescription)"
        }
    }
​
    private func send() {
        let prompt = draft.trimmingCharacters(in: .whitespacesAndNewlines)
        guard !prompt.isEmpty, !selectedModel.isEmpty, !isSending else { return }
​
        let model = selectedModel
        messages.append(ChatLine(role: "user", content: prompt))
        let history = messages.map { ChatPayload(role: $0.role, content: $0.content) }
        draft = ""
        errorText = nil
        isSending = true
​
        sendTask = Task {
            do {
                let reply = try await client.answer(model: model, messages: history)
                try Task.checkCancellation()
                messages.append(ChatLine(role: "assistant", content: reply))
            } catch {
                messages.removeLast()
                draft = prompt
                errorText = Task.isCancelled
                    ? "Request stopped. Your message is ready to retry."
                    : error.localizedDescription
            }
            isSending = false
            sendTask = nil
        }
    }
}

The request copies the visible conversation into the API payload. The Send button is disabled while one request is active, and Stop cancels the stored task. On cancellation or error, the in-flight user line is removed and its text returns to the input, so Retry is a new Send rather than a duplicate turn. Changing models clears the current conversation. The example stores no transcript on disk.

🟨 Scope of this example: It type-checks as a SwiftUI app, but a production chat app should bound history and input size, manage window lifetime explicitly, show progress and accessibility announcements, and decide whether to persist transcripts. The 180-second request timeout is a teaching default, not a capacity estimate. Do not send private files or tool results to the model without a separate permission design.

Streaming, memory, and privacy choices

The tutorial uses stream:false so one response is easy to decode and cancellation is easy to see. For token-by-token display, omit that flag or set it to true, then consume newline-delimited JSON instead of decoding the entire body as one JSON object. Append each chunk's message.content to one assistant line, handle the final done event, and stop the stream when the view or task is canceled. Ollama streaming reference. Do not use a naive string split on arbitrary network byte chunks; a JSON line can cross byte boundaries.

The model download size is not the runtime memory budget. Weights, context/KV cache, and other applications all consume memory; a larger Qwen tag can make the app slow or fail to load. Choose an installed model based on the Mac's available memory, then measure time to first response, total latency, and peak memory. Model quantization and memory explains the sizing terms.

Local inference means this GUI calls a server on the same Mac. The initial model pull uses the internet, and other apps or plugins may still have their own network paths. Ollama's FAQ says its default listener is loopback and documents OLLAMA_NO_CLOUD=1 or disable_ollama_cloud for disabling Ollama's cloud features after configuring and restarting the actual server process. That setting does not govern your GUI, operating system, or future plugins. Keep this sample on loopback and inspect its real network behavior before making a strict offline claim. Private local AI blueprint covers that wider boundary.

Extensions after the first chat works

Next capabilityAdd only after checking
Saved historyA local storage format, deletion policy, migration, and a visible clear action
Streaming repliesIncremental NDJSON parsing, cancellation, partial-output state, and accessibility announcements
File or code toolsUser-selected paths, a tool broker, scoped permissions, reviewable effects, and denial tests
Physical iPhone clientAuthenticated Mac/backend bridge, TLS, network reachability, and explicit data policy
Different runtimeCompatible model format, API adapter, cancellation semantics, and measured quality/speed

Practice: diagnose a localhost mistake

Prompt: The SwiftUI app works on a Mac. You copy its URL unchanged into an iPhone app, but the phone cannot connect. A teammate suggests binding Ollama to every network interface and opening the port publicly. Explain the failure and propose a safe next step.

Answer

On the phone, 127.0.0.1 is the phone itself. It is not the Mac. Keep the Mac's model server private while you design an authenticated bridge or companion service for the phone, with encrypted transport and controlled access. Test the app and bridge using synthetic prompts. Opening an unauthenticated model endpoint publicly would give other clients access to inference and would invalidate the simple local-only privacy claim.

Quick Recap

  • The app owns interaction and permission decisions; Qwen supplies weights; Ollama loads and runs them.
  • A runtime handles tokenization, memory, computation, and the local API. A model file alone cannot answer HTTP requests.
  • A macOS app can use Mac loopback; a physical iPhone cannot use that same loopback address to reach the Mac.
  • GET /api/tags lists installed models; POST /api/chat with stream:false returns one JSON response.
  • Local inference, Ollama cloud disablement, and strict offline operation are different claims.

Key Takeaways

Build the smallest working loop first: download a model that fits, verify Ollama's local API, send one typed request, render the response, and handle errors and cancellation. Add streaming, persistence, tools, and mobile access only after their memory and privacy boundaries are explicit.