Step 4 — Think (give your companion a real AI brain)

Goal: give your companion a real AI brain. You speak, it understands, thinks with an AI model and answers out loud — with its own name and personality, and it remembers what you said. :stopwatch: ~30 minutes. :white_check_mark: Tested: builds in Xcode (iOS 17).

Builds on Step 3 — See you.

1. Get an API key (pick one)

Any provider with an OpenAI-compatible chat API works:

Provider Where to get a key Notes
Google Gemini aistudio.google.com → Get API key Generous free tier. Default in this guide.
Groq console.groq.com → API Keys Free tier, very fast.
OpenAI platform.openai.com → API keys Pay as you go.
OpenRouter openrouter.ai → Keys Many models behind one key.

:warning: Never paste your key into the code or share it in screenshots. In this step it lives in the iPhone Keychain, set from a settings screen.

2. Add Mind.swift

import Foundation
import Security

/// Where the AI "brain" lives and how it behaves. Plain settings go to UserDefaults;
/// the API key goes to the iPhone Keychain — never into your code or your Git repo.
enum MindSettings {
    static let apiKeyKey = "mind.apiKey"
    static let defaultBaseURL = "https://generativelanguage.googleapis.com/v1beta/openai"
    static let defaultModel = "gemini-2.5-flash"
    static let defaultPersona = """
        You are Loona, a friendly and curious desk companion robot. \
        Answer in one or two short sentences, warmly and with a little humor. \
        Reply in the same language the user speaks.
        """

    static var baseURL: String { UserDefaults.standard.string(forKey: "mind.baseURL") ?? defaultBaseURL }
    static var model: String { UserDefaults.standard.string(forKey: "mind.model") ?? defaultModel }
    static var persona: String { UserDefaults.standard.string(forKey: "mind.persona") ?? defaultPersona }
}

/// A tiny wrapper around the Keychain for storing one secret string per key.
enum Keychain {
    static func save(_ value: String, for key: String) {
        let base: [String: Any] = [kSecClass as String: kSecClassGenericPassword,
                                   kSecAttrAccount as String: key]
        SecItemDelete(base as CFDictionary)
        guard !value.isEmpty else { return }
        var item = base
        item[kSecValueData as String] = Data(value.utf8)
        item[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlock
        SecItemAdd(item as CFDictionary, nil)
    }

    static func read(_ key: String) -> String {
        let query: [String: Any] = [kSecClass as String: kSecClassGenericPassword,
                                    kSecAttrAccount as String: key,
                                    kSecReturnData as String: true,
                                    kSecMatchLimit as String: kSecMatchLimitOne]
        var result: AnyObject?
        guard SecItemCopyMatching(query as CFDictionary, &result) == errSecSuccess,
              let data = result as? Data else { return "" }
        return String(decoding: data, as: UTF8.self)
    }
}

/// 🧠 Mind: talks to any OpenAI-compatible chat API (OpenAI, Gemini, Groq, OpenRouter, Ollama…)
/// and remembers the conversation while the app is open.
@MainActor
final class Mind: ObservableObject {
    @Published var isThinking = false
    private var history: [[String: String]] = []

    var isConfigured: Bool { !Keychain.read(MindSettings.apiKeyKey).isEmpty }

    func reply(to text: String) async -> String {
        history.append(["role": "user", "content": text])
        history = Array(history.suffix(20))                     // keep the last 10 exchanges
        isThinking = true
        defer { isThinking = false }

        let messages = [["role": "system", "content": MindSettings.persona]] + history
        do {
            let answer = try await Self.complete(baseURL: MindSettings.baseURL,
                                                 apiKey: Keychain.read(MindSettings.apiKeyKey),
                                                 model: MindSettings.model,
                                                 messages: messages)
            history.append(["role": "assistant", "content": answer])
            return answer
        } catch {
            return "Hmm, I couldn't reach my brain. \(error.localizedDescription)"
        }
    }

    /// One call to `POST {baseURL}/chat/completions`.
    nonisolated static func complete(baseURL: String, apiKey: String, model: String,
                                     messages: [[String: String]]) async throws -> String {
        let base = baseURL.trimmingCharacters(in: .whitespacesAndNewlines)
            .trimmingCharacters(in: CharacterSet(charactersIn: "/"))
        guard let url = URL(string: base + "/chat/completions") else { throw URLError(.badURL) }

        var request = URLRequest(url: url, timeoutInterval: 30)
        request.httpMethod = "POST"
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        if !apiKey.isEmpty { request.setValue("Bearer \(apiKey)", forHTTPHeaderField: "Authorization") }
        let body: [String: Any] = ["model": model, "messages": messages]
        request.httpBody = try JSONSerialization.data(withJSONObject: body)

        let (data, response) = try await URLSession.shared.data(for: request)
        let status = (response as? HTTPURLResponse)?.statusCode ?? 0
        guard status == 200 else {
            let detail = String(decoding: data.prefix(200), as: UTF8.self)
            throw NSError(domain: "Mind", code: status,
                          userInfo: [NSLocalizedDescriptionKey: "Error \(status): \(detail)"])
        }

        struct Reply: Decodable {
            struct Choice: Decodable {
                struct Message: Decodable { let content: String? }
                let message: Message
            }
            let choices: [Choice]
        }
        let reply = try JSONDecoder().decode(Reply.self, from: data)
        return reply.choices.first?.message.content?
            .trimmingCharacters(in: .whitespacesAndNewlines) ?? "…"
    }
}

What’s inside:

