<?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 Luai Abuelsamen on Medium]]></title>
        <description><![CDATA[Stories by Luai Abuelsamen on Medium]]></description>
        <link>https://medium.com/@luai_abuelsamen?source=rss-dc48e504a710------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*tDjkAdIeuXf4UNiCnTz2OQ.jpeg</url>
            <title>Stories by Luai Abuelsamen on Medium</title>
            <link>https://medium.com/@luai_abuelsamen?source=rss-dc48e504a710------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 08:02:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@luai_abuelsamen/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[How Useful is AI Research in Robotics for the Real World?]]></title>
            <link>https://medium.com/@luai_abuelsamen/robotics-is-still-waiting-for-its-chatgpt-moment-2ef40b464eec?source=rss-dc48e504a710------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ef40b464eec</guid>
            <category><![CDATA[robotics]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[embodied-ai]]></category>
            <dc:creator><![CDATA[Luai Abuelsamen]]></dc:creator>
            <pubDate>Sat, 10 May 2025 08:44:18 GMT</pubDate>
            <atom:updated>2025-10-01T02:21:41.734Z</atom:updated>
            <content:encoded><![CDATA[<p>While AI has transformed fields like language processing and image recognition, industrial robotics remains bound by decades-old control systems and rigid logic, making true autonomy elusive. However, recent advancements in reinforcement learning and large language models signal that change is coming, though perhaps not as quickly as the hype suggests.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*qYWIHQdQB3kev8H3j6ihzA.gif" /></figure><h3>The Promise and Reality of Embodied AI</h3><p>Over the past year, there has been a surge of attention on physical and embodied AI, bringing renewed excitement about how AI could revolutionize robotics. While traditional AI focused on static tasks like image recognition and text generation, embodied AI, which enables AI systems to interact with the physical world, has seen rapid progress in research labs but limited deployment in real-world applications. The impressive demos of robots folding towels or manipulating objects often mask the reality that these systems frequently fail when confronted with novel situations or slight variations in their environment.</p><p>Reinforcement learning has played a crucial role in this shift, with its roots dating back to the 1970s with Richard Sutton’s seminal work, gaining prominence in the 1980s. The field experienced a renaissance in the 2010s with deep reinforcement learning, particularly after DeepMind’s 2015 breakthrough in Deep Q-Networks demonstrated that neural networks could learn complex behaviors in virtual environments, though transferring these skills to physical robots proved far more challenging.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*kbDnXHEnPrDFgQU4UxFE1Q.gif" /></figure><h3>Behind the Curtain of Research Demonstrations</h3><p>Researchers at Berkeley, like Sergey Levine, and teams at Google DeepMind expanded this work, applying RL to robotic control in ways that significantly improved robotic dexterity and adaptability, at least in controlled settings. What many papers and press releases don’t emphasize is that these demonstrations often require hundreds of attempts to capture the successful version shown in publications. The gap between these carefully curated demonstrations and reliable, deployable systems remains substantial.</p><p>By 2023–2024, large language models (LLMs) entered robotics, with projects like RT-1 and RT-2 from Google DeepMind showing how foundation models could enable robots to understand and execute tasks from natural language commands. While this provides a promising framework for behavior specification, these systems still require extensive task-specific training data. The language model primarily helps with understanding human instructions, not with solving the fundamental challenges of physical control and adaptation.</p><h3>Industrial Robotics: Automatic, Not Autonomous</h3><p>Robotics isn’t new. Industrial robots have been used in automation and manufacturing for decades. The first industrial robot, Unimate, was introduced in 1961 by George Devol and deployed in a General Motors assembly line. Since then, robots have played a critical role in handling complex and hazardous tasks with precision and efficiency.</p><p>However, it’s important to recognize that these systems — from Unimate to today’s most advanced factory robots — operate using pre-programmed motions in highly structured environments. They’re “automatic” but not truly “autonomous.” They execute the same movements repeatedly and cannot adapt to significant changes in their environment without human reprogramming.</p><p>The rise of computer-controlled robotics in the 1980s and 1990s saw companies like FANUC, ABB, and KUKA dominate factory automation with robotic arms. By the 2000s, collaborative robots (cobots) like those from Universal Robots further expanded automation capabilities, but even these systems rely on carefully defined parameters and lack true adaptability.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*sD8NYulqb-fiOwjo3ssuwQ.gif" /></figure><h3>The PLC Problem</h3><p>The robotics industry, at least in its most widely deployed form, prioritizes safety through redundant systems, fallback mechanisms, and, unfortunately, the frustrating world of programmable logic controllers (PLCs), which have been a mainstay of industrial automation since the 1960s.</p><p>PLCs use ladder logic, a visual programming language that resembles electrical circuit diagrams from the 1960s. Despite modern integrated development environments (IDEs), this approach fundamentally limits complexity and integration with AI systems. While software developers in other fields work with powerful object-oriented languages, cloud computing, and modern frameworks, industrial robotics programmers are often stuck with tools that feel like “programming on a potato.”</p><p>The disconnect between modern software development practices and industrial automation programming creates a significant barrier to innovation. Factory floors running on decades-old programming paradigms cannot easily integrate with the cutting-edge AI systems being developed in research labs.</p><h3>Hardware Acceleration vs. Fundamental Innovation</h3><p>Jensen Huang, NVIDIA’s CEO, recently stated, “The ChatGPT moment for general robotics is just around the corner.” The renewed AI-driven interest in robotics has sparked positive developments even beyond AI itself. Companies like NVIDIA have introduced platforms like ISAAC, Omniverse, and motion planners like CuRobo, leveraging modern computing power to enhance the capabilities of traditional robotics.</p><p>However, these tools primarily accelerate existing algorithms rather than solving fundamental robotics challenges. Hardware acceleration alone can’t bridge the gap between current capabilities and true general-purpose robotics. The physics of the real world, sensor limitations, and the complexity of unstructured environments pose challenges that no amount of computational power can overcome without corresponding algorithmic and engineering breakthroughs.</p><p>This push toward modernization is long overdue, as classical robotics has lagged behind the rest of the tech industry in embracing these advancements. Our capstone project is centered on this very challenge — integrating NVIDIA’s motion planning tools, which leverage GPUs to enable safer and more efficient motion planning in factory automation.</p><h3>Safety vs. Adaptability</h3><p>Right now, robotics stands at a crossroads. On one side, LLM-powered systems offer powerful reasoning and generalizable behavior, theoretically enabling robots to perform complex, dexterous tasks without additional programming. In practice, these systems still require extensive task-specific data collection and training, and the language model primarily serves as an interface layer, not as the solution to physical control challenges.</p><p>Conversely, AI-driven robotics is inherently unpredictable, making it unsuitable for manufacturing, where safety is paramount. This tension mirrors the ongoing debate in self-driving cars — between hierarchical control approaches like Waymo’s and end-to-end AI models like Tesla’s. As of early 2025, Waymo’s conservative approach has resulted in fewer accidents per mile (approximately one reportable incident per 500,000 miles) compared to Tesla’s more aggressive but less predictable Full Self-Driving system, highlighting the real-world tradeoffs between different control philosophies.</p><p>The economic reality further complicates this picture. While AI promises to lower costs through generalization and reduced programming, custom robotics solutions remain prohibitively expensive for many applications. A typical industrial robot cell can cost hundreds of thousands of dollars, with programming and integration often exceeding the hardware costs.</p><h3>Bridging Control Theory and AI</h3><p>One promising path forward lies in leveraging established control-theoretic methods alongside modern AI-driven approaches. Techniques like Control Barrier Functions (CBFs) provide a mathematically rigorous way to enforce safety constraints by defining energy-based boundaries that prevent robots from entering unsafe states.</p><p>For example, a CBF could establish a virtual “force field” around human workers in a factory, ensuring that a robot arm — regardless of its AI control system — cannot enter spaces where it might cause harm. As the robot’s control system calculates movements, the CBF continuously evaluates whether these actions would violate safety constraints and modifies them if necessary.</p><p>Geometric control methods, which respect the natural manifold structure of a robot’s configuration space, enable more precise motion planning while ensuring stability. Additionally, safety-critical control on manifolds extends these ideas to high-dimensional robotic systems, ensuring that safety constraints remain intact even in complex environments.</p><p>The disconnect between academic robotics research and industrial applications represents another significant challenge. Many breakthroughs never make it to production due to the gap between laboratory conditions and the harsh realities of industrial environments. Bridging this gap requires closer collaboration between researchers and industry practitioners.</p><h3>Beyond the Hype Cycle</h3><p>The robotics industry needs a refresh. It’s time to align its technological foundation with advancements elsewhere in tech. However, this transition can’t come at the cost of safety. The key challenge now is fostering collaboration between control engineers and embodied AI developers to create intelligent systems that incorporate safety guarantees using existing control methods.</p><p>While everyone waits for the “ChatGPT moment” in robotics, we must recognize that the physical world presents challenges fundamentally different from digital domains. Success may not look like a single breakthrough but rather incremental advances across multiple fronts — better sensors, improved control algorithms, more sophisticated simulation environments, and gradual integration of AI techniques into existing systems.</p><p>The goal is to develop a system like a human brain that can learn and generalize behaviors while maintaining reasonable boundaries on unpredictability. As we navigate this shift, it’s critical to find ways to accelerate progress using the tools we already have, while maintaining realistic expectations about the unique challenges posed by the physical world.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ef40b464eec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Robots Work Together: Understanding Consensus]]></title>
            <link>https://medium.com/@luai_abuelsamen/how-robots-work-together-understanding-consensus-4886cdfb3c3a?source=rss-dc48e504a710------2</link>
            <guid isPermaLink="false">https://medium.com/p/4886cdfb3c3a</guid>
            <category><![CDATA[robotics]]></category>
            <category><![CDATA[swarm-intelligence]]></category>
            <category><![CDATA[multi-robot]]></category>
            <category><![CDATA[multi-agent-systems]]></category>
            <dc:creator><![CDATA[Luai Abuelsamen]]></dc:creator>
            <pubDate>Fri, 04 Oct 2024 05:39:05 GMT</pubDate>
            <atom:updated>2024-10-04T05:39:05.387Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R8uxwosycIoJSBHAKh3fNw.png" /></figure><h3>Introduction</h3><p>In today’s world, multi-agent systems are becoming increasingly vital, from autonomous drone swarms to decentralized decision-making in robotics. As these systems grow in complexity, one of the most critical challenges is achieving <strong>consensus</strong> — where all agents, despite their distributed nature and varying environments, can come to a shared agreement on specific states or decisions.</p><p>Whether you’re dealing with drones that need to coordinate without colliding, or robots that must decide on a common strategy in a dynamic environment, <strong>consensus algorithms</strong> form the backbone of these systems. These algorithms enable agents to agree on shared objectives, synchronize states like heading or speed, and navigate complex network conditions such as switching topologies or communication delays.</p><p>In this article, we’ll dive into the <strong>mechanics of consensus algorithms</strong>, specifically focusing on how they work in networks where communication conditions vary, topologies switch, and time delays affect agent interactions. I’ll walk you through the core concepts of consensus, provide practical examples, and show how these algorithms can be simulated and applied to real-world multi-agent systems.</p><h3>What is Consensus?</h3><p>At the heart of any multi-agent system, like a fleet of drones or a group of autonomous robots, is the need for <strong>coordination</strong>. But coordination is more than just moving in the same direction — agents need to continuously exchange information to reach a shared understanding or objective. This process is what we call <strong>consensus</strong>.</p><p>In simple terms, <strong>consensus</strong> refers to the process where each agent in a network agrees on a specific value or state. This could be something like agreeing on:</p><ul><li>A common velocity or heading for a group of drones.</li><li>A shared decision in task allocation (e.g., which area to survey).</li><li>Synchronizing movement in a specific formation without collisions.</li></ul><p>The challenge? <strong>Communication constraints</strong>, <strong>time delays</strong>, and <strong>dynamic network topologies</strong> — factors that can make reaching consensus more complex.</p><h4>Key Problems in Consensus:</h4><p>When implementing consensus algorithms, several practical issues arise, particularly in real-world systems:</p><ol><li><strong>Switching Topology</strong>: The structure of the network may change over time. For example, drones might move in and out of range with one another, causing the network connections to shift.</li><li><strong>Time-Delays</strong>: Communication between agents isn’t always instantaneous. Latency in receiving updates from neighboring agents can affect how quickly (and whether) consensus is reached.</li><li><strong>Directed Networks</strong>: In some networks, communication isn’t always bidirectional. A drone might send updates to a neighbor without receiving information in return.</li></ol><h4>How Consensus Algorithms Handle These Challenges</h4><p>Consensus algorithms are designed to tackle these problems head-on. Let’s break down the most important scenarios:</p><h3>1. Consensus in Balanced Directed Networks</h3><p>In a balanced directed network, each agent has an equal number of incoming and outgoing connections — meaning every agent gets as much information as it gives. This symmetry allows for simpler consensus algorithms because the information flow is consistent across the network.</p><p>In this case, the <strong>Laplacian matrix</strong> plays a crucial role. The Laplacian represents the network’s structure, where the rows and columns indicate the connections between agents. Consensus can be achieved if the Laplacian matrix’s second smallest eigenvalue (known as the <strong>algebraic connectivity</strong>) is positive, meaning the network is connected.</p><p>Let’s simulate a basic example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZnYtGC2M3d_UFxl6gQlRqw.png" /></figure><p>In this example, the agents start with random initial states, and through consensus, they eventually converge to a common value. The balanced nature of the network ensures a smooth and fast convergence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vpFisEFKQV_SMhoqzzE2Fg.png" /></figure><p>Notice how they converge to the average of initial values as expected by our consensus protocol</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uDynl1ur2zw2f25-iOIgHQ.png" /></figure><h3>2. Consensus with Time-Delays</h3><p>In many real-world systems, communication isn’t perfect — there’s often a delay between when an agent sends a message and when another receives it. This is particularly true for systems with large distances between agents, such as drones in a wide-area survey or satellites in space.</p><p>When there are <strong>time-delays</strong>, consensus becomes more challenging. Each agent is working with slightly outdated information from its neighbors, which can slow down convergence or, in extreme cases, cause the system to become unstable.</p><p>Here’s how we can simulate a consensus protocol with time-delays, using the same graph as the previous example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BqZS1BzBD7FS98YeQXwt-A.png" /><figcaption>Time delay of 0.3</figcaption></figure><p>In this case, agents still converge to a common state, but the process is slower due to the delay in communication. The time-delay introduces a “lag,” making the system less responsive.</p><p>However, as we increase the time delay we will start seeing some explosions!</p><p>In many real-world systems, communication isn’t perfect — there’s often a delay between when an agent sends a message and when another receives it. Time-delays can make consensus more challenging, as each agent is working with slightly outdated information from its neighbors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BBQiqNC-7K_UMHQhb0iYcg.png" /><figcaption>Time delay of 0.5</figcaption></figure><h3>3. Consensus with Switching Topology</h3><p>In mobile networks — like fleets of drones or autonomous vehicles — the network’s <strong>topology</strong> may not stay fixed. As agents move around, they can lose or gain communication links. This creates a dynamic environment where the network’s structure is constantly changing, and the consensus algorithm must adapt to this shifting topology.</p><p>To handle this, consensus algorithms can switch between different <strong>Laplacian matrices</strong>, each representing the network’s structure at a given time. Let’s see this in action:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w0XgKLsmIMugzNARX1W6hQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tTEbkEv_-USLn5SejaHNig.png" /><figcaption>A topology that switches every 10 time steps for 5 time steps</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8Y9ksuS3EDqSjO5q86h50g.png" /></figure><p>Here, agents are adjusting to two different network structures. The algorithm switches between the two Laplacians, ensuring that despite the changing connections, the agents still converge to consensus.</p><h3>Once again, what is consensus?</h3><p>In multi-agent systems (like drones or robots), <strong>consensus</strong> is the idea that every agent in a network agrees on something — be it a number, a decision, or a state — based on the local information they exchange with each other.</p><p>Imagine you have a group of friends deciding on a meeting spot. Each person has a different opinion initially, but after some rounds of discussion, they all agree to meet at one common location. This is <strong>consensus</strong>: everyone starts with different opinions (initial states), but by sharing information, they converge to the same final decision (a common state).</p><h3>What do the Converging Graphs of x’s Mean?</h3><p>In the context of a <strong>consensus algorithm</strong>, those graphs of x (state values) converging simply show that, despite starting with different values, each agent’s state gradually <strong>moves closer to the average</strong> of the initial values. All agents, after sharing information, end up in the same state.</p><p><strong>Real-world parallel:</strong> Think of this as drones agreeing on a <strong>common heading direction</strong>. Initially, each drone might be heading in slightly different directions, but as they communicate, they all adjust their headings until they fly in the same direction. The graph shows their individual headings converging until they’re all aligned.</p><h3>Why is This Important in Real-World Systems?</h3><ol><li><strong>Drones Avoiding Collisions</strong>: Imagine you have a swarm of drones surveying a large area. You don’t want all drones to converge to the same location (because they would collide), but you do want them to agree on a shared <strong>strategy</strong> or <strong>formation</strong> (e.g., evenly distributing themselves across the area). This <strong>shared strategy</strong> is the consensus. Consensus might mean agreeing on the spacing between drones to form a grid or ensuring they all move at the same speed to cover more ground.</li><li><strong>Robots in Factories</strong>: In an automated factory, several robots might need to coordinate their movements to assemble parts. Each robot might start with different positions and tasks, but over time, they need to agree on <strong>timing</strong> and <strong>sequence</strong> (for instance, which robot should act next). Here, <strong>consensus</strong> ensures they all sync their actions so that no robot is delayed or ahead of schedule, allowing smooth, synchronized production.</li><li><strong>Self-Driving Cars in Traffic</strong>: Imagine self-driving cars needing to merge onto a highway. They initially have different speeds and positions, but through communication, they reach <strong>consensus</strong> on a safe, common merging strategy. This prevents accidents and ensures smooth traffic flow.</li></ol><h3>How Does Consensus Work in Practice?</h3><ul><li><strong>Step 1</strong>: Every agent (drone, robot, or car) starts with its own initial value (e.g., speed, heading, or decision).</li><li><strong>Step 2</strong>: Agents share information with nearby agents (their neighbors in the network).</li><li><strong>Step 3</strong>: Each agent updates its value based on its neighbors’ values, slowly inching closer to an agreed-upon state.</li><li><strong>Step 4</strong>: Over time, every agent in the network reaches <strong>the same value</strong>, and consensus is achieved.</li></ul><p>If you would like to view the code used to generate and simulate this system along with the math behind it, please view my notebook here:</p><p><a href="https://colab.research.google.com/drive/1V-H8iJU05zzyWTZQQtkB4jWkmgL0xdS2?usp=sharing">https://colab.research.google.com/drive/1V-H8iJU05zzyWTZQQtkB4jWkmgL0xdS2?usp=sharing</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4886cdfb3c3a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Mechanical Engineer in Robotics, What Does That Look Like?]]></title>
            <link>https://medium.com/@luai_abuelsamen/a-mechanical-engineer-in-robotics-what-does-that-look-like-518bd1ec6e4b?source=rss-dc48e504a710------2</link>
            <guid isPermaLink="false">https://medium.com/p/518bd1ec6e4b</guid>
            <category><![CDATA[robotics]]></category>
            <category><![CDATA[mechanical-engineering]]></category>
            <category><![CDATA[embedded-systems]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Luai Abuelsamen]]></dc:creator>
            <pubDate>Fri, 27 Sep 2024 00:22:43 GMT</pubDate>
            <atom:updated>2024-09-27T00:22:43.998Z</atom:updated>
            <content:encoded><![CDATA[<p>The typical mechanical engineering typically involves coursework centered around the following ‘bubbles’</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CtZNbI1ZMfmyOW6vbS2ToQ.png" /></figure><p><strong>You’ve just graduated, taken a few classes in each branch of mechanical engineering, and now you feel like a useless generalist. What do you do?</strong></p><p>If you’re following the hype around artificial intelligence and humanoid robots, as we enter a new age of industrialization, you’re probably wondering how to break into the industry or where academia is headed. The beauty of robotics is that the field thrives on people who are “useless generalists.”</p><p>In robotics, especially today, generalists have a massive edge because you need to understand <strong>AI, software, hardware, and mechanical systems</strong> to thrive. Now, let’s dive into some key types of robots:</p><h3>Wheeled Robots (Mars rovers, self-driving cars, robot vacuums)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*dtsWWY4vi5yWsZJFCIynhQ.png" /></figure><p>This is the most common type, especially in industrial settings like Amazon warehouses, where efficiency and scalability matter. But, it’s not all smooth sailing — <strong>orchestrating multi-agent systems</strong> (i.e., coordinating multiple robots) presents unique challenges, from communication to efficient task distribution​</p><p>For <strong>self-driving cars</strong>, this is arguably one of the toughest applications. Why? Because aside from sensing and navigating, they need to make decisions based on human behavior — other drivers, pedestrians — none of which are easily formulated into rules. Companies are tackling this through advanced AI models, but it’s a huge unsolved problem.</p><h3>Aerial and Underwater Robots (Drones, AUVs)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*ufR3bC15UNm0YROtSulMvg.png" /></figure><p>Drones are popular, particularly in commercial applications like photography, delivery, and inspection. However, <strong>autonomous underwater vehicles (AUVs)</strong> are mainly used in niche fields like defense and marine research. One key challenge for both is mastering the <strong>aerodynamics (or hydrodynamics) of the surrounding fluid</strong>. New developments in <strong>grasping and perching</strong> for drones are enhancing their ability to interact with environments, whether that’s for maintenance tasks or environmental monitoring.</p><h3>Humanoid Robots (Tesla Bot, Figure)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*ineiN-7iVihk4cc6BnlEVQ.png" /></figure><p>This is the hottest and most complex area. The promise of humanoid robots is massive, but balancing, navigating, interacting, manipulating objects, and vision are major hurdles​. The appeal here is obvious — robots that can move in environments built for humans. There’s also growing interest in using these robots in dangerous or repetitive jobs, so humans can focus on more creative tasks​. That said, the tech is still in its early stages — humanoids remain in R&amp;D, and we’re far from seeing them on a mass scale.</p><h3>Robot Arms (UR arms, Fanuc, etc.)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hb65rcJYV2yywtvaqzaSTw.png" /></figure><p>Robot arms are a largely “solved” problem, with most development now focused on <strong>cost reduction</strong> and <strong>modular applications</strong>. These systems are being integrated with <strong>vision components</strong> and software layers to perform more complex tasks, especially in industries like automotive and electronics​</p><p>That being said, these arms are key to solving bigger robotics problems, acting as modular parts for more sophisticated systems like mobile manipulators​</p><p>So what can you do to help? With the knowledge you most likely have.</p><p><strong>Manufacturing, Design: Cost of Actuators</strong></p><ul><li>The high cost of precise actuators (motors, sensors) is a barrier to scaling systems. Advances in <strong>material science</strong> and <strong>smart manufacturing</strong> techniques like <strong>additive manufacturing</strong> are driving down costs, but more focus is needed on reducing production costs without sacrificing performance.</li></ul><p><strong>Fluid Mechanics: Supporting Controls for AUVs</strong></p><ul><li>Modeling the <strong>fluid dynamics</strong> around AUVs is critical for their controls. <strong>Computational Fluid Dynamics (CFD)</strong> and simpler <strong>real-time models</strong> of underwater turbulence are improving, making it easier to control these vehicles in complex environments.</li></ul><p><strong>Controls, Dynamics, and Math: Orchestration and SLAM</strong></p><ul><li>The challenge of orchestrating multiple robots and improving <strong>SLAM</strong> for real-time mapping and navigation in dynamic environments is being tackled through AI-driven <strong>control systems</strong> and <strong>sensor fusion</strong> techniques. These methods help robots understand and interact with their surroundings more effectively, especially in unstructured environments.</li></ul><p>Now what are the skills that are not typically taught in the mechanical engineering curriculum that you will benefit greatly from if you wanted to expand your reach in robotics?</p><h4>Programming</h4><p>This is a big no-no for a lot of mechanical engineers, but it’s not as intimidating as it sounds. It’s not easy either, but if you enjoy logic and math, programming is one of the quickest and neatest ways to lay out your logic and gain satisfaction from seeing a finished product.</p><p>What programming are we talking about?</p><h4>What programming are we talking about?</h4><ol><li><strong>Controls</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/1*koh22qoV4JCET02TLL9adA.png" /></figure><p>In the world of controls, we usually talk about straightforward programming, which is increasingly common in <strong>Python</strong> and historically in <strong>Matlab</strong> or <strong>Simulink</strong>. These tools are often used to simulate and generate control code that can be deployed in <strong>C</strong> for embedded systems. Learning programming for controls not only helps in implementing algorithms but also in optimizing systems through simulation and testing. This understanding can then be applied in <strong>robot operating systems (ROS)</strong> to run higher-level controls in robots.</p><ol><li><strong>Embedded Systems</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*UgG2qzSyakQmoSwiazNOOA.png" /></figure><p>Typically in <strong>C/C++</strong>, embedded systems are closely linked with controls but involve more hardware-specific programming. This includes understanding <strong>microcontroller architectures</strong>, designing firmware with constraints like limited memory, and working with <strong>real-time operating systems (RTOS)</strong>. The learning curve here is steep, especially for those coming from a mechanical engineering background, but it’s vital for building reliable systems that control robot actuators, sensors, and power management efficiently.</p><ol><li><strong>AI and Machine Learning</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*rZwdNZ_DxGtZf8BYDW7jzQ.png" /></figure><p>AI has become a key part of robotics, especially for tasks like perception, decision-making, and control. <strong>Neural networks</strong>, <strong>reinforcement learning</strong>, and <strong>computer vision</strong> are all integral components of modern robotic systems. Mechanical engineers often excel in this area due to their strong math background. They can leverage their understanding of dynamics and control systems to work with <strong>Physics-Informed Neural Networks (PINNs)</strong>, which combine physical laws with machine learning, making them highly effective for applications like robotic control and dynamic simulations.</p><h3>Electronics</h3><p>Another adjacent field that mechanical engineers must become proficient in if they want to deepen their expertise in robotics.</p><h4>1. Electric Machinery</h4><p>This one you’re likely already somewhat familiar with. <strong>Actuators, servo motors, and induction motors</strong> are core components in converting logic and code into real-world physical changes. These devices allow robots to move, lift, or perform tasks. Familiarity with how these motors work, along with understanding key input-output parameters like <strong>torque, power consumption</strong>, and <strong>speed control</strong>, is essential. For example, <strong>servo motors</strong> allow for precise control of angular or linear position, which is crucial in robotic arms and jointed systems.</p><p>Understanding motor types, such as <strong>brushed vs. brushless motors</strong>, and learning how to select the appropriate motor for different robotic applications can improve your system’s efficiency and durability.</p><h4>2. Sensors</h4><p>This is a familiar concept for most mechanical engineers, but critical in robotics. Sensors are the components through which robotic systems interact with the real world. Internal sensors like <strong>encoders</strong> (for position feedback), <strong>strain gauges</strong> (for force sensing), and <strong>thermistors</strong> (for temperature sensing) are crucial for fine-tuning mechanical movements. External sensors such as <strong>cameras, LiDAR, and SONAR</strong> provide vital input for a robot’s perception of its environment. These are used in applications like <strong>autonomous navigation</strong>, obstacle detection, and <strong>SLAM</strong> (Simultaneous Localization and Mapping).</p><p>Understanding how to process and integrate sensor data is also key to reducing <strong>noise</strong> and improving decision-making algorithms in robotics systems. Learning about <strong>sensor fusion</strong>, where data from multiple sensors are combined, is also useful in creating more accurate models of the robot’s environment.</p><h4>3. Microelectronics</h4><p><strong>Microcontrollers</strong> and <strong>microprocessors</strong> are essential for robotics as they manage sensor data, actuate motors, and execute control algorithms. Robotics often involves working with <strong>embedded systems</strong>, where microcontrollers are used to run real-time control systems. Becoming proficient in <strong>digital electronics</strong> and <strong>signal processing</strong> will give you the capability to handle the electronics that control mechanical systems. Furthermore, learning to interface with <strong>analog sensors</strong> and <strong>digital buses</strong> (such as <strong>I2C</strong>, <strong>SPI</strong>, or <strong>CAN</strong>) is essential for controlling motors and collecting sensor data.</p><h4>4. Programmable Logic Controllers (PLCs)</h4><p>Although more common in <strong>industrial automation</strong>, <strong>PLCs</strong> are valuable tools for controlling robots in manufacturing environments. They offer real-time, deterministic control over machines, including robotic systems, and are used in applications like <strong>conveyor belts, robotic arms</strong>, and complex manufacturing processes. Learning how to program and interface with PLCs using <strong>ladder logic</strong> or <strong>function block diagrams</strong> gives mechanical engineers another powerful tool for integrating robotics into large-scale industrial applications.</p><p>Expanding into robotics from a mechanical engineering background requires developing adjacent skills in <strong>programming</strong>, <strong>embedded systems</strong>, <strong>AI</strong>, and <strong>electronics</strong>. Mechanical engineers already have strong fundamentals in systems design, mechanics, and math, but gaining proficiency in software development (particularly <strong>Python</strong>, <strong>C/C++</strong>), control systems, and embedded systems will open up more opportunities in robotics. In addition, understanding the <strong>electronics</strong> behind actuators, sensors, microcontrollers, and PLCs is essential to interfacing physical systems with computational logic.</p><h3>Word of Advice:</h3><p>Start small and build your knowledge step by step. If you’re diving into <strong>programming</strong>, begin with Python as it’s beginner-friendly and widely used in robotics. Then, explore <strong>embedded systems</strong> and <strong>C/C++</strong> to understand how software interacts with hardware. In terms of <strong>AI</strong>, don’t be afraid to dive into machine learning as it ties closely to the math you already know. Finally, stay curious and keep learning — robotics is a fast-moving field, so continuous improvement and hands-on projects will accelerate your growth.</p><p>Interesting Reads:</p><p><a href="https://www.frontiersin.org/journals/robotics-and-ai/articles/10.3389/frobt.2022.938775/full">Frontiers</a></p><p><a href="https://www.frontiersin.org/journals/robotics-and-ai/articles/10.3389/frobt.2022.938775/full">Frontiers</a></p><p><a href="https://ifr.org/ifr-press-releases/news/top-5-robot-trends-2024">IFR International Federation of Robotics</a></p><p><a href="https://deepmind.google/discover/blog/shaping-the-future-of-advanced-robotics/">Google DeepMind</a></p><p><a href="https://www.frontiersin.org/journals/robotics-and-ai/articles/10.3389/frobt.2021.739173/full">Frontiers</a></p><p><a href="https://www.frontiersin.org/journals/robotics-and-ai/articles/10.3389/frobt.2021.739173/full">Frontiers</a></p><p><a href="https://robots.net/news/top-robotics-experts-discuss-the-future-of-robotics-humanoids-generative-ai-and-more/">Robots.net</a></p><p><a href="https://ifr.org/ifr-press-releases/news/top-5-robot-trends-2024">IFR International Federation of Robotics</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=518bd1ec6e4b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MPC vs RL: Stabilizing the Cart-Pendulum System]]></title>
            <link>https://medium.com/@luai_abuelsamen/mpc-vs-rl-stabilizing-the-cart-pendulum-system-69f11b6c0af2?source=rss-dc48e504a710------2</link>
            <guid isPermaLink="false">https://medium.com/p/69f11b6c0af2</guid>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[model-predictive-control]]></category>
            <category><![CDATA[robotics]]></category>
            <dc:creator><![CDATA[Luai Abuelsamen]]></dc:creator>
            <pubDate>Thu, 26 Sep 2024 05:38:45 GMT</pubDate>
            <atom:updated>2024-09-26T05:38:45.699Z</atom:updated>
            <content:encoded><![CDATA[<p>When it comes to controlling complex systems, two powerful approaches often come into play: Model Predictive Control (MPC) and Reinforcement Learning (RL). Both methods have distinct advantages and applications, but they approach problems in very different ways. In this article, we will explore these techniques by applying them to this classic control problem.</p><h3>The Cart-Pendulum Problem</h3><p>Imagine a cart on a track with a pendulum attached to it. The goal is to move the cart horizontally in such a way that the pendulum remains upright, a classic problem in control theory. This is a challenging task, as small deviations can cause the pendulum to fall. Both MPC and RL can be used to solve this problem, but they do so with fundamentally different philosophies.</p><h3>Model Predictive Control (MPC)</h3><p>MPC is a model-based approach. It relies on a mathematical model of the system to predict future states and optimize control actions accordingly. MPC solves an optimization problem at each time step, trying to minimize a cost function (e.g., how far the pendulum deviates from the upright position).</p><p><strong>Advantages</strong>:</p><ul><li>Highly interpretable.</li><li>Efficient for linear and well-understood systems.</li><li>Can incorporate system constraints naturally.</li></ul><p><strong>Disadvantages</strong>:</p><ul><li>Requires an accurate model of the system.</li><li>Solving the optimization problem at each time step can be computationally expensive.</li><li>May struggle with non-linearities or unmodeled dynamics.</li></ul><h3>Reinforcement Learning (RL)</h3><p>Reinforcement Learning, on the other hand, is a model-free approach. It doesn’t rely on knowing the system’s dynamics upfront. Instead, RL learns by interacting with the system, trying different actions, and receiving feedback in the form of rewards or penalties. Over time, it learns which actions maximize the reward (e.g., keeping the pendulum upright).</p><p><strong>Advantages</strong>:</p><ul><li>Doesn’t require a precise model of the system.</li><li>Can adapt to non-linear systems and unmodeled dynamics.</li><li>Capable of solving very complex control problems.</li></ul><p><strong>Disadvantages</strong>:</p><ul><li>Requires a large amount of data (i.e., many interactions with the environment).</li><li>The training process can be slow.</li><li>May be less interpretable than MPC.</li></ul><h3>A Case Study: Cart-Pendulum System</h3><p>Let’s apply both MPC and RL to the cart-pendulum problem to see how they perform.</p><h4>Define the system</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/668/1*BEAOuluv3-ZYR6WEAJVz1g.png" /></figure><pre># Physical constants for the cart-pendulum system<br>M = 0.5  # Cart mass<br>m = 0.2  # Pendulum mass<br>b = 0.1  # Coefficient of friction for cart<br>I = 0.006  # Mass moment of inertia of the pendulum<br>g = 9.8  # Gravity<br>l = 0.3  # Length to pendulum center of mass<br>dt = 0.1  # Time step<br><br>p = I * (M + m) + M * m * l ** 2</pre><p>Defining the state space based on the equations of motion</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wDbrTpgN7YviD9aL5a0gMg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eny7BB5yjdbewv2ooJ3q8w.png" /></figure><pre>A = np.array([[0, 1, 0, 0],<br>              [0, -(I + m * l ** 2) * b / p, (m ** 2 * g * l ** 2) / p, 0],<br>              [0, 0, 0, 1],<br>              [0, -(m * l * b) / p, m * g * l * (M + m) / p, 0]])<br><br>B = np.array([[0],<br>              [(I + m * l ** 2) / p],<br>              [0],<br>              [m * l / p]])<br><br>C = np.array([[1, 0, 0, 0],<br>              [0, 0, 1, 0]])<br><br>D = np.array([[0],<br>              [0]])</pre><h4>MPC Implementation</h4><p>In the MPC approach, we derive the system’s state-space equations using physical constants like the cart’s mass, the pendulum’s mass, and the length of the pendulum. At each time step, MPC predicts the pendulum’s future states and solves an optimization problem to determine the best control input. The optimization minimizes the cost function, typically designed to keep the pendulum upright and the cart within bounds.</p><p>We define an optimization problem with a cost function that penalizes deviations from the desired state and excessive control efforts</p><pre>def run_mpc():<br>    cost = 0.<br>    constr = [x[:, 0] == x_init]<br>    for t in range(N):<br>        cost += cp.quad_form(xr - x[:, t], Q) + cp.quad_form(u[:, t], R)<br>        constr += [cp.norm(u[:, t], &#39;inf&#39;) &lt;= 10.]<br>        constr += [x[:, t + 1] == A_zoh * x[:, t] + B_zoh * u[:, t]]<br>    cost += cp.quad_form(x[:, N] - xr, Q)<br>    problem = cp.Problem(cp.Minimize(cost), constr)<br>    return problem</pre><ul><li><strong>Cost function</strong>: The total cost includes penalties for the difference between the current state and the desired state Q and the magnitude of the control inputs R.</li><li><strong>Constraints</strong>: The system dynamics are enforced, and control inputs are constrained to keep the control effort within a reasonable range.</li></ul><h4>2. System Dynamics</h4><p>The matrices A_zoh and B_zoh represent the discrete-time approximation of the continuous system dynamics. These dynamics are integrated into the MPC formulation, ensuring the future states evolve according to the cart-pendulum model.</p><pre>[nx, nu] = B_zoh.shape<br>Q = sparse.diags([10., 5., 100., 5.])  # Weights for state deviations<br>R = np.array([[.1]])  # Weights for control efforts<br>xr = np.array([0., 0., 0., 0.])  # Desired states<br>N = 10  # MPC Horizon length</pre><ul><li>N is the prediction horizon for MPC, meaning the controller predicts future states over a fixed window of 10 time steps.</li></ul><h4>3. Simulation Loop</h4><p>The system is simulated over nsim time steps, repeatedly solving the MPC problem at each time step to find the optimal control inputs:</p><pre>for i in range(1, nsim+1):<br>    prob = run_mpc()<br>    x_init.value = x0<br>    prob.solve(solver=cp.OSQP, warm_start=True)<br>    x0 = A_zoh.dot(x0) + B_zoh.dot(u[:, 0].value)<br>    time.append(i)<br>    cart_pos.append(x0[0])<br>    cart_vel.append(x0[1])<br>    pend_ang.append(x0[2])<br>    pend_ang_vel.append(x0[3])<br>    ctrl_effort.append(u[:, 0].value)</pre><ul><li>At each iteration, the MPC problem is solved using the <strong>OSQP solver</strong>. The system state is updated based on the current control inputs, and the process repeats.</li></ul><h4>4. Results</h4><p>Throughout the simulation, data is collected for time, cart position, velocity, pendulum angle, and control effort:</p><p>This data is then used to visualize the system’s behavior, showing how MPC balances the pendulum while controlling the cart’s movement.</p><h4>RL Implementation</h4><p>In the RL approach, we discretize the state space (e.g., cart position, velocity, pendulum angle) and use Q-learning to learn a policy for controlling the cart. Over thousands of episodes, the RL agent tries different actions (moving the cart left, right, or not at all) and receives rewards based on how well it keeps the pendulum upright. Over time, the agent learns the best actions to take in each state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FxKbjaD-4tVKJ9JF9XNqJg.png" /></figure><p>We start by initializing the Q-table, which holds the learned values for each state-action pair. Each entry in this table corresponds to the expected reward for taking a particular action in a given state. Initially, the table is filled with random values.</p><pre>def initialize_q_table(n_states, n_actions):<br>    return np.random.uniform(low=-1, high=1, size=(n_states + [n_actions]))</pre><p>Since Q-learning works with discrete states, the continuous state space (cart position, cart velocity, pendulum angle, and angular velocity) needs to be discretized into bins.</p><pre>def discretize(state, bins):<br>    return tuple(np.digitize(s, b) for s, b in zip(state, bins))</pre><p>The cart-pendulum system is simulated by updating its state based on the current control input (action). The reward is designed to penalize deviations from the upright pendulum position (θ=0\theta = 0θ=0) and the cart’s central position (x=0x = 0x=0).</p><pre>def step(state, action, A_zoh, B_zoh):<br>    u = np.array([[action]])<br>    next_state = A_zoh @ state.reshape(-1, 1) + B_zoh @ u<br>    next_state = next_state.flatten()<br>    reward = - (abs(next_state[2]) + abs(next_state[0]))<br>    done = abs(next_state[2]) &gt; np.pi / 2 or abs(next_state[0]) &gt; 2.4<br>    return next_state, reward, done</pre><p>The agent selects an action using the epsilon-greedy strategy: it either explores by choosing a random action or exploits the best-known action based on the Q-table.</p><pre>def choose_action(state, q_table, action_space, epsilon, bins):<br>    if random.uniform(0, 1) &lt; epsilon:<br>        return random.choice(action_space)<br>    else:<br>        state_discrete = discretize(state, bins)<br>        return action_space[np.argmax(q_table[state_discrete])]</pre><p>After taking an action and observing the resulting state and reward, the Q-table is updated using the Q-learning update rule:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8WiBsctMulXxmb6Xgr9btA.png" /></figure><pre>def update_q_table(state, action, reward, next_state, q_table, action_space, alpha, gamma, bins):<br>    state_discrete = discretize(state, bins)<br>    next_state_discrete = discretize(next_state, bins)<br>    action_idx = action_space.index(action)<br>    q_table[state_discrete + (action_idx,)] += alpha * (reward + gamma * np.max(q_table[next_state_discrete]) - q_table[state_discrete + (action_idx,)])</pre><p>We simulate the system for multiple episodes (training iterations). The agent interacts with the environment by selecting actions and updating the Q-table based on the observed rewards.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PMZHDkSGneoMuK8k6iVLjw.png" /></figure><pre>def train(q_table, A_zoh, B_zoh, action_space, bins, alpha, gamma, epsilon, num_episodes, x0):<br>    for _ in range(num_episodes):<br>        state = np.copy(x0)<br>        done = False<br>        while not done:<br>            action = choose_action(state, q_table, action_space, epsilon, bins)<br>            next_state, reward, done = step(state, action, A_zoh, B_zoh)<br>            update_q_table(state, action, reward, next_state, q_table, action_space, alpha, gamma, bins)<br>            state = next_state</pre><p>After training, we can test the learned policy by running a simulation where the agent uses its learned Q-values to select the optimal actions.</p><pre>def simulate_cart_pendulum(q_table, A_zoh, B_zoh, action_space, bins, x0, num_steps):<br>    state = np.copy(x0)<br>    x_traj = []<br>    for _ in range(num_steps):<br>        action = choose_action(state, q_table, action_space, 0.0, bins)  # epsilon is 0 to use learned policy<br>        state, _, done = step(state, action, A_zoh, B_zoh)<br>        if done:<br>            break<br>        x_traj.append((state[0], state[2]))<br>    return x_traj</pre><p>To train the agent, we specify the number of episodes, the number of steps per episode, and other key hyperparameters such as the learning rate α, discount factor γ, and exploration rate ϵ.</p><pre># Set hyperparameters and training setup<br>alpha = 0.1<br>gamma = 0.99<br>epsilon = 0.1<br>n_states = [15, 15, 15, 15]  # Discretized states<br>n_actions = 3  # Number of actions<br>action_space = [-10, 0, 10]  # Discrete actions<br># Discretization bins for state variables<br>bins = [np.linspace(-2.4, 2.4, n_states[0] - 1),<br>        np.linspace(-3.0, 3.0, n_states[1] - 1),<br>        np.linspace(-np.pi / 2, np.pi / 2, n_states[2] - 1),<br>        np.linspace(-2.0, 2.0, n_states[3] - 1)]<br># Initialize Q-table and train<br>q_table = initialize_q_table(n_states, n_actions)<br>train(q_table, A_zoh, B_zoh, action_space, bins, alpha, gamma, epsilon, num_episodes, x0)</pre><p>To view the results and simulations (with animation) check out the Jupyter notebook here:</p><p><a href="https://colab.research.google.com/drive/1TH0vAwN_XLSCY2T1Oie6phkw-dBA2AlR#scrollTo=5031ZDaemnBs">https://colab.research.google.com/drive/1TH0vAwN_XLSCY2T1Oie6phkw-dBA2AlR#scrollTo=5031ZDaemnBs</a></p><h4>AI vs Controls</h4><p>AI-based controls, such as reinforcement learning (RL), and classical controls, like PID and Model Predictive Control (MPC), offer two distinct approaches to managing dynamic systems. Classical control methods rely on precise mathematical models of system dynamics, offering well-defined and interpretable solutions to problems with known behavior and constraints. These methods, like MPC, excel in environments where the system is well-understood and constraints are critical.</p><p>In contrast, AI-driven controls do not require explicit system models. They learn optimal policies through interaction with the environment, making them more adaptable to complex or non-linear systems where modeling is difficult. However, AI methods can require extensive training and may lack the transparency and real-time efficiency of classical controls, making them better suited for scenarios with uncertain dynamics or changing environments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=69f11b6c0af2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Making a Chat-GPT app with a Custom GPT in Swift]]></title>
            <link>https://medium.com/@luai_abuelsamen/a-step-by-step-guide-to-using-openais-api-in-swift-dee46a1027ad?source=rss-dc48e504a710------2</link>
            <guid isPermaLink="false">https://medium.com/p/dee46a1027ad</guid>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[api-development]]></category>
            <category><![CDATA[swift-threads]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Luai Abuelsamen]]></dc:creator>
            <pubDate>Fri, 09 Aug 2024 22:24:19 GMT</pubDate>
            <atom:updated>2024-09-16T05:37:04.810Z</atom:updated>
            <content:encoded><![CDATA[<p>Unlock the power of OpenAI’s GPT models in your Swift applications by deploying your personalized AI assistant. Whether you’re building a custom chatbot, a content generator, or any AI-driven tool, this guide will help you integrate the OpenAI Assistant API seamlessly into your Swift projects. In this guide, we’ll cover everything from setting up your environment to making your first API call, complete with practical code snippets tailored for easy integration.</p><h3>1. Setting Up Your Swift Environment</h3><p>Before diving into API interactions, it’s essential to ensure that your Swift environment is ready. Swift’s URLSession will be your primary tool for making HTTP requests. While Swift&#39;s Foundation library provides robust JSON handling, you can enhance functionality using the Swift Package Manager or CocoaPods if needed. Security is paramount when dealing with API keys. Instead of hard-coding your API key directly into your code, consider storing it securely in environment variables or using the Keychain. Here&#39;s how you can access your API key securely in Swift:</p><pre>guard let apiKey = ProcessInfo.processInfo.environment[&quot;OPENAI_API_KEY&quot;]<br>else {<br>    fatalError(&quot;API Key not found&quot;)<br>}</pre><p>With your API key securely stored, you’re ready to start interacting with OpenAI’s Assistant API.</p><h3>2. Managing API Requests with OpenAIManager</h3><p>The core of your API interactions will be managed by the OpenAIManager class. Here&#39;s a streamlined structure for this class, which will handle all your OpenAI API requests:</p><pre>import Foundation<br><br>class OpenAIManager {<br>    private<br>    let apiKey: String<br>    private<br>    let session = URLSession.shared<br><br>    init(apiKey: String) {<br>        self.apiKey = apiKey<br>    }<br>    // Functions for API interaction will go here<br>}</pre><h3>3. Creating a New Conversation Thread</h3><p>The first step in interacting with the OpenAI Assistant API is to create a new thread, which will manage the conversation context. Here’s a function to do just that:</p><pre>func createThread(completion: @escaping(String? ) -&gt; Void) {<br><br>    guard let url = URL(string: &quot;https://api.openai.com/v1/threads&quot;)<br>    else {<br>        print(&quot;Invalid URL&quot;)<br>        completion(nil)<br>        return<br>    }<br><br>    var request = URLRequest(url: url)<br>    request.httpMethod = &quot;POST&quot;<br>    request.addValue(&quot;Bearer \(apiKey)&quot;, forHTTPHeaderField: &quot;Authorization&quot;)<br>    request.addValue(&quot;application/json&quot;, forHTTPHeaderField: &quot;Content-Type&quot;)<br>    request.addValue(&quot;assistants=v1&quot;, forHTTPHeaderField: &quot;OpenAI-Beta&quot;)<br><br>    let task = session.dataTask(with: request) {<br>        data,<br>        response,<br>        error in<br><br>        if let error = error {<br>            print(&quot;Network error: \(error)&quot;)<br>            completion(nil)<br>            return<br>        }<br><br>    guard let httpResponse = response as? HTTPURLResponse,<br>            httpResponse.statusCode == 200<br>        else {<br>            print(&quot;HTTP Error: \(response?.description ?? &quot;No response &quot;)&quot;)<br>            completion(nil)<br>            return<br>        }<br><br>    guard let data = data,<br>            let jsonObject =<br>                try? JSONSerialization.jsonObject(with: data) as? [String: Any],<br>                let id = jsonObject[&quot;id&quot;] as? String<br>        else {<br>            print(&quot;Failed to parse JSON or missing &#39;id&#39;&quot;)<br>            completion(nil)<br>            return<br>        }<br><br>        completion(id)<br>    }<br>    task.resume()<br>}</pre><p>This function initiates a new thread and returns a thread ID that you’ll need for future interactions.</p><h3>4. Sending a Message to the Thread</h3><p>Once you’ve created a thread, you can send messages to the GPT model. Here’s how you can send a message within the thread:</p><pre>func createMessage(threadId: String, content: String, completion: @escaping(Bool) -&gt; Void) {<br>    guard<br>    let url = URL(string: &quot;https://api.openai.com/v1/threads/\(threadId)/messages&quot;)<br>    else {<br>        print(&quot;Invalid URL&quot;)<br>        completion(false)<br>        return<br>    }<br>    var request = URLRequest(url: url)<br>    request.httpMethod = &quot;POST&quot;<br>    request.addValue(&quot;Bearer \(apiKey)&quot;, forHTTPHeaderField: &quot;Authorization&quot;)<br>    request.addValue(&quot;application/json&quot;, forHTTPHeaderField: &quot;Content-Type&quot;)<br>    request.addValue(&quot;assistants=v1&quot;, forHTTPHeaderField: &quot;OpenAI-Beta&quot;)<br>    let messageData: [String: Any] = [&quot;content&quot;: content]<br>    do {<br>        request.httpBody =<br>            try JSONSerialization.data(withJSONObject: messageData, options: [])<br>    } catch {<br>        print(&quot;Error creating request body: \(error)&quot;)<br>        completion(false)<br>        return<br>    }<br>    let task = session.dataTask(with: request) {<br>        data,<br>        response,<br>        error in<br>        if error != nil || (response as? HTTPURLResponse)? .statusCode != 200 {<br>            completion(false)<br>            return<br>        }<br>        completion(true)<br>    }<br>    task.resume()<br>}</pre><p>This function securely includes your API key and sends the message content to the specified thread.</p><h3>5. Fetching Messages from the Thread</h3><p>To retrieve the GPT model’s response, you’ll need to fetch the messages from the thread. Here’s a function to handle that:</p><pre>func fetchMessages(threadId: String, completion: @escaping([Message]? ) -&gt; Void) {<br>    guard<br>    let url = URL(string: &quot;https://api.openai.com/v1/threads/\(threadId)/messages&quot;)<br>    else {<br>        print(&quot;Invalid URL&quot;)<br>        completion(nil)<br>        return<br>    }<br>    var request = URLRequest(url: url)<br>    request.httpMethod = &quot;GET&quot;<br>    request.addValue(&quot;Bearer \(apiKey)&quot;, forHTTPHeaderField: &quot;Authorization&quot;)<br>    request.addValue(&quot;application/json&quot;, forHTTPHeaderField: &quot;Content-Type&quot;)<br>    let task = session.dataTask(with: request) {<br>        data,<br>        response,<br>        error in<br>        if let error = error {<br>            print(&quot;Network error: \(error)&quot;)<br>            completion(nil)<br>            return<br>        }<br>    guard let httpResponse = response as? HTTPURLResponse,<br>            httpResponse.statusCode == 200<br>        else {<br>            print(&quot;HTTP Error or invalid response&quot;)<br>            completion(nil)<br>            return<br>        }<br>    guard let data = data<br>        else {<br>            print(&quot;No data received&quot;)<br>            completion(nil)<br>            return<br>        }<br>        do {<br>            let decoder = JSONDecoder()<br>            let messageList =<br>                try decoder.decode(MessageList.self, from: data)<br>            completion(messageList.data)<br>        } catch {<br>            print(&quot;Failed to decode JSON: \(error)&quot;)<br>            completion(nil)<br>        }<br>    }<br>    task.resume()<br>}</pre><p>This function retrieves the messages from the thread, allowing you to extract the model’s response.</p><h3>6. Bringing It All Together</h3><p>Here’s how you can integrate these functions into a workflow to send a message, fetch the response, and display it:</p><pre>let openAIManager = OpenAIManager(apiKey: &quot;your_api_key_here&quot;)<br>openAIManager.createThread {<br>    threadId in<br>        guard<br>    let threadId = threadId<br>    else {<br>        print(&quot;Failed to create thread&quot;)<br>        return<br>    }<br>    openAIManager.createMessage(threadId: threadId, content: &quot;Tell me a joke!&quot;) {<br>        success in<br>            guard success<br>        else {<br>            print(&quot;Failed to send message&quot;)<br>            return<br>        }<br>        openAIManager.fetchMessages(threadId: threadId) {<br>            messages in<br>                guard<br>            let messages = messages<br>            else {<br>                print(&quot;Failed to fetch messages&quot;)<br>                return<br>            }<br>            if let response = messages.last? .content.first? .text? .value {<br>                print(&quot;GPT Response: \(response)&quot;)<br>            } else {<br>                print(&quot;No response found&quot;)<br>            }<br>        }<br>    }<br>}</pre><p>This code flow demonstrates how to create a new thread, send a message, and retrieve the response, allowing your personalized GPT to interact within your Swift application.</p><h3>7. Advanced Tips</h3><ul><li><strong>Error Handling:</strong> Implement robust error handling with retry logic to manage network failures and API rate limits.</li><li><strong>Batching Messages:</strong> If sending multiple messages, consider batching them to optimize API calls.</li><li><strong>Logging:</strong> Keep track of API usage and errors by implementing logging mechanisms to improve debugging and monitoring. With this setup, you’re well-equipped to build sophisticated, AI-driven applications in Swift using OpenAI’s Assistant API. Whether you’re enhancing user experiences or automating tasks, your personalized GPT is now ready to be deployed.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dee46a1027ad" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>