<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Lawrence Norman on Medium]]></title>
        <description><![CDATA[Stories by Lawrence Norman on Medium]]></description>
        <link>https://medium.com/@lawrencenorman7hills?source=rss-36967447924d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*vXqBacYYzA4g9NuR</url>
            <title>Stories by Lawrence Norman on Medium</title>
            <link>https://medium.com/@lawrencenorman7hills?source=rss-36967447924d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 03:29:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@lawrencenorman7hills/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Building in mChatAI+ AI Software as Assembly, Not One-Shot Generation: from Chess to Speed Chess to…]]></title>
            <link>https://medium.com/@lawrencenorman7hills/building-in-mchatai-ai-software-as-assembly-not-one-shot-generation-from-chess-to-speed-chess-to-20071ebbc682?source=rss-36967447924d------2</link>
            <guid isPermaLink="false">https://medium.com/p/20071ebbc682</guid>
            <dc:creator><![CDATA[Lawrence Norman]]></dc:creator>
            <pubDate>Wed, 15 Jul 2026 23:03:40 GMT</pubDate>
            <atom:updated>2026-07-15T23:03:40.998Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building in mChatAI+ AI Software as Assembly, Not One-Shot Generation: from Chess to Speed Chess to Chaos Chess.</h3><p><em>I built a chess game up over a series of turns, one focused edit at a time. From there I was able to quickly iterate different versions like Speed Chess, 6x6 chess and completely new games like Chaos Chess.</em></p><p>We’ve all seen the demos: you type one sentence, a giant model thinks for a while, and a finished program falls out. But that isn’t how useful software actually gets built.</p><p>What is more realistic in AI software-building is <strong>assembly plus iteration</strong>. A model — perhaps even a cheap one — can compose from already-correct reusable parts, and then from there evolve it one focused change at a time.</p><p>You can browse the <a href="https://mchatai.com/hub">mchatai.com/hub</a> and peruse the 100s of games that use lego code, but for today let’s focus on the chess games in the hub which are live, playable and easy enough to turn into completely new game iterations with just a little imagination.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8bl2Tw2XpI3oq7pYVgbVgg.png" /></figure><h3>The original ask was demanding</h3><p>Here’s the exact goal that kicked it off, verbatim:</p><blockquote>“Chess versus the computer with an Easy / Medium / Hard difficulty selector. The computer opponent MUST use a real chess engine (minimax with piece-square evaluation) that defends its pieces and does not give away material — not random moves. Easy = shallow search, Hard = deeper search.”</blockquote><p>Note that it asks for a <em>real chess engine</em> — one that defends, that gets stronger with search depth, that isn’t shuffling pieces at random. This is the request that usually exposes toy AI builders, because a legal-move-generating, check-aware, alpha-beta-pruning chess engine is genuinely fiddly to get right from scratch.</p><p><strong>But the model did not write a chess engine from scratch.</strong></p><h3>The engine came from the registry as Lego</h3><p>Instead, it assembled the game out of reusable components — we call them Lego — pulled from a public code registry called mchatai-source. The parts it wired together, by their real paths:</p><ul><li>entities/Board8x8.js — the 8×8 board model</li><li>entities/ChessRules.js — the legal-move engine</li><li>entities/ChessAI.js — the opponent</li><li>entities/MinimaxAI.js — the generic search</li><li>core/TurnBasedManager.js — turn orchestration</li><li>resources/AudioManager.js — procedural sound</li></ul><p>ChessRules.js does per-piece pseudo-legal move generation, then filters those moves so you can&#39;t leave your own king in check (_wouldLeaveKingInCheck / isKingInCheck). It detects checkmate and stalemate. It handles castling, en passant, and pawn promotion. It has a FEN position parser and a move-history stack. ChessAI.js is negamax with alpha-beta pruning — literally if (alpha &gt;= beta) break — over a material-plus-piece-square-table evaluation. The piece values are the classic ones: pawn 100, knight 320, bishop 330, rook 500, queen 900, king 20000.</p><p>The difficulty selector is a search depth knob: DEPTHS = { easy: 2, medium: 3, hard: 4 } plies. Depth 3 gets you a competent move in about a second; depth 0 is an instant random legal move. &quot;Easy = shallow search, Hard = deeper search&quot;.</p><blockquote>The engine is correct because its parts were already correct and tested — not because a very large model got lucky on one very long generation.</blockquote><p>“MUST use a real chess engine” — is satisfied by reaching for parts that were already correct, not by asking a model to reinvent them and hoping.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2l9WkmsuQVc4USlqznmtXw.png" /></figure><h3>Then the interesting work started: iteration</h3><p>A working chess-vs-computer game is the <em>beginning</em>, not the end. The real fun showed up when I started evolving it with further bug fixes and iterations:</p><p><strong>mobile-first.</strong> Maximize the board to fill the mobile width with 44px-plus touch targets.</p><p><strong>castling notation.</strong> Handle castling.</p><p><strong>the speed clock.</strong> Two mm:ss countdown clocks (whiteTime / blackTime); on each move you stop your clock and start your opponent&#39;s; at 0:00 that side loses on time — &quot;White wins on time&quot; / &quot;Black wins on time&quot; —That single feature turned &quot;chess vs. computer&quot; into <strong>Speed Chess</strong>.</p><p>So the true arc is small and legible: <strong>chess engine origin → mobile-friendly → castling → speed clock, shipped as v5.</strong> Nobody sat down and specced “Speed Chess” up front. It <em>became</em> Speed Chess because we already had chess, and each new step was cheap to make and cheap to verify.</p><blockquote>The frontier-model flex is to generate a whole program from scratch. The assembly approach is gradual sculpting from known good lego components.</blockquote><h3>What the harness does between those edits</h3><p>That last part — “cheap to verify” — is where the tooling earns its keep. The builder is AI Harness, inside mChatAI+ for macOS. It turns a plain-English goal into a playable mini-app and then iterates the same way. Four behaviors made the chess arc safe to run at speed:</p><ol><li><strong>Verified before install.</strong> Each build is loaded and render-checked <em>before</em> it lands. If it fails, the harness auto-iterates instead of handing me something broken.</li><li><strong>Made offline-safe.</strong> External references get localized, so the final artifact runs with no network at all.</li><li><strong>Side-by-side versions.</strong> Base, castling, clock, mobile — kept as distinct, comparable builds, so “did the clock break castling?” is a thing you can actually look at.</li><li><strong>One publish flow.</strong> A single step ships a self-contained bundle to the Community Hub, playable in any browser with nothing for the player to install.</li></ol><p>You can play the result right now: <a href="https://mchatai.com/hub/speed-chess-v5/play"><strong>Speed Chess</strong></a>. The build materials and version detail live at <a href="https://mchatai.com/hub/speed-chess-v5"><strong>the detail page</strong></a> behind a free sign-in.</p><h3>The rest of the platform</h3><p>The chess story leans on three more pieces worth naming.</p><p><strong>The open-source companion, and a sandbox boundary.</strong> mChatAI+ ships from one codebase on two channels. The <strong>Mac App Store build is fully sandboxed and clean</strong>: it talks to models directly with your keys and renders + verifies mini-apps in a WKWebView. It does not shell out. The unsandboxed muscle — driving coding-agent CLIs, running local toolchains and microservices — is delegated to a <em>separate</em>, open-source menu-bar companion, <strong>mChatAIShell</strong>. It runs a local HTTP server on port 8765 with bearer-token auth on every request, does capability probes, executes shell, manages Python microservice sidecars and git packages, and takes screenshots via ScreenCaptureKit. It spawns Claude Code, Codex, and Gemini as dev sessions. API keys live in the macOS Keychain — mChatAI+ is the <em>writer</em>, mChatAIShell is a <em>reader</em> that injects them as env vars into dev processes. No keys in files, none over HTTP. Splitting muscle from the sandboxed app is deliberate and it respects Apple’s sandbox, and it’s honest about what runs where.</p><p><strong>The iOS bridge.</strong> mChatAI for iOS calls hundreds of cloud models from your phone (BYOK), and it bridges to your Mac over a Firebase relay — so you can kick off and preview Harness jobs running on your mChatAI+ Mac, remotely, from your phone. <a href="https://apps.apple.com/us/app/mchatai/id6445939409">Get it on the App Store</a>.</p><p><strong>mchatai-source: prompts, wisdom, and resources.</strong> <a href="https://github.com/LawrenceNorman/mchatai-source">mchatai-source</a> is a public, MIT-licensed code registry on GitHub — skills/, miniapps/, games/, microservices/, frameworks/ (home of the web-components Lego), pipelines/, agents/, wisdom/, llm-catalog/, and a master catalog.json. Every artifact carries a manifest.json and a quality score. It also carries <em>wisdom packs</em>: versioned JSON rules, each with a WHY grounded in a real complaint or a real shipped bug.</p><h3>Chess can keep branching</h3><p>Speed Chess wasn’t the only thing that came out of that core:</p><ul><li><a href="https://mchatai.com/hub/chaos-chess"><strong>chaos-chess</strong></a> — chess, but every three turns a dice roll drops a brand-new piece onto the board. Same legal-move engine underneath; one wild rule layered on top.</li><li><a href="https://mchatai.com/hub/pawnkeep-chess-6x6"><strong>6×6 chess</strong></a> — the same game on a compact 6×6 board.</li></ul><p>The <strong>same</strong> registry Lego — Board8x8, ChessRules, ChessAI — assembles into a purist&#39;s game <em>and</em> into dice-roll chaos.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wa34jH2mtGV5I7S8uTiujg.png" /></figure><h3>The reframe</h3><p>Don’t just picture AI software as one enormous model dictating a finished program. Picture affordable models reaching into a git registry of already-correct parts, wiring them into something that works, verifying it before it lands, and then evolving it one prompt at a time.</p><p>If you want the sandboxed builder itself, it’s on the Mac App Store: <a href="https://apps.apple.com/us/app/mchatai/id6757826624?mt=12"><strong>mChatAI+</strong></a> — it builds and verifies mini-apps in-sandbox with your own keys. <em>(The CLI dev-sessions in the receipts above run through the separate open-source companion, mChatAIShell.)</em> The parts are public at <a href="https://github.com/LawrenceNorman/mchatai-source">mchatai-source</a> on GitHub. And the chess is <a href="https://mchatai.com/hub/speed-chess-v5/play">right here</a> — go take time off the computer.</p><p><em>More build write-ups at </em><a href="https://mchatai.com/blog"><em>mchatai.com/blog</em></a><em>.</em></p><p>— Lawrence</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=20071ebbc682" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Upgrading from Expo SDK 52 to SDK 53: Firebase JS SDK Migration to React Native Firebase]]></title>
            <link>https://medium.com/@lawrencenorman7hills/upgrading-from-expo-sdk-52-to-sdk-53-firebase-js-sdk-migration-to-react-native-firebase-1c2e0ae2b544?source=rss-36967447924d------2</link>
            <guid isPermaLink="false">https://medium.com/p/1c2e0ae2b544</guid>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[expo]]></category>
            <category><![CDATA[firebase]]></category>
            <dc:creator><![CDATA[Lawrence Norman]]></dc:creator>
            <pubDate>Sun, 06 Jul 2025 16:55:38 GMT</pubDate>
            <atom:updated>2025-07-07T17:52:54.036Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A continuation of my Expo upgrade series — this time tackling a mandatory Firebase migration upgrade.</em></p><p>After successfully navigating the <a href="https://medium.com/@lawrencenorman7hills/upgrading-from-expo-sdk-51-to-expo-sdk-52-cf5f66e29843">Expo SDK 51 to 52 upgrade</a>, I hopeful this next Expo upgrade from 52 to 53, would go easy. But I found that when I attempted to upgrade my Quiznect React Native app from Expo SDK 52 to SDK 53, I hit what initially seemed like a simple dependency issue but turned out to be a complete architectural shift that required migrating my entire Firebase implementation.</p><h3>The Dead End: Firebase JS SDK vs Expo SDK 53</h3><p>The upgrade started normally enough:</p><pre>npx expo install expo@latest<br>npx expo install --fix</pre><p>But after upgrading, and encountering:</p><p>❌ Pods/React-RuntimeHermes: Redefinition of module ‘react_runtime’</p><p>and writing a plugin to address that issue, I finally got a working build, and I was hopeful. But when I ran my Quiznect app, I encountered this error:</p><p><strong>Error: Component auth has not been registered yet, js engine: hermes</strong></p><p>Currently as of July 6, 2025, this is an open issue: [SDK 53] Firebase JS SDK for Auth is incompatible with Metro’s package.json:exports #36588: <a href="https://github.com/expo/expo/issues/36588">https://github.com/expo/expo/issues/36588</a></p><p>We have two Firebase approaches:</p><ol><li><strong>React Native Firebase</strong> (@react-native-firebase/app) — the native SDK</li><li><strong>Firebase JS SDK</strong> (firebase/app, firebase/auth) — the web/JS SDK</li></ol><p>It was time to convert to the React Native Firebase package, but this would involve extensive code changes all over my app, ultimately involving more than 14 different files. It was something I had considered earlier and put off; but at some point you have to bite the bullet, and there are advantages to React Native Firebase.</p><h3>Why React Native Firebase is Recommended</h3><p>For a mobile application, <strong>React Native Firebase is unequivocally better</strong> than the Firebase JS SDK. I found that the primary benefits of using the native SDK on mobile are:</p><ul><li><strong>Better Performance:</strong> It uses the native iOS and Android Firebase SDKs directly, which is much faster than running everything through the JavaScript bridge required by the web SDK.</li><li><strong>Access to Native-Only Features:</strong> You gain access to critical mobile services that are impossible to implement with the JS SDK, most notably <strong>Firebase Crashlytics</strong> and <strong>Performance Monitoring</strong>.</li><li><strong>Superior Offline Support:</strong> The native SDK has more robust and reliable offline data persistence for features like Firestore, which is essential for a good mobile user experience.</li><li><strong>Proper Platform Integration:</strong> It provides deeper, more reliable integration with core mobile platform services like push notifications (Firebase Cloud Messaging), background tasks, and more.</li></ul><h3>The Migration Strategy</h3><p>Rather than attempt a partial migration, I decided to convert all Firebase usage in one go. Here’s the systematic approach I took:</p><h3>Step 1: Remove Firebase JS SDK Completely</h3><pre>npm uninstall firebase<br>npm uninstall @firebase/auth @firebase/firestore @firebase/analytics @firebase/functions @firebase/storage @firebase/app</pre><h3>Step 2: Install React Native Firebase Modules</h3><pre>npx expo install @react-native-firebase/app<br>npx expo install @react-native-firebase/auth<br>npx expo install @react-native-firebase/firestore<br>npx expo install @react-native-firebase/functions<br>npx expo install @react-native-firebase/analytics</pre><h3>Step 3: Update firebase.js Configuration</h3><p>The biggest change was replacing my Firebase configuration file:</p><p><strong>OLD (Firebase JS SDK):</strong></p><pre>import { initializeApp } from &#39;firebase/app&#39;;<br>import { initializeAuth, getReactNativePersistence } from &#39;firebase/auth&#39;;<br>import { getFirestore } from &#39;firebase/firestore&#39;;<br>import AsyncStorage from &#39;@react-native-async-storage/async-storage&#39;;<br><br>const firebaseConfig = {<br>  // config object<br>};<br>const app = initializeApp(firebaseConfig);<br>const auth = initializeAuth(app, {<br>  persistence: getReactNativePersistence(AsyncStorage),<br>});<br>const firestore = getFirestore(app);<br>export { auth, firestore };</pre><p><strong>NEW (React Native Firebase):</strong></p><pre>import &#39;@react-native-firebase/app&#39;;<br>import authModule from &#39;@react-native-firebase/auth&#39;;<br>import firestoreModule from &#39;@react-native-firebase/firestore&#39;;<br>import functionsModule from &#39;@react-native-firebase/functions&#39;;<br>import analyticsModule from &#39;@react-native-firebase/analytics&#39;;<br><br>export const auth = authModule;<br>export const firestore = firestoreModule;<br>export const analytics = analyticsModule;<br>export const functions = functionsModule;</pre><p>React Native Firebase automatically uses your GoogleService-Info.plist and google-services.json files, so no manual configuration is needed.</p><h3>The Syntax Translation Challenge</h3><p>The most time-consuming part was converting all Firebase operations throughout my codebase. Here are the key syntax changes:</p><h3>Authentication</h3><pre>// OLD<br>import { signInWithEmailAndPassword, sendEmailVerification } from &#39;firebase/auth&#39;;<br>await signInWithEmailAndPassword(auth, email, password);<br>await sendEmailVerification(user);<br><br>// NEW<br>await auth().signInWithEmailAndPassword(email, password);<br>await user.sendEmailVerification();</pre><h3>Firestore Operations</h3><pre>// OLD<br>import { doc, getDoc, setDoc, collection, addDoc, query, where, orderBy, getDocs, serverTimestamp } from &#39;firebase/firestore&#39;;<br><br>const userDocRef = doc(firestore, &#39;users&#39;, uid);<br>const userDoc = await getDoc(userDocRef);<br>await setDoc(userDocRef, data, { merge: true });<br>await addDoc(collection(firestore, &#39;userScores&#39;), data);<br>const q = query(<br>  collection(firestore, &#39;users&#39;),<br>  where(&#39;screenName&#39;, &#39;==&#39;, name),<br>  orderBy(&#39;score&#39;, &#39;desc&#39;)<br>);<br>const snapshot = await getDocs(q);<br><br><br>// NEW<br>const userDocRef = firestore().collection(&#39;users&#39;).doc(uid);<br>const userDoc = await userDocRef.get();<br>await userDocRef.set(data, { merge: true });<br>await firestore().collection(&#39;userScores&#39;).add(data);<br>const snapshot = await firestore()<br>  .collection(&#39;users&#39;)<br>  .where(&#39;screenName&#39;, &#39;==&#39;, name)<br>  .orderBy(&#39;score&#39;, &#39;desc&#39;)<br>  .get();<br>// Timestamps<br>// OLD: serverTimestamp()<br>// NEW: firestore.FieldValue.serverTimestamp()</pre><h3>Files That Required Updates</h3><p>In my project, I had to update <strong>14 different files</strong> that used Firebase, and each file required careful conversion of every Firebase operation.</p><h3>The Build Process</h3><p>After completing the code migration:</p><pre># Ensure all packages are compatible<br>npx expo install --fix<br><br># Clean build to remove any cached JS SDK references<br>npx expo prebuild --clean<br><br># Test the app<br>npx expo run:ios</pre><h3>Key Lessons Learned</h3><ol><li><strong>Don’t mix Firebase SDKs</strong> — Choose one approach and stick with it</li><li><strong>Authentication state is critical</strong> — Always verify auth before Firestore operations</li><li><strong>Plan for a complete migration</strong> — Partial migrations create more problems</li><li><strong>Test thoroughly</strong> — Auth-related bugs can be subtle and crash-inducing</li><li><strong>Expo SDK upgrades often require architectural changes</strong> — Not just dependency updates</li></ol><h3>Performance Benefits</h3><p>After the migration, I noticed several improvements:</p><ul><li><strong>Faster cold starts</strong> — Native Firebase initialization is quicker</li><li><strong>Better offline support</strong> — React Native Firebase handles offline scenarios better</li><li><strong>Improved reliability</strong> — Fewer authentication-related issues</li></ul><h3>Conclusion</h3><p>While this upgrade was significantly more complex than previous ones, the migration to React Native Firebase was ultimately necessary and beneficial. The forced architectural change, while painful in the short term, resulted in a more robust and performant app.</p><p>If you’re facing a similar upgrade path, my advice is:</p><ol><li><strong>Accept that this is a major migration</strong>, not a simple dependency update</li><li><strong>Budget adequate time</strong> — This took me a full day</li><li><strong>Test authentication flows thoroughly</strong> — They’re the most likely to break</li><li><strong>Consider it an investment</strong> — React Native Firebase is the future</li></ol><p>The Firebase JS SDK served us well, but React Native Firebase is clearly the path forward for React Native development.</p><p>So to conclude this journey, after pushing a new android build with Expo 53 we see: <strong>Target SDK 35</strong></p><p>So the requirement:</p><p><em>App updates with these issues will be rejected</em></p><p><em>App must target Android 15 (API level 35) or higher — Fix by Aug 30</em></p><p><strong>Have been met!</strong></p><p><em>This article is part of my ongoing series about Expo SDK upgrades. You can read about my previous upgrade adventure in </em><a href="https://medium.com/@lawrencenorman7hills/upgrading-from-expo-sdk-51-to-expo-sdk-52-cf5f66e29843"><em>Upgrading from Expo SDK 51 to SDK 52</em></a><em>.</em></p><p><strong>About the Author:</strong> I’m Lawrence Norman, developer of Quiznect, a React Native quiz app built with Expo. Follow my development journeys on medium.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c2e0ae2b544" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Native: Upgrading from Expo SDK 51 to Expo SDK 52 with Firebase JS]]></title>
            <link>https://medium.com/@lawrencenorman7hills/upgrading-from-expo-sdk-51-to-expo-sdk-52-cf5f66e29843?source=rss-36967447924d------2</link>
            <guid isPermaLink="false">https://medium.com/p/cf5f66e29843</guid>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[expo]]></category>
            <dc:creator><![CDATA[Lawrence Norman]]></dc:creator>
            <pubDate>Thu, 03 Jul 2025 23:19:51 GMT</pubDate>
            <atom:updated>2025-07-07T00:05:06.458Z</atom:updated>
            <content:encoded><![CDATA[<p>A React Native guide to upgrading from Expo SDK 51 to Expo SDK 52 for a Android and iOS App with Firebase JS.</p><p>Maybe like me you have recently gotten this email:</p><blockquote>“Your app is affected by Google Play’s target API level requirements… Update your app to target the latest Android version before Aug 31, 2025.”</blockquote><p>For me, this meant it was time to upgrade my Quiznect React Native app from <strong>Expo SDK 51</strong> all the way to <strong>Expo SDK 53</strong>. Having waded through a previous descent into the Podfile abyss when upgrading from Expo SDK 50 to SDK 51 <a href="https://medium.com/@lawrencenorman7hills/react-native-expo-sdk-51-upgrade-my-descent-into-the-podfile-abyss-and-how-i-climbed-out-553cae49f024">react-native-expo-sdk-51-upgrade-my-descent-into-the-podfile-abyss-and-how-i-climbed-out</a>, I was hoping for a smoother ride. I was wrong.</p><p>After half a day of resolving a series of Expo build errors I got my app upgraded. Hopefully, these steps can save you a few hours.</p><p>A word of advice: Always upgrade sequentially (e.g., 51 → 52, then 52 → 53). This is the 51 → 52 part of the journey, for second part 52 → 53 take a look at: <a href="https://medium.com/@lawrencenorman7hills/upgrading-from-expo-sdk-52-to-sdk-53-firebase-js-sdk-migration-to-react-native-firebase-1c2e0ae2b544">upgrading-from-expo-sdk-52-to-sdk-53-firebase-js-sdk-migration-to-react-native-firebase</a>. Making large jumps across multiple SDK versions at once is a recipe for disaster, as you’ll be hit with the cumulative breaking changes from every version you skip.</p><h3>The “Happy Path” Standard Upgrade</h3><p>According to the official <a href="https://docs.expo.dev/workflow/upgrading-expo-sdk-walkthrough/">Expo Upgrade Walkthrough</a>, the process should be straightforward. In your terminal, you run:</p><pre>npx expo install expo@^52.0.0<br>npx expo install --fix</pre><p>But unfortunately I have yet to see these expo upgrades go easily. ;-)</p><h3>The Modular Headers Error</h3><p>Immediately after upgrading, I tried to generate the native code for my project to test it. You will want to delete your old ios and android folders and regenerate them, and run:</p><pre>npx expo prebuild --clean</pre><p>However, it failed with a pod install error:</p><blockquote><em>For my configuration, since I use Firebase, the Swift pod </em><em>FirebaseCoreInternal depends upon </em><em>GoogleUtilities, which does not define modules. To opt into those targets generating module maps... you may set </em><em>use_modular_headers!globally in your Podfile...</em></blockquote><p>This error occurs because some dependencies (especially Firebase) need to be compiled in a specific way that requires a global setting in the iOS Podfile. The challenge is that you can&#39;t just edit the Podfile directly; Expo will overwrite your changes.</p><h3>The Fix: A Config Plugin for Modular Headers</h3><p>The correct way to solve this is with an Expo Config Plugin that automatically adds the required line to your Podfile every time it&#39;s generated.</p><p><strong>1. Create the Plugin File</strong></p><p>In your project root, create a plugins folder, and inside it, a file named withIosModularHeaders.js.</p><p><strong>2. Add the Plugin Code</strong></p><p>Paste this code into the new file. It finds the platform :ios line in your Podfile and injects use_modular_headers! right after it.</p><pre>// plugins/withIosModularHeaders.js<br>const { withDangerousMod } = require(&#39;@expo/config-plugins&#39;);<br>const fs = require(&#39;fs&#39;);<br>const path = require(&#39;path&#39;);<br>const withIosModularHeaders = (config) =&gt; {<br>  return withDangerousMod(config, [<br>    &#39;ios&#39;,<br>    async (config) =&gt; {<br>      const podfilePath = path.join(config.modRequest.projectRoot, &#39;ios&#39;, &#39;Podfile&#39;);<br>      let podfileContent = fs.readFileSync(podfilePath, &#39;utf8&#39;);<br>      const stringToAdd = &quot;use_modular_headers!&quot;;<br>      const platformLine = /platform :ios, .*/;<br>      if (!podfileContent.includes(stringToAdd)) {<br>        podfileContent = podfileContent.replace(<br>          platformLine,<br>          `$&amp; \n\n  ${stringToAdd}`<br>        );<br>        fs.writeFileSync(podfilePath, podfileContent, &#39;utf8&#39;);<br>      }<br>      <br>      return config;<br>    },<br>  ]);<br>};<br>module.exports = (config, _props) =&gt; config ? withIosModularHeaders(config) : config;</pre><p><strong>3. Activate the Plugin in </strong><strong>app.json</strong></p><pre>// app.json<br>&quot;plugins&quot;: [<br>  &quot;expo-font&quot;,<br>  &quot;./plugins/withIosModularHeaders.js&quot;<br>]</pre><p>With this in place, running npx expo prebuild --clean again allowed pod install to succeed.</p><h3>Redefinition of module &#39;ReactCommon&#39; Error</h3><p>With the pod install error fixed, I kicked off a build on EAS: eas build -p ios. It failed, but this time with an intimidating error during the compilation phase:</p><blockquote><em>❌ Pods/React-RCTAppDelegate: Redefinition of module ‘ReactCommon’</em></blockquote><p>It means that after we forced modular headers, two different parts of the React Native core library were now conflicting with each other, both trying to define the same ReactCommon module.</p><p>This creates a Catch-22:</p><ul><li>Without modular headers, pod install fails.</li><li>With modular headers, the build compiles but fails with a ReactCommon redefinition.</li></ul><p>After trying several things (including other config plugins that patched the Podfile post-install, and clearing the EAS cache with a cache.key, the definitive solution emerged, inspired by <a href="https://github.com/expo/expo/issues/29004">this GitHub issue thread</a>. The solution requires a two-pronged attack that addresses both problems at the correct stage of the EAS build process.</p><p>We need to let pod install succeed and <em>then</em>, immediately after, patch the files that it created to prevent the redefinition error.</p><h3>Create a Post-Install Script</h3><p>We will use a special EAS lifecycle hook called eas-build-post-install. This lets us run a script on the build server <em>after</em> the dependencies and pods have been installed, but <em>before</em> the code is compiled.</p><p><strong>1. Create the Script File</strong></p><p>In your project root, create a scripts folder, and inside it, a file named eas-post-install.js.</p><p><strong>2. Add the Script Code</strong></p><p>This script finds the specific file (React-RuntimeApple.modulemap) that creates the duplicate module definition and simply comments out its entire contents.</p><pre>// scripts/eas-post-install.js<br>const fs = require(&#39;fs&#39;);<br>const path = require(&#39;path&#39;);<br>console.log(&#39;Running post-install script to fix ReactCommon redefinition...&#39;);<br>const filePath = path.resolve(&#39;./ios/Pods/Headers/Public/ReactCommon/React-RuntimeApple.modulemap&#39;);<br>try {<br>  let fileContent = fs.readFileSync(filePath, &#39;utf-8&#39;);<br>  const commentedContent = fileContent<br>    .split(&#39;\n&#39;)<br>    .map(line =&gt; `// ${line}`)<br>    .join(&#39;\n&#39;);<br>  <br>  fs.writeFileSync(filePath, commentedContent, &#39;utf-8&#39;);<br>  console.log(&#39;Successfully commented out React-RuntimeApple.modulemap.&#39;);<br>} catch (error) {<br>  if (error.code === &#39;ENOENT&#39;) {<br>    console.log(&#39;React-RuntimeApple.modulemap not found, skipping patch. This might be okay.&#39;);<br>  } else {<br>    console.error(&#39;Error modifying React-RuntimeApple.modulemap:&#39;, error);<br>  }<br>}</pre><h3>Step 3: Trigger the Script in package.json</h3><p>Finally, open your package.json and add the eas-build-post-install hook to your scripts section.</p><pre>// package.json<br>&quot;scripts&quot;: {<br>  &quot;start&quot;: &quot;expo start&quot;,<br>  &quot;android&quot;: &quot;expo run:android&quot;,<br>  &quot;ios&quot;: &quot;expo run:ios&quot;,<br>  &quot;web&quot;: &quot;expo start --web&quot;,<br>  &quot;eas-build-post-install&quot;: &quot;node ./scripts/eas-post-install.js&quot;<br>},</pre><h3>Build Success! 🚀</h3><p>With this two-part solution in place, you can commit your changes and run your build.</p><pre>eas build -p ios</pre><p>The build process will now correctly:</p><ul><li>Generate the ios project.</li><li>Add use_modular_headers! via the config plugin.</li><li>Run pod install successfully.</li><li>Run your eas-post-install.js script, neutralizing the ReactCommon conflict.</li><li>Compile the app successfully.</li></ul><p>This journey was a reminder that modern mobile development often involves navigating complex layers of dependencies. While the fixes can be obscure, they are almost always solvable with persistence and community support. I hope this guide saves you from the hours of debugging it took me to find this solution.</p><p>Unfortunately if you are trying to meet Android SDK requirements, this isn’t the end of the journey. You will still see:</p><p>Your highest non-compliant target API level is Android 14 (API level 34).</p><p>App must target Android 15 (API level 35) or higher</p><p>Fix by Aug 30</p><p>We took a very important step, but we are not done with this journey, read on for the next step of upgrading Expo SDK 52 to Expo SDK 53 for Firebase: <a href="https://medium.com/@lawrencenorman7hills/upgrading-from-expo-sdk-52-to-sdk-53-firebase-js-sdk-migration-to-react-native-firebase-1c2e0ae2b544">upgrading-from-expo-sdk-52-to-sdk-53-firebase-js-sdk-migration-to-react-native-firebase</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cf5f66e29843" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a ChatGPT-Like App with Apple’s On-Device LLMs]]></title>
            <link>https://medium.com/@lawrencenorman7hills/building-a-chatgpt-like-app-with-apples-on-device-llms-3022c2251d2e?source=rss-36967447924d------2</link>
            <guid isPermaLink="false">https://medium.com/p/3022c2251d2e</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Lawrence Norman]]></dc:creator>
            <pubDate>Tue, 24 Jun 2025 03:45:33 GMT</pubDate>
            <atom:updated>2025-06-24T03:45:33.708Z</atom:updated>
            <content:encoded><![CDATA[<p>Apple has recently made significant strides in on-device large language models (LLMs) with its Foundation Models, introduced with iOS 26 and macOS 26. These local LLMs open up exciting possibilities for developers to create powerful, private, and responsive AI-powered applications directly on Apple Silicon devices.</p><p>In this article, we’ll walk through the process of setting up a basic ChatGPT-like application using Apple’s Foundation Models framework. You’ll learn how to interact with the on-device LLM, manage conversation context, and stream responses for a fluid user experience.</p><h3>Prerequisites</h3><p>Before you begin, ensure you have:</p><ul><li><strong>Xcode Beta</strong>: The latest version that supports iOS 26/macOS 26 development.</li><li><strong>iOS 26+ / macOS 26+</strong>: An Apple Silicon device (A17 Pro, A18, M1, M2, M3, M4 series chips) running the latest beta operating system.</li><li><strong>Apple Intelligence Enabled</strong>: On your device, navigate to Settings and ensure Apple Intelligence features are enabled. The model assets may download automatically upon first use.</li></ul><h3>The Core: ChatBotService</h3><p>Our central component for interacting with the Apple Foundation Model will be a ChatBotService class. This class will encapsulate the logic for initializing the LanguageModelSession, sending prompts, receiving streamed responses, and managing conversational context.</p><p>Here’s how ChatBotService is structured:</p><pre>import Foundation<br>import FoundationModels<br>import SwiftUI // Used for @ObservableObject and @MainActor <br>class ChatBotService: ObservableObject {<br>    private var session: LanguageModelSession?<br>    private var currentInstruction: String?<br>    @Published var isReady: Bool = false<br>    init() {<br>        Task {<br>            await initializeSession(withInstruction: nil)<br>        }<br>    }<br>    @MainActor<br>    func initializeSession(withInstruction instruction: String?) async {<br>        isReady = false<br>        self.session = nil<br>        self.currentInstruction = instruction<br>        let model = SystemLanguageModel.default<br>        print(&quot;Checking SystemLanguageModel availability...&quot;)<br>        switch model.availability {<br>        case .available:<br>            print(&quot;SystemLanguageModel is available. Initializing LanguageModelSession...&quot;)<br>            do {<br>                if let instructionText = instruction, !instructionText.isEmpty {<br>                    self.session = LanguageModelSession(model: model, instructions: Instructions(instructionText))<br>                } else {<br>                    self.session = LanguageModelSession(model: model)<br>                }<br>                print(&quot;LanguageModelSession initialized successfully.&quot;)<br>                self.isReady = true<br>            } catch {<br>                print(&quot;Failed to initialize LanguageModelSession: \(error.localizedDescription)&quot;)<br>                if let genError = error as? LanguageModelSession.GenerationError {<br>                    print(&quot;Generation Error Context: \(genError.localizedDescription)&quot;)<br>                }<br>                self.isReady = false<br>            }<br>        case .unavailable(let reason):<br>            print(&quot;SystemLanguageModel is unavailable: \(reason)&quot;)<br>            print(&quot;Reason details: \(reason)&quot;)<br>            switch reason {<br>            case .deviceNotEligible:<br>                print(&quot;Device is not eligible. Requires Apple Silicon (A17 Pro, A18, M1, M2, M3, M4 series chips).&quot;)<br>            case .appleIntelligenceNotEnabled:<br>                print(&quot;Apple Intelligence is not enabled in system settings.&quot;)<br>            case .modelNotReady:<br>                print(&quot;Model assets are not ready. They may be downloading or require more space.&quot;)<br>            @unknown default:<br>                print(&quot;An unknown unavailability reason occurred.&quot;)<br>            }<br>            self.isReady = false<br>        }<br>    }<br>    func sendMessage(<br>        _ prompt: String,<br>        instruction: String? = nil,<br>        onNewToken: @escaping (String) -&gt; Void,<br>        onComplete: @escaping (Result&lt;String, Error&gt;) -&gt; Void<br>    ) {<br>        Task { @MainActor in<br>            if instruction != currentInstruction || session == nil || !isReady {<br>                print(&quot;Instruction changed or session not ready. Re-initializing session...&quot;)<br>                await initializeSession(withInstruction: instruction)<br>            }<br>            guard let currentSession = session, isReady else {<br>                onComplete(.failure(NSError(domain: &quot;ChatBotService&quot;, code: 1, userInfo: [NSLocalizedDescriptionKey: &quot;LanguageModelSession is not initialized or not available after attempt.&quot;])))<br>                return<br>            }<br>            do {<br>                var fullResponse = &quot;&quot;<br>                for try await chunk in currentSession.streamResponse(to: prompt) {<br>                    fullResponse += chunk<br>                    onNewToken(chunk)<br>                }<br>                onComplete(.success(fullResponse))<br>            } catch {<br>                print(&quot;Error sending message: \(error.localizedDescription)&quot;)<br>                if let genError = error as? LanguageModelSession.GenerationError {<br>                    print(&quot;Generation Error Type: \(genError)&quot;)<br>                    print(&quot;Recovery Suggestion: \(genError.recoverySuggestion ?? &quot;None&quot;)&quot;)<br>                }<br>                onComplete(.failure(error))<br>            }<br>        }<br>    }<br>    @MainActor<br>    func startNewConversation() async {<br>        print(&quot;Starting a new conversation...&quot;)<br>        await initializeSession(withInstruction: nil)<br>    }<br>}</pre><h3>Explanation of ChatBotService:</h3><ul><li><strong>LanguageModelSession</strong>: This is the core object from FoundationModels. We maintain a single instance (session) for multi-turn conversations. When the instruction (e.g., the AI&#39;s persona) changes, we recreate the session to apply the new instruction.</li><li><strong>initializeSession(withInstruction:)</strong>: This async function checks the availability of the SystemLanguageModel.default. If available, it initializes LanguageModelSession, optionally providing an Instructions object to define the model&#39;s behavior. It updates the @Published var isReady property, which our UI will observe.</li><li><strong>sendMessage(...)</strong>: This method takes the user&#39;s prompt and an optional instruction. It&#39;s designed to stream the response using currentSession.streamResponse(to: prompt). Each chunk received from the stream is sent via onNewToken for real-time UI updates, mimicking a ChatGPT-like streaming effect.</li><li><strong>startNewConversation()</strong>: This simply calls initializeSession with a nil instruction, effectively clearing the previous conversational context and starting fresh.</li></ul><h3>Integrating with SwiftUI: FoundationLLMContentView</h3><p>Next, we’ll create a SwiftUI View to act as our chat interface. This View will use @StateObject to hold an instance of ChatBotService and display chat messages, an input field, and control buttons.</p><pre>import SwiftUI<br>import FoundationModels <br>struct FoundationLLMContentView: View {<br>    @StateObject private var chatService = ChatBotService()<br>    @State private var inputText: String = &quot;&quot;<br>    @State private var chatHistory: [String] = []<br>    @State private var currentStreamedText: String = &quot;&quot;<br>    @State private var isLoading: Bool = false<br>    @State private var personaInstruction: String = &quot;You are a helpful and concise assistant.&quot;<br>    var body: some View {<br>        VStack {<br>            ScrollView {<br>                VStack(alignment: .leading) {<br>                    ForEach(chatHistory, id: \.self) { message in<br>                        Text(message)<br>                            .padding(8)<br>                            .background(message.hasPrefix(&quot;You:&quot;) ? Color.blue.opacity(0.1) : Color.green.opacity(0.1))<br>                            .cornerRadius(10)<br>                            .frame(maxWidth: .infinity, alignment: message.hasPrefix(&quot;You:&quot;) ? .trailing : .leading)<br>                    }<br>                    if isLoading {<br>                        Text(currentStreamedText)<br>                            .padding(8)<br>                            .background(Color.green.opacity(0.1))<br>                            .cornerRadius(10)<br>                            .frame(maxWidth: .infinity, alignment: .leading)<br>                    }<br>                }<br>                .padding()<br>            }<br>            TextField(&quot;Set Assistant Persona (optional)&quot;, text: $personaInstruction)<br>                .textFieldStyle(RoundedBorderTextFieldStyle())<br>                .padding(.horizontal)<br>                .disabled(isLoading)<br>            HStack {<br>                TextField(&quot;Type your message...&quot;, text: $inputText, axis: .vertical)<br>                    .textFieldStyle(RoundedBorderTextFieldStyle())<br>                    .padding(.vertical, 8)<br>                    .disabled(isLoading)<br>                    .lineLimit(1...5)<br>                Button(&quot;Send&quot;) {<br>                    sendMessage()<br>                }<br>                .disabled(inputText.isEmpty || isLoading || !chatService.isReady)<br>                .padding(.vertical, 8)<br>            }<br>            .padding(.horizontal)<br>            Button(&quot;New Chat&quot;) {<br>                Task {<br>                    await chatService.startNewConversation()<br>                    chatHistory.removeAll()<br>                    currentStreamedText = &quot;&quot;<br>                    inputText = &quot;&quot;<br>                }<br>            }<br>            .padding(.bottom)<br>            .disabled(isLoading)<br>        }<br>        .navigationTitle(&quot;Apple LLM Chat&quot;)<br>        .task {<br>            await chatService.initializeSession(withInstruction: personaInstruction)<br>        }<br>    }<br>    private func sendMessage() {<br>        let userMessage = &quot;You: \(inputText)&quot;<br>        chatHistory.append(userMessage)<br>        isLoading = true<br>        currentStreamedText = &quot;AI: &quot;<br>        let promptToSend = inputText<br>        inputText = &quot;&quot;<br>        chatService.sendMessage(<br>            promptToSend,<br>            instruction: personaInstruction,<br>            onNewToken: { chunk in<br>                DispatchQueue.main.async {<br>                    currentStreamedText += chunk<br>                }<br>            },<br>            onComplete: { result in<br>                DispatchQueue.main.async {<br>                    isLoading = false<br>                    switch result {<br>                    case .success(let fullResponse):<br>                        chatHistory.append(&quot;AI: \(fullResponse.replacingOccurrences(of: &quot;AI: &quot;, with: &quot;&quot;))&quot;)<br>                        currentStreamedText = &quot;&quot;<br>                    case .failure(let error):<br>                        chatHistory.append(&quot;Error: \(error.localizedDescription)&quot;)<br>                        currentStreamedText = &quot;&quot;<br>                    }<br>                }<br>            }<br>        )<br>    }<br>}</pre><h3>Explanation of FoundationLLMContentView:</h3><ul><li><strong>@StateObject private var chatService = ChatBotService()</strong>: This creates and manages the lifecycle of our ChatBotService instance. SwiftUI automatically re-renders the view when chatService&#39;s @Published properties change.</li><li><strong>@State Properties</strong>: inputText, chatHistory, currentStreamedText, isLoading, and personaInstruction manage the UI state.</li><li><strong>UI Layout</strong>: A VStack contains a ScrollView for messages, a TextField for setting the persona, and an HStack for the input field and send button. A &quot;New Chat&quot; button allows resetting the conversation.</li><li><strong>sendMessage()</strong>: This function is called when the user taps &quot;Send&quot;. It adds the user&#39;s message to chatHistory, sets isLoading to true, and then calls chatService.sendMessage. The onNewToken and onComplete closures update the UI with streamed and final responses.</li><li><strong>.task { await chatService.initializeSession(withInstruction: personaInstruction) }</strong>: This modifier ensures that the ChatBotService is initialized when the View appears, using the initial personaInstruction.</li></ul><h3>Setting Up Your Project</h3><p>To get this running in your Xcode project, follow these steps:</p><ol><li><strong>Create </strong><strong>FoundationLLM.swift</strong>: Create a new Swift file named FoundationLLM.swift and paste the ChatBotService class and FoundationLLMContentView struct (from the previous code blocks) into it.</li><li><strong>Modify Your Main </strong><strong>ContentView.swift</strong>: Open your project&#39;s primary ContentView.swift (the one referenced by your mChatAIApp.swift). Add a NavigationLink to this ContentView to navigate to FoundationLLMContentView.</li><li>Here’s an example of how you might update your main ContentView to include a button for the Apple LLM:</li></ol><pre>// ContentView.swift (Your existing main ContentView)<br>import SwiftUI<br>// Make sure to import FoundationModels if you use any of its types directly here<br>// or if FoundationLLM.swift is in a different module.<br><br>struct ContentView: View {<br>    // ... (your existing @StateObject for LLMManager and other properties) ...<br><br>    var body: some View {<br>        NavigationView {<br>            VStack(spacing: 15) {<br>                // ... (your existing UI elements, like Text, Image, Status Area, Model Buttons) ...<br><br>                // Your existing Chat button<br>                NavigationLink(destination: ChatView(chatState: llmManager.chatState)<br>                                            .environmentObject(llmManager)<br>                ) {<br>                    Text(&quot;Chat (MLCEngine)&quot;)<br>                        .font(.title2)<br>                        .padding(.horizontal, 20)<br>                        .padding(.vertical, 10)<br>                        .background( (llmManager.isModelLoaded &amp;&amp; llmManager.isChatReady &amp;&amp; !llmManager.isLlama3Downloading &amp;&amp; llmManager.generalLoadingMessage == nil) ? Color.accentColor : Color.gray.opacity(0.5))<br>                        .foregroundColor(.white)<br>                        .cornerRadius(8)<br>                }<br>                .disabled(!llmManager.isModelLoaded || !llmManager.isChatReady || llmManager.isLlama3Downloading || llmManager.generalLoadingMessage != nil)<br><br>                // NEW: Button to navigate to FoundationLLMContentView<br>                NavigationLink(destination: FoundationLLMContentView()) {<br>                    Text(&quot;Try Apple LLM&quot;)<br>                        .font(.title2)<br>                        .padding(.horizontal, 20)<br>                        .padding(.vertical, 10)<br>                        .background(Color.purple) // Distinct color<br>                        .foregroundColor(.white)<br>                        .cornerRadius(8)<br>                }<br>                .padding(.top, 10) // Add some spacing<br><br>                Spacer()<br>            }<br>            .onAppear {<br>                // ... (your existing onAppear logic) ...<br>            }<br>            .alert(&quot;Delete Llama3 Model&quot;, isPresented: $showingDeleteLlama3Confirmation, actions: {<br>                Button(&quot;Delete&quot;, role: .destructive) {<br>                    llmManager.deleteLlama3ModelFiles()<br>                }<br>                Button(&quot;Cancel&quot;, role: .cancel) { }<br>            }, message: {<br>                Text(&quot;Are you sure you want to delete the downloaded Llama3 model files? This will free up space but require re-downloading.&quot;)<br>            })<br>            .navigationTitle(&quot;LLM Control&quot;)<br>            .navigationBarHidden(true)<br>        }<br>        .navigationViewStyle(.stack)<br>    }<br>}<br><br>#Preview {<br>    ContentView()<br>}</pre><p><strong>Deployment Target</strong>: Double-check that your project’s deployment target is set to <strong>iOS 26.0</strong> (or <strong>macOS 26.0</strong>) or higher in your project settings. This is crucial for the FoundationModels framework to be available.</p><h3>Conclusion</h3><p>By following these steps, you’ve successfully integrated Apple’s on-device Foundation Models into a basic ChatGPT-like application. This setup allows you to leverage the power of local LLMs for private, efficient, and context-aware AI interactions on compatible Apple devices.</p><p>From here, you can expand on this foundation by:</p><ul><li><strong>Refining UI/UX</strong>: Enhance the chat interface, add features like message history persistence, and improve styling.</li><li><strong>Advanced Instructions</strong>: Experiment with more complex persona instructions or dynamic instruction generation based on user intent.</li><li><strong>Tool Integration</strong>: Explore integrating custom tools with the FoundationModels framework to allow the LLM to interact with other parts of your app or external services.</li><li><strong>Error Handling</strong>: Implement more user-friendly error messages and recovery options for model unavailability or generation failures.</li></ul><p>The future of on-device AI is bright, and Apple’s Foundation Models provide a robust platform for developers to build innovative and intelligent applications. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3022c2251d2e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering AI Workflow Automation: Quickstart to run n8n on Your Mac (Local Self-Hosting)]]></title>
            <link>https://medium.com/@lawrencenorman7hills/mastering-ai-workflow-automation-quickstart-to-run-n8n-on-your-mac-local-self-hosting-5747eade5a69?source=rss-36967447924d------2</link>
            <guid isPermaLink="false">https://medium.com/p/5747eade5a69</guid>
            <dc:creator><![CDATA[Lawrence Norman]]></dc:creator>
            <pubDate>Mon, 09 Jun 2025 20:36:32 GMT</pubDate>
            <atom:updated>2025-06-09T20:36:32.523Z</atom:updated>
            <content:encoded><![CDATA[<p>Tired of juggling countless apps and manual tasks? N8n (pronounced “n-eight-n”) is a powerful open-source workflow automation tool that lets you connect services, automate processes, and build sophisticated workflows without coding. While n8n offers cloud hosting, self-hosting provides ultimate control, data privacy, and cost-effectiveness for personal projects or internal tools.</p><h3>Why Self-Host n8n Locally on Your Mac? (Pros &amp; Cons)</h3><h4>The Upsides (Pros):</h4><ul><li><strong>Zero Recurring Cloud Costs (for local n8n):</strong> You’re leveraging your existing hardware, so there are no hourly or usage-based fees for n8n itself. This is perfect for learning and experimentation.</li><li><strong>Simplified Initial Setup:</strong> Compared to configuring cloud services, databases, and network rules, getting a Docker container up and running on your Mac is remarkably straightforward.</li><li><strong>Complete Data Privacy &amp; Control:</strong> Your n8n data (workflows, credentials, execution history) stays entirely on your machine. You have full control over your data, which is crucial for sensitive automations.</li><li><strong>Offline Capability:</strong> Build and test workflows even without an internet connection (though external service nodes will still require connectivity).</li></ul><h4>The Downsides (Cons):</h4><ul><li><strong>Availability:</strong> n8n will only run when your Mac is powered on and Docker Desktop is active. If your laptop goes to sleep, shuts down, or loses power, n8n stops, making it <strong>unsuitable for production workflows</strong> that need to run continuously (e.g., scheduled tasks, webhook listeners).</li><li><strong>Public Access Challenges:</strong> If your workflows need to receive webhooks from external services (e.g., Stripe, Shopify, custom APIs), your local n8n instance typically won’t be directly accessible from the internet. You’d need tunneling services like ngrok for testing, or a publicly deployed instance for live webhooks.</li><li><strong>Maintenance Overhead:</strong> You’re responsible for keeping Docker Desktop, Node.js (if installing directly), and n8n itself updated.</li><li><strong>Not for Production:</strong> As mentioned, the default SQLite database used in this quick local setup is <strong>not robust enough for production environments</strong>. It can lead to data corruption or performance issues under load.</li></ul><p><strong>In summary:</strong> Self-hosting n8n on your Mac is the <em>absolute best way to start</em> if you’re learning, developing, or prototyping. It provides a fast, free, and forgiving environment. When your workflows are robust and require continuous operation or public access, that’s when you graduate to cloud deployment like Google Cloud Run.</p><h3>Step-by-Step: Quick n8n Setup on Your Mac with Docker</h3><h4>Prerequisites:</h4><ul><li>An active internet connection for the initial download.</li><li>Basic familiarity with the macOS Terminal.</li></ul><h4>Step 1: Install Docker Desktop for Mac</h4><ol><li><strong>Download Docker Desktop:</strong> Head over to the official Docker website: <a href="https://docs.docker.com/desktop/install/mac-install/">https://docs.docker.com/desktop/install/mac-install/</a></li><li><strong>Select Your Chip:</strong> Download the version compatible with your Mac’s processor (Apple Chip for M-series, Intel Chip for older Macs).</li><li><strong>Install:</strong> Open the downloaded .dmg file and drag Docker Desktop.app to your Applications folder.</li><li><strong>Launch &amp; Configure:</strong> Open Docker Desktop from your Applications folder. Follow any on-screen prompts to grant necessary permissions (you may need to enter your Mac’s password). Wait for the Docker whale icon to appear in your Mac’s menu bar, indicating it’s fully started.</li></ol><h4>Step 2: Create a Dedicated Directory for n8n</h4><ol><li><strong>Open Terminal:</strong> Find it in Applications/Utilities/Terminal or use Spotlight (Cmd + Space, type &quot;Terminal&quot;).</li><li><strong>Create and Navigate:</strong></li></ol><pre>mkdir ~/n8n-local <br>cd ~/n8n-local</pre><p>This creates a folder named n8n-local in your home directory and places you inside it.</p><h4>Step 3: Craft Your docker-compose.yml File</h4><p>This YAML file instructs Docker how to run your n8n container, including essential configurations and data persistence.</p><ol><li><strong>Create the File:</strong> In your ~/n8n-local directory, create a file named docker-compose.yml. You can use your favorite code editor (like VS Code, Sublime Text) or a terminal editor like nano:</li></ol><p>Assuming you have vscode installed:</p><pre>code docker-compose.yml</pre><ol><li><strong>Paste the Content:</strong> Copy and paste the following configuration into your docker-compose.yml file:</li><li>YAML</li></ol><pre>services:<br>  n8n:<br>    image: n8nio/n8n # Uses the official n8n Docker image<br>    restart: always # Ensures n8n restarts if it crashes or after a system reboot<br>    ports:<br>      - &quot;5678:5678&quot; # Maps your Mac&#39;s port 5678 to the container&#39;s port 5678<br>    volumes:<br>      # This is CRUCIAL for data persistence! It maps a hidden folder in your Mac&#39;s home directory<br>      # to the n8n data directory inside the container. All your workflows, credentials, etc.,<br>      # will be saved here and persist across container restarts or removals.<br>      - ~/.n8n:/home/node/.n8n<br>    environment:<br>      # --- ESSENTIAL SECURITY &amp; CONFIGURATION SETTINGS (EDIT THESE!) ---<br>      - N8N_BASIC_AUTH_ACTIVE=true # Enables basic HTTP authentication for n8n access<br>      - N8N_BASIC_AUTH_USER=your_admin_username # &lt;--- CHANGE THIS to your desired username<br>      - N8N_BASIC_AUTH_PASSWORD=your_strong_secure_password # &lt;--- CHANGE THIS to a VERY STRONG, UNIQUE PASSWORD<br>      - N8N_ENCRYPTION_KEY=a_long_random_string_for_encryption_1234567890 # &lt;--- CHANGE THIS to a long, complex, random key (e.g., 32+ chars). DO NOT LOSE THIS!<br>      # ------------------------------------------------------------------<br><br>      # General n8n network settings for local access<br>      - N8N_HOST=localhost<br>      - N8N_PORT=5678<br>      - N8N_PROTOCOL=http<br>      - N8N_PATH=/<br>      - NODE_ENV=development # Good for local debugging (more verbose logging)<br>      - TZ=America/Los_Angeles # &lt;--- CHANGE THIS to your actual timezone (e.g., Europe/London, Asia/Tokyo)<br><br>      # Database settings: SQLite is the default for convenience here.<br>      # REMINDER: SQLite is NOT recommended for production environments.<br>      # For production, you&#39;d configure PostgreSQL or MySQL here.<br>      # - DB_TYPE=sqlite (not strictly necessary as it&#39;s the default if no other DB is configured)</pre><p><strong>Customize Environment Variables:</strong> <strong>This is the most important step for security and proper function!</strong></p><ul><li><strong>N8N_BASIC_AUTH_USER</strong>: Change your_admin_username to your preferred username.</li><li><strong>N8N_BASIC_AUTH_PASSWORD</strong>: <strong>Replace </strong><strong>your_strong_secure_password with a unique, robust password.</strong> This is your primary login credential.</li><li><strong>N8N_ENCRYPTION_KEY</strong>: <strong>Generate a long, random string (e.g., 32 characters or more) and use it here.</strong> This key encrypts sensitive data like credentials within n8n. <strong>Losing this key means losing access to your saved credentials!</strong></li><li><strong>TZ</strong>: Update America/Los_Angeles to your correct timezone (e.g., Europe/Berlin, Asia/Singapore). You can find a list of valid timezones <a href="https://en.wikipedia.org/wiki/List_of_tz_database_time_zones">here</a>.</li></ul><p><strong>Save the File:</strong> Save docker-compose.yml (Ctrl+X, then Y, then Enter if using nano).</p><h4>Step 4: Launch n8n with Docker Compose</h4><p>Now, let Docker do its magic!</p><p><strong>Ensure you’re in the correct directory:</strong></p><pre>cd ~/n8n-local</pre><p><strong>Start n8n:</strong></p><pre>docker compose up -d</pre><ul><li>docker compose up: Reads your docker-compose.yml and starts the defined services.</li><li>-d: Runs the containers in &quot;detached&quot; mode, so they operate in the background, freeing up your terminal.</li></ul><p>The first time, Docker will download the n8n image, which may take a few minutes. Subsequent starts will be much faster. You’ll see output similar to what you shared, indicating the image being pulled and the container starting.</p><p>To verify it’s running:</p><pre>docker compose ps</pre><p>You should see STATUS as Up for the n8n service.</p><p>To stop n8n from running:</p><pre>docker compose down</pre><h4>Step 5: Access Your Local n8n Instance</h4><p>You’re ready to dive into workflow building!</p><ol><li><strong>Open your chrome web browser:</strong> Go to <a href="http://localhost:5678.">http://localhost:5678.</a></li><li><strong>Login:</strong> You’ll be prompted for the username and password you configured in your docker-compose.yml (your_admin_username and your_strong_secure_password).</li><li><strong>Initial Setup:</strong> The first time you log in, n8n will guide you through a quick administrator account setup.</li></ol><p>Congratulations! You now have a fully functional n8n instance running locally on your Mac. You can begin creating workflows, experimenting with nodes, and exploring the power of automation right away.</p><h3>What’s Next?</h3><p>With n8n running locally, you can:</p><ul><li><strong>Explore the UI:</strong> Familiarize yourself with the n8n interface, the nodes panel, and the workflow canvas.</li><li><strong>Build Your First Workflow:</strong> Try a simple workflow, like sending a Slack message when you trigger a webhook, or resizing an image from a local folder.</li><li><strong>Experiment with Nodes:</strong> Drag and drop different nodes onto the canvas and see what they can do.</li><li><strong>Learn Debugging:</strong> The NODE_ENV=development setting will give you more verbose logs for troubleshooting.</li></ul><p>When your local workflows are polished and you’re ready for continuous operation, public access, or higher scale, the next step will be to explore deploying n8n to a cloud environment like Google Cloud Run, where you’ll transition to a robust database like PostgreSQL. But for now, enjoy the freedom and flexibility of local self-hosting!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fmd-UXpGPLLy3LlKuOuxLA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W7LKBitwQpVVYA2pXRNmVA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*avPd9atjI9BDXqBlbXBrdw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5747eade5a69" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part I: I’m working on training small models that can run on Apple Silicon, and thought I would…]]></title>
            <link>https://medium.com/@lawrencenorman7hills/part-i-im-working-on-training-small-models-that-can-run-on-apple-silicon-and-thought-i-would-94e7014cc49a?source=rss-36967447924d------2</link>
            <guid isPermaLink="false">https://medium.com/p/94e7014cc49a</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[huggingfacemodels]]></category>
            <category><![CDATA[lora]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Lawrence Norman]]></dc:creator>
            <pubDate>Thu, 24 Apr 2025 20:44:54 GMT</pubDate>
            <atom:updated>2025-04-24T20:48:24.432Z</atom:updated>
            <content:encoded><![CDATA[<h3>Part I: I’m working on training small models that can run on Apple Silicon, and thought I would start with a Spanish/English tutor. — From Fine-Tuning to Mobile Deployment: A Step-by-Step Journey with Hugging Face, LoRA, and Core ML</h3><p>In this article, I’ll discuss the workflow — from getting a translation fine-tuning script running on macOS, to experimenting with LoRA adapters and quantization, all the way through to converting a Phi-3 model for iOS deployment via Core ML. Note that this was run on a MacBook Pro M4Max with 64GB RAM.</p><h3>1. Initial Setup &amp; Dependencies</h3><p>Script: We started with preproccessLLM.py, which loads the “microsoft/phi-3-mini-4k-instruct” model, prepares an English–Spanish dataset, and runs training via Hugging Face’s Trainer.</p><pre># preproccessLLM.py<br>import json<br>from transformers import TrainingArguments, Trainer<br>from transformers import AutoTokenizer, AutoModelForCausalLM<br>from transformers import DataCollatorForLanguageModeling<br>from datasets import Dataset<br>from peft import LoraConfig, get_peft_model<br>import torch<br><br>model_name = &quot;microsoft/Phi-3-mini-4k-instruct&quot;<br>tokenizer = AutoTokenizer.from_pretrained(model_name, token=True)<br><br># Load model without quantization for MPS<br>model = AutoModelForCausalLM.from_pretrained(<br>    model_name,<br>    device_map=&quot;auto&quot;,<br>    torch_dtype=torch.float16  # Using float16 instead of quantization<br>)<br><br># Print all Linear layer names to find the correct target modules<br>print(&quot;Available Linear layers in the model:&quot;)<br>for name, module in model.named_modules():<br>    if isinstance(module, torch.nn.Linear):<br>        print(name)<br><br># Configure LoRA with the correct target modules for Phi-3<br>lora_config = LoraConfig(<br>    r=4,<br>    lora_alpha=8,<br>    target_modules=[<br>        &quot;self_attn.o_proj&quot;,<br>        &quot;self_attn.qkv_proj&quot;,<br>        &quot;mlp.gate_up_proj&quot;,<br>        &quot;mlp.down_proj&quot;<br>    ],<br>    lora_dropout=0.05,<br>    bias=&quot;none&quot;,<br>    task_type=&quot;CAUSAL_LM&quot;<br>)<br><br># Create PEFT model<br>model = get_peft_model(model, lora_config)<br><br># Dataset processing with smaller subset<br>with open(&quot;eng_spa_translation_pairs.json&quot;, &quot;r&quot;, encoding=&quot;utf-8&quot;) as f:<br>    data = json.load(f)<br><br># Use smaller subset for testing<br># data = data[:10000]<br>dataset = Dataset.from_list(data)<br><br>def preprocess_function(examples):<br>    inputs = [<br>        &quot;Tutor: &quot; + eng + &quot;\nStudent: &quot; + spa<br>        for eng, spa in zip(examples[&quot;sentence_eng&quot;], examples[&quot;sentence_spa&quot;])<br>    ]<br>    tokenized = tokenizer(inputs, padding=&quot;max_length&quot;, truncation=True, max_length=128)<br>    tokenized[&quot;labels&quot;] = tokenized[&quot;input_ids&quot;].copy()<br>    return tokenized<br><br>tokenized_dataset = dataset.map(preprocess_function, batched=True)<br><br># Optimized training arguments for MPS with more memory utilization<br>training_args = TrainingArguments(<br>    output_dir=&quot;./phi3_spanish_tutor&quot;,<br>    per_device_train_batch_size=12,   <br>    gradient_accumulation_steps=64,  <br>    num_train_epochs=1,<br>    logging_steps=100,<br>    logging_dir=&quot;./logs&quot;,<br>    save_steps=1000,<br>    optim=&quot;adamw_torch&quot;,<br>    learning_rate=1e-4,<br>    warmup_ratio=0.05,<br>    max_grad_norm=0.3,<br>    save_total_limit=3,<br>)<br><br>data_collator = DataCollatorForLanguageModeling(tokenizer=tokenizer, mlm=False)<br><br>trainer = Trainer(<br>    model=model,<br>    args=training_args,<br>    train_dataset=tokenized_dataset,<br>    data_collator=data_collator<br>)<br><br>trainer.train()</pre><p>Errors &amp; Fixes — ModuleNotFoundError: transformers: Resolved by installing:</p><pre>pip install transformers torch datasets peft huggingface_hub</pre><p>Authentication: to ensure use_auth_token=True would work</p><pre>huggingface-cli login <br>huggingface-cli whoami</pre><h3>2. Monitoring &amp; Optimizing Training</h3><p>Initial Progress: On macOS/MPS, each iteration took ~100 s, projecting years for full convergence.</p><p>Speed-Ups:</p><ol><li>Increase gradient_accumulation_steps.</li><li>Reduce epochs (e.g. num_train_epochs=1).</li><li>Use a data subset (e.g. 10k examples) as a sanity check.</li><li>Consider smaller models (e.g. “phi-2” or “distilgpt2”) or cloud GPUs.</li></ol><h3>3. LoRA Fine-Tuning with peft &amp; BitsAndBytes</h3><pre>  pip install peft bitsandbytes</pre><ul><li>Configuration: We set up a LoraConfig targeting the correct projection layers in Phi-3, avoiding NoneType errors.</li><li>Training: Successfully fine-tuned with LoRA, hitting a final loss ~1.28 in ~15 hr on MPS.</li></ul><h3>4. Merging Adapter into Base Model</h3><p>Once training finished, we merged LoRA weights back into the base model:</p><pre># merge_model.py<br>from transformers import AutoModelForCausalLM, AutoTokenizer<br>from peft import PeftModel<br><br>base = AutoModelForCausalLM.from_pretrained(&quot;microsoft/phi-3-mini-4k-instruct&quot;)<br>adapter = PeftModel.from_pretrained(base, &quot;phi3_spanish_tutor/checkpoint-352&quot;)<br>merged = adapter.merge_and_unload()<br>merged.save_pretrained(&quot;phi3_spanish_tutor_merged&quot;)<br>AutoTokenizer.from_pretrained(&quot;microsoft/phi-3-mini-4k-instruct&quot;) \<br>    .save_pretrained(&quot;phi3_spanish_tutor_merged&quot;)</pre><h3>5. Quantization &amp; Core ML Conversion Challenges</h3><p>Our goal: a quantized, deployable model on iOS. We explored multiple routes:</p><ul><li>optimum.exporters.coreml</li><li>Missing optimum[coreml] extras on Python 3.13</li><li>Repeated dependency conflicts (libcoremlpython not found)</li><li>TorchScript + xcrun coremlc</li><li>Scripted via torch.jit.trace but ran into unsupported ops (DynamicCache, variable kwargs, bitwise_or_)</li><li>Core ML compiler rejected the PyTorch format.</li><li>Direct Core ML conversion via coremltools</li><li>Encountered unimplemented PyTorch→MIL ops (e.g. bitwise_or_)</li><li>Tried dynamic axes, fixed shapes, float16 precision — still blocked.</li></ul><h3>6. The ONNX Intermediate Approach</h3><p>Ultimately the ONNX path succeeded in exporting:</p><pre># save_onnx.py<br>import torch<br>from transformers import AutoModelForCausalLM, AutoTokenizer<br><br>model = AutoModelForCausalLM.from_pretrained(&quot;phi3_spanish_tutor_merged&quot;, torch_dtype=torch.float16)<br>model.eval()<br><br>class Wrapper(torch.nn.Module):<br>    def __init__(self, m): super().__init__(); self.m = m<br>    def forward(self, input_ids):<br>        mask = torch.ones_like(input_ids)<br>        logits, = self.m(input_ids=input_ids, attention_mask=mask, return_dict=False)<br>        return logits<br><br>wrapper = Wrapper(model)<br>wrapper.eval()<br><br>tok = AutoTokenizer.from_pretrained(&quot;phi3_spanish_tutor_merged&quot;)<br>inputs = tok(&quot;Translate to Spanish: Hello&quot;, return_tensors=&quot;pt&quot;)<br><br>torch.onnx.export(<br>    wrapper, (inputs.input_ids,), &quot;phi3_spanish_tutor.onnx&quot;,<br>    input_names=[&#39;input_ids&#39;], output_names=[&#39;logits&#39;],<br>    dynamic_axes={&#39;input_ids&#39;:{0:&#39;batch&#39;,1:&#39;seq&#39;}, &#39;logits&#39;:{0:&#39;batch&#39;,1:&#39;seq&#39;}},<br>    opset_version=17<br>)</pre><h3>7. Final Conversion with Core ML Tools</h3><p>With ONNX in hand, conversion to Core ML can be done (in a compatible environment, e.g. Python 3.9 via Conda):</p><pre># convert_onnx.py<br>import coremltools as ct<br><br>model = ct.converters.onnx.convert(<br>    model=&quot;phi3_spanish_tutor.onnx&quot;,<br>    convert_to=&quot;mlprogram&quot;,<br>    minimum_deployment_target=ct.target.iOS16,<br>    compute_units=ct.ComputeUnit.ALL,<br>    skip_model_load=True<br>)<br>model.save(&quot;phi3_spanish_tutor.mlpackage&quot;)</pre><p>Or via Apple’s command-line compiler:</p><pre>xcrun coremlcompiler compile phi3_spanish_tutor.onnx phi3_spanish_tutor.mlpackage</pre><h3>8. Lessons Learned &amp; Next Steps</h3><ol><li>Environment Compatibility: Python 3.13 + Core ML Tools has rough edges — Conda with Python 3.9 is smoother.</li><li>Dynamic Ops: Custom attention masks and caching break tracing; ONNX is a robust bridge.</li><li>Quantization Trade-offs: LoRA + FP16 works on mobile but int4 training on Mac/MPS is limited without CUDA.</li><li>Iterate in Small Steps: Test with few tokens, fixed shapes, then scale to full inputs.</li><li>Deployment: Once .mlpackage is generated, integrate in Xcode via Generate API or use Core ML Swift bindings.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=94e7014cc49a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part II: I’m working on training small models that can run on Apple Silicon, and thought I would…]]></title>
            <link>https://medium.com/@lawrencenorman7hills/im-working-on-training-small-models-that-can-run-on-apple-silicon-and-thought-i-would-start-with-998932d16cde?source=rss-36967447924d------2</link>
            <guid isPermaLink="false">https://medium.com/p/998932d16cde</guid>
            <category><![CDATA[model-conversion]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[coreml]]></category>
            <dc:creator><![CDATA[Lawrence Norman]]></dc:creator>
            <pubDate>Thu, 24 Apr 2025 03:54:29 GMT</pubDate>
            <atom:updated>2025-04-24T20:38:18.581Z</atom:updated>
            <content:encoded><![CDATA[<h3>Part II: I’m working on training small models that can run on Apple Silicon, and thought I would start with a Spanish/English tutor.</h3><h3>Converting a Fine-Tuned Phi-3 Model to Core ML:</h3><p>Converting large language models (LLMs) like Phi-3 for on-device inference on iOS requires converting them to Apple’s Core ML format. While tools like coremltools exist, the path isn&#39;t always straightforward, especially with fine-tuned models or specific environment configurations. Here&#39;s a breakdown of the steps and hurdles encountered while converting a fine-tuned Spanish/English tutor Phi-3 model.</p><h3>Initial Goal: ONNX to Core ML</h3><p>The initial plan was to export the fine-tuned and merged PyTorch model to the ONNX format and then convert the ONNX file to Core ML using coremltools.</p><h3>Step 1: Export to ONNX</h3><p>First, the merged PyTorch model (phi3_spanish_tutor_merged) was loaded and exported to ONNX using torch.onnx.export.</p><pre># save_onnx.py (Simplified)<br>import torch<br>from transformers import AutoModelForCausalLM, AutoTokenizer<br><br>model_path = &quot;phi3_spanish_tutor_merged&quot;<br>tokenizer = AutoTokenizer.from_pretrained(model_path)<br>model = AutoModelForCausalLM.from_pretrained(model_path, torch_dtype=torch.float16)<br>model.eval()<br># Simple wrapper might be needed<br>class SimpleWrapper(torch.nn.Module):<br>    # ... (wrapper definition) ...<br>wrapped_model = SimpleWrapper(model)<br>wrapped_model.eval()<br>inputs = tokenizer(&quot;Translate to Spanish: Hello&quot;, return_tensors=&quot;pt&quot;)<br>torch.onnx.export(<br>    wrapped_model,<br>    args=(inputs.input_ids,),<br>    f=&quot;phi3_spanish_tutor.onnx&quot;,<br>    input_names=[&#39;input_ids&#39;],<br>    output_names=[&#39;logits&#39;],<br>    dynamic_axes={ # Important for variable sequence length<br>        &#39;input_ids&#39;: {0: &#39;batch_size&#39;, 1: &#39;sequence&#39;},<br>        &#39;logits&#39;: {0: &#39;batch_size&#39;, 1: &#39;sequence&#39;}<br>    },<br>    opset_version=17 # Use a recent opset<br>)<br>print(&quot;ONNX export complete!&quot;)</pre><h3>Step 2: Attempt ONNX to Core ML Conversion</h3><p>The next step involved using coremltools to convert the generated phi3_spanish_tutor.onnx file.</p><pre># convert_simple.py (Initial attempt)<br>import coremltools as ct<br><br>model = ct.convert(<br>    model=&quot;phi3_spanish_tutor.onnx&quot;,<br>    source=&quot;onnx&quot;, # Specify source format<br>    # ... other parameters ...<br>)<br>model.save(&quot;phi3_spanish_tutor.mlpackage&quot;)</pre><h3>Hurdles Encountered (ONNX Path)</h3><p>This seemingly simple conversion hit several roadblocks:</p><ol><li><strong>Environment Issues:</strong> Initial ModuleNotFoundError errors indicated coremltools wasn&#39;t installed correctly in the active virtual environment. Switching Python versions (from 3.13 to 3.10) was also necessary as coremltools had compatibility issues with newer Python releases.</li><li><strong>API Changes:</strong> An AttributeError showed that the older ct.converters.onnx.convert API was being used instead of the current ct.convert(..., source=&quot;onnx&quot;).</li><li><strong>Dependency Conflicts (NumPy):</strong> Warnings and errors related to NumPy versions (A module that was compiled using NumPy 1.x cannot be run in NumPy 2.x...) required downgrading NumPy using pip install &quot;numpy&lt;2&quot;.</li><li><strong>Large Model Issues (&gt;2GB):</strong> The ONNX model exceeded 2GB. This caused onnx.checker.check_model(onnx.load(path)) to fail. The fix was to validate using the file path directly: onnx.checker.check_model(path).</li><li><strong>Persistent </strong><strong>coremltools Error:</strong> Despite fixing the above, coremltools (both v7.1 and v8.2) consistently failed with ValueError: Unrecognized value of argument &quot;source&quot;: onnx. This occurred even after the ONNX file passed validation, strongly suggesting an internal limitation or bug in coremltools when handling multi-gigabyte ONNX files via this pathway.</li></ol><h3>Strategy Shift: Direct PyTorch to Core ML</h3><p>Given the persistent issues with the large ONNX file, the strategy shifted to converting the PyTorch model directly to Core ML, bypassing the ONNX step.</p><h3>Step 3: Prepare for Direct Conversion</h3><p>This involved loading the merged PyTorch model and preparing it for tracing using torch.jit.trace.</p><pre># convert_pytorch_direct.py (Setup)<br>import torch<br>from transformers import AutoModelForCausalLM, AutoTokenizer<br>import coremltools as ct<br>import numpy as np<br><br>model_path = &quot;phi3_spanish_tutor_merged&quot;<br>tokenizer = AutoTokenizer.from_pretrained(model_path)<br>model_fp16 = AutoModelForCausalLM.from_pretrained(model_path, torch_dtype=torch.float16)<br>model_fp16.eval()<br># Wrapper for tracing<br>class TraceWrapper(torch.nn.Module):<br>    def __init__(self, model):<br>        super().__init__()<br>        self.model = model<br>    def forward(self, input_ids, attention_mask): # Include attention_mask<br>        outputs = self.model(<br>            input_ids=input_ids,<br>            attention_mask=attention_mask,<br>            use_cache=False,<br>            return_dict=False<br>        )<br>        return outputs[0]<br># Example input<br>max_seq_length = 64<br>inputs = tokenizer(&quot;Translate to Spanish: Hello&quot;, return_tensors=&quot;pt&quot;, max_length=max_seq_length, padding=&#39;max_length&#39;, truncation=True)<br>example_input_ids = inputs.input_ids<br>example_attention_mask = inputs.attention_mask</pre><h3>Step 4: Trace the Model</h3><p>Tracing captures the model’s execution graph. A key issue arose here.</p><ul><li><strong>Hurdle:</strong> RuntimeError: &quot;addmm_impl_cpu_&quot; not implemented for &#39;Half&#39;. PyTorch&#39;s CPU implementation for certain operations doesn&#39;t support float16 (&#39;Half&#39;) precision.</li><li><strong>Fix:</strong> Load the model in float16, but create a temporary float32 version <em>just for tracing</em>. The final Core ML conversion can still target float16.</li></ul><pre># convert_pytorch_direct.py (Tracing)<br>model_fp32_for_trace = model_fp16.to(torch.float32) # Cast to FP32 for trace<br>trace_wrapper_fp32 = TraceWrapper(model_fp32_for_trace)<br>trace_wrapper_fp32.eval()<br><br>with torch.no_grad():<br>    traced_model = torch.jit.trace(<br>        trace_wrapper_fp32,<br>        example_inputs=(example_input_ids, example_attention_mask), # Pass both inputs<br>        # ... trace parameters ...<br>    )</pre><h3>Step 5: Convert Traced Model to Core ML</h3><p>The traced model was then passed to ct.convert.</p><ul><li><strong>Hurdle:</strong> RuntimeError: PyTorch convert function for op &#39;bitwise_or_&#39; not implemented. The traced graph contained an in-place bitwise OR operation (likely from attention mask logic) that coremltools (even v8.2) didn&#39;t support.</li><li><strong>Fix (Workaround):</strong> This required modifying the installed transformers library source code. Specifically, in transformers/models/phi3/modeling_phi3.py, within the _prepare_4d_causal_attention_mask_with_cache_position method, the line performing boolean arithmetic (which was itself a workaround for the original bitwise_or_) was replaced with torch.logical_or.</li></ul><pre># Inside modeling_phi3.py (Conceptual Change)<br># Change from the arithmetic simulation or bitwise_or_<br># To:<br>diagonal_attend_mask = torch.logical_or(diagonal_attend_mask, sliding_attend_mask)</pre><ul><li><strong>Conversion Call:</strong></li></ul><pre># convert_pytorch_direct.py (Conversion)<br>input_ids_tensor = ct.TensorType(name=&quot;input_ids&quot;, shape=(1, max_seq_length), dtype=np.int32)<br>attention_mask_tensor = ct.TensorType(name=&quot;attention_mask&quot;, shape=(1, max_seq_length), dtype=np.float32) # Use float32 for mask<br><br>coreml_model = ct.convert(<br>    traced_model,<br>    inputs=[input_ids_tensor, attention_mask_tensor],<br>    convert_to=&quot;mlprogram&quot;,<br>    compute_units=ct.ComputeUnit.ALL,<br>    minimum_deployment_target=ct.target.iOS16,<br>    compute_precision=ct.precision.FLOAT16 # Target FP16<br>)<br><br>coreml_model.save(&quot;phi3_spanish_tutor_direct_fp16.mlpackage&quot;)</pre><h3>Success!</h3><p>After modifying the transformers source code to use torch.logical_or, the direct PyTorch-to-Core ML conversion using coremltools 8.2 finally succeeded, producing the phi3_spanish_tutor_direct_fp16.mlpackage file.</p><h3>Key Takeaways</h3><ul><li>Converting large models (&gt;2GB) via ONNX can hit limitations in coremltools.</li><li>Direct PyTorch-to-Core ML conversion using torch.jit.trace is often more robust but requires careful handling of data types (trace in FP32 if FP16 CPU ops fail).</li><li>Unsupported PyTorch operations (bitwise_or_ in this case) are a common hurdle. Sometimes, modifying the source library (carefully!) is the only workaround if the converter lacks support.</li><li>Always ensure your Python environment, coremltools version, and dependencies like NumPy are compatible.</li></ul><p>This process highlights the iterative nature of model conversion, often requiring debugging dependency issues, API changes, and sometimes even patching library code to bridge gaps between frameworks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=998932d16cde" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ From Idea to Cloud‑Deployed AI Agent on GCP (with Google ADK)]]></title>
            <link>https://medium.com/@lawrencenorman7hills/from-idea-to-cloud-deployed-ai-agent-on-gcp-with-google-adk-50e8e669c557?source=rss-36967447924d------2</link>
            <guid isPermaLink="false">https://medium.com/p/50e8e669c557</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[adk]]></category>
            <category><![CDATA[ai-agent-tutorial]]></category>
            <dc:creator><![CDATA[Lawrence Norman]]></dc:creator>
            <pubDate>Mon, 21 Apr 2025 02:31:57 GMT</pubDate>
            <atom:updated>2025-04-21T14:25:24.450Z</atom:updated>
            <content:encoded><![CDATA[<p><em>I am in the process of converting my existing AI functions into ADK Agents for my learning platform Quiznect.com, and here I’ve started with validation of any learning goal in real‑time &amp; wiring it into the Quiznect React Native app</em></p><blockquote><em>In ~30 minutes we’ll go from zero to a fully deployed Cloud Run service that tells you whether a user’s “learning goal” is a valid topic.</em></blockquote><blockquote><em>Tech stack: </em><strong><em>Google Model Context Protocol + Agent Development Kit (ADK)</em></strong><em>, </em><strong><em>FastAPI</em></strong><em>, </em><strong><em>Gemini API</em></strong><em>, </em><strong><em>Docker</em></strong><em>, </em><strong><em>Cloud Build/Run</em></strong><em>, and a tiny </em><strong><em>React Native</em></strong><em> snippet.</em></blockquote><h3>1. Why ADK?</h3><p>The <strong>Agent Development Kit</strong> lets you wrap <em>any</em> Python (or Go / Node) code — including LLM calls — into “tools” and compose them into deterministic workflows. Here we only need <strong>one tool</strong> (validate_topic) but the same pattern scales to multi‑step tutoring agents later on.</p><h3>2. Folder layout</h3><pre>learningAgent/<br>└─ validate_topic_agent/<br>   ├─ agent.py          # FastAPI + ADK glue<br>   ├─ utils.py          # calls Gemini to classify the topic<br>   ├─ tools.py          # ADK FunctionTool wrapper (future‑proofing)<br>   ├─ requirements.txt  # Python deps<br>   └─ Dockerfile        # container for Cloud Run</pre><h3>3. Local dev: create &amp; test the validator</h3><h3>3.1 Install deps</h3><pre>python -m venv .venv<br>source .venv/bin/activate<br>pip install -r requirements.txt</pre><h3>3.2 utils.py</h3><pre>import os, google.generativeai as genai<br><br>SYSTEM_PROMPT = &quot;&quot;&quot;<br>You are a strict classifier that decides if a user&#39;s query is a VALID LEARNING TOPIC.<br>Return JSON:<br>  {&quot;valid&quot;: bool, &quot;normalized_topic&quot;: &quot;&lt;title|&#39;&#39;&gt;&quot;, &quot;reason&quot;: &quot;&lt;why_invalid|&#39;&#39;&gt;&quot;}<br>&quot;&quot;&quot;<br>def validate_topic(query: str) -&gt; str:<br>    model = genai.GenerativeModel(&quot;gemini-1.5-flash&quot;)<br>    response = model.generate_content(<br>        SYSTEM_PROMPT + f&quot;\nUser: {query}&quot;,<br>        generation_config={&quot;response_mime_type&quot;: &quot;application/json&quot;}<br>    )<br>    return response.text.strip()</pre><h3>3.3 agent.py</h3><pre>import json<br>from fastapi import FastAPI<br>from pydantic import BaseModel<br>from utils import validate_topic<br><br>app = FastAPI()<br>class Query(BaseModel):<br>    query: str<br>@app.post(&quot;/validate&quot;)<br>async def validate(q: Query):<br>    try:<br>        return json.loads(validate_topic(q.query))<br>    except json.JSONDecodeError:<br>        return {&quot;valid&quot;: False,<br>                &quot;normalized_topic&quot;: &quot;&quot;,<br>                &quot;reason&quot;: &quot;Failed to parse model response&quot;}a</pre><h3>3.4 Run locally</h3><pre>export GOOGLE_API_KEY=&quot;YOUR_GEMINI_KEY&quot;<br><br>uvicorn agent:app --reload --port 8080<br><br>curl -X POST http://localhost:8080/validate \<br>  -H &quot;Content-Type: application/json&quot; \<br>  -d &#39;{&quot;query&quot;:&quot;I want to learn linear algebra&quot;}&#39;</pre><p>Expected:</p><pre>{&quot;valid&quot;: true, &quot;normalized_topic&quot;: &quot;Linear Algebra&quot;, &quot;reason&quot;: &quot;&quot;}</pre><h3>4. Dockerize</h3><h3>Dockerfile</h3><pre>FROM python:3.11-slim<br>WORKDIR /app<br>COPY requirements.txt .<br>RUN pip install --no-cache-dir -r requirements.txt<br>COPY . .<br>EXPOSE 8080<br>CMD [&quot;sh&quot;, &quot;-c&quot;, &quot;uvicorn agent:app --host 0.0.0.0 --port ${PORT:-8080}&quot;]</pre><p>requirements.txt</p><pre>fastapi<br>uvicorn[standard]<br>google-generativeai<br>python-dotenv</pre><h3>5. Build &amp; push with Cloud Build</h3><pre>gcloud config set project YOUR_PROJECT_ID<br>gcloud builds submit . \<br>  --tag gcr.io/YOUR_PROJECT_ID/validate-topic:latest</pre><h3>6. Deploy to Cloud Run</h3><pre>gcloud run deploy validate-topic-service \<br>  --image gcr.io/YOUR_PROJECT_ID/validate-topic:latest \<br>  --region us-central1 \<br>  --platform managed \<br>  --allow-unauthenticated \<br>  --set-env-vars GOOGLE_API_KEY=&quot;YOUR_GEMINI_KEY&quot;</pre><p>Note: Cloud Run injects a runtime $PORT; our Dockerfile already respects it.</p><h3>7. Smoke test in prod</h3><pre>SERVICE_URL=$(gcloud run services describe validate-topic-service \<br>                --region us-central1 --format=&#39;value(status.url)&#39;)</pre><pre>curl -X POST ${SERVICE_URL}/validate \<br>  -H &quot;Content-Type: application/json&quot; \<br>  -d &#39;{&quot;query&quot;:&quot;Learn guitar&quot;}&#39;</pre><p>You should see a JSON verdict from the cloud.</p><h3>8. Wire it into React Native</h3><pre>// src/api/validateTopic.ts<br>const VALIDATION_URL =<br>  &quot;https://validate-topic-service-xxxxxxxxxx-uc.a.run.app/validate&quot;;</pre><pre>export async function validateLearningGoal(query: string) {<br>  const res = await fetch(VALIDATION_URL, {<br>    method: &quot;POST&quot;,<br>    headers: { &quot;Content-Type&quot;: &quot;application/json&quot; },<br>    body: JSON.stringify({ query }),<br>  });<br>  if (!res.ok) throw new Error(`HTTP ${res.status}`);<br>  return await res.json(); // {valid, normalized_topic, reason}<br>}</pre><pre>// inside your LearningFocusScreen<br>async function handleSaveGoal() {<br>  if (!input.trim()) return;<br>  setLoading(true);</pre><pre>  try {<br>    const verdict = await validateLearningGoal(input.trim());<br>    if (!verdict.valid) {<br>      Alert.alert(&quot;Try again&quot;, verdict.reason || &quot;Not a valid learning topic&quot;);<br>      return;<br>    }<br>    // ✅ good topic — proceed with Firestore write or PlanGenerator<br>    saveGoalToFirebase(verdict.normalized_topic);<br>  } catch (err) {<br>    Alert.alert(&quot;Network error&quot;, String(err));<br>  } finally {<br>    setLoading(false);<br>  }<br>}</pre><p><em>Your existing banned‑word logic can stay — this simply adds an AI gate ahead of it.</em></p><h3>👋 That’s it!</h3><p>You now have a production‑grade, serverless AI microservice that vets any learning goal in milliseconds — and it slots directly into your React Native flow. Scale up by adding new ADK tools, or fork this article to spin up your own domain‑specific validators.</p><p>Happy building — and may your learning journeys always start with a valid topic!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=50e8e669c557" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Native Expo SDK 51 Upgrade: My Descent into the Podfile Abyss (and How I Climbed Out)]]></title>
            <link>https://medium.com/@lawrencenorman7hills/react-native-expo-sdk-51-upgrade-my-descent-into-the-podfile-abyss-and-how-i-climbed-out-553cae49f024?source=rss-36967447924d------2</link>
            <guid isPermaLink="false">https://medium.com/p/553cae49f024</guid>
            <category><![CDATA[react-native]]></category>
            <dc:creator><![CDATA[Lawrence Norman]]></dc:creator>
            <pubDate>Mon, 14 Apr 2025 19:21:45 GMT</pubDate>
            <atom:updated>2025-04-14T21:56:56.231Z</atom:updated>
            <content:encoded><![CDATA[<p>If you are a React Native developer you want to stay in the sweet spot in terms of library stability, but at some point you find that a deadline looms that forces your hand. You start getting these emails from Apple, and it’s time to bite the bullet and pay some technical debt:</p><blockquote><strong><em>App Store Connect</em></strong></blockquote><blockquote><strong><em>Hello,</em></strong></blockquote><blockquote><em>We noticed one or more issues with a recent delivery for the following app:</em></blockquote><blockquote><em>Quiznect</em></blockquote><blockquote><em>Version 1.0.40</em></blockquote><blockquote><em>Build 40</em></blockquote><blockquote><em>Although delivery was successful, you may want to correct the following issues in your next delivery. Once you’ve corrected the issues, upload a new binary to App Store Connect.</em></blockquote><blockquote><strong><em>ITMS-90725: SDK version issue</em></strong><em> — This app was built with the iOS 17.5 SDK. Starting April 24, 2025, all iOS and iPadOS apps must be built with the iOS 18 SDK or later, included in Xcode 16 or later, in order to be uploaded to App Store Connect or submitted for distribution.</em></blockquote><blockquote>Apple Developer Relations</blockquote><p>So, you need to upgrade your React Native’s Expo app. Apple’s latest SDK requirement deadline is looming (hello, iOS 18!). You run npx expo upgrade, follow the prompts, and hope for the best. Sometimes it works flawlessly. And sometimes... well, sometimes you end up on a multi-day debugging odyssey, diving deep into Podfiles, build logs, environment variables, and EAS configurations.</p><p>This is the story of my recent upgrade from Expo SDK 50 to SDK 51 for a React Native app using the <strong>Bare Workflow</strong>. It wasn’t pretty, but I eventually emerged with an iOS 18 SDK compliant build, and hopefully, my detailed tale of woe and eventual triumph can save you some time and sanity.</p><p><a href="https://www.reddit.com/r/expo/comments/1gqblmj/expo_sdk_52/"><em>(Note: that when I tried to upgrade to the Expo’s latest (Expo SDK 52 from Expo SDK 50), I crashed and burned for half a day with that, so if you are in the same boat, I suggest you might want to make incremental upgrades from one stable Expo to the next (50-&gt;51). Looks like latest 52 might need a bit more bake time or perhaps at this point I’m in a better position to do the upgrade to 52 (having gone from 50–&gt;51 first): https://www.reddit.com/r/expo/comments/1gqblmj/expo_sdk_52/)</em></a></p><h3>The Goal:</h3><p>Upgrade from Expo SDK 50 to SDK 51 to meet Apple’s upcoming SDK requirements and stay reasonably up-to-date.</p><h3>Initial Steps &amp; The First Hurdle: Dependencies &amp; Workflow</h3><p>Like a good developer, I committed my changes and ran the standard upgrade command:</p><pre>npx expo upgrade</pre><p>Right away, the modern Expo CLI doesn’t automate everything. It correctly identified I needed manual steps and pointed me to the <a href="https://docs.expo.dev/workflow/upgrading-expo-sdk-walkthrough/">official upgrade walkthrough</a>. The guide highlights the difference between the Managed workflow and the Bare workflow. I manage my ios and android folders directly (they aren&#39;t in .gitignore), so I knew I was in the Bare camp, requiring manual native adjustments.</p><ul><li><strong>Lesson 1:</strong> Know your workflow (Managed vs. Bare/Manual Native Dirs). The upgrade steps differ significantly.</li></ul><p>Before diving deep, I made sure my dependencies were reasonably clean. I’d previously used patch-package for a workaround, which caused build failures early on because it was a devDependency and wasn&#39;t found on the build server. Removing the patch and the dependency simplified things.</p><ul><li><strong>Lesson 2:</strong> Clean up obsolete workarounds (patch-package) and dependencies <em>before</em> upgrading. npm prune</li></ul><h3>Targeting the Right SDK (and Dependencies)</h3><p>I initially aimed for expo@latest (SDK 52) but after going down an unfruitful rabbit hole with that, I needed to pivot to the stable SDK 51 for this upgrade. This required manually editing package.json:</p><pre>// package.json excerpt - BEFORE<br>&quot;dependencies&quot;: {<br>  &quot;expo&quot;: &quot;latest&quot;,<br>  &quot;react&quot;: &quot;...&quot;,<br>  &quot;react-native&quot;: &quot;...&quot;,<br>  // ...<br>},</pre><pre>// package.json excerpt - AFTER<br>&quot;dependencies&quot;: {<br>  &quot;expo&quot;: &quot;~51.0.0&quot;, // Target stable SDK 51<br>  &quot;react&quot;: &quot;18.2.0&quot;, // Correct React for RN 0.74<br>  &quot;react-native&quot;: &quot;0.74.2&quot;, // Correct RN for Expo 51<br>  // ... other dependencies aligned later ...<br>},<br>// REMOVED direct &quot;expo-modules-core&quot; dependency if present</pre><p>Then, I attempted to align dependencies using npx expo install --fix. However, verification using npm list expo react react-native expo-modules-core showed critical mismatches persisted (like RN 0.76 still present, old expo-modules-core).</p><p>The fix required a more forceful approach:</p><ol><li>Manually ensure package.json had the correct versions for expo, react, and react-native.</li><li>Thoroughly clean the environment:</li></ol><p>npm cache clean --force sudo rm -rf node_modules # Needed sudo due to permissions rm package-lock.json</p><p>Reinstall using the Expo tool:</p><ul><li>npx expo install --fix</li></ul><p>Verify again with npm list. This time it showed the correct versions (Expo 51.0.x, RN 0.74.x, React 18.2.0, expo-modules-core 1.12.x).</p><ul><li><strong>Lesson 3:</strong> Target a specific, stable SDK version. Manually edit package.json <em>before</em> installing. Verify key dependencies (expo, react, react-native, expo-modules-core) with npm list after installing; don&#39;t blindly trust --fix. Perform clean installs (rm -rf node_modules/lockfile) when dependencies get stuck.</li></ul><h3>The pod install Gauntlet: Welcome to Dependency Hell</h3><p>With JavaScript dependencies finally aligned, I moved to the native side (cd ios &amp;&amp; pod install, or using npx pod-install from the root). This unleashed a cascade of errors:</p><h3>Error 1: uninitialized constant FlipperConfiguration</h3><ul><li><strong>Cause:</strong> Old Flipper setup in ios/Podfile incompatible with RN 0.74.</li><li><strong>Fix:</strong> Removed old Flipper logic, eventually commented out :flipper_configuration line inside use_react_native!</li></ul><h3>Error 2: cannot load such file ... native_modules</h3><ul><li><strong>Cause:</strong> Podfile tried to require_relative a file from @react-native-community/cli-platform-ios that didn&#39;t exist.</li><li><strong>Fix:</strong> Installed CLI (npm install --save-dev @react-native-community/cli), clean install, eventually commented out the require_relative line itself in ios/Podfile.</li></ul><h3>Error 3: undefined method use_expo_modules!</h3><ul><li><strong>Cause:</strong> Accidentally commented out the require for expo/scripts/autolinking in ios/Podfile.</li><li><strong>Fix:</strong> Restored the correct require line (require File.join(...)).</li></ul><h3>Error 4: React-RuntimeHermes ... required a higher minimum deployment target</h3><ul><li><strong>Cause:</strong> RN 0.74 needed iOS &gt;= 14.0 (or 15.0), but Podfile defaulted to 13.4.</li><li><strong>Fix:</strong> Updated platform :ios, ... || &#39;15.0&#39; in ios/Podfile. (Started with 14.0, needed 15.0).</li></ul><h3>Error 5: Unable to find a specification for fmt</h3><ul><li><strong>Cause:</strong> Stale ios/Podfile.lock from SDK 50 conflicted with RN 0.74&#39;s fmt requirement.</li><li><strong>Fix:</strong> rm ios/Podfile.lock.</li></ul><h3>Error 6: Unable to find a specification for ExpoModulesCore (triggered by various pods)</h3><ul><li><strong>Cause:</strong> Initially triggered by deprecated expo-random. Also persisted due to potential spec repo/cache issues or JS dependency inconsistencies (expo-modules-core showing as extraneous or old version).</li><li><strong>Fixes:</strong></li><li>Migrated: npm uninstall expo-random &amp; npx expo install expo-crypto &amp; updated JS imports.</li><li>Verified/fixed expo-modules-core JS install using npx expo install expo-modules-core. Checked existence with ls node_modules/expo-modules-core/ExpoModulesCore.podspec.</li><li>Cleaned pod cache: pod cache clean --all.</li><li>Updated pod repos: pod repo update.</li><li>Added source to Podfile: source &#39;https://cdn.cocoapods.org/&#39;.</li><li><strong>Lesson 4:</strong> pod install errors are sequential. Fix one, the next appears. Be methodical.</li><li><strong>Lesson 5:</strong> Check minimum deployment targets (platform :ios) required by your React Native version.</li><li><strong>Lesson 6:</strong> Podfile.lock conflicts are common; deleting it forces fresh resolution. Commit the <em>new</em> lock file after a successful install.</li><li><strong>Lesson 7:</strong> Pay attention to deprecation warnings! Migrating can solve underlying pod issues.</li><li><strong>Lesson 8:</strong> Verify core JS dependencies are correctly installed <em>and</em> their native counterparts (.podspec files) exist. Use npx expo install &lt;package&gt; for Expo packages. Keep pod repos (pod repo update) and cache (pod cache clean --all) clean.</li></ul><h3>The EAS Build Environment Saga</h3><p>Getting pod install working locally wasn&#39;t the end. The cloud build had its own environment quirks:</p><h3>Error 1: expo doctor Failures in Cloud</h3><ul><li><strong>Command:</strong> eas build --profile &lt;profile_name&gt; --platform ios</li><li><strong>Problem:</strong> The build log showed expo doctor failing checks related to app.json schema, extraneous packages, mismatched config-plugins, and outdated dependencies – issues that <em>should</em> have been fixed locally.</li><li><strong>Fix (Local):</strong> Re-ran local fixes diligently:</li><li>Corrected app.json schema (removed runtimeVersion from updates, removed android.foregroundService, kept top-level runtimeVersion). Final relevant app.json structure:</li><li>// app.json excerpt { &quot;expo&quot;: { &quot;version&quot;: &quot;1.0.40&quot;, // ... &quot;runtimeVersion&quot;: &quot;1.0.40&quot;, // Kept this top-level one &quot;updates&quot;: { &quot;url&quot;: &quot;...&quot; // No runtimeVersion here }, &quot;android&quot;: { // No foregroundService here } // ... } }</li><li>Ran npm prune</li><li>Forced correct config-plugins: npx expo install @expo/config-plugins@~8.0.0.</li><li>Ran npx expo install --check and fixed all reported mismatches using npx expo install &lt;package@version&gt;.</li><li><strong>Committed</strong> all changes via git (package.json, package-lock.json, app.json).</li></ul><h3>Error 2: eas.json validation: cocoapodsVersion not allowed</h3><ul><li><strong>Command:</strong> eas build -p ios</li><li><strong>Problem:</strong> Attempting to set &quot;ios&quot;: { &quot;cocoapodsVersion&quot;: &quot;1.16.2&quot; } in eas.json failed validation, initially due to an outdated <em>local</em> eas-cli.</li><li><strong>Diagnosis:</strong> Used which eas revealing multiple conflicting installations (~/.proto, /opt/homebrew)</li><li><strong>Fix 1 (Local Env):</strong> Manually removed old binaries (rm &lt;path&gt;), updated global CLI (npm install -g eas-cli), ensured correct PATH setup in .zshrc (removing hardcoded paths, relying on proto shims, potentially adding the correct Node bin path manually if shims failed). Verified with eas --version.</li><li><strong>Problem 2:</strong> The <em>updated</em> eas-cli <em>still</em> rejected ios.cocoapodsVersion.</li><li><strong>Fix 2 (eas.json):</strong> Removed the ios.cocoapodsVersion key entirely from eas.json.</li></ul><h3>Error 3: redefinition of module &#39;ReactCommon&#39; (In Cloud Build)</h3><ul><li><strong>Command:</strong> eas build ...</li><li><strong>Problem:</strong> Native compilation failed again. Removing cocoapodsVersion meant EAS used its default (likely older, incompatible) CocoaPods version.</li><li><strong>Fix 1 (eas.json):</strong> Set build image: &quot;ios&quot;: { &quot;image&quot;: &quot;sdk-51&quot; }. Still failed with ReactCommon error.</li><li><strong>Fix 2 (Podfile):</strong> Investigated modular headers based on GitHub issues and error logs.</li><li>Commented out global use_modular_headers! in ios/Podfile. Failed with Firebase errors needing modular headers.</li><li>Final Podfile Fix: Kept global use_modular_headers! commented out, but <em>selectively enabled</em> it for Firebase/Google pods:</li><li># Inside target &#39;quiznect&#39; do in ios/Podfile pod &#39;FirebaseCoreInternal&#39;, :modular_headers =&gt; true pod &#39;GoogleUtilities&#39;, :modular_headers =&gt; true</li><li><strong>Final Local Steps:</strong> Cleaned pods (rm ios/Podfile.lock ios/Pods), ran npx pod-install, committed Podfile and Podfile.lock.</li></ul><h3>Meeting Apple’s Deadline (ITMS-90725)</h3><ul><li><strong>Problem:</strong> The successful SDK 51 build used Xcode 15.x. Apple required Xcode 16 / iOS 18 SDK by April 24, 2025.</li><li><strong>Fix (eas.json):</strong> Updated the build image in eas.json to one with Xcode 16. Checked the valid image list provided by a previous EAS error.</li><li>// eas.json excerpt &quot;development-simulator&quot;: { // ... &quot;ios&quot;: { &quot;simulator&quot;: true, &quot;image&quot;: &quot;macos-sonoma-14.6-xcode-16.1&quot; // Or similar valid Xcode 16 image } // ... },</li><li><strong>Lesson 9:</strong> Fix expo doctor issues locally <em>before</em> building on EAS. Commit your lockfiles!</li><li><strong>Lesson 10:</strong> Ensure your <em>local</em> eas-cli is up-to-date (npm install -g eas-cli) and actually <em>running</em>. Debug PATH conflicts (which eas, .zshrc) carefully, especially with version managers like nvm or proto.</li><li><strong>Lesson 11:</strong> If eas.json keys are rejected, check if they&#39;re deprecated or if your CLI is outdated. Use the image property in eas.json to control the build environment tooling if defaults cause issues.</li><li><strong>Lesson 12:</strong> Native compilation errors like module redefinitions are complex. Consider use_frameworks!, use_modular_headers!, and library conflicts. Sometimes selective configuration (:modular_headers =&gt; true) is the answer.</li></ul><h3>iOS Build Success!</h3><p>After applying the final Podfile (selective modular headers) and eas.json (Xcode 16 image) fixes, cleaning the local Pods state, committing, and running eas build --clear-cache, the build <em>finally</em> succeeded and met Apple&#39;s requirements!</p><pre># Final successful build command (example for production)<br>eas build --profile production --platform ios --clear-cache</pre><p>Upgrading Expo SDKs in the Bare workflow isn’t always straightforward, but it’s manageable. It requires understanding both the JavaScript dependencies and the intricacies of the native build process (especially CocoaPods) and the cloud build environment. Hopefully, documenting these specific errors, diagnostic commands (npm list, which eas, npx expo install --check, npx expo-doctor), config file changes, and solutions helps someone else facing a similar upgrade challenge!</p><h3>Bonus Round: Fixing the Android Build</h3><p>Just when I thought I was out, they pull me back in! After the iOS build succeeded using the Xcode 16 image, I kicked off an Android build (eas build --platform android ...) only to find a new set of native challenges specific to Gradle.</p><h3>Error 1: Flipper Dependency Resolution (Could not find com.facebook.react:flipper-integration:)</h3><ul><li><strong>Command:</strong> eas build -p android ...</li><li><strong>Problem:</strong> Gradle couldn’t find the Flipper integration library because the version wasn’t specified correctly for React Native 0.74.</li><li><strong>Fix Part 1 (android/gradle.properties):</strong> Added the correct Flipper version variable.</li><li># android/gradle.properties FLIPPER_VERSION=0.212.0</li><li><strong>Fix Part 2 (android/app/build.gradle):</strong> Ensured the dependencies block actually <em>used</em> this variable and only included Flipper for debug builds. The key was replacing the simple implementation(&quot;com.facebook.react:flipper-integration&quot;) with conditional logic:</li><li>// android/app/build.gradle (inside dependencies block) def flipperVersion = findProperty(&#39;FLIPPER_VERSION&#39;) ?: &#39;0.0.0&#39; if (flipperVersion != &#39;0.0.0&#39;) { debugImplementation(&quot;com.facebook.flipper:flipper:${flipperVersion}&quot;) { /* excludes */ } debugImplementation(&quot;com.facebook.react:flipper-integration:${flipperVersion}&quot;) { /* excludes */ } // ... other flipper plugins ... }</li></ul><h3>Error 2: Kotlin Compilation (Unresolved reference: unstable_useRuntimeSchedulerAlways)</h3><ul><li><strong>Command:</strong> eas build -p android</li><li><strong>Problem:</strong> The build failed compiling MainApplication.kt, trying to reference a flag related to the New Architecture (which I had disabled) and likely incompatible/unavailable in RN 0.74.</li><li><strong>Fix (MainApplication.kt):</strong> Located the problematic if block in the onCreate method and removed it, along with the ReactFeatureFlags import.</li><li>// Removed this block from MainApplication.kt -&gt; onCreate() // if (!BuildConfig.REACT_NATIVE_UNSTABLE_USE_RUNTIME_SCHEDULER_ALWAYS) { // ReactFeatureFlags.unstable_useRuntimeSchedulerAlways = false // }</li></ul><h3>Other Gradle Updates</h3><p>During the process, I also ensured my top-level android/build.gradle had compatible versions for key buildscript dependencies required by Expo 51 / RN 0.74:</p><pre>// android/build.gradle (buildscript.dependencies)<br>dependencies {<br>    classpath(&#39;com.android.tools.build:gradle:8.2.1&#39;) // Added correct AGP version<br>    classpath(&#39;com.facebook.react:react-native-gradle-plugin&#39;)<br>    classpath(&#39;com.google.gms:google-services:4.4.2&#39;) // Updated Google Services<br>    // Ensure ext.kotlinVersion was also updated, e.g., &#39;1.9.20&#39;<br>}</pre><p>With these Android-specific fixes applied and committed, the Android build finally succeeded as well!</p><h3>Android Build Success!</h3><pre># Final successful build commands (example for production)<br>eas build --profile production --platform android --clear-cache</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=553cae49f024" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>