  • MindSettings — provider URL, model and personality (UserDefaults).
  • Keychain — stores the API key securely on the device.
  • Mind — sends the conversation to POST {baseURL}/chat/completions and keeps the last 10 exchanges, so your companion remembers context.

3. Add SettingsView.swift

import SwiftUI

/// ⚙️ Pick an AI provider, paste your key and give your companion a personality.
struct SettingsView: View {
    @Environment(\.dismiss) private var dismiss
    @AppStorage("mind.baseURL") private var baseURL = MindSettings.defaultBaseURL
    @AppStorage("mind.model") private var model = MindSettings.defaultModel
    @AppStorage("mind.persona") private var persona = MindSettings.defaultPersona
    @State private var apiKey = Keychain.read(MindSettings.apiKeyKey)

    private struct Preset: Identifiable {
        let name: String, url: String, model: String
        var id: String { name }
    }

    private let presets = [
        Preset(name: "Google Gemini", url: "https://generativelanguage.googleapis.com/v1beta/openai", model: "gemini-2.5-flash"),
        Preset(name: "OpenAI", url: "https://api.openai.com/v1", model: "gpt-4o-mini"),
        Preset(name: "Groq", url: "https://api.groq.com/openai/v1", model: "llama-3.3-70b-versatile"),
        Preset(name: "OpenRouter", url: "https://openrouter.ai/api/v1", model: "openai/gpt-4o-mini"),
    ]

    var body: some View {
        NavigationStack {
            Form {
                Section("Quick setup") {
                    ForEach(presets) { preset in
                        Button(preset.name) {
                            baseURL = preset.url
                            model = preset.model
                        }
                    }
                }
                Section("AI provider") {
                    TextField("Base URL", text: $baseURL)
                        .keyboardType(.URL)
                        .textInputAutocapitalization(.never)
                        .autocorrectionDisabled()
                    TextField("Model", text: $model)
                        .textInputAutocapitalization(.never)
                        .autocorrectionDisabled()
                    SecureField("API key", text: $apiKey)
                }
                Section("Personality") {
                    TextEditor(text: $persona)
                        .frame(minHeight: 140)
                    Button("Reset to default") { persona = MindSettings.defaultPersona }
                }
                Section {
                    Text("Your API key is stored in this iPhone's Keychain. It is never written into your code, so you can share your project safely.")
                        .font(.footnote)
                        .foregroundStyle(.secondary)
                }
            }
            .navigationTitle("Brain")
            .toolbar {
                ToolbarItem(placement: .confirmationAction) {
                    Button("Done") {
                        Keychain.save(apiKey.trimmingCharacters(in: .whitespacesAndNewlines),
                                      for: MindSettings.apiKeyKey)
                        dismiss()
                    }
                }
            }
        }
    }
}

4. Update ContentView.swift

import SwiftUI

struct ContentView: View {
    @StateObject private var ears = Ears()
    @StateObject private var voice = Voice()
    @StateObject private var sight = Sight()
    @StateObject private var mind = Mind()
    @State private var showSettings = false
    @State private var blinking = false
    @State private var look: CGSize = .zero
    @State private var lastReply = ""

