<?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 Ruichen He on Medium]]></title>
        <description><![CDATA[Stories by Ruichen He on Medium]]></description>
        <link>https://medium.com/@kylehe970128?source=rss-27e59be9bb61------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*MbtEMOXXJTOTkUI_bWYflA.jpeg</url>
            <title>Stories by Ruichen He on Medium</title>
            <link>https://medium.com/@kylehe970128?source=rss-27e59be9bb61------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 10:20:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kylehe970128/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[Why I Built a Draggable Command Center for SwiftUI in the AI Era]]></title>
            <link>https://medium.com/@kylehe970128/why-i-built-a-draggable-command-center-for-swiftui-in-the-ai-era-8a087a4cd58b?source=rss-27e59be9bb61------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a087a4cd58b</guid>
            <category><![CDATA[mobile-app-design]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[ui]]></category>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[Ruichen He]]></dc:creator>
            <pubDate>Sun, 11 Jan 2026 06:53:34 GMT</pubDate>
            <atom:updated>2026-01-11T06:53:34.618Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>An experiment in interaction-first UI for modern, AI-powered apps</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oQL-sQmxnnPk9TlJVnWa5A.png" /></figure><p>For years, mobile app interaction has been centered around navigation. Tabs, stacks, sheets, and modals define how users move through an app — and, by extension, how they interact with it. This model has worked well, but it’s starting to show its limits as apps become more capable, more contextual, and increasingly powered by AI.</p><p>In the AI era, interaction is no longer confined to a single screen. Users may want to ask a question, trigger an action, or get a summary regardless of where they are in the app. Voice, text, and intent-based interactions don’t naturally fit into deep navigation hierarchies. They want to be global, always accessible, and decoupled from the current view.</p><p>That tension is what led me to build a small experiment: a draggable, always-available command center entry point for SwiftUI — designed to sit above navigation, not inside it.</p><h4>A small experiment: a floating command center</h4><p>To make this idea concrete, I built a small diary app with a floating, draggable command center entry point. The button is always accessible, can be moved anywhere on screen, and remembers its position across launches. Tapping it reveals a lightweight command panel with global actions.</p><p>The important part is not what the actions do, but <strong>where they live</strong>. They’re not tied to a specific screen, tab, or navigation state. They exist at a higher interaction layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U9bPmR9Kf5lzO0CQvL4HCg.gif" /></figure><blockquote>Think of it less as a button, and more as an entry point.</blockquote><p>This pattern feels immediately different from traditional navigation. There’s no need to “go back” or “find the right tab” before interacting. The command center is simply there when you need it, regardless of where you are in the app.</p><h4>Why this isn’t just another floating button</h4><p>Floating UI elements aren’t new. What interested me wasn’t the visual affordance itself, but the role it plays in the interaction model.</p><p>A command center:</p><ul><li>Is <strong>global</strong>, not contextual</li><li>Survives deep navigation stacks</li><li>Works naturally with AI, voice, or text-based interaction</li><li>Can evolve without changing your navigation structure</li></ul><p>In an AI-powered app, users don’t think in terms of screens — they think in terms of <strong>intent</strong>. This kind of entry point aligns much more closely with that mental model.</p><h4>Design principles behind the command center</h4><p>This experiment wasn’t about adding a new UI element — it was about rethinking where interaction lives. A few design principles guided the implementation.</p><p><strong>1.Interaction should be global, not screen-bound</strong></p><p>In many apps, actions are only available once you’ve navigated to the “right” place. That works for linear flows, but it breaks down as apps grow more complex.</p><p>A command center exists independently of the current screen. It doesn’t care whether the user is in a list, a detail view, or five levels deep in a navigation stack. This makes interaction feel immediate and reduces the cognitive cost of “finding” functionality.</p><p><strong>2.Spatial memory matters</strong></p><p>The floating entry point can be dragged anywhere and remembers its position. This is intentional.</p><p>Users build spatial memory quickly. When something stays where they left it, interaction becomes muscle memory instead of a decision. This is especially important for frequently used, cross-cutting actions.</p><p><strong>3.Decoupling interaction from navigation</strong></p><p>Navigation is about where you are. Interaction is about what you want to do. These are related, but not the same.</p><p>By placing the command center above the navigation hierarchy, interaction becomes composable. The same entry point can trigger UI actions, background work, or AI-driven behaviors — without restructuring the app’s navigation.</p><p><strong>4. Composability over prescription</strong></p><p>The command center doesn’t assume what it contains. It might show buttons today, a chat interface tomorrow, or a voice input layer later.</p><p>The goal is to provide a stable interaction surface while letting the content evolve. This flexibility is critical as AI capabilities change faster than UI patterns.</p><h4>Why this pattern fits the AI era</h4><p>AI introduces a different interaction model. Instead of navigating to features, users express intent: <em>summarize this</em>, <em>create a new entry</em>, <em>what changed today?</em></p><p>These interactions are:</p><ul><li>Global</li><li>Cross-context</li><li>Often asynchronous</li></ul><p>A floating command center becomes a natural entry point for these behaviors. It acts as a bridge between traditional UI and intent-driven interaction — whether that intent comes from text, voice, or automation.</p><p>In this sense, the UI pattern is as important as the model behind it. Without a global interaction surface, AI features risk being buried inside screens and flows that weren’t designed for them.</p><h4>Introducing HodosKit</h4><p>To explore this pattern beyond a one-off demo, I packaged the core idea into a small SwiftUI library called <strong>HodosKit</strong>.</p><p>HodosKit is intentionally minimal. It’s not a navigation framework, an AI SDK, or a UI abstraction layer. Instead, it provides a single, composable building block for creating global interaction surfaces — like the floating command center shown above — without making assumptions about how the rest of your app is structured.</p><p>The library focuses on three things:</p><ul><li>A stable, always-available interaction entry point</li><li>Predictable spatial behavior across devices</li><li>Clean integration with existing SwiftUI apps</li></ul><p>Everything else is left up to the app.</p><h4>A minimal, composable API</h4><p>At its core, HodosKit exposes a single view: FloatingOverlay. It’s designed to be explicit and unsurprising.</p><p>A simplified version of the demo looks like this:</p><pre>FloatingOverlay(<br>    isPresented: $showPanel,<br>    position: .persistent(key: &quot;diaryDemo.floatingEntry&quot;),<br>    config: .init(edgePadding: 16, snapToEdge: false, defaultAnchor: .bottomTrailing)<br>) {<br>    DiaryHomeView()<br>} entry: {<br>    FloatingEntryButton(isActive: showPanel)<br>} overlay: {<br>    CommandCenterPanel()<br>}</pre><p>There are three closures, each with a clear responsibility:</p><ul><li><strong>content</strong> is your main application UI. HodosKit doesn’t care what navigation model you use.</li><li><strong>entry</strong> defines the floating affordance—typically a button or icon the user can drag and tap.</li><li><strong>overlay</strong> is the interaction surface itself, which can contain buttons, a chat interface, or any custom UI.</li></ul><p>The library handles gesture coordination, safe-area awareness, normalized positioning, and persistence. The app controls everything else.</p><h4>Designed to stay out of the way</h4><p>One of the explicit goals of HodosKit is to avoid becoming a central dependency. You can:</p><ul><li>Remove it without refactoring your navigation</li><li>Swap the overlay content freely</li><li>Use it purely as a UI affordance, or as an entry point for AI-driven interactions</li></ul><p>In the diary demo, the command center shows simple buttons. In a real app, the same pattern could surface an assistant, accept voice input, or route high-level intents into your existing state and navigation logic.</p><p>HodosKit doesn’t try to solve those problems for you — it just makes room for them.</p><h4>Open source and evolving</h4><p>HodosKit is open source and still early. The goal isn’t to define a final pattern, but to explore how interaction-first UI might evolve as AI becomes a native part of mobile apps.</p><p>If this resonates with you, the code is available on <a href="https://github.com/RuichenHe/HodosKit">GitHub:<strong> HodosKit</strong></a>.</p><p>Android support and additional experiments are planned, but the core idea — global, intent-friendly interaction — remains the same.</p><h4>Rethinking where interaction begins</h4><p>This experiment started with a simple question: what happens if we stop treating navigation as the center of interaction?</p><p>As AI becomes a native part of our apps, users will increasingly interact through intent — asking questions, triggering actions, and moving across contexts without caring where they are in the interface. Patterns like a floating command center aren’t about adding another button; they’re about creating room for this shift to happen gracefully.</p><p>HodosKit is just one exploration of that idea. You can use it, ignore it, or build something entirely different — but the underlying question remains the same: <strong>where should interaction begin in an AI-first app?</strong></p><p>If this sparked ideas or challenged assumptions, that alone makes the experiment worthwhile.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a087a4cd58b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Airflow Pools: The Gotcha I Wish I Knew Before Wasting a Day]]></title>
            <link>https://medium.com/@kylehe970128/airflow-pools-the-gotcha-i-wish-i-knew-before-wasting-a-day-8d025c171a99?source=rss-27e59be9bb61------2</link>
            <guid isPermaLink="false">https://medium.com/p/8d025c171a99</guid>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[workflow-orchestration]]></category>
            <category><![CDATA[apache-airflow]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Ruichen He]]></dc:creator>
            <pubDate>Sun, 07 Sep 2025 03:50:12 GMT</pubDate>
            <atom:updated>2025-09-07T03:50:12.672Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/1*YBEORan5TV1qcVx8IgV1ug.png" /></figure><p>After spending a full day experimenting with Apache Airflow, I ran into a limitation that isn’t obvious until you try: <strong>Airflow pools can’t be assigned dynamically at runtime.</strong></p><p>I had a clear use case — restrict the number of parallel DAG runs <em>per team</em> by simply passing a team_alias parameter to my DAG and mapping it to a pool. On paper, it felt straightforward. In reality, it turned into a dead end.</p><p>Here’s what I learned, why it matters, and what you should keep in mind before going down the same path.</p><h4>Background: Why Pools Look Like the Perfect Solution</h4><p>Airflow pools are a built-in mechanism for controlling concurrency. They let you define limits such as:</p><ul><li>Pool gpu_jobs: max 5 concurrent tasks.</li><li>Pool team_a: max 20 concurrent tasks.</li></ul><p>This makes pools a natural fit if you want fair resource distribution across multiple teams. The idea was simple:</p><ol><li>Add a team_alias parameter to the DAG.</li><li>Assign each team’s tasks to a pool (e.g., team_a_pool, team_b_pool).</li><li>Control parallelism by adjusting each pool’s capacity.</li></ol><p>That way, no single team could overwhelm the system. At least, that was the plan.</p><h4>The Experiment</h4><p>I added a team_alias parameter to my DAG configuration and tried dynamically setting the pool assignment inside the DAG code. Something like:</p><pre>TEAM_POOLS = {<br>    &quot;team_a&quot;: &quot;team_a_pool&quot;,<br>    &quot;team_b&quot;: &quot;team_b_pool&quot;,<br>}<br><br>task = SomeOperator(<br>    ...,<br>    pool=TEAM_POOLS[team_alias]<br>)</pre><p>The expectation was simple: whichever team triggered the DAG would automatically have its tasks routed into the correct pool.</p><h4>The Reality Check</h4><p>Here’s where things broke down: <strong>pool assignments are locked in at DAG parse time, not runtime.</strong></p><p>Airflow’s scheduler looks at the DAG definition — including which pool each task belongs to — <em>before</em> execution ever starts. By the time you supply parameters like team_alias, the scheduler has already made its decisions.</p><p>That means:</p><ul><li>Pools are part of scheduling criteria, not something you can compute dynamically.</li><li>Runtime values from DAG params don’t affect pool assignment.</li><li>In practice, your pool mapping logic is ignored.</li></ul><p>This isn’t a bug. It’s how Airflow is designed. Pools live at the scheduler level, not the task execution level.</p><h4>Workarounds (and Why They’re Ugly)</h4><p>The only way to approximate “dynamic pools” is to predefine separate tasks per team, each hardcoded to a different pool, and then branch to the right task at runtime.</p><p>But that leads to problems:</p><ul><li><strong>Exponential DAG growth</strong> as more teams are added.</li><li><strong>High maintenance overhead</strong> when teams change.</li><li><strong>Longer DAG parsing times</strong> and more scheduler memory usage.</li></ul><p>In short: it scales terribly.</p><h4>The Takeaway</h4><p>If you’re considering dynamic pool assignment in Airflow — save yourself the time. It won’t work because pools are a design-time construct, not a runtime variable.</p><p>Instead, you’ll need to:</p><ul><li>Predefine DAGs or tasks for each pool.</li><li>Manage concurrency limits outside of Airflow.</li><li>Or wait for future improvements in Airflow’s design.</li></ul><h4>Current Status</h4><p>As of today, this is simply a limitation of Airflow’s architecture. There is an <a href="https://github.com/apache/airflow/discussions/47860">initial GitHub discussion</a> on the topic, but so far no one has submitted a formal <strong>Airflow Improvement Proposal (AIP)</strong> to change this behavior.</p><p>So, for now, the safest bet is to design with the limitation in mind rather than trying to work around it. Hopefully, this post spares you from burning a day chasing the same idea.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8d025c171a99" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Jetpack Compose Elevation Explained: Tonal, Shadow, and How to Use Them]]></title>
            <link>https://medium.com/@kylehe970128/jetpack-compose-elevation-explained-tonal-shadow-and-how-to-use-them-7697f80bca20?source=rss-27e59be9bb61------2</link>
            <guid isPermaLink="false">https://medium.com/p/7697f80bca20</guid>
            <category><![CDATA[material-design]]></category>
            <category><![CDATA[ui]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Ruichen He]]></dc:creator>
            <pubDate>Sat, 06 Sep 2025 05:33:30 GMT</pubDate>
            <atom:updated>2025-09-06T05:41:33.535Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dQX-HuKHNpZwx6KKRrwtmw.png" /></figure><p>When I first started building apps, my world revolved around <strong>iOS development</strong>. I lived in SwiftUI and UIKit, where elevation usually meant shadows and blur effects. Recently, I began exploring the <strong>Android side with Jetpack Compose</strong>, and I quickly ran into something new: not just shadows, but <strong>two different concepts of elevation</strong> — <strong>tonal</strong> and <strong>shadow</strong>.</p><p>At first, it felt confusing. Why would Material 3 give me two ways to show depth? Which one should I use for a card, a bottom sheet, or a floating action button?</p><p>The answer is: both have their place. Understanding the differences will help you design interfaces that look polished in <strong>Light and Dark themes</strong>, adapt naturally to <strong>dynamic color</strong>, and feel right at home in <strong>Material You</strong>.</p><p>In this post, I’ll walk through what I learned while experimenting:</p><ol><li>What tonal vs shadow elevation really means in Jetpack Compose.</li></ol><p>2. Code snippets and screenshots of each approach.</p><p>3. Practical rules of thumb on when to use tonal, shadow, or both.</p><p>If you’ve ever felt unsure about elevation in Compose — or if, like me, you’re crossing over from iOS and want to build Android UIs with confidence — this guide is for you.</p><p>When you hear <em>elevation</em>, you might immediately think of a shadow. That’s true for many design systems — but in <strong>Jetpack Compose with Material You (Material 3)</strong>, elevation has two different faces:</p><h4>1. Tonal Elevation</h4><p>Instead of casting a shadow, tonal elevation <strong>shifts the surface color</strong>. It blends your surface color with a surfaceTint, making elevated components look lighter (or darker, depending on theme). This approach works especially well in <strong>Dark theme</strong>, where shadows often get lost, but color differences remain visible.</p><p>Example use cases: Surface, Card, BottomSheet, navigation bars.</p><h4>2. Shadow Elevation</h4><p>This is the more familiar version: components cast <strong>a blurred shadow</strong> based on their shape. In Compose, you apply it with Modifier.shadow(...). Shadows stand out clearly in <strong>Light theme</strong> or against busy backgrounds (like photos). Example use cases: dialogs, menus, floating action buttons (FABs).</p><h4>Why two?</h4><p>Google’s Material You design system emphasizes <strong>personalization and color-driven depth</strong>. Tonal elevation helps your app fit seamlessly with dynamic color schemes and look clean in Dark theme, while shadow elevation is still useful when you need stronger visual separation.</p><p>Think of it like this:</p><ul><li><strong>Tonal = depth through color.</strong></li><li><strong>Shadow = depth through light.</strong></li></ul><p>Both are valid tools — the key is knowing <strong>when</strong> to use each.</p><p>Let’s start with <strong>tonal elevation</strong>, since this is the <em>default</em> in Material 3 and shows up in most built-in components like Surface and Card.</p><p>Tonal elevation doesn’t rely on shadows at all. Instead, it <strong>adjusts the surface color</strong> by blending it with a tint. The higher the elevation, the more the tint changes the background, making the surface appear raised. This approach is effective in <strong>both Light and Dark themes</strong>, though the visual effect looks different depending on which mode you’re in.</p><pre>@Composable<br>fun TonalElevationDemo() {<br>    val levels = listOf(0.dp, 1.dp, 3.dp, 6.dp, 12.dp)<br><br>    Row(<br>        horizontalArrangement = Arrangement.spacedBy(12.dp),<br>        modifier = Modifier.fillMaxWidth()<br>    ) {<br>        levels.forEach { e -&gt;<br>            Surface(<br>                tonalElevation = e,<br>                shape = MaterialTheme.shapes.medium,<br>                modifier = Modifier.size(60.dp)<br>            ) {<br>                Box(<br>                    modifier = Modifier.fillMaxSize(),<br>                    contentAlignment = Alignment.Center<br>                ) {<br>                    Text(<br>                        text = &quot;${e.value.toInt()}dp&quot;,<br>                        style = MaterialTheme.typography.labelSmall<br>                    )<br>                }<br>            }<br>        }<br>    }<br>}</pre><h4>Screenshot (Dark theme)</h4><figure><img alt="Five surfaces labeled “0dp”, “1dp”, “3dp”, “6dp”, “12dp”, each with slightly different tonal tint." src="https://cdn-images-1.medium.com/max/499/1*0TlYQjw6OWIGylunzr1z_g.png" /></figure><p><strong>What to Notice</strong></p><ul><li>No shadows at all.</li><li>Depth is expressed through <strong>brighter tints</strong> (the surface lightens as elevation increases).</li><li>Higher elevation → lighter surface → more contrast against the dark background.</li><li>This keeps elevated elements visible even without shadows.</li></ul><h4>Screenshot (Light theme)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/469/1*2sb1qHw6H9M96KS3dAkq3w.png" /></figure><p><strong>What to Notice</strong></p><ul><li>No shadows.</li><li>Depth is expressed through <strong>darker/paler tints</strong>.</li><li>Higher elevation → surface looks slightly darker compared to the base white.</li><li>Subtle, but provides hierarchy when stacking components.</li></ul><p>While tonal elevation changes a surface’s <strong>color tint</strong>, shadow elevation takes the more traditional route: it uses <strong>shadows</strong> to suggest depth. In Jetpack Compose, you apply it with Modifier.shadow(...), which draws a blurred outline around a component based on its elevation value and shape.</p><p>Shadows are most effective in <strong>Light theme</strong> or when your UI sits on top of a <strong>busy background</strong> (like photos or gradients). They provide strong separation from surrounding content, something tonal elevation alone can’t always achieve.</p><pre>@Composable<br>fun ShadowElevationDemo() {<br>    val levels = listOf(0.dp, 1.dp, 3.dp, 6.dp, 12.dp)<br><br>    Row(<br>        horizontalArrangement = Arrangement.spacedBy(12.dp),<br>        modifier = Modifier.fillMaxWidth()<br>    ) {<br>        levels.forEach { e -&gt;<br>            Box(<br>                modifier = Modifier<br>                    .size(60.dp)<br>                    .shadow(e, MaterialTheme.shapes.medium, clip = false)<br>                    .background(MaterialTheme.colorScheme.surface, MaterialTheme.shapes.medium),<br>                contentAlignment = Alignment.Center<br>            ) {<br>                Text(<br>                    text = &quot;${e.value.toInt()}dp&quot;,<br>                    style = MaterialTheme.typography.labelSmall<br>                )<br>            }<br>        }<br>    }<br>}</pre><h4>Screenshot (Light theme)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/473/1*FTFg7rgGB8DC-qRlD3fSnA.png" /></figure><p><strong>What to Notice</strong></p><ul><li>The <strong>surface color does not change</strong> — unlike tonal elevation.</li><li>Depth is shown entirely through <strong>shadows</strong>.</li><li>Higher elevation = a larger, blurrier shadow.</li><li>Works especially well on <strong>light backgrounds</strong>, where shadows stand out clearly.</li></ul><h4>Screenshot (Dark theme)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/461/1*PtWgxEpzxuZqUPWR642TDg.png" /></figure><p><strong>What to Notice</strong></p><ul><li>Shadows become <strong>less effective</strong> on dark backgrounds.</li><li>They can appear muddy or even vanish if contrast is too low.</li><li>This is why tonal elevation is often preferred in Dark theme.</li></ul><p>Shadow elevation feels immediately familiar if you’ve designed for Material 2 or iOS. In Material 3, however, it’s no longer the default — it’s a <strong>selective tool</strong> you use when you need strong separation, extra contrast, or a more tactile feel.</p><p>So far, we explored <strong>tonal elevation</strong> — depth expressed through subtle color shifts. Additionally, we looked at <strong>shadow elevation</strong> — depth expressed through light and blur. In practice, you rarely use them completely in isolation. Most polished UIs live somewhere in between, using both tonal and shadow together.</p><p>To make this idea more concrete, I built a simple grid that combines the two. Think of it as an <strong>elevation map</strong>:</p><ul><li><strong>Columns (left → right):</strong> increasing tonal elevation. Each step blends more tint into the surface, so the circles look progressively “lifted” by color.</li><li><strong>Rows (top → bottom):</strong> increasing shadow elevation. Each step adds a stronger shadow, making the circles float higher above the background.</li><li><strong>Top-left cell:</strong> flat — no tonal, no shadow.</li><li><strong>Bottom-right cell:</strong> maximum elevation — strong tonal tint and a heavy shadow.</li></ul><p>This grid exaggerates the values, so the effect is easy to see in screenshots. In production UIs, you’d use smaller numbers for a subtler, balanced look.</p><h3>Example: Tonal × Shadow Grid</h3><pre>@Composable<br>fun TonalShadowGrid_WithSurface() {<br>    val cs = MaterialTheme.colorScheme<br>    val tonalLevels  = listOf(0.dp, 8.dp, 16.dp, 24.dp)   // columns → tonal ↑<br>    val shadowLevels = listOf(0.dp, 8.dp, 16.dp, 24.dp)   // rows    → shadow ↑<br><br>    Column(verticalArrangement = Arrangement.spacedBy(16.dp), horizontalAlignment = Alignment.CenterHorizontally) {<br>        Text(&quot;Rows: shadow ↑   •   Columns: tonal ↑&quot;, style = MaterialTheme.typography.labelMedium)<br><br>        shadowLevels.forEach { shadowDp -&gt;<br>            Row(horizontalArrangement = Arrangement.spacedBy(16.dp), verticalAlignment = Alignment.CenterVertically) {<br>                tonalLevels.forEach { tonalDp -&gt;<br>                    Surface(<br>                        color = cs.surface,<br>                        shape = CircleShape,<br>                        tonalElevation = tonalDp,<br>                        modifier = Modifier<br>                            .size(56.dp)<br>                            .shadow(shadowDp, CircleShape, clip = false)<br>                    ) {<br>                        Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {<br>                            Icon(Icons.Default.Add, contentDescription = null, tint = cs.onSurface)<br>                        }<br>                    }<br>                }<br>            }<br>        }<br>    }<br>}</pre><p><strong>Screenshot (Light theme):</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/385/1*WOMgTSpcPk76QPElul1VtA.png" /></figure><p><strong>Screenshot (Dark theme):</strong></p><figure><img alt="The same grid in Dark theme. Tonal elevation brightens circles; shadows appear softer and less distinct." src="https://cdn-images-1.medium.com/max/394/1*L_KjKBJjyWZcQt3UALENjQ.png" /></figure><h4>What to Notice</h4><ul><li><strong>Light theme:</strong> tonal makes surfaces slightly darker/paler than the base, while shadows do the heavy lifting.</li><li><strong>Dark theme:</strong> tonal brightens surfaces to maintain contrast, while shadows fade into the background.</li><li>The <strong>middle area of the grid</strong> (moderate tonal + modest shadow) usually feels the most natural for real UI components.</li></ul><h4>Takeaways</h4><ul><li><strong>Start with tonal.</strong> It adapts to Light and Dark themes automatically.</li><li><strong>Add a small shadow</strong> when you need stronger separation, especially over images or patterned backgrounds.</li><li><strong>Test in both themes.</strong> Tonal and shadow play differently depending on background and color scheme.</li></ul><p>In this post we explored the two flavors of elevation in Jetpack Compose:</p><ul><li><strong>Tonal elevation</strong> — depth expressed through <strong>color shifts</strong>, theme-aware and dynamic color–friendly.</li><li><strong>Shadow elevation</strong> — depth expressed through <strong>light and blur</strong>, especially effective in Light theme and over busy backgrounds.</li><li><strong>Combined elevation</strong> — tonal and shadow working together. Our final 4×4 grid showed how the two axes interact, from completely flat to highly elevated.</li></ul><p>The key takeaway is simple: <strong>start with tonal, add shadow only when you need extra separation.</strong> Together, they give you a flexible design toolkit that works across Light and Dark themes.</p><p>I’ve personally learned a lot coming from an iOS background, where shadows are the default. Seeing how Material 3 uses tonal elevation as the baseline gave me a fresh perspective on designing depth for Android.</p><h4>What’s Next</h4><p>This post focused on elevation in Jetpack Compose, but my exploration doesn’t stop at UI details. On one side, I’ll continue experimenting with <strong>Material 3 design patterns</strong> — things like dynamic color, surface hierarchies, and cross-platform comparisons between iOS (SwiftUI) and Android (Compose).</p><p>At the same time, I’m also starting to dig into something bigger: <strong>how AI can be integrated directly into mobile apps</strong>. Both iOS and Android are opening up interesting possibilities for on-device intelligence and AI-powered features. I’ll be sharing what I learn as I prototype ideas, compare frameworks, and figure out how to bridge AI with real user experiences.</p><p>So, if you’re interested not only in Compose and UI craft, but also in where <strong>AI meets mobile development</strong>, stick around — I’ll have more experiments and lessons to share soon.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7697f80bca20" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying a Generative AI Image Creation Demo Using Google Colab and ngrok: A Step-by-Step Guide in…]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@kylehe970128/deploying-a-generative-ai-image-creation-demo-using-google-colab-and-ngrok-a-step-by-step-guide-in-fb124eaf947c?source=rss-27e59be9bb61------2"><img src="https://cdn-images-1.medium.com/max/960/1*xwjxT1VaBJI-uj0NfPYShA.jpeg" width="960"></a></p><p class="medium-feed-snippet">In the ever-evolving field of artificial intelligence, generative models have gained significant attention for their ability to create&#x2026;</p><p class="medium-feed-link"><a href="https://medium.com/@kylehe970128/deploying-a-generative-ai-image-creation-demo-using-google-colab-and-ngrok-a-step-by-step-guide-in-fb124eaf947c?source=rss-27e59be9bb61------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@kylehe970128/deploying-a-generative-ai-image-creation-demo-using-google-colab-and-ngrok-a-step-by-step-guide-in-fb124eaf947c?source=rss-27e59be9bb61------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb124eaf947c</guid>
            <category><![CDATA[ngrok]]></category>
            <category><![CDATA[hugging-face]]></category>
            <category><![CDATA[colab]]></category>
            <category><![CDATA[generative-art]]></category>
            <category><![CDATA[web]]></category>
            <dc:creator><![CDATA[Ruichen He]]></dc:creator>
            <pubDate>Mon, 22 Jul 2024 03:26:56 GMT</pubDate>
            <atom:updated>2024-07-22T03:26:56.225Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[From Upload to Display: Streamlining Image Workflows with Cloudflare and ReactJS in 2024]]></title>
            <link>https://medium.com/@kylehe970128/from-upload-to-display-streamlining-image-workflows-with-cloudflare-and-reactjs-in-2024-cb49f6a1d046?source=rss-27e59be9bb61------2</link>
            <guid isPermaLink="false">https://medium.com/p/cb49f6a1d046</guid>
            <category><![CDATA[cloudflare-images]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[cloudflare]]></category>
            <category><![CDATA[content-delivery-network]]></category>
            <dc:creator><![CDATA[Ruichen He]]></dc:creator>
            <pubDate>Mon, 15 Apr 2024 20:37:30 GMT</pubDate>
            <atom:updated>2024-04-15T20:37:30.201Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3myUw19kDCAyQJ8ggKj23Q.png" /></figure><p>In the ever-evolving web landscape of 2024, efficient image management stands as a pivotal challenge for developers, demanding seamless integration of front-end dynamism with robust back-end solutions. Leveraging ReactJS, renowned for its component-based architecture and reactive data flow, offers an intuitive framework for building responsive user interfaces that handle images gracefully. When paired with Cloudflare Images, which automates optimization and ensures global delivery with unmatched speed, this combination promises a revolutionary approach to streamlining image workflows from upload to display, setting a new standard for web performance and user experience.</p><p>In this blog, we will dive into the real action together: how to let people pick a picture in our app, send it off to Cloudflare with a bit of behind-the-scenes magic, and then get a link back that anyone can use to see the image. Think of it as teaching your app to take a photo, give it a special address, and then share it with the world. We’ll walk you through each step, from making a spot in the app where you can choose a photo, to talking to Cloudflare to get that special spot for your photo, and finally, sending the photo over. And don’t worry, we’ll make it super clear with easy steps and helpful hints along the way. Let’s get started!</p><h3>Environment Setup</h3><p>Before we start, make sure you have the following installed:</p><ul><li><a href="https://docs.npmjs.com/downloading-and-installing-node-js-and-npm">Node.js</a></li><li>npm</li></ul><p>If you haven’t installed these yet, please install them. You may follow the link <a href="https://docs.npmjs.com/downloading-and-installing-node-js-and-npm">here</a>.</p><p>In addition, you need to get <strong>Azure Functions Core Tools</strong> installed. You can find the guide <a href="https://learn.microsoft.com/en-us/azure/azure-functions/functions-run-local?tabs=macos%2Cisolated-process%2Cnode-v4%2Cpython-v2%2Chttp-trigger%2Ccontainer-apps&amp;pivots=programming-language-javascript">here</a>.</p><p>Last thing you need to do is to setup your CloudFlare account. Create an account if you haven’t done so. If you already have the account, follow the <a href="https://developers.cloudflare.com/fundamentals/api/get-started/create-token/">link</a> to create a API token.</p><p>Now, you can use the command to create a new ReactJS application:</p><pre>npx create-react-app my-app</pre><p>Inside the my-app, we use the following command to create another application that for our backend API calling, and install necessary packages.</p><pre>cd my-app<br>func init api --worker-runtime javascript --model V4<br>npm install axios</pre><h3>Endpoint to Obtain CloudFlare Upload URL</h3><p>As mentioned in the <a href="https://developers.cloudflare.com/images/upload-images/direct-creator-upload/">document</a>, we can use the Direct Creator Upload feature in Cloudflare Images to obtain a one-time upload URL without exposing our API key or token to the client.</p><p>To do so, we first need to add our API token and your account ID inside the /api/local.settings.json file.</p><pre>{<br>  &quot;Values&quot;: {<br>      &quot;CLOUDFLARE_API_TOKEN&quot;: &quot;YOUR_API_TOKEN&quot;,<br>      &quot;CLOUDFLARE_ACCOUNT_ID&quot;: &quot;YOUR_ACCOUNT_ID&quot;,<br>      &quot;FUNCTIONS_WORKER_RUNTIME&quot;: &quot;node&quot;<br>  },<br>  &quot;IsEncrypted&quot;: false<br>}</pre><p>Then, to call the Cloudflare API, we need to use POST method to obtain it from Cloudflare endpoint:</p><pre>const url = `https://api.cloudflare.com/client/v4/accounts/${process.env.CLOUDFLARE_ACCOUNT_ID}/images/v2/direct_upload`;<br>const formData = new FormData();<br>formData.append(&#39;metadata&#39;, JSON.stringify({ key: &#39;value&#39; }));<br>formData.append(&#39;requireSignedURLs&#39;, &#39;false&#39;);<br>const response = await axios.post(url, formData, {<br>    headers: {<br>        ...formData.getHeaders(),<br>        &#39;Authorization&#39;: `Bearer ${process.env.CLOUDFLARE_API_TOKEN}`,<br>    },<br>});</pre><p>Once we get the response, we can extract the uploadURL from it</p><pre>const uploadURL = await response.data.result.uploadURL;</pre><p>Combing all the components together, we can form the following api, which will later be called from our frontend:</p><pre><br>const { app } = require(&#39;@azure/functions&#39;);<br>const axios = require(&#39;axios&#39;);<br>const FormData = require(&#39;form-data&#39;);<br>app.http(&#39;obtainCloudFlareUploadURL&#39;, {<br>  methods: [&#39;POST&#39;],<br>  authLevel: &#39;anonymous&#39;,<br>  route: &#39;getuploadurl&#39;,<br>  handler: async (request, context) =&gt; {<br>    const url = `https://api.cloudflare.com/client/v4/accounts/${process.env.CLOUDFLARE_ACCOUNT_ID}/images/v2/direct_upload`;<br>    const formData = new FormData();<br>    formData.append(&#39;metadata&#39;, JSON.stringify({ key: &#39;value&#39; }));<br>    formData.append(&#39;requireSignedURLs&#39;, &#39;false&#39;);<br><br>    try {<br>      const response = await axios.post(url, formData, {<br>      headers: {<br>          ...formData.getHeaders(),<br>          &#39;Authorization&#39;: `Bearer ${process.env.CLOUDFLARE_API_TOKEN}`, <br>      },<br>      });<br><br>      if (response.statusText !== &quot;OK&quot;) {<br>        console.log(response);<br>        throw new Error(`HTTP error! Status: ${response.status}`);<br>      }<br>      console.log(response.data);<br>      const uploadURL = await response.data.result.uploadURL; <br>      console.log(&#39;Upload successful:&#39;, uploadURL);<br>      return {<br>        jsonBody: {uploadURL: uploadURL}<br>      };<br>    } catch (error) {<br>      console.error(&#39;Upload failed:&#39;, error);<br>      return {<br>        success: false,<br>        message: `An error occurred during the image upload: ${error.message}`<br>      };<br>    }<br>  },<br>});</pre><h3>Interface Design</h3><p>Now, we need to set up our interface. It should include the following components:</p><pre>&lt;div&gt;<br>    &lt;form<br>        onSubmit={handleSubmit}<br>        encType=&quot;multipart/form-data&quot;<br>    &gt;<br>    &lt;input type=&quot;file&quot; id=&quot;myFile&quot; name=&quot;file&quot; onChange={handleChange} /&gt;<br>    &lt;input type=&quot;text&quot; id=&quot;textInput&quot; name=&quot;textInput&quot; placeholder=&quot;Enter text here&quot; /&gt;<br>    &lt;input type=&quot;submit&quot; /&gt;<br>    &lt;/form&gt;<br>    {imagePreview &amp;&amp; &lt;img src={imagePreview} alt=&quot;Preview&quot; style={{ maxWidth: &#39;200px&#39;, maxHeight: &#39;200px&#39; }} /&gt;}<br>    {imageURL &amp;&amp; &lt;a href={imageURL} target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot;&gt;Image url&lt;/a&gt;}<br>&lt;/div&gt;</pre><p>It creates a form for uploading files and submitting text, equipped with event handlers for processing changes (handleChange) and form submissions (handleSubmit). It also features an optional image preview components to display the user uploaded image. Additionally, once the image is successfully uploaded to Cloudflare, a link will be displayed next to the previewed image which user can use to navigate to the uploaded image’s public url.</p><p>We also need to create to function, i.e., the handleChange for updating the preview image, and the handleSubmit for obtaining one-time uploadURL from our backend API and upload the image.</p><p>First, let’s craft the handleChange function:</p><pre>const handleChange = (event) =&gt; {<br>    if (event.target.files &amp;&amp; event.target.files[0]) {<br>        const file = event.target.files[0];<br>  <br>        // Use FileReader to read the file and display it<br>        const reader = new FileReader();<br>        reader.onload = (e) =&gt; {<br>          // Set the loaded file&#39;s data URL as the imagePreview state<br>          setImagePreview(e.target.result);<br>        };<br>        reader.readAsDataURL(file);<br>        setImageURL(null);<br>    }<br>};</pre><p>Then, we need to work on the handleSubmit function:</p><pre>const handleSubmit = async (event) =&gt; {<br>      event.preventDefault(); // Prevent the default form submission behavior<br>      await setCloudFlareUploadURL(); // Make sure storeImage has already set the new upload URL in state<br>      if (!uploadUrl) {<br>        console.log(&#39;No upload URL&#39;);<br>        return; // Exit if there&#39;s no upload URL<br>      }<br><br>      const formData = new FormData();<br>      if (event.target.file.files.length &gt; 0) {<br>        const file = event.target.file.files[0];<br>        formData.append(&#39;file&#39;, file);<br>      } else {<br>        console.log(&#39;No file selected&#39;);<br>        return; // Exit the function if no file is selected<br>      }<br>      console.log(&#39;Preparing to upload file...&#39;);<br>      try {<br>        const response = await fetch(uploadUrl, {<br>          method: &#39;POST&#39;,<br>          body: formData, // Send the form data as the request body<br>        });<br>  <br>        if (!response.ok) {<br>          throw new Error(`HTTP error! Status: ${response.status}`);<br>        }<br>  <br>        const data = await response.json();<br>        console.log(&#39;Upload successful, image public url:&#39;, data.result.variants[0]);<br>        setImageURL(data.result.variants[0]);<br>  <br>      } catch (error) {<br>        console.error(&#39;Upload failed:&#39;, error);<br>      }<br>    };</pre><p>In order to make it work, we need to form the additional setCloudFlareUploadURL function, to obtain the URL and set it up:</p><pre>const setCloudFlareUploadURL = async () =&gt; {<br>    const result = await fetch(&quot;/api/getuploadurl&quot;, {<br>        method: &quot;POST&quot;,<br>        headers: {<br>            &quot;Content-Type&quot;: &quot;application/json&quot;,<br>        },<br>      })<br>    const response = await result.json(); // Parse the JSON response body<br>    if (response.uploadURL) {<br>        setUploadUrl(response.uploadURL);<br>    }<br>}</pre><p>Combining all components together, and importing necessary packages, we will form our App.js file:</p><pre>import React, { useState, useEffect } from &quot;react&quot;;<br>function App() {<br>    const [uploadUrl, setUploadUrl] = useState(&#39;&#39;);<br>    const [imagePreview, setImagePreview] = useState(null);<br>    const [imageURL, setImageURL] = useState(null);<br>    const handleChange = (event) =&gt; {<br>      if (event.target.files &amp;&amp; event.target.files[0]) {<br>        const file = event.target.files[0];<br>  <br>        // Use FileReader to read the file and display it<br>        const reader = new FileReader();<br>        reader.onload = (e) =&gt; {<br>          // Set the loaded file&#39;s data URL as the imagePreview state<br>          setImagePreview(e.target.result);<br>        };<br>        reader.readAsDataURL(file);<br>        setImageURL(null);<br>      }<br>    };<br>    const setCloudFlareUploadURL = async () =&gt; {<br>      const result = await fetch(&quot;/api/getuploadurl&quot;, {<br>        method: &quot;POST&quot;,<br>        headers: {<br>            &quot;Content-Type&quot;: &quot;application/json&quot;,<br>        },<br>      })<br>      const response = await result.json(); // Parse the JSON response body<br>      if (response.uploadURL) {<br>        setUploadUrl(response.uploadURL);<br>      }<br>    }<br><br>    useEffect(() =&gt; {<br>      setCloudFlareUploadURL();<br>    }, []); // The empty array ensures this effect runs only once<br><br>    const handleSubmit = async (event) =&gt; {<br>      event.preventDefault(); // Prevent the default form submission behavior<br>      await setCloudFlareUploadURL(); // Make sure storeImage has already set the new upload URL in state<br>      if (!uploadUrl) {<br>        console.log(&#39;No upload URL&#39;);<br>        return; // Exit if there&#39;s no upload URL<br>      }<br><br>      const formData = new FormData();<br>      if (event.target.file.files.length &gt; 0) {<br>        const file = event.target.file.files[0];<br>        formData.append(&#39;file&#39;, file);<br>      } else {<br>        console.log(&#39;No file selected&#39;);<br>        return; // Exit the function if no file is selected<br>      }<br>      console.log(&#39;Preparing to upload file...&#39;);<br>      try {<br>        const response = await fetch(uploadUrl, {<br>          method: &#39;POST&#39;,<br>          body: formData, // Send the form data as the request body<br>        });<br>  <br>        if (!response.ok) {<br>          throw new Error(`HTTP error! Status: ${response.status}`);<br>        }<br>  <br>        const data = await response.json();<br>        setImageURL(data.result.variants[0]);<br>        console.log(&#39;Upload successful, image public url:&#39;, data.result.variants[0]);<br><br>  <br>      } catch (error) {<br>        console.error(&#39;Upload failed:&#39;, error);<br>      }<br>    };<br><br>    return (<br>      &lt;div&gt;<br>        &lt;form<br>          onSubmit={handleSubmit}<br>          encType=&quot;multipart/form-data&quot;<br>        &gt;<br>          &lt;input type=&quot;file&quot; id=&quot;myFile&quot; name=&quot;file&quot; onChange={handleChange} /&gt;<br>          &lt;input type=&quot;text&quot; id=&quot;textInput&quot; name=&quot;textInput&quot; placeholder=&quot;Enter text here&quot; /&gt;<br>          &lt;input type=&quot;submit&quot; /&gt;<br>        &lt;/form&gt;<br>        {imagePreview &amp;&amp; &lt;img src={imagePreview} alt=&quot;Preview&quot; style={{ maxWidth: &#39;200px&#39;, maxHeight: &#39;200px&#39; }} /&gt;}<br>        {imageURL &amp;&amp; &lt;a href={imageURL} target=&quot;_blank&quot; rel=&quot;noopener noreferrer&quot;&gt;Image url&lt;/a&gt;}<br>      &lt;/div&gt;<br>      <br>    <br>    );<br>}<br> <br>export default App;</pre><p>The GitHub repo for the whole demo can be found <a href="https://github.com/RuichenHe/react-cloudflare-image-demo">here</a>.</p><h3>Next Steps</h3><p>We’ve just walked through the process of setting up an image pipeline, including selecting an image, displaying it on your website, and uploading it to Cloudflare. This guide should provide you with a foundational understanding to efficiently manage images in your web projects.</p><p>Looking for More Resources? If you’re eager to dive deeper and expand your capabilities, consider exploring additional resources:</p><ul><li><a href="https://developers.cloudflare.com/images/upload-images/">Cloudflare image document</a></li><li><a href="https://developers.cloudflare.com/images/pricing/">Cloudflare image pricing model</a></li><li><a href="https://developers.cloudflare.com/api/operations/cloudflare-images-list-images">Cloudflare API document</a></li></ul><p>Thanks for reading, hope you enjoy it!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cb49f6a1d046" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Use OpenAI API in React JS: Enhancing Your Applications with AI in 2024]]></title>
            <link>https://medium.com/@kylehe970128/how-to-use-openai-api-in-react-js-enhancing-your-applications-with-ai-in-2024-02e248fdc889?source=rss-27e59be9bb61------2</link>
            <guid isPermaLink="false">https://medium.com/p/02e248fdc889</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <dc:creator><![CDATA[Ruichen He]]></dc:creator>
            <pubDate>Sun, 07 Apr 2024 04:35:50 GMT</pubDate>
            <atom:updated>2024-04-10T05:40:57.501Z</atom:updated>
            <content:encoded><![CDATA[<p>Recent advancements in AI, like OpenAI’s GPT and DALL-E, have significantly changed the game, enabling new levels of text generation and image creation. These tools offer unprecedented capabilities right at our fingertips. React JS, with its wide adoption and flexibility, makes an excellent partner for these AI technologies, allowing for seamless integration and creation of dynamic, intelligent web applications.</p><p>In this blog, we’ll dive straight into how to blend the power of OpenAI’s APIs with React to build an application that showcases real-time conversational AI and dynamic image generation. We’ll walk you through the entire process, from setting up your development environment to making API calls and rendering the results. Let’s get started on enhancing your React applications with cutting-edge AI functionalities.</p><h3>Environment Setup</h3><p>Before we start, make sure you have the following installed:</p><ul><li><a href="https://docs.npmjs.com/downloading-and-installing-node-js-and-npm">Node.js</a></li><li>npm</li></ul><p>If you haven’t installed these yet, please install them. You may follow the link <a href="https://docs.npmjs.com/downloading-and-installing-node-js-and-npm">here</a>.</p><p>In addition, you need to get <strong>Azure Functions Core Tools</strong> installed. You can find the guide <a href="https://learn.microsoft.com/en-us/azure/azure-functions/functions-run-local?tabs=macos%2Cisolated-process%2Cnode-v4%2Cpython-v2%2Chttp-trigger%2Ccontainer-apps&amp;pivots=programming-language-javascript">here</a>.</p><p>Last thing you need to do before we dive in to the code, is to get a OpenAI API key for you application. You can follow the link <a href="https://platform.openai.com/docs/quickstart?context=python">here</a>.</p><p>Now, you can use the command to create a new ReactJS application:</p><pre>npx create-react-app my-app</pre><p>Inside the my-app, we use the following command to create another application that for our backend API calling.</p><pre>cd my-app<br>func init api --worker-runtime javascript --model V4</pre><p>Then, inside the api folder, we will install the OpenAI SDK by running the following command:</p><pre>cd api<br>npm install openai</pre><p>Now let’s start building the demo together and learn how to use OpenAI API inside our ReactJS application.</p><p>Below is the structure of our demo application. Our interface design will be stored in <strong>/src/App.js</strong>. And we will create a API endpoint in <strong>/api/index.js</strong> so that we can call it in our interface.</p><pre>.<br>├── api<br>│   ├── host.json<br>│   ├── index.js<br>│   ├── local.settings.json<br>│   ├── package-lock.json<br>│   └── package.json<br>├── package-lock.json<br>├── package.json<br>└── src<br>    ├── App.css<br>    ├── App.js<br>    ├── index.css<br>    ├── index.js<br>    ├── reportWebVitals.js<br>    └── style.css</pre><h3>Endpoint to Call OpenAI API</h3><p>First, we will work on our endpoint for calling OpenAI API. Inside the /api folder, we will add our OPENAI_API_KEY inside the local.settings.json file.</p><pre>{<br>  &quot;Values&quot;: {<br>      &quot;OPENAI_API_KEY&quot;: &quot;ENTER_YOUR_KEY_HERE&quot;,<br>      &quot;FUNCTIONS_WORKER_RUNTIME&quot;: &quot;node&quot;<br>  },<br>  &quot;IsEncrypted&quot;: false<br>}</pre><p>Once we add the API key, we then need to create an endpoint which will take user-input description in the request, pass it to OpenAI API, then send the respond from OpenAI side back to our frontend interface. In this demo, we will use the user input as a prompt for (1) text generation, and (2) image generation.</p><p>First, we need to include the OpenAI from the openai package, and initialize it.</p><pre>const { OpenAI } = require(&quot;openai&quot;);<br></pre><pre>const openai = new OpenAI({<br>    apiKey: process.env.OPENAI_API_KEY<br>});</pre><p>To get the text output using the user input text, we can utilize <a href="https://platform.openai.com/docs/guides/text-generation/chat-completions-api">OpenAI’s chat API</a>:</p><pre>const responseGenerate = async (inputText) =&gt; {<br>    const completion = await openai.chat.completions.create({<br>      model: &quot;gpt-4-0125-preview&quot;,<br>      messages: [<br>        {&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: &quot;You are a assistant helping user analyze their dreams. User will give you the desciprtion of the dream, you help me them analyze them. Respond should be in paragraph format, avoid using any markdown symbol&quot;},<br>        {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: `Write an analysis based on the description of my dream: &quot;${inputText}&quot;`}<br>      ]<br>    });</pre><p>As mentioned in OpenAI API’s website, the main input of the chat completion API is the messages parameter. Messages must be an array of message objects, where each object has a role (either “system”, “user”, or “assistant”) and content. Conversations can be as short as one message or many back and forth turns. In this demo, we want to analyze user input dream description, so we use the following as part of our message:</p><pre>&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: &quot;You are a assistant helping user analyze their dreams. User will give you the desciprtion of the dream, you help me them analyze them. Respond should be in paragraph format, avoid using any markdown symbol&quot;</pre><p>And to send the user input, we just add it as part of the message as well:</p><pre>&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: `Write an analysis based on the description of my dream: &quot;${inputText}&quot;`</pre><p>To get the image output using the user input text as the prompts, we can utilize <a href="https://platform.openai.com/docs/guides/images/introduction?context=node">OpenAI’s image API</a>:</p><pre>const response =  await openai.images.generate({<br>      model: &quot;dall-e-3&quot;,<br>      prompt: `Generate a beautiful, fantastical image visualizing the dream: &quot;${inputText}&quot;`,<br>      size: &quot;1024x1024&quot;,<br>      quality: &quot;standard&quot;,<br>      n: 1,<br>    });</pre><p>To add the user input as part of the prompt, we can simply use the following line as the prompt:</p><pre>prompt: `Generate a beautiful, fantastical image visualizing the dream: &quot;${inputText}&quot;`</pre><p>Warping all the components together inside a handler, we will get this full code for our endpoint.</p><pre><br>const { app } = require(&#39;@azure/functions&#39;);<br>const { OpenAI } = require(&quot;openai&quot;);<br><br>app.http(&#39;getAIResponse&#39;, {<br>    methods: [&#39;POST&#39;],<br>    authLevel: &#39;anonymous&#39;,<br>    route: &#39;ai&#39;,<br>    handler: async (request, context) =&gt; {<br>        const openai = new OpenAI({<br>            apiKey: process.env.OPENAI_API_KEY<br>        });<br><br>        const body = await request.json();<br>        inputText = body.inputText;<br><br>        const completion = await openai.chat.completions.create({<br>            model: &quot;gpt-4-0125-preview&quot;,<br>            messages: [<br>              {&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: &quot;You are a assistant helping user analyze their dreams. User will give you the desciprtion of the dream, you help me them analyze them. Respond should be in paragraph format, avoid using any markdown symbol&quot;},<br>              {&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: `Write an analysis based on the description of my dream: &quot;${inputText}&quot;`}<br>            ]<br>          });<br><br>        const response =  await openai.images.generate({<br>            model: &quot;dall-e-3&quot;,<br>            prompt: `Generate a beautiful, fantastical image visualizing the dream: &quot;${inputText}&quot;`,<br>            size: &quot;1024x1024&quot;,<br>            quality: &quot;standard&quot;,<br>            n: 1,<br>        });<br><br>        return {<br>            jsonBody: {imageURL: response.data[0].url, analysis: completion.choices[0].message.content}<br>        }<br>    },<br>});<br><br></pre><h3>Interface Design</h3><p>Now, we need to set up our interface. It should include the following components:</p><pre>&lt;div className=&quot;App&quot;&gt;<br>    &lt;header className=&quot;App-header&quot;&gt;<br>        &lt;h2&gt;<br>            Dreamweaver<br>        &lt;/h2&gt;<br>    &lt;/header&gt;<br>    &lt;div className=&#39;App-container&#39;&gt;<br>        &lt;textarea <br>            value={description}<br>            placeholder=&quot;Tell me your dream&quot; <br>            onChange={e =&gt; setDescription(e.target.value)}<br>            className=&quot;dream-description&quot;<br>        &gt;&lt;/textarea&gt;<br>        &lt;button onClick={submitDescription} className=&#39;submit-button&#39;&gt;{submitStatus}&lt;/button&gt;<br>        &lt;span className=&quot;dream-analysis&quot;&gt;<br>            {dreamAnalysis}<br>        &lt;/span&gt;<br>        {imageUrl &amp;&amp; &lt;img src={imageUrl} alt=&quot;Loaded&quot;  style={{ maxWidth: &#39;300px&#39;}}/&gt;}<br>    &lt;/div&gt;<br>&lt;/div&gt;</pre><ul><li>Text Area for User Input: A text area will be the primary interface for users to enter their dream descriptions.</li><li>Submit Button: Below the text area, a submit button will initiate the process of sending the user’s dream description to the OpenAI API.</li><li>Response Text Box: Below the text area and submit button, a dedicated text box will display the dream analysis provided by the OpenAI Chat API.</li><li>Visualization Image: Alongside the textual analysis, an image section will present a visual representation of the dream, generated by the OpenAI Image API based on the description provided.</li></ul><p>In addition, we need to create a function to handle the endpoint calling using user input text:</p><pre>const responseGenerate = async (inputText) =&gt; {<br>    const prompt = {<br>      inputText: inputText<br>    }<br><br>    const result = await fetch(&quot;/api/ai&quot;, {<br>      method: &quot;POST&quot;,<br>      headers: {<br>          &quot;Content-Type&quot;: &quot;application/json&quot;,<br>      },<br>      body: JSON.stringify(prompt)<br>    })<br><br>    if (result.ok) {<br>      const airespond = await result.json(); // Parse the JSON response body<br>      setDreamAnalysis(airespond.analysis);<br>      setImageUrl(airespond.imageURL);<br>      setSubmitStatus(&quot;Submit&quot;);<br>    } else {<br>      setSubmitStatus(&quot;Retry&quot;);<br>    }<br>  };</pre><p>Combine all these components together, we will have our App.js ready. Below is the full code:</p><pre>import &#39;./App.css&#39;;<br>import &#39;./style.css&#39;;<br>import { useState } from &#39;react&#39;;<br><br>function App() {<br>  const [description, setDescription] = useState(&quot;&quot;);<br>  const [submitStatus, setSubmitStatus] = useState(&quot;Submit&quot;);<br>  const [dreamAnalysis, setDreamAnalysis] = useState(&quot;&quot;);<br>  const [imageUrl, setImageUrl] = useState(&quot;&quot;)<br><br>  const responseGenerate = async (inputText) =&gt; {<br>    const prompt = {<br>      inputText: inputText<br>    }<br><br>    const result = await fetch(&quot;/api/ai&quot;, {<br>      method: &quot;POST&quot;,<br>      headers: {<br>          &quot;Content-Type&quot;: &quot;application/json&quot;,<br>      },<br>      body: JSON.stringify(prompt)<br>    })<br><br>    if (result.ok) {<br>      const airespond = await result.json(); // Parse the JSON response body<br>      setDreamAnalysis(airespond.analysis);<br>      setImageUrl(airespond.imageURL);<br>      setSubmitStatus(&quot;Submit&quot;);<br>    } else {<br>      setSubmitStatus(&quot;Retry&quot;);<br>    }<br>  };<br><br>  <br><br>  async function submitDescription() {<br>    setSubmitStatus(&quot;Waiting&quot;);<br>    responseGenerate(description);<br>  }<br>  return (<br>    &lt;div className=&quot;App&quot;&gt;<br>      &lt;header className=&quot;App-header&quot;&gt;<br>        &lt;h2&gt;<br>          Dreamweaver<br>        &lt;/h2&gt;<br>      &lt;/header&gt;<br>      &lt;div className=&#39;App-container&#39;&gt;<br>        &lt;textarea <br>            value={description}<br>            placeholder=&quot;Tell me your dream&quot; <br>            onChange={e =&gt; setDescription(e.target.value)}<br>            className=&quot;dream-description&quot;<br>        &gt;&lt;/textarea&gt;<br>        &lt;button onClick={submitDescription} className=&#39;submit-button&#39;&gt;{submitStatus}&lt;/button&gt;<br>        &lt;span className=&quot;dream-analysis&quot;&gt;<br>          {dreamAnalysis}<br>        &lt;/span&gt;<br>        {imageUrl &amp;&amp; &lt;img src={imageUrl} alt=&quot;Loaded&quot;  style={{ maxWidth: &#39;300px&#39;}}/&gt;}<br>      &lt;/div&gt;<br>      <br>    &lt;/div&gt;<br>  );<br>}<br><br>export default App;</pre><p>The GitHub repo can be found <a href="https://github.com/RuichenHe/react-openai-api-demo">here</a>.</p><h3>Presenting the Demo</h3><p>After adding additional style to the app, here comes the demo:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vCFARNJc5UCkDYMUPJsMqQ.png" /></figure><p>You can also find a deployed version <a href="https://wonderful-pebble-056e9ea10.5.azurestaticapps.net/">here</a>.</p><h3>Next Steps</h3><p>And there you have it — a step-by-step guide to integrating the transformative powers of OpenAI’s GPT and DALL-E models into your React applications. By now, you should have a functional demo that not only demonstrates the integration process but also showcases the potential of AI in enhancing web applications with intelligent and creative capabilities.</p><p>Hungry for more? Expand your knowledge and skills with these resources:</p><ul><li><a href="https://platform.openai.com/docs/overview">OpenAI API Documentation</a> to explore other AI capabilities provided by OpenAI API.</li><li><a href="https://platform.openai.com/docs/guides/images?context=node">OpenAI Image Generation</a> to explore more features about image API.</li><li><a href="https://platform.openai.com/docs/guides/text-generation">OpenAI Text Completion</a> to explore more features about chat API.</li></ul><p>Thanks for reading, hope you enjoy it!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=02e248fdc889" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>