    var body: some View {
        ZStack {
            Color.black.ignoresSafeArea()

            VStack(spacing: 40) {
                Spacer()
                HStack(spacing: 56) {
                    Eye(blinking: blinking, talking: voice.isSpeaking)
                    Eye(blinking: blinking, talking: voice.isSpeaking)
                }
                .offset(mind.isThinking ? CGSize(width: 25, height: -35) : look)   // glance up while thinking
                .animation(.easeInOut(duration: 0.4), value: mind.isThinking)
                .scaleEffect(ears.isListening ? 1.12 : 1)          // eyes widen while listening
                .animation(.easeInOut(duration: 0.3), value: ears.isListening)

                Text(ears.isListening ? ears.transcript : lastReply)
                    .font(.title3)
                    .foregroundStyle(.white.opacity(0.8))
                    .multilineTextAlignment(.center)
                    .frame(minHeight: 60)
                    .padding(.horizontal)

                Spacer()

                Button(action: toggleListening) {
                    Image(systemName: ears.isListening ? "stop.circle.fill" : "mic.circle.fill")
                        .font(.system(size: 72))
                        .foregroundStyle(ears.isListening ? .red : Color(red: 0.16, green: 0.55, blue: 0.89))
                }
                .padding(.bottom, 30)

                if ears.permissionDenied {
                    Text("Allow Microphone and Speech Recognition in Settings.")
                        .font(.footnote).foregroundStyle(.orange)
                }
            }
        }
        .overlay(alignment: .topTrailing) {
            Button { showSettings = true } label: {
                Image(systemName: "gearshape.fill")
                    .font(.title2)
                    .foregroundStyle(.white.opacity(0.5))
                    .padding()
            }
        }
        .sheet(isPresented: $showSettings) { SettingsView() }
        .statusBarHidden()
        .task { await live() }
        .task { await sight.start() }
        .onDisappear { sight.stop() }
        .onChange(of: sight.face) { _, face in
            guard let face else { return }                         // nobody there: idle wandering takes over
            withAnimation(.easeOut(duration: 0.25)) {
                look = CGSize(width: face.x * 45, height: face.y * 30)   // look toward the person
            }
        }
    }

    /// Tap once to start listening, tap again to stop — then the companion answers.
    func toggleListening() {
        if ears.isListening {
            ears.stop()
            let heard = ears.transcript
            Task {
                if mind.isConfigured && !heard.isEmpty {
                    lastReply = "…"
                    lastReply = await mind.reply(to: heard)      // real AI (Step 4)
                } else {
                    lastReply = Brain.reply(to: heard)           // simple rules (Step 2) until a key is set
                }
                voice.say(lastReply)
            }
        } else {
            Task {
                guard await ears.requestPermissions() else { return }
                try? ears.start()
            }
        }
    }

    func blink() async {
        withAnimation(.easeIn(duration: 0.08)) { blinking = true }
        try? await Task.sleep(for: .milliseconds(110))
        withAnimation(.easeOut(duration: 0.14)) { blinking = false }
    }

    func live() async {
        while !Task.isCancelled {
            try? await Task.sleep(for: .seconds(Double.random(in: 2...5)))
            await blink()
            if Bool.random() && !ears.isListening && sight.face == nil {
                withAnimation(.spring(response: 0.6, dampingFraction: 0.7)) {
                    look = CGSize(width: .random(in: -40...40), height: .random(in: -20...20))
                }
            }
        }
    }
}

struct Eye: View {
    var blinking: Bool
    var talking: Bool
    @State private var bounce = false
    private let blue = Color(red: 0.16, green: 0.55, blue: 0.89)

    var body: some View {
        Ellipse()
            .fill(blue)
            .frame(width: 90, height: 130)
            .scaleEffect(x: 1, y: blinking ? 0.08 : (talking && bounce ? 0.85 : 1))
            .shadow(color: blue.opacity(0.8), radius: 24)
            .onChange(of: talking) { _, isTalking in
                withAnimation(isTalking ? .easeInOut(duration: 0.18).repeatForever() : .default) {
                    bounce = isTalking
                }
            }
    }
}

#Preview { ContentView() }

New: a :gear: button opens Settings; after you stop talking, the app asks the Mind (if a key is set) or falls back to the simple rules from Step 2. While it thinks, the eyes glance up. :thinking:

5. Run it

  1. Tap :gear: → Google Gemini (or another preset) → paste your API key → edit the personality if you like → Done.
  2. Tap the mic and ask anything: “Tell me a fun fact about the Moon”, “What should I cook tonight?”, “What did I just ask you?” (it remembers!).
  3. Tap stop — the eyes glance up while it thinks, then it answers out loud.

Give it a personality :performing_arts:

The personality text is the system prompt. Make it yours:

You are Nova, a cheerful robot who loves space facts and bad puns. Keep answers under two sentences.

Troubleshooting

  • “Error 401/403” → wrong or missing API key.
  • “Error 404” → check the base URL and model name for your provider.
  • “Error 429” → you hit the provider’s rate limit; wait a minute.

Make it yours :artist_palette:

Ask your AI assistant:

  • “Tell the AI what the camera sees: add ‘A person is looking at you’ to the message when a face is in view.”
  • “Stream the answer and start speaking the first sentence before the rest arrives.”
  • “Add a ‘forget’ voice command that clears the conversation history.”
  • “Pick the speech voice and recognizer language from Settings.”

Show us your companion’s personality in Show & Tell! :robot:

:left_arrow: Step 3 — See you · :right_arrow: Next: Step 5 — Move :locked: members-only (trust level 2) — it unlocks automatically after a little time and activity on the forum.

This is a wiki post — model names change often; please update them when needed.

1 Like