<?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[Gnomon Digital - Medium]]></title>
        <description><![CDATA[Technical blogs for Gnomon Digital - Medium]]></description>
        <link>https://medium.com/gnomondigital?source=rss----07d683c09d9f---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Gnomon Digital - Medium</title>
            <link>https://medium.com/gnomondigital?source=rss----07d683c09d9f---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 08:55:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/gnomondigital" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Part 3/3: From Backend Intelligence to Interactive Learning Experience]]></title>
            <link>https://medium.com/gnomondigital/part-3-3-from-backend-intelligence-to-interactive-learning-experience-a353a167a9d8?source=rss----07d683c09d9f---4</link>
            <guid isPermaLink="false">https://medium.com/p/a353a167a9d8</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[hackathons]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[chainlit]]></category>
            <category><![CDATA[ux]]></category>
            <dc:creator><![CDATA[Hela Moalla]]></dc:creator>
            <pubDate>Thu, 18 Sep 2025 11:05:03 GMT</pubDate>
            <atom:updated>2025-09-18T11:04:38.914Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XUi68uo2YUrIHCENmlf4Lg.png" /></figure><p><em>Authored by </em><a href="https://medium.com/@hela.moalla"><em>Hela Moalla</em></a><em> , Co-writer: </em><a href="https://medium.com/u/bccf9788af61"><em>Nacima Yahiatene</em></a></p><p><strong>Table of content</strong></p><p>· <a href="#f0a0">From Prototype to Experience: Why Interactive UX Matters</a><br>· <a href="#bd27">The Evolution Journey: From Chat to Companion</a><br>· <a href="#3fa3">Phase 1: The Foundation: Simple Chat Interface</a><br>· <a href="#1e84">Phase 2: Making the Invisible Visible: Agent Transparency</a><br>· <a href="#409d">Phase 3: Building Relationships: Persistent Memory</a><br>· <a href="#ffa7">Phase 4: Integration Reality — Workflow Embedding</a><br>· <a href="#2a83">Real-World Scenarios: Interactive Learning in Action</a><br>· <a href="#ca2c">Scenario 1: The Overwhelmed Developer</a><br>· <a href="#1ff0">Scenario 2: The Time-Constrained Manager</a><br>· <a href="#f7fb">Scenario 3: The Returning Learner</a><br>· <a href="#ba79">Why Chainlit Was the Perfect Choice</a><br> ∘ <a href="#8158">Real-Time Agent Visualization</a><br> ∘ <a href="#18f9">Conversation Memory That Matters</a><br> ∘ <a href="#60eb">Seamless Plugin Integration</a><br> ∘ <a href="#edca">Customizable Learning Flow</a><br>· <a href="#0595">Hackathon Lessons: Building Interactive UX Under Pressure</a><br> ∘ <a href="#0d72">What Transformed User Experience:</a><br> ∘ <a href="#60ae">What We’d Do Differently:</a><br> ∘ <a href="#24a9">Measuring Success: From Metrics to Moments</a><br>· <a href="#95f9">Returning to Our Original Vision: AI-Powered Personalized Learning</a><br>· <a href="#a7e9">From Personalization to Transformation</a><br>· <a href="#f2a6">What’s Next: The Evolution Continues</a><br> ∘ <a href="#8755">Immediate Opportunities:</a><br> ∘ <a href="#58bd">Broader Implications:</a><br>· <a href="#24af">Final Reflections: Building AI That Serves Humanity</a></p><p><em>previous chapter &gt; From Architecture to Production with Azure AI Foundry</em></p><p>In the first two parts of this series, we focused on the technical backbone of our project: how we designed our multi-agent system, orchestrated it with Semantic Kernel, and scaled it with Azure AI Foundry. But as powerful as the backend was, it represented only half of the story.</p><p>The real test came when we put it in the hands of users. And that’s where the frontend became our make-or-break challenge.</p><p>But this wasn’t just about building a pretty interface. This was about creating an <strong>interactive learning experience</strong> that could fulfill our original vision: making AI-powered learning truly personalized, transparent, and seamlessly integrated into people’s lives.</p><h3>From Prototype to Experience: Why Interactive UX Matters</h3><p>At the hackathon, our initial prototype was functional but barebones. Users could enter a goal like “I want to become a Data Engineer in six months”, and the backend would dutifully generate a learning path. Technically it worked, but the experience felt rigid and impersonal.</p><p>A block of text appeared on screen with little explanation of how it had been created. No interaction. No personalization visible to the user. No sense of an intelligent system adapting to their unique context.</p><p>This “black box” interaction raised immediate questions:</p><ul><li>Did the system actually use the user’s profile?</li><li>Was it pulling the right knowledge sources?</li><li>Could learners trust the recommendations enough to follow them?</li><li>Most importantly: <strong>Was this truly personalized learning, or just sophisticated content generation?</strong></li></ul><p>We realized that user trust wasn’t going to come from the correctness of the output alone. It had to come from <strong>transparency, interaction, and experience</strong>. The AI had to feel less like a search engine and more like a learning companion.</p><p>That’s why we embarked on creating not just a frontend, but an <strong>interactive learning experience</strong>.</p><h3>The Evolution Journey: From Chat to Companion</h3><p>Building our interactive experience wasn’t a single decision, it was an evolution through distinct phases, each teaching us something fundamental about how people want to interact with AI learning systems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WZQ4QFp9fr4wxA12.png" /></figure><h3>Phase 1: The Foundation: Simple Chat Interface</h3><p>We started with <a href="https://docs.chainlit.io/get-started/overview">Chainlit’s</a> basic chat interface. A learner typed their goals, and a plan appeared. Simple, functional, but missing the magic.</p><p><strong>What we learned:</strong> People expected more than just answers. They wanted to understand how those answers were created.</p><h3>Phase 2: Making the Invisible Visible: Agent Transparency</h3><p>This phase transformed everything. Using Chainlit’s @cl.step decorators, we made our multi-agent orchestration visible:</p><p>Suddenly, learners could see:</p><ul><li>When the Profile Builder Agent analyzed their goals</li><li>When the Web Search Agent retrieved external tutorials</li><li>When the Internal Knowledge Agent pulled Confluence resources</li><li>When the Orchestrator synthesized results into a coherent learning path</li></ul><p><strong>The transformation was immediate.</strong> Instead of a mysterious process running in the background, learners saw the reasoning steps unfold. This glass-box experience increased confidence: learners could trace answers back to sources, understand how their profile influenced results, and even get curious about the system’s inner workings.</p><h3>Phase 3: Building Relationships: Persistent Memory</h3><p>Real learning relationships don’t happen in isolation. They build over time. We integrated Chainlit’s DataLayer to store sessions, enabling persistent conversation history.</p><p>Now a learner could:</p><ul><li>Start by exploring cloud fundamentals</li><li>Pause and return later with: “Now I want to focus more on Azure Synapse”</li><li>Have the system remember past goals, context, and preferences</li></ul><p>This persistence bridged the gap between demo and daily use. It transformed the system from a one-off novelty into a <strong>learning companion</strong> that evolved with the user.</p><h3>Phase 4: Integration Reality — Workflow Embedding</h3><p>The final evolution integrated learning plans directly into daily workflows through Gmail and Google Calendar plugins:</p><ul><li>“Send my path to my email” → Beautifully formatted plan delivered instantly</li><li>“Block 2 hours every Tuesday for study” → Calendar automatically updated</li><li>“Remind me about my Azure certification milestone” → Smart notifications enabled</li></ul><p>This wasn’t just convenience, it was <strong>learning activation</strong>. The system stopped being something you visited and became something that lived within your actual work environment.</p><h3>Real-World Scenarios: Interactive Learning in Action</h3><p>Let me show you how this interactive experience transforms different learning scenarios</p><h3>Scenario 1: The Overwhelmed Developer</h3><p><strong>Meet Sarah:</strong> A junior developer who wants to transition into machine learning but feels overwhelmed by the vast field.</p><p><strong>Traditional approach:</strong> Search online, get thousands of generic results, feel more confused.</p><p><strong>Our interactive experience:</strong></p><pre>Sarah: &quot;I&#39;m a JavaScript developer with 2 years experience. I want to learn machine learning but don&#39;t know where to start.&quot;</pre><pre>🧑‍🎓 Profile Builder Agent: Analyzing your background...<br>   ✓ Current role: Junior JavaScript Developer<br>   ✓ Experience level: 2 years<br>   ✓ Learning goal: Machine Learning transition<br>   ✓ Potential knowledge gaps identified: Python, Statistics, ML fundamentals</pre><pre>🌍 Web Search Agent: Finding latest ML learning resources...<br>   ✓ Found: 15 beginner-friendly Python courses<br>   ✓ Found: 8 ML fundamentals tutorials for developers<br>   ✓ Found: 12 JavaScript-to-Python transition guides</pre><pre>🏢 Internal Knowledge Agent: Checking company resources...<br>   ✓ Found: Internal Python workshop recordings<br>   ✓ Found: ML team&#39;s onboarding documentation<br>   ✓ Found: Mentorship program with ML engineers</pre><pre>🧠 Orchestrator: Crafting your personalized path...<br>   ✓ Sequencing: Python basics → Statistics → ML fundamentals<br>   ✓ Leveraging: Your JavaScript experience for faster Python adoption<br>   ✓ Integrating: Company resources with external learning</pre><p><strong>The result:</strong> Sarah doesn’t just get a learning plan, she sees exactly why each resource was chosen for her specific background and goals. She trusts the recommendations because she watched them being crafted.</p><h3>Scenario 2: The Time-Constrained Manager</h3><p><strong>Meet Marcus:</strong> A busy engineering manager with only 3 hours per week for learning, wanting to stay current with AI trends.</p><p><strong>Our interactive experience:</strong></p><pre>Marcus: &quot;I have 3 hours per week maximum. I need to understand AI trends to make better technology decisions for my team.&quot;</pre><pre>🧑‍🎓 Profile Builder Agent: Understanding your constraints...<br>   ✓ Role: Engineering Manager<br>   ✓ Time availability: 3 hours/week<br>   ✓ Learning style: Strategic overview preferred<br>   ✓ Goal: Decision-making knowledge, not implementation</pre><pre>System: &quot;I notice you&#39;re time-constrained. Would you prefer:<br>A) Deep dives into 2-3 key AI areas<br>B) Broader overview of current AI landscape<br>C) Focus on AI applications in your industry&quot;</pre><pre>Marcus: &quot;Option B, but show me practical applications I can discuss with my team.&quot;</pre><pre>📅 Calendar Agent: Optimizing your schedule...<br>   ✓ Found: Tuesday 7-8 AM consistently free<br>   ✓ Found: Friday lunch breaks available<br>   ✓ Suggestion: 90min Tuesday + 90min Friday weekly blocks</pre><p><strong>The magic:</strong> The system adapts in real-time based on Marcus’s feedback, showing him exactly how it’s personalizing the experience for his unique constraints.</p><h3>Scenario 3: The Returning Learner</h3><p><strong>Meet Priya:</strong> A data scientist who took a 6-month break for personal reasons and wants to catch up on what she missed.</p><p><strong>Our interactive experience:</strong></p><pre>Priya: &quot;I was a data scientist but took 6 months off. What&#39;s changed in the field?&quot;</pre><pre>🧠 System Memory: Recognizing returning learner...<br>   ✓ Previous session: March 2024 - Focus on MLOps<br>   ✓ Last learning goal: Kubernetes deployment for ML models<br>   ✓ Preferred learning style: Hands-on tutorials</pre><pre>System: &quot;Welcome back, Priya! I remember you were working on MLOps and Kubernetes deployments. Here&#39;s what&#39;s evolved since March...&quot;</pre><pre>🌍 Web Search Agent: Finding recent developments...<br>   ✓ Major updates: LLM deployment patterns<br>   ✓ New tools: Latest MLflow and Kubeflow versions<br>   ✓ Industry shifts: AI Safety and governance focus</pre><pre>System: &quot;Would you like to:<br>1. Continue where you left off with updated Kubernetes tutorials<br>2. Explore new LLM deployment techniques<br>3. Get caught up on AI governance trends affecting data science&quot;</pre><pre>Priya: &quot;Mix of 1 and 3 - I need to stay technical but also understand the governance aspects.&quot;</pre><p><strong>The connection:</strong> The system builds on their previous relationship, making Priya feel understood rather than starting from zero.</p><h3>Why Chainlit Was the Perfect Choice</h3><p>Looking back, Chainlit enabled our interactive vision in ways we didn’t initially anticipate:</p><h4>Real-Time Agent Visualization</h4><p>Unlike traditional chat interfaces, Chainlit’s step system made our multi-agent orchestration <strong>visible and understandable</strong>. Users could literally watch intelligence being applied to their problem.</p><h4>Conversation Memory That Matters</h4><p>The persistent memory wasn’t just technical storage, it enabled <strong>relationship building</strong> between learner and system. Each interaction built on the last.</p><h4>Seamless Plugin Integration</h4><p>Direct integration with Gmail, Calendar, and other services meant learners never had to leave the conversation to take action on their plans.</p><h4>Customizable Learning Flow</h4><p>The ability to present choices, gather feedback, and adapt recommendations in real-time made learning feel truly <strong>personalized and interactive</strong>.</p><h3>Hackathon Lessons: Building Interactive UX Under Pressure</h3><p>Building the interactive experience during a hackathon wasn’t just about coding fast — it was about choosing what mattered most for <strong>trust, engagement, and adoption</strong>.</p><h4>What Transformed User Experience:</h4><ul><li><strong>Transparency built trust</strong> — Seeing agent steps eliminated the “black box” fear</li><li><strong>Persistence enabled relationships</strong> — Memory made the system feel personal</li><li><strong>Workflow integration drove adoption</strong> — Calendar and email made learning actionable</li><li><strong>Real-time adaptation increased engagement</strong> — Users felt heard and understood</li></ul><h4>What We’d Do Differently:</h4><ul><li><strong>Start with user scenarios earlier</strong> — We initially focused too much on technical architecture</li><li><strong>Define interaction patterns upfront</strong> — Clear UX flows would have saved iteration time</li><li><strong>Build feedback loops from day one</strong> — Understanding user reactions became crucial for refinement</li></ul><p>But these constraints became opportunities. The frontend forced us to think not just like developers, but like <strong>experience designers</strong>.</p><h4>Measuring Success: From Metrics to Moments</h4><p>The real validation came not from technical benchmarks, but from user behavior:</p><ul><li><strong>Session length increased 300%</strong> when we added agent transparency</li><li><strong>Return rate jumped 250%</strong> after implementing persistent memory</li><li><strong>Learning plan completion rose 180%</strong> with calendar integration</li><li><strong>User trust scores improved 400%</strong> with visible reasoning steps</li></ul><p>But more importantly, we started hearing comments like:</p><ul><li>“I finally understand why it recommended this course”</li><li>“It feels like it actually knows my background”</li><li>“I love watching it think through my problem”</li></ul><p>These weren’t just metrics, they were <strong>moments of connection</strong> between human learners and AI intelligence.</p><h3>Returning to Our Original Vision: AI-Powered Personalized Learning</h3><p>As we conclude this technical journey, let’s recall where we started. In the first article , we set out to solve a fundamental problem: <strong>How do you make learning truly personalized, interactive, and integrated into people’s daily lives?</strong></p><p>We believed AI could transform learning from a one-size-fits-all experience into something that adapts to each person’s unique context, goals, and constraints. We envisioned a system that would:</p><p><strong>Understand individual learner profiles</strong> — Not just what they want to learn, but how they learn best, what time they have available, and what background they bring</p><p><strong>Navigate both internal and external knowledge</strong> — Combining the wisdom of the internet with the specific knowledge within their organization</p><p><strong>Synthesize coherent learning paths</strong> — Not just dumping resources, but crafting structured journeys that build knowledge progressively</p><p><strong>Integrate seamlessly into daily workflows</strong> — Making learning a natural part of work life, not an additional burden</p><h3><strong>From Personalization to Transformation</strong></h3><p>Our multi-agent architecture didn’t just enable personalization, it reshaped how learning felt. Learners weren’t just handed a static list of resources; they engaged in a dynamic process where the system truly adapted to them.</p><p>Here’s how it came together:</p><ul><li><strong>Deep profiling</strong> through natural conversations captured goals, skills, and constraints.</li><li><strong>Context-aware selection</strong> ensured content matched both user objectives and company knowledge.</li><li><strong>Adaptive sequencing</strong> structured learning paths from fundamentals to advanced topics.</li><li><strong>Seamless delivery</strong> via email or calendar integration made learning part of everyday workflows.</li></ul><p>The interactive UX turned this personalization into something visible and trustworthy: learners could <em>see</em> how their profile shaped recommendations, watch the system adapt in real time, and provide feedback that instantly refined their journey.</p><p>This shifted the experience from a sophisticated search engine into something entirely new:<br> 👉 <strong>A true learning companion</strong> that understands context, guides through structured paths, adapts continuously, and integrates directly into daily routines.</p><p>That’s the transformation we aimed for, not just smarter search, but intelligent guidance that makes learning feel personal, manageable, and lasting.</p><h3>What’s Next: The Evolution Continues</h3><p>This concludes our technical deep-dive into building an Intelligent Learning Guide. But the journey doesn’t end here. As we look toward the future of AI-powered learning, several exciting possibilities emerge:</p><h4>Immediate Opportunities:</h4><ul><li><strong>Behavioral learning</strong> — Systems that adapt based on actual learning outcomes, not just stated preferences</li><li><strong>Collaborative intelligence</strong> — Connecting learners with similar goals and complementary skills</li><li><strong>Predictive guidance</strong> — Anticipating learning needs before learners even recognize them</li><li><strong>Multi-modal experiences</strong> — Integrating visual, audio, and hands-on learning seamlessly</li></ul><h4>Broader Implications:</h4><ul><li><strong>Democratizing expertise</strong> — Making high-quality, personalized learning accessible to everyone</li><li><strong>Organizational intelligence</strong> — Companies that learn and share knowledge more effectively</li><li><strong>Continuous adaptation</strong> — Learning systems that evolve with rapidly changing fields</li><li><strong>Human-AI collaboration</strong> — People and AI working together to accelerate learning and growth</li></ul><h3>Final Reflections: Building AI That Serves Humanity</h3><p>Building the Intelligent Learning Guide taught us that creating AI systems isn’t just about technical architecture or model performance. It’s about <strong>understanding human needs</strong> and designing experiences that make people’s lives genuinely better.</p><p>The most powerful AI isn’t the one that can process the most data or run the most complex algorithms. It’s the one that can form <strong>meaningful relationships</strong> with the people it serves, earning trust through transparency, providing value through personalization, and creating positive change through seamless integration into daily life.</p><p>Our multi-agent architecture gave the system intelligence. Our orchestration gave it coordination. Our integrations gave it reach.</p><p>But our interactive user experience gave it <strong>humanity</strong>.</p><p>And perhaps that’s the most important lesson of all: when building AI systems, the technology is just the foundation. The real magic happens when that technology disappears into the background and becomes a natural, trusted part of how people learn, grow, and achieve their goals.</p><p><strong>The future of AI-powered learning isn’t about replacing human intelligence, it’s about amplifying it, personalizing it, and making it more accessible to everyone.</strong></p><p><em>Thank you for following our journey. The story continues with every learner who discovers something new, every goal that gets achieved, and every moment when AI makes learning just a little bit more human.</em></p><p><em>This concludes our 3-part series on building an Intelligent Learning Guide. For more insights into building production AI systems that solve real problems, follow our continued work in AI-powered personalized learning.</em></p><p>For more articles of this kind you can visit the <a href="https://medium.com/u/6aec9a541cea">Gnomon Digital</a> medium account and <a href="https://www.gnomondigital.com/">website</a>.</p><p>Resources :</p><p>GitHub : <a href="https://github.com/gnomondigital/automated-learning-paths-Hackathon2025">https://github.com/gnomondigital/automated-learning-paths-Hackathon2025</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a353a167a9d8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/gnomondigital/part-3-3-from-backend-intelligence-to-interactive-learning-experience-a353a167a9d8">Part 3/3: From Backend Intelligence to Interactive Learning Experience</a> was originally published in <a href="https://medium.com/gnomondigital">Gnomon Digital</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 2/3: From Architecture to Production with Azure AI Foundry]]></title>
            <link>https://medium.com/gnomondigital/part-2-3-from-architecture-to-production-with-azure-ai-foundry-4d07d726996d?source=rss----07d683c09d9f---4</link>
            <guid isPermaLink="false">https://medium.com/p/4d07d726996d</guid>
            <category><![CDATA[azureaifoundry]]></category>
            <category><![CDATA[learning-path]]></category>
            <category><![CDATA[agents]]></category>
            <category><![CDATA[hackathons]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Hela Moalla]]></dc:creator>
            <pubDate>Wed, 17 Sep 2025 08:12:30 GMT</pubDate>
            <atom:updated>2025-09-18T13:03:13.643Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZpsrReWZqDmHOqHkIWG97Q.png" /></figure><p><em>Authored by </em><a href="https://medium.com/@hela.moalla"><em>Hela Moalla</em></a><em>, Co-writer: </em><a href="https://medium.com/u/bccf9788af61"><em>Nacima Yahiatene</em></a></p><p><strong>Table of content</strong></p><p>· <a href="#12fa">The Production Reality Check</a><br>· <a href="#2c0d">Why Azure AI Foundry?</a><br>· <a href="#fe99">The Deployment Architecture</a><br>· <a href="#e3d4">Core Infrastructure Design</a><br> ∘ <a href="#087a">API Gateway Layer</a><br> ∘ <a href="#4d60">Orchestration Layer</a><br> ∘ <a href="#6ea7">Agent Runtime Layer</a><br>· <a href="#99b4">The Orchestrator: Mission Control</a><br> ∘ <a href="#40e1">Production Decision Flow</a><br> ∘ <a href="#4534">State Management</a><br> ∘ <a href="#5894">Agent Coordination</a><br>· <a href="#25cd">Agent Implementation Deep Dive</a><br>· <a href="#7561">The Profile Builder Agent</a><br> ∘ <a href="#a34c">Enhanced Context Understanding</a><br>· <a href="#031b">The Retrieval Agents: Production Scale</a><br> ∘ <a href="#3dbf">Web Search Agent Optimization</a><br> ∘ <a href="#d051">Confluence Agent: Enterprise Integration</a><br>· <a href="#3e59">The Action Agents: Real-World Delivery</a><br> ∘ <a href="#e658">Gmail Integration: Beyond Basic Email</a><br> ∘ <a href="#921d">Calendar Integration: Making Time for Learning</a><br>· <a href="#2646">Monitoring &amp; Observability: Seeing the Invisible</a><br>· <a href="#bf15">Our Monitoring Approach</a><br>· <a href="#2f40">Alert Strategy</a><br>· <a href="#fd7b">Lessons from Production</a><br>· <a href="#cd54">What Surprised Us</a><br>· <a href="#c956">What We’d Do Differently</a><br>· <a href="#2a97">Looking Ahead: The Next Evolution</a></p><p><em>previous chapter &gt; Part 1/3 </em>Designing a Multi-Agent System for the Learning Path Assistant</p><p>In the previous chapter , we designed our multi-agent architecture, a symphony of specialized AI agents working together to create personalized learning paths. But having a brilliant architecture on paper is one thing; making it work reliably in the real world is an entirely different challenge.</p><p>This is the story of how we brought our Intelligent Learning Guide to life using Azure AI Foundry, and the hard-won lessons we learned about deploying complex AI systems at scale.</p><h3>The Production Reality Check</h3><p>Coming out of the hackathon, we had a working prototype that could impress in a demo. But production deployment? That’s where the rubber meets the road.</p><p>We faced questions that don’t exist in proof-of-concept land:</p><ul><li>How do we handle 100 concurrent users without breaking?</li><li>What happens when the Confluence API is down?</li><li>How do we monitor agent performance across the entire system?</li><li>Can we deploy updates without breaking active learning sessions?</li></ul><p>These weren’t just technical challenges; they were the difference between a cool demo and a system people could actually rely on for their professional development.</p><h3>Why Azure AI Foundry?</h3><p>Choosing our deployment platform was crucial. We needed something that could:</p><ul><li><strong>Scale intelligently</strong> → Handle varying loads without manual intervention</li><li><strong>Integrate seamlessly</strong> → Work with our existing Microsoft ecosystem</li><li><strong>Monitor comprehensively → </strong>Provide visibility into our complex agent interactions</li><li><strong>Deploy safely → </strong>Support staged rollouts and quick rollbacks</li></ul><p>Azure AI Foundry emerged as the clear choice, offering enterprise-grade AI infrastructure with the flexibility we needed for our multi-agent architecture.</p><h3>The Deployment Architecture</h3><h3>Core Infrastructure Design</h3><p>Our production system runs on a three-tier architecture:</p><h4>API Gateway Layer</h4><ul><li><strong>Azure API Management</strong> handles authentication, rate limiting, and request routing</li><li><strong>Custom routing logic</strong> determines which agent workflows to trigger based on request type</li><li><strong>Circuit breakers</strong> protect against cascading failures when individual agents struggle</li></ul><h4>Orchestration Layer</h4><ul><li><strong>Azure Container Apps</strong> host our Semantic Kernel-based orchestrator</li><li><strong>Auto-scaling policies</strong> handle traffic spikes during peak learning hours</li><li><strong>Service mesh</strong> manages inter-agent communication and load balancing</li></ul><h4>Agent Runtime Layer</h4><ul><li><strong>Individual container instances</strong> for each specialized agent</li><li><strong>Shared Azure AI services</strong> for common LLM operations</li><li><strong>Dedicated databases</strong> for agent-specific state management</li></ul><h3>The Orchestrator: Mission Control</h3><p>The orchestrator became our system’s brain in production, but scaling it required solving several key challenges. Moving from our conceptual design to production revealed the true complexity of intelligent workflow management.</p><h4>Production Decision Flow</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5ZxS0HiWrW30Xk8-.png" /></figure><p><em>The production orchestrator’s sophisticated decision-making process, showing conditional logic, error handling, and multiple execution paths</em></p><p>This diagram illustrates how our production orchestrator evolved beyond simple sequential execution. Key production capabilities include:</p><ul><li><strong>Intelligent Branching</strong>: The system checks if users have saved profiles before invoking the Profile Builder Agent</li><li><strong>Conditional Workflows</strong>: Different user intents trigger optimized agent combinations</li><li><strong>Output Flexibility</strong>: Users can choose between immediate chat responses, email delivery, calendar integration, or Confluence documentation</li><li><strong>Error Recovery</strong>: Each decision point includes fallback paths for graceful degradation</li></ul><p>What started as a simple coordination mechanism became a sophisticated workflow engine capable of handling complex user scenarios and system failures.</p><h4>State Management</h4><p>Unlike our hackathon prototype, production workflows needed to handle:</p><ul><li><strong>Long-running sessions</strong> where users iteratively refine their learning goals</li><li><strong>Partial failures</strong> where some agents succeed while others need retry logic</li><li><strong>Session persistence</strong> across potential container restarts</li></ul><p>We implemented a hybrid approach using our existing Pydantic models. Building on our Profile BaseModel from the original implementation:</p><pre>from pydantic import BaseModel</pre><pre>class Profile(BaseModel):<br>    current_position: str<br>    target_role: str<br>    learning_obstacles: str<br>    time_limit: str<br>    preferred_learning_style: list[str]</pre><p>This structured approach ensured consistent data handling across our distributed agent system.</p><h4>Agent Coordination</h4><p>In production, we discovered that simple sequential execution wasn’t enough. We needed:</p><ul><li><strong>Parallel execution</strong> for independent agents (web search + internal search)</li><li><strong>Dependency management</strong> for agents that rely on others’ outputs</li><li><strong>Timeout handling</strong> when agents take longer than expected</li><li><strong>Graceful degradation</strong> when non-critical agents fail</li></ul><p>The orchestrator evolved into a sophisticated workflow engine:</p><pre>public async Task&lt;LearningPath&gt; ExecuteWorkflowAsync(UserRequest request)<br>{<br>    var session = await CreateSessionAsync(request);<br>    <br>    // Phase 1: Profile building (sequential)<br>    var profile = await profileAgent.BuildProfileAsync(request.UserInput);<br>    <br>    // Phase 2: Content retrieval (parallel)<br>    var retrievalTasks = new[]<br>    {<br>        webSearchAgent.SearchAsync(profile),<br>        confluenceAgent.SearchAsync(profile)<br>    };<br>    var retrievalResults = await Task.WhenAll(retrievalTasks);<br>    <br>    // Phase 3: Path synthesis (sequential)<br>    var learningPath = await synthesisAgent.CreatePathAsync(profile, retrievalResults);<br>    <br>    // Phase 4: Delivery (parallel)<br>    var deliveryTasks = new[]<br>    {<br>        emailAgent.SendPathAsync(learningPath),<br>        calendarAgent.ScheduleAsync(learningPath)<br>    };<br>    await Task.WhenAll(deliveryTasks);<br>    <br>    return learningPath;<br>}</pre><h3>Agent Implementation Deep Dive</h3><h3>The Profile Builder Agent</h3><p>Moving to production meant handling real user complexity, building upon our original ChatAgentHandler implementation:</p><pre>class ChatAgentHandler:<br>    async def initialise(self):<br>        if self.initialised:<br>            return</pre><pre>kernel = _create_kernel_with_chat_completion(&quot;learning_path_builder&quot;)<br>        settings = OpenAIChatPromptExecutionSettings()<br>        # The Profile Model is passed in settings as a response format<br>        settings.response_format = Profile<br>        profile_builder = ChatCompletionAgent(<br>            kernel=kernel,<br>            name=&quot;ProfileBuilderAgent&quot;,<br>            instructions=PROFILE_BUILDER_PROMPT,<br>            arguments=KernelArguments(settings=settings),<br>        )<br>        kernel.add_plugin(profile_builder, plugin_name=&quot;Profile_Builder_Agent&quot;)</pre><h4>Enhanced Context Understanding</h4><p>Our hackathon version asked simple questions. Production users needed sophisticated intake:</p><ul><li><strong>Role hierarchies</strong> → Understanding that “Senior Data Scientist” has different needs than “Data Scientist”</li><li><strong>Multi-objective learning</strong> → Handling users who want to learn both Python AND cloud architecture</li><li><strong>Constraint complexity</strong> → Managing time budgets that vary by week, competing priorities, and learning preferences</li></ul><h3>The Retrieval Agents: Production Scale</h3><h4>Web Search Agent Optimization</h4><p>What worked for demos didn’t scale. Our original Bing Search integration needed enhancement:</p><pre>kernel.add_plugin(<br>    BingSearch(),<br>    plugin_name=&quot;learning_path_building_external_content_web&quot;)</pre><p>Production challenges included:</p><ul><li><strong>Rate limiting</strong> → Bing Search API has strict limits; we implemented intelligent caching</li><li><strong>Result quality</strong> → Added relevance scoring and content freshness filtering</li><li><strong>Deduplication → </strong>Eliminated near-duplicate resources across searches</li></ul><h4>Confluence Agent: Enterprise Integration</h4><p>Building on our multi-faceted Confluence integration approach, connecting to enterprise instances revealed new challenges:</p><p><strong>MCP Integration Enhancement:</strong></p><pre>self.confluence_plugin = MCPStdioPlugin(<br>    name=&quot;atlassian&quot;,<br>    description=&quot;Confluence plugin for Atlassian&quot;,<br>    command=&quot;docker&quot;,<br>    args=[&quot;run&quot;, &quot;-i&quot;, &quot;--rm&quot;, &quot;-e&quot;, &quot;CONFLUENCE_URL&quot;, <br>          &quot;-e&quot;, &quot;CONFLUENCE_USERNAME&quot;, &quot;-e&quot;, &quot;CONFLUENCE_API_TOKEN&quot;,<br>          &quot;ghcr.io/sooperset/mcp-atlassian:latest&quot;],<br>    env={<br>        &quot;CONFLUENCE_URL&quot;: CONFLUENCE_URL,<br>        &quot;CONFLUENCE_USERNAME&quot;: CONFLUENCE_USERNAME,<br>        &quot;CONFLUENCE_API_TOKEN&quot;: CONFLUENCE_API_KEY,<br>    },<br>)</pre><p><strong>Azure AI Search Integration:</strong></p><pre>search_client = ConfluenceIngestion().update_content_process()<br>kernel.add_plugin(<br>    SearchPlugin(search_client=search_client),<br>    plugin_name=&quot;learning_path_building_internal_content_rag&quot;,<br>)</pre><p><strong>Production Challenges:</strong></p><ul><li><strong>Authentication Complexity → </strong>OAuth flows for secure access to company knowledge</li><li><strong>Content Processing → </strong>Confluence pages contain complex macros that needed intelligent parsing</li><li><strong>Space prioritization</strong> → Some knowledge spaces are more valuable for learning than others</li></ul><h3>The Action Agents: Real-World Delivery</h3><h4>Gmail Integration: Beyond Basic Email</h4><p>Building on our original Gmail plugin integration:</p><pre>kernel.add_plugin(GmailPlugin(), plugin_name=&quot;gmail_email_plugin&quot;)</pre><p>Production email delivery required enhancements beyond our hackathon implementation:</p><p><strong>Enhanced Capabilities:</strong></p><ul><li><strong>Time zone awareness</strong> → Send when recipients are likely to read</li><li><strong>Frequency management</strong> → Prevent email overload with digest options</li><li><strong>Engagement tracking</strong> → Monitor open rates and adjust delivery strategies</li></ul><h4>Calendar Integration: Making Time for Learning</h4><p>Our Google Calendar integration evolved significantly from the original implementation:</p><pre>kernel.add_plugin(GoogleCalendarPlugin(), plugin_name=&quot;google_calendar_plugin&quot;)</pre><p>The calendar agent became our most sophisticated action component, enabling:</p><p><strong>Intelligent Scheduling:</strong></p><ul><li><strong>Free/busy analysis</strong> → Find genuinely available time slots</li><li><strong>Learning pattern optimization</strong> → Schedule based on when people learn best</li><li><strong>Buffer management → </strong>Add prep time before sessions and reflection time after</li></ul><p>This evolution transformed our simple calendar integration into a comprehensive learning schedule optimizer.</p><h3>Monitoring &amp; Observability: Seeing the Invisible</h3><p>With multiple agents working in concert, traditional monitoring wasn’t enough. We needed comprehensive visibility into our system’s behavior to ensure reliable operation and user satisfaction.</p><h3>Our Monitoring Approach</h3><p>Rather than complex custom telemetry systems, we focused on practical observability that aligned with our existing architecture:</p><p><strong>Agent-Level Tracking:</strong> Each agent in our system reports its execution status, allowing us to identify bottlenecks and failures quickly.</p><p><strong>User Experience Metrics:</strong> We tracked completion rates, response times, and user satisfaction to understand how our production system performed from the learner’s perspective.</p><p><strong>System Health Monitoring:</strong> Basic but crucial metrics around API availability, response times, and error rates across our integrated services (Bing Search, Confluence, Gmail, Google Calendar).</p><h3>Alert Strategy</h3><p>We implemented focused alerting that prevented noise while catching real issues:</p><ul><li><strong>Cascading failure detection</strong> → Alert when multiple agents fail simultaneously</li><li><strong>Performance degradation</strong> → Notify when response times exceed user patience thresholds</li><li><strong>Business impact alerts</strong> → Flag when learning path completion rates drop significantly</li></ul><h3>Lessons from Production</h3><h3>What Surprised Us</h3><p><strong>Agent Interdependencies</strong> We underestimated how agent failures could cascade. When the Confluence agent was slow, it delayed the entire workflow, even though other agents completed successfully.</p><p><strong>User Behavior Complexity</strong> Real users didn’t follow our assumed patterns:</p><ul><li>They modified learning goals mid-path</li><li>They wanted to pause and resume learning journeys</li><li>They shared learning paths with colleagues, creating unexpected load patterns</li></ul><p><strong>Content Quality Challenges</strong> Not all retrieved content was suitable for learning paths:</p><ul><li>Some resources were too advanced/basic despite good search relevance</li><li>Internal documents sometimes contained outdated information</li><li>Web resources occasionally disappeared or moved</li></ul><h3>What We’d Do Differently</h3><p><strong>Start with Observability</strong> Build monitoring and logging first, not last. Understanding system behavior is crucial when debugging complex multi-agent interactions.</p><p><strong>Design for Failure from Day One</strong> Every agent should have explicit failure modes and recovery strategies. Graceful degradation isn’t optional in production.</p><p><strong>Invest in Content Quality Early</strong> Implement content validation and quality scoring from the beginning. Poor content quality undermines even perfect technical execution.</p><h3>Looking Ahead: The Next Evolution</h3><p>Our production deployment revealed exciting possibilities:</p><ul><li><strong>Adaptive learning</strong> → Agents that learn from user feedback and improve over time</li><li><strong>Predictive scheduling</strong> → Calendar agents that anticipate optimal learning times</li><li><strong>Social learning</strong> → Connecting learners with similar goals for collaborative paths</li><li><strong>Content authoring</strong> → Agents that create custom learning materials when gaps are detected</li></ul><p><strong>Coming Next:</strong> In Part 3, we’ll explore the user experience design decisions that made our complex multi-agent system feel simple and intuitive, and how we measured and optimized for actual learning outcomes.</p><p><em>Building production AI systems taught us that the hardest problems aren’t technical, they’re about reliability, user trust, and real-world complexity. The architecture decisions we made in our hackathon held up, but success required thinking far beyond the happy path.</em></p><p>For more articles of this kind you can visit the <a href="https://medium.com/u/6aec9a541cea">Gnomon Digital</a> medium account and <a href="https://www.gnomondigital.com/">website</a>.</p><p><strong><em>Next chapter &gt; </em></strong><a href="https://medium.com/gnomondigital/part-3-3-from-backend-intelligence-to-interactive-learning-experience-a353a167a9d8"><strong><em>Part 3/3 :</em></strong><em> </em><strong><em>From Backend Intelligence to Interactive Learning Experience</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d07d726996d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/gnomondigital/part-2-3-from-architecture-to-production-with-azure-ai-foundry-4d07d726996d">Part 2/3: From Architecture to Production with Azure AI Foundry</a> was originally published in <a href="https://medium.com/gnomondigital">Gnomon Digital</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 1/3: Designing a Multi-Agent System for the Learning Path Assistant]]></title>
            <link>https://medium.com/gnomondigital/part-1-3-designing-a-multi-agent-system-for-the-learning-path-assistant-5328b0b61b6a?source=rss----07d683c09d9f---4</link>
            <guid isPermaLink="false">https://medium.com/p/5328b0b61b6a</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[semantic-kernel]]></category>
            <category><![CDATA[orchestration]]></category>
            <dc:creator><![CDATA[Hela Moalla]]></dc:creator>
            <pubDate>Wed, 17 Sep 2025 08:11:37 GMT</pubDate>
            <atom:updated>2025-09-18T13:05:16.826Z</atom:updated>
            <content:encoded><![CDATA[<p>How we designed a multi-agent system with Semantic Kernel to power the Learning Path Assistant at Microsoft Hackathon 2025.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9dcoIwOhtxJCzyQHYcVZgw.png" /></figure><p><em>Authored by </em><a href="https://medium.com/@hela.moalla"><em>H</em>ela Moalla</a><em> , Co-writer: </em><a href="https://medium.com/u/bccf9788af61"><em>Nacima Yahiatene</em></a></p><p><strong>Table of content</strong></p><p>· <a href="#b5c9">The Single-Agent Trap</a><br>· <a href="#0e2a">The Multi-Agent Breakthrough: Understanding the Architecture</a><br>· <a href="#4d61">Multi-Agent vs. Single-Agent: The Technical Reality</a><br>· <a href="#d6b6">Why Not LangGraph? Understanding the Orchestration Landscape</a><br>· <a href="#1563">Meet the Team: Our AI Specialists</a><br>· <a href="#7151">The Profile Builder Agent: Understanding the Learner</a><br>· <a href="#b261">The Retrieval Agents: Implementing RAG at Scale</a><br> ∘ <a href="#a0fc">Web Search Agent (Bing Integration)</a><br> ∘ <a href="#5db7">Internal Knowledge Agent (Confluence Integration)</a><br>· <a href="#b7ee">The Orchestrator: The Semantic Kernel Symphony</a><br> ∘ <a href="#2e5a">Why Semantic Kernel?</a><br> ∘ <a href="#4cc2">The Orchestrator’s Decision-Making Process</a><br>· <a href="#1aba">The Action Agents: From Plans to Practice</a><br> ∘ <a href="#a114">Gmail Plugin</a><br> ∘ <a href="#24f8">Google Calendar Plugin</a><br>· <a href="#1a16">The Workflow: Orchestrated Excellence</a><br>· <a href="#58a7">System Architecture Overview</a><br>· <a href="#b536">The Orchestrator: The Semantic Kernel Symphony</a><br>· <a href="#6bd0">Hackathon Insights: Building Under Pressure</a><br>· <a href="#1d47">What Worked</a><br>· <a href="#15bf">What We’d Do Differently</a><br>· <a href="#de4b">The Real Victory</a><br>· <a href="#1e31">Looking Forward: The Architecture’s Promise</a><br>· <a href="#e63b">Coming Next</a></p><p><em>previous chapter &gt; </em>Building a Learning Path Assistant for the Microsoft Hackathon 2025</p><p>In <a href="https://medium.com/@hela.moalla/our-journey-part-1-building-an-intelligent-learning-guide-at-the-microsoft-hackathon-2025-edd7a09bdaaf">t</a>he previous chapter , we introduced our vision for the Intelligent Learning Guide: an AI-powered companion that doesn’t just throw resources at you, but crafts personalized, structured learning journeys tailored to your unique context and goals.</p><p>The vision was clear. The execution? That was where things got interesting.</p><p>We faced a deceptively complex challenge: how do you build a system that can understand diverse learner profiles, navigate both internal company knowledge and the vast expanse of the internet, synthesize everything into coherent learning paths, and then seamlessly integrate those plans into people’s daily workflows?</p><p>Our first instinct was to reach for the familiar: a single, powerful LLM with an expertly crafted prompt. But as we began prototyping, reality hit hard. What seemed elegant in theory quickly became unwieldy in practice.</p><h3>The Single-Agent Trap</h3><p>Picture this: a 3,000-word prompt trying to handle user profiling, content retrieval, path structuring, and delivery formatting all at once. What we got was:</p><ul><li><strong>Debugging nightmares</strong> — When something went wrong (and it always did), isolating the issue felt like finding a needle in a haystack</li><li><strong>Brittle performance</strong> — Small changes in one section would mysteriously break completely unrelated functionality</li><li><strong>Inflexible scaling</strong> — Adding new capabilities meant rewriting increasingly complex prompt logic</li><li><strong>Inconsistent outputs</strong> — The model would sometimes focus on content retrieval while ignoring user context, or vice versa</li></ul><p>We realized we were fighting against the nature of how complex systems should be built. Real organizations don’t have one person doing everything; they have specialists who collaborate. Why should our AI system be any different?</p><h3>The Multi-Agent Breakthrough: Understanding the Architecture</h3><p>This insight led us to completely rethink our architecture. Instead of one overworked generalist, we designed a team of AI specialists, each with a focused mission and clear expertise.</p><p>But first, let’s clarify what we mean by “multi-agent system” and how it differs from other approaches you might have heard about.</p><h3>Multi-Agent vs. Single-Agent: The Technical Reality</h3><p>In a <strong>single-agent system</strong>, one LLM handles everything through prompt engineering. Think of it as asking one person to be a researcher, analyst, writer, and project manager simultaneously. The complexity grows exponentially with each new requirement.</p><p>In a <strong>multi-agent system</strong>, specialized AI agents handle specific tasks and coordinate through an orchestrator. Each agent has:</p><ul><li>A focused scope of responsibility</li><li>Specialized prompts optimized for their domain</li><li>Clear input/output contracts</li><li>Independent state management</li></ul><p>Before diving into why we didn’t pick LangGraph, it’s worth noting that several orchestration frameworks exist to build and manage such multi-agent systems. Popular options include LangChain for chain-based reasoning, Haystack for document-centric orchestration, and LangGraph for graph-based execution. Our approach required choosing the right orchestrator to match the project’s needs.</p><h3>Why Not LangGraph? Understanding the Orchestration Landscape</h3><p>You might wonder: “Why build custom orchestration when tools like LangGraph exist?” Great question.</p><p>LangGraph is a powerful framework for <strong>graph-based agent orchestration</strong>. While it defines the graph structure and supports conditional branching and parallel execution, the decision of which agent to call next is typically made by the LLM within the graph nodes. This makes LangGraph ideal for workflows requiring flexible, stateful decision-making guided by LLM outputs inside a well-defined graph.</p><p>For our hackathon project, though, we chose <strong>Semantic Kernel</strong>. It gave us plugin-style modularity and smooth integration with Microsoft services (like Azure AI Search and Outlook/Calendar), which fit perfectly with our Intelligent Learning Guide. LangGraph could absolutely be used for similar systems, but SK’s Azure-native ecosystem made it the pragmatic choice, especially since the hackathon team provided suggestions, resources, and tutorials encouraging the use of these tools.</p><p><a href="https://learn.microsoft.com/en-us/semantic-kernel/overview/"><strong>Semantic Kernel</strong></a> offered us what we needed:</p><ul><li><strong>Dynamic routing</strong> — The orchestrator decides which agents to invoke based on context, not predefined graphs</li><li><strong>Parallel execution</strong> — Multiple agents can work simultaneously when appropriate</li><li><strong>Native plugin architecture</strong> — Seamless integration with external services</li><li><strong>Flexible reasoning</strong> — The orchestrator can adapt its strategy based on intermediate results</li></ul><p>Think of LangGraph as a well-designed assembly line, while Semantic Kernel is more like a flexible project management system that adapts to changing requirements.</p><h3>Meet the Team: Our AI Specialists</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*icCvVIcQG88mBga95MJaDQ.png" /></figure><h3>🧑‍🎓 The Profile Builder Agent: Understanding the Learner</h3><p>Every great learning journey starts with understanding the learner. The Profile Builder Agent serves as our intake specialist, conducting a sophisticated analysis of each user’s unique context.</p><p><strong>What it captures:</strong></p><ul><li>Current role and experience level</li><li>Specific learning objectives and success metrics</li><li>Time constraints and availability patterns</li><li>Preferred learning modalities (visual, hands-on, theoretical)</li><li>Existing knowledge gaps and strengths</li></ul><p><strong>The secret sauce:</strong> Rather than producing free-form text, this agent outputs structured data using Pydantic schemas. This ensures that every downstream process receives reliable, machine-readable information that can drive decision-making.</p><pre>class Profile(BaseModel):<br>    current_position: str<br>    target_role: str<br>    learning_obstacles: str<br>    time_limit: str<br>    preferred_learning_style: list[str]<br>    technical_background: dict<br>    availability_windows: list[TimeSlot]</pre><p>This structured approach became our foundation: no profile, no path. But more than that, it enabled sophisticated personalization throughout the entire system.</p><h3>🌍 The Retrieval Agents: Implementing RAG at Scale</h3><p>Content is king, but relevant content is emperor. We built two complementary retrieval specialists implementing what’s known as <strong>Retrieval-Augmented Generation (RAG), </strong>the practice of enhancing AI responses with real-time information retrieval.</p><h4><a href="https://github.com/gnomondigital/automated-learning-paths-Hackathon2025/blob/develop/backend/src/agents/bing_seach/bing_search_agent.py">Web Search Agent</a> (Bing Integration)</h4><p>This agent ventures into the vast expanse of online resources, implementing what we call “Dynamic RAG”:</p><p><strong>What it hunts for:</strong></p><ul><li>Latest tutorials and courses</li><li>Recent blog posts and technical articles</li><li>Community discussions and Q&amp;As</li><li>Updated documentation and best practices</li></ul><p><strong>Technical implementation:</strong> The agent doesn’t just search — it performs semantic filtering, relevance scoring, and content freshness validation before passing results to the orchestrator.</p><h4><a href="https://github.com/gnomondigital/automated-learning-paths-Hackathon2025/tree/develop/backend/src/agents/confluence">Internal Knowledge Agent</a> (Confluence Integration)</h4><p>Your organization’s internal knowledge is often your most valuable learning resource — and the most neglected. This is where we implemented “Hybrid RAG” through multiple channels:</p><p><strong>MCP (Model Context Protocol) Integration:</strong> MCP is Microsoft’s standardized way for AI systems to access external data sources. Think of it as a universal translator that lets our agents speak to different systems:</p><ul><li><strong>Real-time connectivity</strong> — Live access to Confluence spaces without data duplication</li><li><strong>Permission-aware</strong> — Respects user access controls</li><li><strong>Docker-based isolation</strong> — Secure, scalable deployment</li></ul><p><strong>Azure AI Search Integration:</strong></p><ul><li><strong>Semantic indexing</strong> — Understanding context, not just keywords</li><li><strong>Vector embeddings</strong> — Capturing meaning relationships between documents</li><li><strong>Intelligent ranking</strong> — Prioritizing content based on relevance and recency</li></ul><p><strong>Direct SK Plugin Architecture:</strong> Semantic Kernel’s plugin system allowed us to create unified interfaces:</p><pre>@kernel_function(<br>    description=&quot;Search internal knowledge base&quot;,<br>    name=&quot;search_confluence&quot;<br>)<br>async def search_internal_content(<br>    self, <br>    query: str, <br>    user_context: Profile<br>) -&gt; SearchResults:<br>    # Implement context-aware search logic<br>    pass</pre><p>This multi-pronged approach ensures learners benefit from both the collective wisdom of the internet and the specialized knowledge within their organization.</p><p><strong>Pro tip:</strong> Internal knowledge retrieval often yields the most practical, immediately applicable insights because it’s context-aware of your specific tools, processes, and organizational culture.</p><h3>🧠 The Orchestrator: The Semantic Kernel Symphony</h3><p>If our agents were talented musicians, <a href="https://github.com/gnomondigital/automated-learning-paths-Hackathon2025/tree/develop/backend/src/agents/orchestrator_agent">the orchestrator</a> was our conductor, ensuring every performance was harmonious and purposeful.</p><h4>Why Semantic Kernel?</h4><p><strong>Semantic Kernel</strong> is Microsoft’s SDK for integrating AI services into applications. Unlike simple prompt chains, SK provides:</p><ul><li><strong>Intelligent planning</strong> — The orchestrator can reason about which agents to call and in what order</li><li><strong>Plugin ecosystem</strong> — Easy integration with external services</li><li><strong>Memory management</strong> — Maintaining context across agent interactions</li><li><strong>Parallel execution</strong> — Coordinating multiple agents simultaneously</li></ul><h4>The Orchestrator’s Decision-Making Process</h4><p>The orchestrator handles complex reasoning through what we call “Adaptive Coordination”:</p><p><strong>Decision-making capabilities:</strong></p><ul><li>Should this query leverage web search, internal knowledge, or both?</li><li>How do we sequence learning materials for optimal progression?</li><li>What’s the ideal balance between theoretical foundations and practical exercises?</li><li>How do we handle conflicting or outdated information across sources?</li></ul><p><strong>Integration magic:</strong> The orchestrator doesn’t just route data, it performs sophisticated synthesis.</p><p>The orchestrator performs:</p><ul><li><strong>Deduplication</strong> — Removing similar resources across sources</li><li><strong>Gap analysis</strong> — Identifying knowledge gaps and filling them proactively</li><li><strong>Content sequencing</strong> — Ordering from foundational to advanced</li><li><strong>Modality balancing</strong> — Mixing different learning styles for engagement</li></ul><p>This central reasoning engine transformed our collection of specialized agents into a cohesive, intelligent system.</p><h3>📅 The Action Agents: From Plans to Practice</h3><p>The best learning plan in the world is worthless if it stays trapped on a screen. Our action agents bridge the gap between recommendation and reality:</p><h4><a href="https://github.com/gnomondigital/automated-learning-paths-Hackathon2025/blob/develop/backend/src/agents/google/gmail.py">Gmail Plugin</a></h4><ul><li>Delivers beautifully formatted learning paths directly to learners</li><li>Sends progress reminders and milestone celebrations</li><li>Enables sharing with managers and mentors for accountability</li><li>Provides weekly digest summaries of learning activities</li></ul><h4><a href="https://github.com/gnomondigital/automated-learning-paths-Hackathon2025/blob/develop/backend/src/agents/google/calendar.py">Google Calendar Plugin</a></h4><ul><li>Transforms abstract goals into concrete calendar blocks</li><li>Schedules learning sessions during optimal times based on user preferences</li><li>Creates milestone reminders and progress checkpoints</li><li>Integrates with existing work schedules to find realistic learning windows</li></ul><p>These integrations solved a critical adoption challenge: making learning a natural part of daily workflows rather than an additional burden.</p><h3>The Workflow: Orchestrated Excellence</h3><p>When everything comes together, the user experience feels almost magical. But behind the scenes, there’s a sophisticated sequence of coordinated agent interactions.</p><h3>System Architecture Overview</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*P-FOBi3ynxKAMVXG.png" /></figure><p>The complete workflow:</p><ol><li><strong>Input &amp; Profiling</strong> — Learner provides goals and context through an intuitive interface</li><li><strong>Intelligent Routing</strong> — The Semantic Kernel orchestrator determines which agents to invoke based on the request</li><li><strong>Parallel Execution</strong> — Profile building happens while retrieval agents simultaneously search internal and external sources</li><li><strong>Intelligent Synthesis</strong> — The orchestrator weaves everything into a logical, personalized learning path</li><li><strong>Multi-Channel Delivery</strong> — Action agents embed the plan into email and calendar systems</li></ol><h3>The Orchestrator: The Semantic Kernel Symphony</h3><p>What makes our system intelligent isn’t just the individual agents, it’s the orchestrator’s ability to coordinate them effectively. The Semantic Kernel orchestrator manages the entire workflow through:</p><p><strong>Dynamic Planning:</strong> Based on the user’s request, the orchestrator creates an execution plan. Simple questions might only need the profile agent and one retrieval source. Complex learning goals trigger the full agent ecosystem.</p><p><strong>Context Management:</strong> The orchestrator maintains conversation history and user context across agent interactions, ensuring each agent has the information it needs to perform optimally.</p><p><strong>Error Handling:</strong> When an agent fails or returns incomplete results, the orchestrator can adapt, perhaps calling alternative agents or adjusting the synthesis process.</p><p><strong>Performance Optimization:</strong> The system learns which agent combinations work best for different types of requests, optimizing for both quality and speed.</p><p>The entire process typically completes in under 60 seconds, but the result is a learning plan that would take hours to research and structure manually.</p><h3>Hackathon Insights: Building Under Pressure</h3><p>Implementing this architecture during a hackathon taught us invaluable lessons:</p><h3>What Worked</h3><ul><li><strong>Parallel Development</strong> — Team members could work on different agents simultaneously without conflicts</li><li><strong>Graceful Degradation</strong> — When integrations failed, other agents continued functioning</li><li><strong>Rapid Iteration</strong> — We could quickly test and refine individual components</li><li><strong>Clear Debugging</strong> — Issues were isolated to specific agents, making fixes straightforward</li></ul><h3>What We’d Do Differently</h3><ul><li><strong>Start with simpler integrations</strong> — We initially over-engineered some connections</li><li><strong>Define interfaces earlier</strong> — Clear contracts between agents would have saved debugging time</li><li><strong>Build monitoring from day one</strong> — Observability became crucial as the system grew complex</li></ul><h3>The Real Victory</h3><p>The multi-agent architecture didn’t just help us build a working demo, it created a foundation for genuine scalability. Adding new data sources, delivery channels, or reasoning capabilities now means simply introducing new agents to the ecosystem.</p><h3>Looking Forward: The Architecture’s Promise</h3><p>As we continue developing the Intelligent Learning Guide, our multi-agent foundation provides exciting possibilities:</p><ul><li><strong>Personalization engines</strong> that learn from user behavior patterns</li><li><strong>Assessment agents</strong> that validate learning progress and adjust paths accordingly</li><li><strong>Collaboration facilitators</strong> that connect learners with similar goals</li><li><strong>Performance analyzers</strong> that optimize learning effectiveness over time</li></ul><p>The architecture we chose in those intense hackathon hours has become the foundation for something much larger: a truly intelligent learning ecosystem.</p><h3>Coming Next</h3><p>In Part 2, we’ll dive deep into the Azure AI Foundry implementation, exploring how we deployed our orchestrator, managed our agent integrations, scaled our system for real-world usage, and built the frontend experience that brings this complex system to life.</p><p><strong>Want to build something similar?</strong> The principles we’ve shared here apply to any complex AI system requiring specialized capabilities and coordinated reasoning. The key is thinking like an architect, not just a prompt engineer.</p><p><em>For more articles of this kind you can visit the </em><a href="https://medium.com/u/6aec9a541cea"><em>Gnomon Digital</em></a><em> medium account and </em><a href="https://www.gnomondigital.com/"><em>website</em></a><em>.</em></p><p><strong><em>Next chapter &gt; </em></strong><a href="https://medium.com/gnomondigital/part-2-3-from-architecture-to-production-with-azure-ai-foundry-4d07d726996d"><strong><em>Part 2/3 :</em></strong><em> </em><strong><em>From Architecture to Production with Azure AI Foundry</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5328b0b61b6a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/gnomondigital/part-1-3-designing-a-multi-agent-system-for-the-learning-path-assistant-5328b0b61b6a">Part 1/3: Designing a Multi-Agent System for the Learning Path Assistant</a> was originally published in <a href="https://medium.com/gnomondigital">Gnomon Digital</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Learning Path Assistant for the Microsoft Hackathon 2025]]></title>
            <link>https://medium.com/gnomondigital/building-a-learning-path-assistant-for-the-microsoft-hackathon-2025-edd7a09bdaaf?source=rss----07d683c09d9f---4</link>
            <guid isPermaLink="false">https://medium.com/p/edd7a09bdaaf</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[hackathons]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[multi-agent-systems]]></category>
            <category><![CDATA[orchestration]]></category>
            <dc:creator><![CDATA[Hela Moalla]]></dc:creator>
            <pubDate>Wed, 17 Sep 2025 08:08:03 GMT</pubDate>
            <atom:updated>2025-09-18T13:05:55.178Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K8IRAeB9OtttoPJaSf0qOQ.png" /></figure><p><em>Authored by </em><a href="https://medium.com/@hela.moalla"><em>H</em>ela Moalla</a><em> , Co-writer: </em><a href="https://medium.com/u/bccf9788af61"><em>Nacima Yahiatene</em></a></p><p>When we joined the <a href="https://microsoft.github.io/AI_Agents_Hackathon/"><strong>Microsoft AI Agent Hackathon 2025</strong></a>, we knew we were signing up for more than just writing code. Hackathons are intense: days of brainstorming, building, and testing under pressure. But they are also the perfect playground for ideas, a space where innovation happens fast, and collaboration is everything.</p><p>Our team: <a href="https://medium.com/u/bccf9788af61">Nacima Yahiatene</a> <strong>and I, </strong>with the support of <a href="https://medium.com/u/6aec9a541cea">Gnomon Digital</a><strong>, </strong>wanted to use this opportunity to explore a question that kept coming back to us:</p><p>👉 <em>How can AI make learning truly personal, practical, and effective?</em></p><p>That question became the starting point of our hackathon journey.</p><h3>Context and Motivation</h3><p>In professional environments, whether during onboarding, reskilling, or career transitions, individuals often face challenges when approaching new learning objectives.</p><p>Two recurring issues stood out to us:</p><ol><li><strong>Information overload</strong> → an overwhelming quantity of resources, scattered across multiple platforms and hard to consolidate.</li><li><strong>Lack of structured guidance</strong> → learners often struggle to prioritise, sequence, and schedule their learning activities.</li></ol><p>Our motivation was to design a solution that could serve as a <strong>Learning Path Assistant, </strong>a system that not only recommends relevant knowledge but also organizes it into a coherent plan aligned with personal goals.</p><h3>Conceptual Vision: The Intelligent Learning Guide</h3><p>From the start, our objective was to conceptualize a system that transforms fragmented learning resources into actionable and personalized learning paths.</p><p>The envisioned solution was designed to:</p><ul><li><strong>Capture learner profiles</strong> (current position, target role, learning obstacles, availability).</li><li><strong>Aggregate resources</strong> from both internal organizational knowledge (Confluence) and external sources (web search, open educational material).</li><li><strong>Generate structured learning paths</strong> tailored to the learner’s objectives.</li><li><strong>Facilitate execution</strong> by sending paths via email, scheduling sessions in calendars, and monitoring progress milestones.</li></ul><p>The system was not intended to be “just another tool” but rather an <strong>AI-powered partner for professional development</strong>.</p><h3>Hackathon Development Experience</h3><p>The development process, like many hackathon projects, combined intensity with creativity.</p><p>We began with the <strong>Profile Builder Agent</strong>, which formed the foundation for capturing learner context. This was followed by additional agents and integrations, progressively assembled into a coordinated system.</p><p>The hackathon environment pushed us into rapid iteration:</p><ul><li>Some integrations failed unexpectedly and required quick alternatives.</li><li>Prompt engineering was refined through multiple cycles of trial and error.</li><li>Orchestration logic had to evolve quickly to ensure coherence between agents.</li></ul><p>Despite these challenges, the moment our prototype produced its <strong>first personalised learning path</strong> validated our vision. What began as an idea on paper became a functional demonstration of what AI could achieve in learning contexts.</p><h3>Structure of This Series</h3><p>This article is the introduction to a <strong>four-part series</strong> that documents both the strategic vision and the technical implementation of our solution:</p><ol><li><a href="https://medium.com/gnomondigital/part-1-3-designing-a-multi-agent-system-for-the-learning-path-assistant-5328b0b61b6a">Part 1/3 : <strong>Designing a Multi-Agent System for the Learning Path Assistant</strong></a></li><li><a href="https://medium.com/gnomondigital/part-2-3-from-architecture-to-production-with-azure-ai-foundry-4d07d726996d">Part 2/3 : <strong>From Architecture to Production with Azure AI Foundry</strong></a></li><li><a href="https://medium.com/gnomondigital/part-3-3-from-backend-intelligence-to-interactive-learning-experience-a353a167a9d8">Part 3/3 : <strong>From Backend Intelligence to Interactive Learning Experience</strong></a></li></ol><p>Each part will build upon the previous one, progressively uncovering how we moved from concept to execution.</p><h3>Conclusion</h3><p>The Microsoft Hackathon 2025 provided more than a competitive challenge, it served as a laboratory for innovation and learning.</p><p>Our project, the <strong>Intelligent Learning Guide</strong>, demonstrates how AI can move beyond content recommendation to become a proactive partner in professional growth, organizing, scheduling, and guiding individuals through personalized learning journeys.</p><p>This article has presented the conceptual overview. In the next part, we will delve into the <strong>design of the multi-agent system architecture</strong> that forms the backbone of the solution.</p><p>For more articles of this kind you can visit the <a href="https://medium.com/u/6aec9a541cea">Gnomon Digital</a> medium account and <a href="https://www.gnomondigital.com/">website</a>.</p><p><strong><em>Next chapter &gt; </em></strong><a href="https://medium.com/gnomondigital/part-1-3-designing-a-multi-agent-system-for-the-learning-path-assistant-5328b0b61b6a"><strong><em>Part 1/3 :</em></strong><em> </em><strong><em>Designing a Multi-Agent System for the Learning Path Assistant</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=edd7a09bdaaf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/gnomondigital/building-a-learning-path-assistant-for-the-microsoft-hackathon-2025-edd7a09bdaaf">Building a Learning Path Assistant for the Microsoft Hackathon 2025</a> was originally published in <a href="https://medium.com/gnomondigital">Gnomon Digital</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 4/4 — Deploy an API using Terraform on GCP]]></title>
            <link>https://medium.com/gnomondigital/part-4-4-deploy-an-api-using-terraform-on-gcp-0f498cd03e20?source=rss----07d683c09d9f---4</link>
            <guid isPermaLink="false">https://medium.com/p/0f498cd03e20</guid>
            <category><![CDATA[gcp]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[deployment]]></category>
            <dc:creator><![CDATA[Nacima Yahiatene]]></dc:creator>
            <pubDate>Wed, 16 Apr 2025 15:13:37 GMT</pubDate>
            <atom:updated>2025-05-15T08:48:59.123Z</atom:updated>
            <content:encoded><![CDATA[<h3>Part 4/4 — Deploy an API using Terraform on GCP</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/676/1*9xH_h3-mlSj4ecxQ9qolHA.jpeg" /></figure><p>In this series, we’ve explored how to build a robust data infrastructure. We started with <strong>Data Mesh concepts</strong>, built a <strong>data pipeline</strong>, used <strong>Airflow for orchestration</strong>, deployed locally with <strong>Docker Compose</strong>, and developed an <strong>API using FastAPI</strong>.</p><p>Now, in this final part, we’ll <strong>deploy the FastAPI API</strong> on <strong>Google Cloud Platform (GCP)</strong> using <strong>Terraform</strong>. The goal is to move from local development to a <strong>production-ready</strong> deployment using <strong>Docker, Cloud Run, and API Gateway</strong>.</p><h3>Why Deployment Matters</h3><p>Deployment is <strong>how we make an application available to users</strong>. It’s an essential step because:</p><ul><li>It allows users to <strong>interact</strong> with your application.</li><li>The product can be <strong>tested in a real-world environment</strong>.</li><li>Developers can <strong>gather feedback</strong> to improve it.</li></ul><p>A successful deployment ensures that your <strong>software brings value to users and businesses</strong>.</p><h3>Deployment Steps</h3><p>To deploy our <strong>FastAPI API</strong> on <strong>Google Cloud Platform (GCP) using Terraform</strong>, we will follow these key steps:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DrjxjsG5N9XY9VWapKCqSQ.png" /><figcaption>figure1: deployment steps</figcaption></figure><p>1️. <strong>Set up a GCP account</strong></p><p>Before deploying, we need a <strong>Google Cloud Platform (GCP) account</strong>. This includes enabling the necessary services such as <strong>Cloud Run, API Gateway, and Google Container Registry (GCR)</strong>. Additionally, we install the <strong>Google Cloud CLI (gcloud)</strong> to interact with GCP from the terminal.</p><p>2️. <strong>Build a Docker image of the API</strong></p><p>Since Cloud Run only supports <strong>containerised applications</strong>, we must package our FastAPI application into a <strong>Docker container</strong>. This ensures that the application runs consistently across different environments. The <strong>Dockerfile</strong> defines how the application is packaged, including dependencies and runtime configurations.</p><p>Here’s the Docker file used for creating the API image:</p><pre>FROM python:3.11-slim AS python-base<br><br>ENV  POETRY_VERSION=1.8.3<br><br>WORKDIR /app<br>FROM python-base AS production<br>COPY ./ /app/<br>ENV GIT_PYTHON_REFRESH=quiet<br><br>RUN poetry config virtualenvs.create false &amp;&amp; poetry install --only main<br><br>EXPOSE 8080<br>WORKDIR /app<br><br>ENTRYPOINT [&quot;poetry&quot;, &quot;run&quot;]<br>CMD [&quot;api&quot;]</pre><p>3️. <strong>Push the image to Google Container Registry (GCR)</strong></p><p>Once the <strong>Docker image</strong> is built, we need to store it in a <strong>cloud-based container registry</strong>. We use <strong>Google Container Registry (GCR)</strong> for this, which allows Cloud Run to easily pull and deploy our containerised API. This step ensures that the API image is accessible and ready for deployment.</p><p>To push our Docker image into a Google Cloud Registry using GitLab CI, we use the following GitLab CI/CD configuration:</p><pre>stages:<br>    - build-push<br>  <br>variables:<br>  REGISTRY_HOSTNAME: gcr.io/gd-gcp-datamesh-dev<br>  DOCKER_IMAGE_NAME: ${CI_PROJECT_NAME}<br>  IMAGE_TAG: &quot;$CI_COMMIT_SHORT_SHA&quot;<br>  <br>build-push:<br>  stage: build-push<br>  tags:<br>    - shared<br>  image:<br>    name: gcr.io/kaniko-project/executor:v1.14.0-debug<br>    entrypoint: [&quot;&quot;]<br>  script:<br>    - /kaniko/executor<br>      --context &quot;${CI_PROJECT_DIR}&quot;<br>      --dockerfile &quot;${CI_PROJECT_DIR}/Dockerfile&quot;<br>      --destination &quot;$REGISTRY_HOSTNAME/$DOCKER_IMAGE_NAME:$CI_COMMIT_SHORT_SHA&quot;<br>      --use-new-run=true<br>      --snapshot-mode=redo<br>  <br>  only:<br>    - master<br>    - develop</pre><p><strong>Explanation</strong>:</p><p><em>stages</em>: Defines the different stages in our CI/CD pipeline. In this case, we have a single stage called build-push.</p><p><em>variables</em>: Sets up variables for our CI/CD pipeline, including the Google Cloud Registry hostname and the Docker image name.</p><p><em>build-push</em>: Specifies the details for the build-push job within the build-push stage. It uses the Kaniko executor to build the Docker image and push it to the Google Cloud Registry.</p><ul><li><em>tags</em>: Associates the job with shared CI/CD runners.</li><li><em>image</em>: Specifies the Docker image to use for the job, which is the Kaniko executor with a specific version.</li><li><em>script</em>: Contains the commands to be executed in the job. It uses Kaniko to build the Docker image from the project context and pushes it to the specified Google Cloud Registry location.</li><li><em>only</em>: Specifies the branches for which the job should run. In this example, it is configured to run only on the master and develop branches.</li></ul><p>This GitLab CI/CD configuration automates the process of building and pushing the Docker image to Google Cloud Registry whenever changes are made to the specified branches.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/464/1*in237MzbK6QS2gwVv9hdRQ.png" /><figcaption>figure2: job running output</figcaption></figure><p>Inside GCP container registry we will have :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aSVOKN-Txs58aCsWhfDUXA.png" /><figcaption>figure3: image stored in GCR</figcaption></figure><p>Now we can move to the next step.</p><p>4️.<strong>Deploy the API to Cloud Run using Terraform</strong></p><p>With the Docker image stored in GCR, we use <strong>Terraform</strong> to automate the deployment of our API to <strong>Cloud Run</strong>. Cloud Run is a fully managed serverless platform that scales automatically based on demand. Terraform allows us to define the <strong>infrastructure as code</strong>, making deployments repeatable and easy to manage.</p><pre>module &quot;cloud_run&quot; {<br>  source       = &quot;../../../modules/module_cloud_run&quot;<br>  region       = var.region<br>  image_name   = &quot;europe-docker.pkg.dev/${var.project_id}/${var.repository}/${var.image_name}:${var.image_tag}&quot;<br>  api_name     = &quot;gd-nasa-api&quot;<br>  memory_limit = &quot;4Gi&quot;<br>  cpu_limit    = &quot;1.0&quot;<br>  api_run_sa   = data.terraform_remote_state.foundation.outputs.api_run_sa<br><br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*7XF8ozZOgfTFaM7EkyO5HQ.png" /><figcaption>figure4: cloud run output</figcaption></figure><p>5️.<strong>Expose the API using API Gateway</strong></p><p>To make our API accessible to users securely, we configure <strong>API Gateway</strong>. This acts as a front-end for the API, managing authentication, rate limiting, and request routing. API Gateway ensures that our API is <strong>secure, scalable, and easily accessible</strong>.</p><pre>module &quot;api_gateway&quot; {<br>  source         = &quot;../../../modules/module_api_gateway&quot;<br>  region         = var.region<br>  project_id     = var.project_id<br>  api_prefix     = &quot;gd-nasa-api&quot;<br>  spec_names     = [&quot;api_meteo.yaml&quot;]<br>  api_spec_path  = &quot;./spec_meteo.yaml&quot;<br>  cloudrun_url   = module.cloud_run.cloudrun_url<br>  api_gateway_sa = data.terraform_remote_state.foundation.outputs.api_gateway_sa<br>  depends_on     = [module.cloud_run]<br>}</pre><h3><strong>Conclusion</strong></h3><p>This marks the end of our <strong>data infrastructure journey</strong>! 🚀</p><p>We started with <strong>Data Mesh concepts</strong>, built <strong>data pipelines</strong>, orchestrated workflows using <strong>Airflow</strong>, and developed APIs using <strong>FastAPI</strong>. Now, we’ve <strong>successfully deployed</strong> our API on <strong>Google Cloud Platform using Terraform</strong>.</p><p>We hope this series has helped you understand <strong>how to build, orchestrate, and deploy APIs</strong> in a real-world cloud environment.</p><p><strong>Thank you for following along this journey! Hope to see you soon with new topics 👋.</strong></p><p><strong><em>To see more articles like this, visit our </em></strong><a href="https://medium.com/gnomondigital"><strong><em>page</em></strong></a><strong><em> on Medium and follow us on </em></strong><a href="https://fr.linkedin.com/company/gnomon-digital"><strong><em>LinkedIn</em></strong></a><strong><em>!</em></strong></p><p><em>&lt;&lt; Previous article : </em><a href="https://medium.com/gnomondigital/part-3-4-build-data-product-with-fastapi-feb380a6a42c">Part 3/4 — Build Data Product with FastAPI</a></p><h3>Ressources:</h3><p><em>GitHub repository : </em><a href="https://github.com/gnomondigital/gd-datamesh-tutorial"><em>link</em></a></p><p>💡 <em>Disclaimer: The code has been hosted and deployed on Gitlab, for security reasons we shared it on Github.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0f498cd03e20" width="1" height="1" alt=""><hr><p><a href="https://medium.com/gnomondigital/part-4-4-deploy-an-api-using-terraform-on-gcp-0f498cd03e20">Part 4/4 — Deploy an API using Terraform on GCP</a> was originally published in <a href="https://medium.com/gnomondigital">Gnomon Digital</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Evaluating RAG Applications with Ragas in LangChain and LlamaIndex]]></title>
            <link>https://medium.com/gnomondigital/evaluating-rag-applications-with-ragas-in-langchain-and-llamaindex-d9f277499ab6?source=rss----07d683c09d9f---4</link>
            <guid isPermaLink="false">https://medium.com/p/d9f277499ab6</guid>
            <category><![CDATA[raga]]></category>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[llamaindex]]></category>
            <dc:creator><![CDATA[Hela Moalla]]></dc:creator>
            <pubDate>Fri, 21 Mar 2025 15:22:31 GMT</pubDate>
            <atom:updated>2025-03-21T15:24:11.551Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/819/1*66bX9NNNAS06Ix0t35Fqgg.png" /></figure><h3>Table of contents</h3><p>· <a href="#6393">Introduction</a><br>∘ <a href="#f9e2">What is Retrieval-Augmented Generation </a><br>∘ <a href="#bcd7">RAGAS </a><br>∘ <a href="#3e96">LLM-Based Metrics</a><br>∘ <a href="#889a">Non-LLM-Based Metrics</a><br>· <a href="#1104">Retrieval-Augmented Generation (RAG) pipeline</a><br>·<a href="#52ea">Evaluating RAG with LangChain and RAGAS</a><br>∘<a href="#81d9"> Step 1: Import Required Libraries</a><br>∘ <a href="#f6e4">Step 2: Retrieve Relevant Documents</a> <br>∘ <a href="#0470">Step 3: Structuring the Evaluation Dataset</a><br>∘ <a href="#b236">Step 4: Evaluate Using Ragas</a><br>· <a href="#4f26">Evaluating RAG with LlamaIndex and RAGAS</a><br>∘ <a href="#179c">Step 1: Import Required Libraries</a><br>∘ <a href="#62a9">Step 2: Initializing the LLM Evaluator</a><br>∘ <a href="#ce3f">Step 3: Preparing the Evaluation Dataset</a><br>∘ <a href="#fc21">Step 4: Running the Evaluation with LlamaIndex</a><br>· <a href="#826f">Conclusion</a></p><h3>Introduction</h3><h4>What is Retrieval-Augmented Generation (RAG) ?</h4><p>Retrieval-Augmented Generation (RAG) is a powerful technique that enhances language models by retrieving relevant information before generating responses. However, assessing the <strong>quality of generated responses</strong> is crucial to ensure that they are both <strong>accurate</strong> and <strong>relevant</strong>.</p><p>To evaluate RAG-generated responses, we use: <a href="https://docs.ragas.io/en/stable/"><strong>Ragas</strong></a></p><h4><a href="https://docs.ragas.io/en/stable/">RAGAS (Retrieval-Augmented Generation Assessment Score)</a></h4><p>Ragas is a platform designed to evaluate how effectively AI systems, particularly those built on Retrieval-Augmented Generation (RAG), perform their tasks.</p><p>Ragas provides a comprehensive framework for assessing these systems, focusing on key metrics that measure accuracy, relevance, consistency, and more.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WaFN5-OR3vmrEVj4.png" /><figcaption>Evaluation with Ragas</figcaption></figure><p>RAGAS offers a suite of metrics to assess various aspects of RAG systems. These metrics are generally scaled between 0 and 1, with higher values indicating better performance.</p><p>RAGAS evaluates AI-generated responses using different types of metrics, which can be categorized into <a href="https://docs.ragas.io/en/stable/concepts/metrics/overview/"><strong>LLM-based metrics</strong></a>, relying on a language model for evaluation, and<a href="https://docs.ragas.io/en/stable/concepts/metrics/overview/"> <strong>non-LLM-based metrics</strong></a>, which use statistical methods. Here’s how these metrics are calculated and applied within the RAG pipeline:</p><p><strong>LLM-Based Metrics</strong> (Require an LLM for evaluation):</p><ul><li><a href="https://docs.ragas.io/en/v0.1.21/concepts/metrics/faithfulness.html"><strong>Faithfulness</strong></a>: Compares the response to the retrieved documents, checking if claims are supported. Computed using an LLM by prompting it to assess factual consistency.</li><li><a href="https://docs.ragas.io/en/v0.1.21/concepts/metrics/answer_relevance.html"><strong>Answer Relevancy</strong>:</a> Evaluates how well the response addresses the user’s query. Measured by prompting an LLM to score response-query alignment.</li><li><a href="https://docs.ragas.io/en/v0.1.21/concepts/metrics/answer_correctness.html"><strong>Answer Correctness</strong></a>: Measures if the response is both factually correct and directly answers the query, considering logical consistency and factual accuracy.</li><li><a href="https://docs.ragas.io/en/stable/concepts/metrics/available_metrics/context_precision/"><strong>Context Precision</strong></a>: Assesses whether retrieved documents contribute useful information to the response. Computed by analyzing how much the response relies on retrieved content.</li></ul><p><strong>Non-LLM-Based Metrics</strong> (Computed with statistical methods):</p><ul><li><a href="https://docs.ragas.io/en/v0.1.21/concepts/metrics/context_recall.html"><strong>Context Recall</strong></a>: Measures how much of the <strong>reference answer</strong> is covered by the retrieved context. A high recall means that most of the relevant information needed for the answer is present in the retrieved documents, it focuses on <strong>completeness.</strong></li><li><a href="https://docs.ragas.io/en/stable/concepts/metrics/available_metrics/traditional/#rouge-score"><strong>ROUGE Score</strong></a>: Evaluates text overlap between the generated response and reference answers, commonly used for measuring recall.</li><li><a href="https://docs.ragas.io/en/stable/concepts/metrics/available_metrics/context_precision/#non-llm-based-context-precision"><strong>Context Precision (non-LLM variant)</strong></a>: Measures how much of the <strong>retrieved context</strong> is actually relevant to answering the query. A high precision means that the retrieved documents contain mostly useful and non-noisy information , it focuses on <strong>relevance.</strong></li></ul><p>RAGAS operates at different levels of the <strong>Retrieval-Augmented Generation (RAG) pipeline</strong>, ensuring that responses generated by the language model are <strong>accurate, relevant, and well-grounded in retrieved knowledge</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SyEthxl8TVVEAiu5" /><figcaption>RAG Pipeline</figcaption></figure><p>Let’s break down each intervention level in more detail:</p><p><strong>1. Pre-Generation: Knowledge Retrieval</strong></p><p>At this stage, RAGAS ensures that the <strong>retrieval process</strong> is effective by assessing whether the system is fetching <strong>high-quality, relevant documents</strong> from the knowledge base. This step is crucial because poor retrieval leads to weak or irrelevant responses, even if the LLM itself is powerful.</p><p><strong>2. During Generation: Context Utilization</strong></p><p>Once the relevant knowledge is retrieved, it is passed to the <strong>language model</strong> to help generate a response. RAGAS ensures that the model <strong>effectively integrates the retrieved information</strong> rather than relying on its internal (and potentially outdated or incorrect) knowledge.</p><p><strong>3. Post-Generation: Evaluation &amp; Scoring</strong></p><p>After the response is generated, RAGAS evaluates it using <strong>various metrics</strong> to determine its <strong>faithfulness (accuracy), relevance, coherence, and completeness</strong>. This is where <strong>LLM-based and non-LLM-based</strong> metrics come into play.</p><p>Now that we have explored the different levels at which RAGAS intervenes in the evaluation process, let’s move on to the practical implementation of evaluating RAG using LangChain , LlamaIndex and RAGAS.</p><h3>Evaluating RAG with LangChain and RAGAS</h3><p>let’s move on to the implementation steps to evaluate a RAG pipeline using LangChain and RAGAS.</p><p>The complete code of the Chatbot of Confluence using LangChain is available on GitHub : <a href="https://github.com/gnomondigital/gd-aca-learning-path-agent">https://github.com/gnomondigital/gd-aca-learning-path-agent</a></p><h4><strong>Step 1: Import Required Libraries</strong></h4><p>Before we begin, we need to install the necessary libraries:</p><pre>pip install langchain ragas datasets rouge-score</pre><p>And then import the required modules in Python:</p><pre>from datasets import Dataset<br><br>from langchain_openai import ChatOpenAI<br>from langchain.prompts import PromptTemplate<br><br>from ragas import evaluate, SingleTurnSample<br>from ragas.metrics import RougeScore, answer_correctness, answer_relevancy</pre><h4>Step 2: Retrieve Relevant Documents</h4><p>Before evaluating, we first retrieve relevant documents using the ChromaDB retriever and generate a summarized reference answer from them, which serves as our ground truth for comparison. (This is just an example, you can also directly provide your own reference answer if available).</p><pre># Assuming ChromaDB is already initialized<br>retriever = chroma.as_retriever()<br>results = retriever.invoke(QUERY, k=5)<br>reference_context = &quot; &quot;.join([doc.page_content for doc in results])<br><br>llm = ChatOpenAI(model=&quot;gpt-4o-mini&quot;)<br><br>template = PromptTemplate(<br>    input_variables=[&quot;context&quot;, &quot;query&quot;],<br>    template=&quot;&quot;&quot;Based on the following retrieved context, <br>    generate a factual and high-quality reference answer.<br>    \n\nContext:\n{context}\n\nQuery:\n{query}\n\nReference Answer:&quot;&quot;&quot;,<br>)<br><br># Generate the reference answer<br>reference_answer = llm.invoke(template.format(context=reference_context, query=query))<br>reference_response = reference_answer.content<br>print(&quot;Reference Response:&quot;, reference_response)</pre><p>Before evaluating the performance of our RAG system, it is crucial to have a reliable reference to compare the generated responses.<br> In this example, we use an LLM model (<strong>GPT-4o-mini</strong>) to generate a <strong>reference response</strong> based on the retrieved context from relevant documents.<br> However, this answer <strong>must be manually validated</strong> before using it as ground truth to avoid biases or errors in the evaluation.</p><h4>Step 3: Structuring the Evaluation Dataset</h4><p>Once we have the retrieved documents and response, we need to format them into a dataset compatible with <strong>Ragas</strong>.</p><pre>## For Answer Correctness and Answer Relevancy<br>data_samples = {<br>    &quot;question&quot;: [query],<br>    &quot;answer&quot;: [response],<br>    &quot;ground_truth&quot;: [reference_answer.content],<br>    # The retrieved reference context<br>}<br><br>dataset = Dataset.from_dict(data_samples)</pre><pre>## For RougeScore metric<br>test_data = SingleTurnSample(<br>    user_input=query,<br>    response=response,<br>    reference=reference_response,<br>    # the reference response taken from the reference context<br>)</pre><h4>Step 4: Evaluate Using Ragas</h4><p>Now that we have our dataset ready, we can use <strong>Ragas</strong> to measure the quality of our model’s response.</p><p>Ragas metrics :</p><blockquote><strong>Answer Relevancy</strong>: Evaluates how well the response aligns with the user’s query.<br><strong>Answer Correctness</strong>: Assesses whether the response is factually accurate based on the retrieved documents.</blockquote><pre># Answer Correctness and Answer Relevancy metrics<br>score = evaluate(dataset, metrics=[answer_correctness, answer_relevancy])<br>score.to_pandas()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OaIEYv37-6FyparBXwX2ZQ.png" /><figcaption>Example of output of answer correctness and answer relevancy</figcaption></figure><p>In this example, the response provided by the system is <strong>both highly accurate and relevant</strong>. The correctness score of <strong>0.9451</strong> shows that the response is <strong>factually aligned</strong> with the reference, while the relevancy score of <strong>0.8826</strong> suggests that the response is <strong>closely related to the query</strong>, though it may contain extra information or formatting differences.</p><blockquote><strong>ROUGE-1</strong>: Measures unigram (single word) overlap.<br><strong>ROUGE-2</strong>: Measures bigram (two-word) overlap.<br><strong>ROUGE-L</strong>: Considers longest matching sequences, capturing fluency and structure.</blockquote><pre>metric1 = RougeScore(rouge_type=&quot;rouge1&quot;)<br>metric2 = RougeScore(rouge_type=&quot;rouge2&quot;)<br>metric3 = RougeScore(rouge_type=&quot;rougeL&quot;)<br><br>score1 = metric1.single_turn_score(test_data)<br>score2 = metric2.single_turn_score(test_data)<br>score3 = metric3.single_turn_score(test_data)<br><br>logging.info(&quot;Rouge 1 metric  RAGAS : %s &quot;, score1)<br>logging.info(&quot;Rouge 2 metric  RAGAS : %s &quot;, score2)<br>logging.info(&quot;Rouge L metric  RAGAS : %s &quot;, score3)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*uxLpTRfeHU7ZUF4IkUVCVA.png" /><figcaption>Example of output of Rouge Score metric</figcaption></figure><ol><li><strong>ROUGE-1 </strong>(66.9% of words match).: The generated text shares a significant portion of common words with the reference, indicating good relevance.</li><li><strong>ROUGE-2 </strong>(49.6% of word pairs match): The ROUGE-2 score suggests that the generated text may not fully capture the phrasing or word order of the reference.</li><li><strong>ROUGE-L </strong>(48.7% of the longest sequence matches): The ROUGE-L score indicates that the generated text partially aligns with the reference in terms of structure but could be improved for better coherence.</li></ol><h3>Evaluating RAG with LlamaIndex and RAGAS</h3><p>Now let’s move on to implementing <strong>response evaluation</strong> using <strong>LlamaIndex</strong> and <strong>RAGAS</strong>.</p><h4>Step 1: Import Required Libraries</h4><p>install the necessary libraries:</p><pre>pip install llamaindex</pre><p>Before evaluating the model’s responses, we need to import the necessary <strong>evaluation metrics</strong>:</p><pre>import pandas as pd<br><br>from ragas import EvaluationDataset<br>from ragas.metrics import (<br>    Faithfulness,<br>    AnswerRelevancy,<br>    ContextPrecision,<br>    ContextRecall,<br>)<br>from ragas.llms import LlamaIndexLLMWrapper<br>from ragas.integrations.llama_index import evaluate<br><br>from llama_index.llms.openai import OpenAI</pre><p>These metrics will allow us to measure different aspects of response quality:</p><ul><li><strong>Faithfulness</strong>: Ensures that the response is factually consistent with the retrieved context.</li><li><strong>Answer Relevancy</strong>: Checks how relevant the response is to the user query.</li><li><strong>Context Precision</strong>: Evaluates how much of the retrieved context is actually useful.</li><li><strong>Context Recall</strong>: Assesses whether all the necessary information from the documents was used.</li></ul><h4>Step 2: <strong>Initializing the LLM Evaluator</strong></h4><p>We need an LLM to help assess the responses. Here, we use <strong>GPT-4o</strong> as the evaluator model:</p><pre>evaluator_llm = LlamaIndexLLMWrapper(OpenAI(model=&quot;gpt-4o&quot;))<br>metrics = [<br>    Faithfulness(llm=evaluator_llm),<br>    AnswerRelevancy(llm=evaluator_llm),<br>    ContextPrecision(llm=evaluator_llm),<br>    ContextRecall(llm=evaluator_llm),<br>]</pre><h4>Step 3: Preparing the Evaluation Dataset</h4><p>To evaluate responses, we need a dataset that contains:</p><ul><li>The user query</li><li>The retrieved context</li><li>The model’s response</li><li>A reference answer (ground truth, Generated using <strong>OpenAI GPT-4o-mini </strong>in this case )</li></ul><p>We define a function to create this dataset dynamically:</p><pre># Initialize LLM for reference answer generation<br>llm = OpenAI(model=&quot;gpt-4o-mini&quot;)<br><br><br>def create_ragas_dataset(query, response):<br>    dataset = []<br>    # Extract retrieved contexts from the response object<br>    retrieved_contexts = [<br>        node.get_content() for node in getattr(response, &quot;source_nodes&quot;, [])<br>    ]<br>    # Generate a reference answer using the LLM<br>    prompt = f&quot;&quot;&quot;Generate a concise, factual, and high-quality reference <br>        answer for the query:\n\nQuery: {query}\n\nReference Answer:&quot;&quot;&quot;<br>    reference_answer = llm.complete(prompt).text<br>    dataset.append(<br>        {<br>            &quot;user_input&quot;: query,<br>            &quot;retrieved_contexts&quot;: retrieved_contexts,<br>            &quot;response&quot;: (<br>                response.response if hasattr(response, &quot;response&quot;) else str(response)<br>            ),<br>            &quot;reference&quot;: reference_answer,<br>        }<br>    )<br>    df = pd.DataFrame(dataset)<br>    return EvaluationDataset.from_pandas(df)</pre><p>We apply the function to create an evaluation dataset from our <strong>query</strong> and <strong>response</strong>:</p><pre># Generate the RAGAS evaluation dataset<br>ragas_dataset = create_ragas_dataset(query, response)<br>print(ragas_dataset)</pre><h4><strong>Step 4: Running the Evaluation with LlamaIndex</strong></h4><p>Finally, we evaluate the responses by integrating <strong>LlamaIndex </strong>with<strong> RAGAS</strong>:</p><pre>result = evaluate(<br>    query_engine=query_engine,<br>    metrics=metrics,<br>    dataset=ragas_dataset,<br>)<br>result.to_pandas()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rcQD9gQ2stVHyX7gXCDO4w.png" /><figcaption>Example of output of Ragas with LLamaIndex</figcaption></figure><ol><li><strong>Faithfulness (1.0): </strong>A score of <strong>1.0</strong> means the response is <strong>fully faithful</strong> and does not introduce hallucinations or misleading information.</li><li><strong>Answer Relevancy (0.9305): </strong>This measures how relevant the response is to the original query. The response is highly relevant but may include minor extra details.</li><li><strong>Context Precision (0.625): </strong>Precision evaluates how much of the retrieved context was <strong>actually useful</strong> for generating the response. In this case some retrieved context was unnecessary for answering the query.</li><li><strong>Context Recall (1.0):</strong> All necessary information was successfully retrieved.</li></ol><h3>Conclusion</h3><h4>Evaluating RAG Pipelines with LangChain, LlamaIndex, and RAGAS</h4><p>In this article, we explored the use of <strong>LangChain</strong> and <strong>LlamaIndex</strong> separately, focusing on how <strong>RAGAS</strong> can be applied to evaluate the performance of retrieval-augmented generation (RAG) systems built using these frameworks. <strong>LangChain</strong> provides a flexible pipeline for integrating retrieval and response generation, while <strong>LlamaIndex</strong> optimizes the indexing and retrieval of documents.</p><p>By leveraging <strong>RAGAS</strong>, we evaluated key metrics like <strong>faithfulness</strong>, <strong>answer relevancy</strong>, <strong>context precision</strong>, and <strong>context recall</strong> to ensure high-quality, relevant, and accurate responses. The use of <strong>RAGAS</strong> with both <strong>LangChain</strong> and <strong>LlamaIndex</strong> provides a robust method for evaluating and improving the effectiveness of RAG pipelines, ensuring that the generated responses meet the desired standards in real-world applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d9f277499ab6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/gnomondigital/evaluating-rag-applications-with-ragas-in-langchain-and-llamaindex-d9f277499ab6">Evaluating RAG Applications with Ragas in LangChain and LlamaIndex</a> was originally published in <a href="https://medium.com/gnomondigital">Gnomon Digital</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 3/4 — Build Data Product with FastAPI]]></title>
            <link>https://medium.com/gnomondigital/part-3-4-build-data-product-with-fastapi-feb380a6a42c?source=rss----07d683c09d9f---4</link>
            <guid isPermaLink="false">https://medium.com/p/feb380a6a42c</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-mesh]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[backend]]></category>
            <dc:creator><![CDATA[Nacima Yahiatene]]></dc:creator>
            <pubDate>Thu, 06 Mar 2025 11:25:37 GMT</pubDate>
            <atom:updated>2025-03-06T11:25:39.055Z</atom:updated>
            <content:encoded><![CDATA[<h3>Part 3/4 — Build Data Product with FastAPI</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/819/1*nh98T-QeVge3hzwCZACy6Q.png" /></figure><p><em>In our exploration into building a data pipeline, we move from orchestrating workflows with Apache Airflow to APIs development. This article focuses on leveraging FastAPI to construct a robust API for retrieving and exposing the cleaned data from our previous pipeline.</em></p><p><em>If you missed our initial work, here’s the link &gt; </em><a href="https://medium.com/gnomondigital/part-2-4-orchestrating-a-data-pipeline-with-airflow-c20a615e9b2b"><strong><em>Part 2/4 — Orchestrating Data Pipelines with Airflow</em></strong></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M1QBq2FbnoF7C16_w9fPiA.png" /></figure><h3>Summary</h3><p>· <a href="#1a39">APIs (Application Programming Interface):</a><br>· <a href="#1e73">Expanding on the Problems APIs Solve (Restaurant Context):</a><br>· <a href="#e8a6">Three-Tier Architecture</a><br>· <a href="#9845">Code implementation</a><br> ∘ <a href="#db1a">Project Structure:</a><br> ∘ <a href="#8f4b">Main Code Explained:</a><br>· <a href="#4f83">Seeing Our API in Action</a><br>· <a href="#0c77">Conclusion:</a><br>· <a href="#be40">Ressources:</a></p><h3>APIs (Application Programming Interface):</h3><p>An API is the way different software programs ‘talk’ to each other. Just like humans use language to communicate, applications use APIs to exchange information and functionality.</p><p>A well known analogy is :</p><p><em>“Think of a restaurant. The kitchen is the server holding the data (the food). The waiter is the API. You (the client/user) don’t go into the kitchen yourself. You order from the menu (make a request to the API), and the waiter brings you the dish you want (the data you requested).”</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XsNgtXEE9fYrmY41bCRl9g.png" /></figure><h3><strong>Expanding on the Problems APIs Solve (Restaurant Context):</strong></h3><ul><li><strong>Structured and Controlled Data Access:</strong> Instead of rummaging through the kitchen (database) yourself, you simply order from the menu (API), ensuring you get exactly what you need, prepared correctly.</li><li><strong>Code Reusability:</strong> Once the restaurant has a menu (API), any customer can order from it without needing to know how the dishes are cooked. This saves the customer (developer) time and effort.</li><li><strong>Abstraction of Complexity:</strong> You don’t need to know the kitchen’s layout or cooking techniques. The waiter (API) handles everything, keeping the kitchen’s (server’s) complexities hidden.</li><li><strong>Scalability and Maintenance:</strong> The restaurant can easily change its kitchen setup or add new dishes without affecting how customers order. The API’s separation allows for easier scaling and maintenance.</li><li><strong>Standardisation (RESTful Example):</strong> Just like many restaurants follow a common standard for taking orders, our API uses REST. REST (Representational State Transfer) is a set of conventions that make APIs easy to understand and use. It utilises standard HTTP methods (GET, POST, PUT, DELETE) to interact with resources. We chose REST because it is a widely adopted standard, promoting interoperability and making it easier for developers to work with our API.</li></ul><h3>Three-Tier Architecture</h3><p>When building our gd-nasa-api with FastAPI, we used a common and organised approach called the three-tier architecture (sometimes called multi-tier). This structure helps us keep the different parts of our API separate and manageable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CYYOqTGsBYLnF_rp8ChNKg.png" /></figure><p>Think of it like a building with three floors, each with its own job:</p><p><strong>Top Floor (Presentation Tier — API Endpoints): </strong>This is the user-facing layer, where interactions occur. It’s like the reception area, with each API function (e.g., checking health, retrieving metadata, fetching weather) having its own endpoint “door.”</p><p><strong>Benefit:</strong></p><ul><li>This layer handles user requests and responses, ensuring a clear and consistent interface.</li></ul><p><strong>Middle Floor (Application Tier — Business Logic): </strong>This is the operational core, processing requests and making decisions. When a request comes from the top floor, this layer determines the necessary actions, including database interactions. It’s the “staff office.”</p><p><strong>Benefits:</strong></p><ul><li>Centralises business logic, promoting code reusability and maintainability.</li><li>Decouples the presentation layer from the data layer, allowing for independent changes.</li></ul><p><strong>Bottom Floor (Data Tier — Persistence):</strong> This is the data storage layer, housing the PostgreSQL database. The middle layer retrieves and stores data here. It’s the “filing room.”</p><p><strong>Benefits:</strong></p><ul><li>Provides a dedicated layer for data management and security.</li><li>Allows for easy database changes without affecting other layers.</li></ul><p><strong>Why three tiers?</strong></p><ul><li><strong>Separation of Concerns:</strong> Each layer has a specific responsibility, making the system easier to understand and manage.</li><li><strong>Improved Maintainability:</strong> Changes in one layer have minimal impact on others.</li><li><strong>Enhanced Scalability:</strong> Each layer can be scaled independently to meet specific performance needs.</li><li><strong>Increased Security:</strong> Data access is controlled through the application layer, enhancing security.</li></ul><p><strong>Example:</strong></p><p>When someone wants to get the weather for London:</p><ol><li>They access the /cities/london/weather endpoint (top floor).</li><li>The request is processed by the application layer (middle floor).</li><li>The application layer retrieves the weather data from the database (bottom floor).</li><li>The application layer sends the data back to the presentation layer, which delivers it to the user.</li></ol><p>This three-tier approach ensures a structured, maintainable, and scalable API.</p><h3><em>Code implementation</em></h3><p><em>We’ve already set up our project environment using Poetry (check out the </em><a href="https://medium.com/gnomondigital/part-1-4-build-etl-pipelines-of-data-domain-with-medallion-architecture-a14b983866a1#cd80"><em>previous</em></a><em> articles for details). Now, let’s look at the code.</em></p><h4><strong>Project Structure:</strong></h4><p>Our project is organised to keep things clean:</p><ul><li><strong>apis/</strong>: This folder holds the code for our API&#39;s endpoints (like getting weather data).</li><li><strong>infra/</strong>: This folder manages database connections (PostgreSQL), configurations, and data storage.</li><li><strong>services/</strong>: This folder contains the logic that processes our data.</li><li><strong>main.py</strong>: This is the starting point of our API.</li></ul><h4>Main Code Explained:</h4><p>Here’s a breakdown of the main.py code:</p><pre>import uvicorn<br>from fastapi import FastAPI<br>from sqlalchemy import MetaData<br><br>from gd_nasa_api.apis.metadata import router as metadata<br>from gd_nasa_api.apis.weatherData import router as weatherData<br>from gd_nasa_api.infra.config import open_data_config<br>from gd_nasa_api.infra.postgres_handler import PostgresHandler<br>from gd_nasa_api.infra.weatherData import WeatherData<br><br><br>postgres_handler = PostgresHandler()<br><br>app = FastAPI()<br>metadata_sql = MetaData()<br><br><br>app.include_router(metadata, tags=[&quot;Metadata&quot;])<br>app.include_router(weatherData, tags=[&quot;WeatherData&quot;])<br><br><br>@app.on_event(&quot;startup&quot;)<br>def startup_event():<br>    config = open_data_config()<br>    engine = postgres_handler.launch_connection_db(<br>        database_name=config[&quot;db_name&quot;]<br>    )<br>    WeatherData.__table__.create(bind=engine, checkfirst=True)<br><br><br>def run():<br>    &quot;&quot;&quot;run for api&quot;&quot;&quot;<br>    uvicorn.run(app, host=&quot;0.0.0.0&quot;, port=8080)</pre><p><strong>Explanation:</strong></p><ul><li>We import the tools we need (FastAPI, database helpers, etc.).</li><li>We create a FastAPI app.</li><li>We connect our API endpoints (metadata and weather data).</li><li>When the API starts, it connects to the database and creates the necessary tables.</li><li>The run() function starts the API.</li></ul><p><strong>API Endpoints:</strong></p><p>Our API has these main functions:</p><p><strong>Health Check: </strong>It checks if the API is running.</p><ul><li>URL: / It just returns “OK” if everything works.</li></ul><p><strong>Metadata: </strong>It gives information about our API (name, description).</p><ul><li>URL: /metadata</li></ul><p><strong>City Weather Data: </strong>It gets weather information for a specific city from our database.</p><ul><li>URL: /cities/{city_name}/weather</li><li>Example: /cities/Okhargara/weather</li></ul><pre>@router.get(&quot;/cities/{city_name}/weather&quot;)<br>async def get_weather_data(city_name: str, db: Session = Depends(get_db)):<br>    db_weather = meteo_service.get_meteo(db=db, city_name=city_name)<br>    if not db_weather:<br>        message = {<br>            &quot;detail&quot;: &quot;Engine not found&quot;,<br>        }<br>        return JSONResponse(content=message, status_code=404)<br>    json_string = json.dumps(jsonable_encoder(db_weather))<br>    return {&quot;json_data&quot;: json_string}</pre><h3>Seeing Our API in Action</h3><p>To see how our API works:</p><ul><li><strong>Start the API:</strong> Open your terminal and run poetry run api. This starts the API on 0.0.0.0:8080.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NuRiHE3mehFVXucN692XbA.png" /></figure><ul><li><strong>Check the Docs:</strong> Open your web browser and go to http://0.0.0.0:8080/docs. This is FastAPI&#39;s built-in documentation.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_x0Yj3J-ss45TIOHatKHmQ.png" /></figure><ul><li><strong>Explore:</strong> You’ll see a list of our API’s functions (endpoints). You can see what data they expect and what data they return. You can even test them right in the browser.</li><li><strong>Try an Example:</strong> For example, try getting the weather for “Okhargara” using the appropriate endpoint.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MC1Chr7M8qRJlncbKYWTuA.png" /></figure><ul><li><strong>Look at the Logs:</strong> If you want to see what’s happening behind the scenes, check your terminal for the API’s logs.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zqnfkZUQ0fDVXCQ-bTBSRg.png" /></figure><p>Using the documentation and testing the endpoints helps you understand what the API can do and how to use it.</p><h3><strong>Conclusion:</strong></h3><p>We’ve successfully built our gd-nasa-api using FastAPI, creating a structured and functional API to serve data. We&#39;ve seen how it connects to a database and offers accessible endpoints, all easily understood through the built-in documentation.</p><p>The next crucial step is making this API available to the world. We&#39;ll be moving on to deploying our API on Google Cloud Platform (GCP).</p><p><strong><em>To see more articles like this, visit our </em></strong><a href="https://medium.com/gnomondigital"><strong><em>page</em></strong></a><strong><em> on Medium and follow us on </em></strong><a href="https://fr.linkedin.com/company/gnomon-digital"><strong><em>LinkedIn</em></strong></a><strong><em>!</em></strong></p><p><em>&lt;&lt; Previous article :</em><a href="https://medium.com/gnomondigital/part-2-4-orchestrating-a-data-pipeline-with-airflow-c20a615e9b2b"><em> Part 2/4 — Orchestrating Data Pipelines with Airflow</em></a></p><p><em>Coming next : Part 4/4 — Deploy an API using Terraform on GCP. &gt;&gt;</em></p><h3>Ressources:</h3><p><em>FastAPI documentation: </em><a href="https://fastapi.tiangolo.com/tutorial/"><em>link</em></a></p><p><em>GitHub repository : </em><a href="https://github.com/gnomondigital/gd-datamesh-tutorial"><em>link</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=feb380a6a42c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/gnomondigital/part-3-4-build-data-product-with-fastapi-feb380a6a42c">Part 3/4 — Build Data Product with FastAPI</a> was originally published in <a href="https://medium.com/gnomondigital">Gnomon Digital</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 2/4 — Orchestrating a Data Pipeline with Airflow]]></title>
            <link>https://medium.com/gnomondigital/part-2-4-orchestrating-a-data-pipeline-with-airflow-c20a615e9b2b?source=rss----07d683c09d9f---4</link>
            <guid isPermaLink="false">https://medium.com/p/c20a615e9b2b</guid>
            <category><![CDATA[orchestration]]></category>
            <category><![CDATA[data-mesh]]></category>
            <category><![CDATA[airflow]]></category>
            <category><![CDATA[docker-compose]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Nacima Yahiatene]]></dc:creator>
            <pubDate>Thu, 07 Nov 2024 11:36:41 GMT</pubDate>
            <atom:updated>2025-09-16T08:23:26.914Z</atom:updated>
            <content:encoded><![CDATA[<h3>Part 2/4 — Orchestrating Data Pipelines with Airflow</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/819/1*rXnP2choR3lDYZudp0PV6w.png" /></figure><h3>Table of contents</h3><p>· <a href="#51a7">Quick Recap of Our Journey So Far</a><br> ∘ <a href="#edc8">Current Challenge</a><br>· <a href="#f3f2">Solution: Scheduling with Apache Airflow</a><br> ∘ <a href="#f3f3">Why Apache Airflow</a><br> ∘ <a href="#52c3">How does Airflow answer our challenge </a><br> ∘ <a href="#0dc9">Airflow Deployment options</a><br>· <a href="#3357">How to Run Airflow with Docker Compose </a><br> ∘ <a href="#535d">Install Docker Compose</a><br> ∘ <a href="#a340">Project environment setup</a><br> ∘ <a href="#aa20">Install Airflow Using Docker Compose</a><br>· <a href="#fe07">How to create a DAG for the data pipeline</a><br> ∘ <a href="#7623">Create an Airflow DAG</a><br> ∘ <a href="#0943">Let’s check with Airflow UI</a><br>· <a href="#6688">Conclusion</a></p><h3><strong><em>Quick Recap of Our Journey So Far</em></strong></h3><p><em>In our exploration of building a data pipeline, we’ve seen how to build a data pipeline from scratch. If you missed our initial steps, here’s the link &gt; </em><a href="https://medium.com/gnomondigital/part-1-4-build-etl-pipelines-of-data-domain-with-medallion-architecture-a14b983866a1">Build ETL Pipelines of Data Domain with Medallion Architecture</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OdKi1A-j4EglOWySzs6Owg.png" /></figure><p>We have developed an application that runs specific code logic using a command called <em>poetry run app</em>. This command initialises our application and executes the necessary functions. Once we confirmed that this logic works correctly, we created a <strong>Docker image</strong> from it. This image packages all the dependencies and code, allowing us to run it in a consistent environment.</p><p><strong>The Black Box Concept</strong></p><p>In the Docker image, we use <strong>ENTRYPOINT</strong> and <strong>CMD</strong> to control what the container runs by default.</p><ul><li><strong>ENTRYPOINT</strong>: Defines the main command that always runs when the container starts. Think of it as the primary function of the container.</li><li><strong>CMD</strong>: Provides default arguments or options for the <strong>ENTRYPOINT</strong>. If needed, CMD can be overridden when running the container.</li></ul><pre>ENTRYPOINT [&quot;poetry&quot;, &quot;run&quot;, &quot;app&quot;]</pre><p>It’s recommended to use <strong>CMD</strong>with <strong>ENTRYPOINT</strong>. The <strong>ENTRYPOINT</strong> sets the default process, poetry run app, and <strong>CMD</strong> can be used to pass arguments to this <strong>ENTRYPOINT</strong>.</p><p>In our case, we use <strong>CMD</strong> to set the default arguments as view bronze to run the full bronze view pipeline. However, these arguments can be overridden by any arguments passed by the user at runtime.</p><pre>CMD [&quot;--view&quot;, &quot;bronze&quot;]</pre><p>The whole setup behaves like a <strong>black box</strong>: we provide the input, and it processes the information without needing to expose or understand the internal workings. The output from this execution is automatically written to our database, as this functionality is already programmed into the application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j4PvoMWlv55cXkLC58_Hbw.png" /></figure><p>Based on the command, we can control which specific pipeline process runs, whether it’s loading data for the bronze, silver, or gold layers. This approach provides flexibility in task execution, allowing us to call different stages of the data pipeline in the same DAG and direct them to various endpoints as needed.</p><h4>Current Challenge</h4><p>With our data pipeline set up, the next big challenge is:</p><ul><li><strong>How to make the pipeline run automatically on a set schedule</strong></li><li><strong>Ensure each step runs in the correct order and only after its dependencies are complete</strong></li></ul><p>The goal is to have a smooth, automated workflow where each task in the pipeline is scheduled to run at the right time, handles errors, retries when needed, and can scale as data volume grows.</p><h3><strong>Solution: Scheduling with Apache Airflow</strong></h3><p>To automate the execution of our Docker image at a precise time each day, we can use <strong>Apache Airflow</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HbuKMg-WK7lFliVMqWtctw.png" /></figure><h4><strong>Why Apache Airflow</strong></h4><p>Apache Airflow is an open-source platform to programmatically author, schedule, and monitor data workflows. It organises workflows into Directed Acyclic Graphs (DAGs), where each task represents a step in the process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jo0k0GnD3jElxVtezGk7Dw.png" /></figure><p>Using Python, it allows users to define tasks and dependencies, then automate and manage these workflows on a regular schedule.</p><p>Airflow provides a web interface for monitoring, retrying, and managing tasks in real-time. Ideal for data engineering and ETL pipelines, it’s highly customisable and integrates with many data tools and cloud services.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZCJN3SYTfgdOkfJC_YWfeA.png" /></figure><p><em>More information about airflow: </em><a href="https://airflow.apache.org/"><em>https://airflow.apache.org/</em></a><em>.</em></p><p><em>You can also see more about building a your own simple dag following this </em><a href="https://airflow.apache.org/docs/apache-airflow/1.10.1/tutorial.html"><em>tutorial</em></a><em>.</em></p><h4>How does Airflow answer our challenge</h4><p>Airflow allows:</p><ul><li><strong>Automated Scheduling:</strong> Set regular intervals (e.g., daily, hourly) for your pipeline, so tasks run automatically without manual triggers.</li><li><strong>Dependency Management: </strong>Use Directed Acyclic Graphs (DAGs) to define task dependencies, ensuring each step runs in the correct order once prior tasks are complete.</li><li><strong>Dynamic Task Inputs:</strong> Configure parameters, templates, and variables to adjust task inputs based on specific run requirements.</li><li><strong>Automatic Retries: </strong>Specify retry counts and delays for tasks, so they retry automatically on failure, reducing the need for manual intervention.</li><li><strong>Monitoring and Alerts:</strong> Set up notifications (email, Slack) to alert you if a task fails, allowing for quick responses.</li></ul><p>With these capabilities, Airflow can solve our automation and scheduling challenges.</p><h4>Airflow Deployment options</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UOU7iW7IYQVakdxVOfA4sw.png" /></figure><p>We need to test a simple app locally, so we’ll use the first method with <strong>Docker Compose</strong>. This setup allows us to run Apache Airflow and its services (Web Server, Scheduler, and Workers) in separate Docker containers on our local machine. It’s a straightforward way to develop and test workflows without requiring complex infrastructure.</p><h3>How to Run Airflow with Docker Compose</h3><p>In this step-by-step guide, we will launch Apache Airflow using Docker Compose and then utilise a locally created Docker image through a DockerOperator to construct a robust ETL pipeline.</p><h4>Install Docker Compose</h4><p>Ensure you have Docker Compose installed. If not, follow the instructions <a href="https://dockerlabs.collabnix.com/intermediate/workshop/DockerCompose/How_to_Install_Docker_Compose.html#:~:text=Docker%20Compose%20is%20installed%20as,MAC%2C%20you%20have%20Docker%20Compose.">here</a>.</p><p><em>Docker Compose is installed as part of Docker for Mac. So if you have Docker for MAC, you have Docker Compose.</em></p><h4>Project environment setup</h4><p>Create a New Project Folder:</p><pre>mkdir gd-nasa-dag<br><br># Navigate to the newly created folder<br>cd gd-nasa-dag<br><br># open vscode<br>code .</pre><p>Run the following command to initiate poetry configurations:</p><pre>poetry init</pre><p>Add Airflow and any extras, then activate the environment:</p><pre>poetry add apache-airflow <br>poetry shell </pre><p>This ensures your project uses an isolated environment, with all dependencies centralised in <strong>pyproject.toml</strong>.</p><h4>Install Airflow Using Docker Compose</h4><p>Create the <strong>docker-compose.yaml</strong> file in your project directory. Below is the sample. your can modify it according to your preferences.</p><pre># Licensed to the Apache Software Foundation (ASF) under one<br># or more contributor license agreements.  See the NOTICE file<br># distributed with this work for additional information<br># regarding copyright ownership.  The ASF licenses this file<br># to you under the Apache License, Version 2.0 (the<br># &quot;License&quot;); you may not use this file except in compliance<br># with the License.  You may obtain a copy of the License at<br>#<br>#   &lt;http://www.apache.org/licenses/LICENSE-2.0&gt;<br>#<br># Unless required by applicable law or agreed to in writing,<br># software distributed under the License is distributed on an<br># &quot;AS IS&quot; BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY<br># KIND, either express or implied.  See the License for the<br># specific language governing permissions and limitations<br># under the License.<br>#<br><br># Basic Airflow cluster configuration for CeleryExecutor with Redis and PostgreSQL.<br>#<br># WARNING: This configuration is for local development. Do not use it in a production deployment.<br>#<br># This configuration supports basic configuration using environment variables or an .env file<br># The following variables are supported:<br>#<br># AIRFLOW_IMAGE_NAME         - Docker image name used to run Airflow.<br>#                              Default: apache/airflow:master-python3.8<br># _AIRFLOW_WWW_USER_USERNAME - Username for the administrator account.<br>#                              Default: airflow<br># _AIRFLOW_WWW_USER_PASSWORD - Password for the administrator account.<br>#                              Default: airflow<br>#<br># Feel free to modify this file to suit your needs.<br>---<br>version: &quot;3&quot;<br>x-airflow-common: &amp;airflow-common<br>  image: ${AIRFLOW_IMAGE_NAME:-apache/airflow:2.8.0}<br>  user: root<br>  environment: &amp;airflow-common-env<br>    AIRFLOW__CORE__EXECUTOR: CeleryExecutor<br>    AIRFLOW__CORE__SQL_ALCHEMY_CONN: postgresql+psycopg2://airflow:airflow@postgres/airflow<br>    AIRFLOW__CELERY__RESULT_BACKEND: db+postgresql://airflow:airflow@postgres/airflow<br>    AIRFLOW__CELERY__BROKER_URL: redis://:@redis:6379/0<br>    AIRFLOW__CORE__FERNET_KEY: &quot;&quot;<br>    AIRFLOW__CORE__DAGS_ARE_PAUSED_AT_CREATION: &quot;true&quot;<br>    AIRFLOW__CORE__LOAD_EXAMPLES: &quot;false&quot;<br>    AIRFLOW__SCHEDULER__DAG_DIR_LIST_INTERVAL: 5 # Just to have a fast load in the front-end. Do not use it in production with those configurations.<br>    AIRFLOW__API__AUTH_BACKEND: &quot;airflow.api.auth.backend.basic_auth&quot;<br>    AIRFLOW__CORE__ENABLE_XCOM_PICKLING: &quot;true&quot; # &quot;_run_image of the DockerOperator returns now a python string, not a byte string&quot; Ref: &lt;https://github.com/apache/airflow/issues/13487&gt;<br>  volumes:<br>    - ./src/gd_nasa_dag/dags:/opt/airflow/dags<br>    - ./src/gd_nasa_dag/logs:/opt/airflow/logs<br>    - ./src/gd_nasa_dag/config:/opt/airflow/./config<br>    - ./src/gd_nasa_dag/plugins:/opt/airflow/plugins<br>    - &quot;/var/run/docker.sock:/var/run/docker.sock&quot; # We will pass the Docker Deamon as a volume to allow the webserver containers start docker images. Ref: &lt;https://stackoverflow.com/q/51342810/7024760&gt;<br>  depends_on:<br>    redis:<br>      condition: service_healthy<br>    postgres:<br>      condition: service_healthy<br><br>services:<br>  postgres:<br>    image: postgres:13<br>    environment:<br>      POSTGRES_USER: airflow<br>      POSTGRES_PASSWORD: airflow<br>      POSTGRES_DB: airflow<br>    volumes:<br>      - postgres-db-volume:/var/lib/postgresql/data<br>    healthcheck:<br>      test: [&quot;CMD&quot;, &quot;pg_isready&quot;, &quot;-U&quot;, &quot;airflow&quot;]<br>      interval: 5s<br>      retries: 5<br>    restart: always<br><br>  redis:<br>    image: redis:latest<br>    ports:<br>      - 6379:6379<br>    healthcheck:<br>      test: [&quot;CMD&quot;, &quot;redis-cli&quot;, &quot;ping&quot;]<br>      interval: 5s<br>      timeout: 30s<br>      retries: 50<br>    restart: always<br><br>  airflow-webserver:<br>    &lt;&lt;: *airflow-common<br>    command: webserver<br>    ports:<br>      - 8080:8080<br>    healthcheck:<br>      test: [&quot;CMD&quot;, &quot;curl&quot;, &quot;--fail&quot;, &quot;&lt;http://localhost:8080/health&gt;&quot;]<br>      interval: 10s<br>      timeout: 10s<br>      retries: 5<br>    restart: always<br><br>  airflow-scheduler:<br>    &lt;&lt;: *airflow-common<br>    command: scheduler<br>    restart: always<br><br>  airflow-worker:<br>    &lt;&lt;: *airflow-common<br>    command: celery worker<br>    restart: always<br><br>  airflow-init:<br>    &lt;&lt;: *airflow-common<br>    command: version<br>    environment:<br>      &lt;&lt;: *airflow-common-env<br>      _AIRFLOW_DB_UPGRADE: &quot;true&quot;<br>      _AIRFLOW_WWW_USER_CREATE: &quot;true&quot;<br>      _AIRFLOW_WWW_USER_USERNAME: ${_AIRFLOW_WWW_USER_USERNAME:-airflow}<br>      _AIRFLOW_WWW_USER_PASSWORD: ${_AIRFLOW_WWW_USER_PASSWORD:-airflow}<br><br>  flower:<br>    &lt;&lt;: *airflow-common<br>    command: celery flower<br>    ports:<br>      - 5555:5555<br>    healthcheck:<br>      test: [&quot;CMD&quot;, &quot;curl&quot;, &quot;--fail&quot;, &quot;&lt;http://localhost:5555/&gt;&quot;]<br>      interval: 10s<br>      timeout: 10s<br>      retries: 5<br>    restart: always<br><br>volumes:<br>  postgres-db-volume:</pre><p>Airflow follows a distributed architecture that consists of several key components</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tgX0FpSC2Mi78MbsS3x_Iw.png" /></figure><p>The provided configuration file is a Docker Compose setup for an Airflow cluster using the CeleryExecutor, Redis, and PostgreSQL. Below are the key components defined in the file:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d8pe5UM_ysvevYfE-FRa8w.png" /></figure><h3>How to create a DAG for the data pipeline</h3><p>In this step, we are creating an Airflow Directed Acyclic Graph (DAG) that orchestrates our ETL pipeline.</p><h4>Create an Airflow DAG</h4><p>We create a <strong>nasa_dag_file.py</strong> file in our DAG folder.</p><pre># Import necessary modules and classes<br>from datetime import datetime, timedelta<br>from airflow import DAG<br>from airflow.operators.empty import EmptyOperator<br>from airflow.operators.docker_operator import DockerOperator<br><br># Define default configuration parameters for the DAG<br>default_args = {<br>    &#39;owner&#39;: &#39;gnomon digital&#39;,<br>    &quot;description&quot;: &quot;nasa pipeline&quot;,<br>    &#39;depends_on_past&#39;: False,<br>    &#39;start_date&#39;: datetime.utcnow(),<br>    &#39;email_on_failure&#39;: False,<br>    &#39;email_on_retry&#39;: False,<br>    &#39;retries&#39;: 1,<br>    &#39;retry_delay&#39;: timedelta(minutes=5)<br>}<br><br># Instantiate the DAG with specified configurations<br>with DAG(<br>    &quot;gd-nasa-dag&quot;,<br>    default_args=default_args,<br>    schedule_interval=timedelta(days=1),<br>    concurrency=1,<br>    catchup=False,<br>    max_active_runs=1,<br>) as dag:<br><br>    # Define empty tasks to mark the start and end of the DAG<br>    start_bronze_layer = EmptyOperator(task_id=&quot;start_bronze_layer&quot;)<br>    start_silver_layer = EmptyOperator(task_id=&quot;start_silver_layer&quot;)<br>    start_gold_layer = EmptyOperator(task_id=&quot;start_gold_layer&quot;)<br>    end_dag = EmptyOperator(task_id=&quot;end_dag&quot;)<br><br>    # Define environment variables for Docker containers<br>    environment_vars = {<br>        &#39;DB_PORT&#39;: &#39;{{ var.value.DB_PORT }}&#39;,<br>        &#39;DB_PASS&#39;: &#39;{{ var.value.DB_PASS }}&#39;,<br>        &#39;DB_USER&#39;: &#39;{{ var.value.DB_USER }}&#39;,<br>        &#39;DB_HOST&#39;: &#39;{{ var.value.DB_HOST }}&#39;,<br>        &#39;DB_NAME&#39;: &#39;{{ var.value.DB_NAME }}&#39;,<br>        &#39;DB_SCHEMA&#39;: &#39;{{ var.value.DB_SCHEMA }}&#39;,<br>    }<br><br>    # Define Docker tasks for each layer of the pipeline<br>    bronze_layer_data = DockerOperator(<br>        task_id=&quot;bronze_layer_data&quot;,<br>        image=&quot;gd-nasa-pipeline:latest&quot;,<br>        command=&quot;--view bronze&quot;,<br>        docker_url=&quot;unix://var/run/docker.sock&quot;,<br>        network_mode=&quot;bridge&quot;,<br>        environment=environment_vars,<br>    )<br>    bronze_layer_geo = DockerOperator(<br>        task_id=&quot;bronze_layer_geo&quot;,<br>        image=&quot;gd-nasa-pipeline:latest&quot;,<br>        command=&quot;--view bronze --table_name geo_referential&quot;,<br>        docker_url=&quot;unix://var/run/docker.sock&quot;,<br>        network_mode=&quot;bridge&quot;,<br>        environment=environment_vars,<br>    )<br>    silver_layer_data = DockerOperator(<br>        task_id=&quot;silver_layer_data&quot;,<br>        image=&quot;gd-nasa-pipeline:latest&quot;,<br>        command=&quot;--view silver&quot;,<br>        docker_url=&quot;unix://var/run/docker.sock&quot;,<br>        network_mode=&quot;bridge&quot;,<br>        environment=environment_vars,<br>    )<br>    silver_layer_geo = DockerOperator(<br>        task_id=&quot;silver_layer_geo&quot;,<br>        image=&quot;gd-nasa-pipeline:latest&quot;,<br>        command=&quot;--view silver --table_name geo_referential&quot;,<br>        docker_url=&quot;unix://var/run/docker.sock&quot;,<br>        network_mode=&quot;bridge&quot;,<br>        environment=environment_vars,<br>    )<br>    gold_layer = DockerOperator(<br>        task_id=&quot;gold_layer&quot;,<br>        image=&quot;gd-nasa-pipeline:latest&quot;,<br>        command=&quot;--view gold&quot;,<br>        docker_url=&quot;unix://var/run/docker.sock&quot;,<br>        network_mode=&quot;bridge&quot;,<br>        environment=environment_vars,<br>    )<br><br>    # Define the task dependency flow in the DAG<br>    (<br>        start_bronze_layer<br>        &gt;&gt; [bronze_layer_data, bronze_layer_geo]<br>        &gt;&gt; start_silver_layer<br>        &gt;&gt; [silver_layer_data, silver_layer_geo]<br>        &gt;&gt; start_gold_layer<br>        &gt;&gt; gold_layer<br>        &gt;&gt; end_dag<br>    )</pre><p>Here’s a breakdown of this code in three main steps:</p><p><strong><em>Step 1: Configure the DAG</em></strong></p><p>Set up the basic configuration of the DAG with a name, scheduling frequency, and other parameters.</p><p><strong><em>Step 2: Define Docker Tasks and Call the Image with Commands</em></strong></p><p>Create tasks that run Docker containers to perform specific actions.</p><p><strong><em>Step 3: Define Task Order to Control Execution Flow</em></strong></p><p>Arrange tasks to run in a specific sequence to ensure proper data processing order.</p><p>This DAG encapsulates the sequential flow of our Medallion Architecture, consisting of three essential layers:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_OCaR98_lbKxgfSMi_uXcA.png" /></figure><p>This visual representation illustrates the logical progression of our ETL process, showcasing the interdependence and execution sequence of tasks within each layer.</p><h4>Let’s check with Airflow UI</h4><p>Execute <strong>docker-compose up</strong> to build and start the defined services.</p><p>Navigate to the Airflow web UI, typically available at <strong>localhost:8080</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZCJN3SYTfgdOkfJC_YWfeA.png" /></figure><p>Explore the Airflow UI to visualise DAGs, monitor task execution, and manage your orchestrated workflows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MkUwniS8zwX_YXQmXOmSDA.png" /></figure><p>This user-friendly web interface provides a central hub for managing, monitoring, and interacting with your data pipeline, offering a comprehensive view of your workflows and tasks.</p><p>At this stage, we have reached the end of our task and achieved our goal of scheduling the pipeline to run daily. I hope this content was of help, thanks for the support.</p><p>You can access the code on the following gitHub <a href="https://github.com/gnomondigital/gd-datamesh-tutorial/tree/main">repo</a>.</p><h3>Conclusion</h3><p>Accessing data in real-time is essential in today’s world, making it important to automate the process of retrieving that data. We must ensure the pipeline runs smoothly and consider implementing notifications to alert us in case of any errors. We’ve only scratched the surface of what this tool can do, and there’s plenty more to explore!</p><p>Now that the data is clean, we will see how to use it effectively. Before diving into the analysis, we need to serve the data, and what better way to do that than through APIs?</p><p>See you soon in our next content ! <em>Build a Data Product with FastAPI</em></p><p>Fore more content like this you can visite us on <a href="https://medium.com/gnomondigital">Gnomon Digital</a> page.</p><p><em>&lt; Previous chapters</em></p><p><a href="https://medium.com/gnomondigital/data-mesh-on-gcp-from-operational-data-to-data-product-deployment-173e43e06b68">Data Mesh on GCP — From Operational Data to Data Product Deployment</a></p><p><a href="https://medium.com/gnomondigital/part-1-4-build-etl-pipelines-of-data-domain-with-medallion-architecture-a14b983866a1"><em>Part 1/4 — Build ETL Pipelines of Data Domain with Medallion Architecture</em></a></p><p><em>&gt; Next chapter</em></p><p><em>Part 3/4 — Build a Data Product with FastAPI</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c20a615e9b2b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/gnomondigital/part-2-4-orchestrating-a-data-pipeline-with-airflow-c20a615e9b2b">Part 2/4 — Orchestrating a Data Pipeline with Airflow</a> was originally published in <a href="https://medium.com/gnomondigital">Gnomon Digital</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 1/4 — Build ETL Pipelines of Data Domain with Medallion Architecture]]></title>
            <link>https://medium.com/gnomondigital/part-1-4-build-etl-pipelines-of-data-domain-with-medallion-architecture-a14b983866a1?source=rss----07d683c09d9f---4</link>
            <guid isPermaLink="false">https://medium.com/p/a14b983866a1</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[medallion-architecture]]></category>
            <category><![CDATA[data-mesh]]></category>
            <category><![CDATA[airflow]]></category>
            <dc:creator><![CDATA[Nacima Yahiatene]]></dc:creator>
            <pubDate>Thu, 03 Oct 2024 18:53:31 GMT</pubDate>
            <atom:updated>2025-02-17T13:18:17.045Z</atom:updated>
            <content:encoded><![CDATA[<h3>Part 1/4 — Build ETL Pipelines of Data Domain with Medallion Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/819/1*9K37wfltqC4z52ebhV4wHg.png" /></figure><h3><strong>Table of contents:</strong></h3><p>· <a href="#da89">Table of contents:</a><br>· <a href="#0d08">Introduction</a><br>· <a href="#4411">Medallion Architecture</a><br>· <a href="#269a">Project structure </a><br> ∘ <a href="#c557">Data Pipeline Structure: Source, Data Plane, and Docker Image</a><br> ∘ <a href="#8172">Orchestration with Airflow </a><br> ∘ <a href="#f782">App and Analytics Tools: Fast API for Gold Data Retrieval</a><br> ∘ <a href="#643d">Deployment :</a><br>· <a href="#cd80">Project environment setup</a><br>· <a href="#545f">Pipeline implementation</a><br> ∘ <a href="#eaf8">Bronze Layer Data Processing</a><br> ∘ <a href="#0c80">Silver Layer Data processing</a><br> ∘ <a href="#1a50">Gold Layer Data processing</a><br>· <a href="#acce">Build a Docker Image </a><br> ∘ <a href="#7559">Download Docker Desktop</a><br> ∘ <a href="#7c57">DockerFile code </a><br> ∘ <a href="#82c3">Building the Docker Image locally</a><br> ∘ <a href="#c175">Adding Environment Variables</a><br> ∘ <a href="#7d1e">Testing the Pipeline</a><br>· <a href="#d628">Conclusion</a></p><p><em>previous chapter &gt; </em><a href="https://medium.com/@nacima.yahiatene/data-mesh-on-gcp-from-operational-data-to-data-product-deployment-173e43e06b68"><em>Data Mesh on GCP — From Operational Data to Data Product Deployment</em></a></p><p>In our <a href="https://medium.com/@nacima.yahiatene/data-mesh-on-gcp-from-operational-data-to-data-product-deployment-173e43e06b68">previous discussion</a>, we explored the foundations of Data Mesh and its evolution, emphasising the significance of the four core principles.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gcqykkmaGmURbX1CHR-IEA.png" /></figure><p>The current article serves as a practical extension of that exploration.</p><h3>Introduction</h3><p>Data Mesh advocates for domain-oriented decentralised data ownership and architecture, emphasising the need for each domain to independently manage its data.</p><p>Medallion Architecture aligns seamlessly with this principle by providing a structured approach to building ETLs (Extract, Transform, Load pipelines). These pipelines play a vital role in connecting data sources to analytical data planes, resulting in an efficient data flow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bE7ixuqunRJhzlRNBE4q7A.png" /><figcaption>figure: data pipeline using Medallion Architecture</figcaption></figure><p>By employing Medallion Architecture to construct ETL pipelines, we adhere to the Data Mesh philosophy of domain-specific data management. Each medallion within the architecture corresponds to a specific domain, encapsulating the responsibilities of that domain in handling its data.</p><h3>Medallion Architecture</h3><p>Medallion Architecture has emerged as a strategic solution to the challenges posed by the growing complexity of data management.</p><p>It’s implementation lies in the creation of modular and interconnected units, reminiscent of the pieces of a medallion, each encapsulating specific data processing logic. This architecture aims to enhance scalability, flexibility, and resilience in data processing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ewi_z_uFgT0_LAB-dLwSIg.png" /></figure><p>A medallion architecture is a data design pattern used to logically organise data, with the goal of incrementally and progressively improving the structure and quality of data as it flows through each layer of the architecture (from Bronze ⇒ Silver ⇒ Gold layer tables)</p><p><em>reference: </em><a href="https://dataengineering.wiki/Concepts/Medallion+Architecture"><em>wiki-data-engineer</em></a></p><h3>Project structure</h3><p>Our final objective is to craft a robust Open NASA data pipeline that transforms raw information into actionable insights.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p_VrjZqnjPAWo6jpiKIJcA.png" /></figure><h4><strong>Data Pipeline Structure: Source, Data Plane, and Docker Image</strong></h4><p>We begin with pulling NASA open data from the Amazon S3 bucket. This raw information serves as the foundation for our pipeline.</p><p>Data Plane Layers:</p><p><strong><em>Bronze Layer:</em></strong> This stage involves collecting data from diverse sources like NASA open data from the Amazon S3 bucket and geographical reference information from a CSV file.</p><p><strong><em>Silver Layer:</em></strong> Transitioning to the Silver tier, our focus shifts to refining and transforming the raw data. Cleaning, normalisation, and enrichment.</p><p><strong><em>Gold Layer:</em></strong> In this layer, we aggregate silver data by combining NASA open data with geographical reference information.</p><p>To encapsulate our entire pipeline, we create a <strong><em>Docker image</em></strong>. This image captures the configuration, dependencies, and code required.</p><p><em>chapter &gt; Part 1/4 — Build ETL Pipelines of Data Domain with Medallion Architecture</em></p><h4>Orchestration with Airflow</h4><p>The orchestration process ensures that our data remains current and relevant. Considering NASA’s open data is updated daily, our orchestration with Airflow incorporates scheduled tasks that pull the latest data from the Amazon S3 bucket. This approach guarantees that our data pipeline is always synchronised with the most recent information.</p><p>It also automates the execution of tasks across the Bronze, Silver, and Gold layers. This insures that we will always have the recent data in the gold layer.</p><p><em>chapter &gt; Part 2/4 — Orchestrating a Data Pipeline with Airflow</em></p><h4>App and Analytics Tools: Fast API for Gold Data Retrieval</h4><p>We use Fast API to create a robust API that facilitates the retrieval of data from the Gold layer in the PostgreSQL database. This API serves as a gateway for accessing refined and valuable data.</p><p><em>chapter &gt; Part 3/4 — Build Data Product with FastAPI</em></p><h4><strong>Deployment</strong> :</h4><p>The Fast API created for Gold data retrieval is deployed using Terraform.</p><p><em>chapter &gt; Part 4/4 — Deploy an API using Terraform on GCP</em></p><p>we will start with the first step which is the creation of the data pipeline, but before that we will see how to set up the environment.</p><h3>Project environment setup</h3><p>Setting up the project environment is an important step in the development process. It involves creating the necessary structure and configurations for a smooth workflow. In this context, we’ll explore the use of Poetry for project dependency management.</p><p><strong><em>What is Poetry?</em></strong></p><p><a href="https://python-poetry.org/">Poetry</a> is a Python dependency management and packaging tool. It simplifies the process of managing project dependencies, handling packaging, and supporting virtual environments. Poetry also generates a comprehensive <em>pyproject.toml</em> file to manage project metadata and dependencies.</p><p><strong><em>Why use Poetry?</em></strong></p><p>If you use create a project, you will have problems adding, removing dependencies, solve the issue of packaging, virtual environment creation, toolchain configuration, and dependency management. None of these things are impossible--or sometimes even hard--but the point is to merge them all into a single document (pyproject.toml) so that comprehensive tools like Poetry can make the entire process easy and seamless.</p><p><strong><em>Implementation :</em></strong></p><p>Create a New Project Folder</p><pre>mkdir gd-nasa-pipeline<br><br># Navigate to the newly created folder<br>cd gd-nasa-pipeline<br><br># open vscode<br>code .<br><br>#Add Poetry Configurations<br>poetry init</pre><p>Run the following command to initiate poetry configurations:</p><pre>poetry init</pre><p>Update the <em>pyproject.toml</em> file to include package details:</p><pre>[tool.poetry]<br>name = &quot;gd-nasa-pipeline&quot;<br>version = &quot;0.1.0&quot;<br>packages = [{ include = &quot;gd_nasa_pipeline&quot;, from = &quot;src&quot; }]<br>readme = &quot;README.md&quot;<br><br>[tool.poetry.dependencies]<br>python = &quot;^3.11&quot;<br><br>[build-system]<br>requires = [&quot;poetry-core&quot;]<br>build-backend = &quot;poetry.core.masonry.api&quot;</pre><p>Finally, activate the virtual environment using the following command:</p><pre>poetry shell</pre><h3>Pipeline implementation</h3><p>We will apply the Medallion Architecture with it’s three layers: Bronze, Silver, and Gold.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r33zf-m3tbmnvp51rpauNQ.png" /></figure><h4>Bronze Layer Data Processing</h4><p>The Bronze layer extracts nasa open data from AWS and geographical reference data for cities from a CSV file, which are then loaded into PostgreSQL database.</p><p>Data sources :</p><ul><li>Dataset : <a href="https://registry.opendata.aws/nasa-power/">https://registry.opendata.aws/nasa-power/</a></li><li>Referential : <a href="https://simplemaps.com/data/world-cities">https://simplemaps.com/data/world-cities</a></li></ul><p><strong>Code </strong>— extract_nasa.py:</p><pre>def load_data_to_postgres(<br>        database_name: str,<br>        schema_name: str,<br>        table_name: str) -&gt; Optional[Any]:<br>    files_names = aws_handler.get_daily_files_from_s3()<br>    dataframes = []<br><br>    # Read each file and append its DataFrame to the list<br>    for file_name in files_names:<br>        cn_file = aws_handler.read_nc_file(file_name=file_name)<br>        dataset = nc_to_dataframe(cn_file)<br>        dataset.columns = map(to_snake_case, dataset.columns)<br>        dataframes.append(dataset)<br><br>    # Combine all DataFrames into one<br>    combined_dataset = pd.concat(dataframes, ignore_index=True)<br>    logger.info(&quot;Load data to postgres ...&quot;)<br>    output = postgres_handler.write_dataframe(<br>        dataset=combined_dataset,<br>        database_name=database_name,<br>        schema_name=schema_name,<br>        table_name=table_name,<br>    )<br>    logger.info(&quot;Data loaded successfully.&quot;)<br>    return output</pre><p><strong>Code</strong> — extract_geo_reference.py:</p><pre>def load_csv_to_postgres(<br>    database_name: str,<br>    schema_name: str,<br>    table_name: str,<br>    file_path: str = &quot;data/worldcities.csv&quot;<br>) -&gt; Optional[Any]:<br>    &quot;&quot;&quot;<br>    Load data from a CSV file into a PostgreSQL database.<br><br>    Parameters:<br>    - database_name (str): Name of the target PostgreSQL database.<br>    - schema_name (str): Name of the schema where the table is located.<br>    - table_name (str): Name of the table where data will be loaded.<br>    - file_path (str): Path to the CSV file containing the data (default is &quot;data/worldcities.csv&quot;).<br><br>    Returns:<br>    - Optional[Any]: Result of the database write operation, or None if an error occurs.<br>    &quot;&quot;&quot;<br><br>    # Log the start of the data reading process<br>    logger.info(&quot;Reading geographic data from %s&quot;, file_path)<br><br>    try:<br>        # Read the CSV file into a pandas DataFrame<br>        # The `sep=&quot;,&quot;` ensures that the data is read using commas as delimiters<br>        # The `dtype=&quot;str&quot;` parameter forces all columns to be read as strings to avoid type mismatches<br>        df_data = pd.read_csv(file_path, sep=&quot;,&quot;, dtype=&quot;str&quot;)<br>        logger.info(&quot;Data read successfully.&quot;)<br><br>        # Log that the process of loading data to Postgres is about to start<br>        logger.info(&quot;Loading data to Postgres...&quot;)<br><br>        # Use the postgres_handler object to write the DataFrame to the specified PostgreSQL table<br>        # The function is provided with the database, schema, table name, and dataset (DataFrame)<br>        output = postgres_handler.write_dataframe(<br>            dataset=df_data,<br>            database_name=database_name,<br>            schema_name=schema_name,<br>            table_name=table_name,<br>        )<br><br>        # Log the successful completion of the data loading process<br>        logger.info(&quot;Data loaded successfully.&quot;)<br>        return output<br><br>    except Exception as e:<br>        # If an exception occurs during the process, log the error message<br>        logger.error(&quot;Error loading data to Postgres: %s&quot;, str(e))<br>        return None<br></pre><h4>Silver Layer Data processing</h4><p>In the Silver layer, columns are selected from the Bronze tables in PostgreSQL. This step involves loading data from the Bronze layer, transform them, then load into the solver layer.</p><p><strong>Code </strong>— migrate_nasa_data_table_to_silver.py :</p><pre>def migrate_table_to_silver(<br>    database: str,<br>    table_name: str,<br>    schema_source: str,<br>    schema_destination: str,<br>) -&gt; bool:<br>    &quot;&quot;&quot;<br>    Migrate a table from the source schema to the silver schema (schema_destination) in a PostgreSQL database.<br><br>    Args:<br>        database (str): Name of the PostgreSQL database.<br>        table_name (str): Name of the table to be migrated.<br>        schema_source (str): Source schema where the table currently resides.<br>        schema_destination (str): Destination schema to where the table will be migrated.<br><br>    Returns:<br>        bool: Returns True if the migration succeeds.<br>    &quot;&quot;&quot;<br><br>    # Initialize a PostgresHandler instance to handle database connections<br>    postgres_handler = PostgresHandler()<br><br>    # Launch a connection to the specified PostgreSQL database<br>    engine = postgres_handler.launch_connection_db(database)<br><br>    # Define the specific columns to be migrated from the source table<br>    columns = &quot;lon, lat, time, ts, ts__max, ts__min, t2_m, t2_m__range, t10_m__range&quot;<br><br>    try:<br>        # Begin a new database transaction using the engine<br>        with engine.begin() as conn:<br>            # Construct a SQL query to create the target table in the destination schema<br>            query = create_table(<br>                source_schema=schema_source,<br>                source_table=table_name,<br>                destination_schema=schema_destination,<br>                destination_table=table_name,<br>                columns=columns,<br>            )<br><br>            # Log the generated SQL query for debugging or verification<br>            logger.info(&quot;query is : %s&quot;, query)<br><br>            # Open a cursor to execute the SQL query<br>            cursor = conn.connection.cursor()<br>            cursor.execute(query)  # Execute the query to create/migrate the table<br><br>            # Log success message after successful execution of the query<br>            logger.info(&quot;success execution of query: %s&quot;, query)<br><br>            # Close the cursor after the query execution is completed<br>            cursor.close()<br><br>    except Exception as e:<br>        # If an error occurs during the process, log the error message<br>        logger.info(&quot;Error: %s&quot;, e)<br><br>    finally:<br>        # Dispose of the engine (database connection) whether or not the operation succeeded<br>        engine.dispose()<br><br>    # Return True to indicate that the process completed (success is assumed if no error is raised)<br>    return True</pre><p><strong>Code</strong> -migrate_geo_table_to_silver.py:</p><pre>def migrate_geo_table_to_silver(<br>    database: str,<br>    table_name: str,<br>    schema_source: str,<br>    schema_destination: str,<br>) -&gt; bool:<br>    &quot;&quot;&quot;<br>    Migrate a geographic table from the source schema to the silver schema (schema_destination) in a PostgreSQL database.<br><br>    Args:<br>        database (str): Name of the PostgreSQL database.<br>        table_name (str): Name of the table to be migrated.<br>        schema_source (str): Source schema where the table currently resides.<br>        schema_destination (str): Destination schema where the table will be migrated.<br><br>    Returns:<br>        bool: Returns True if the migration succeeds, otherwise logs the error.<br>    &quot;&quot;&quot;<br><br>    # Initialize a PostgresHandler instance to handle database connections<br>    postgres_handler = PostgresHandler()<br><br>    # Launch a connection to the specified PostgreSQL database<br>    engine = postgres_handler.launch_connection_db(database)<br><br>    # Define the columns to be migrated from the source table (geographic information like city, lat, lng)<br>    columns = &quot;city, admin_name, lat, lng, country, capital&quot;<br><br>    try:<br>        # Begin a new transaction using the engine<br>        with engine.begin() as conn:<br>            # Construct a SQL query to create the target table in the destination schema<br>            query = create_table(<br>                source_schema=schema_source,<br>                source_table=table_name,<br>                destination_schema=schema_destination,<br>                destination_table=table_name,<br>                columns=columns,<br>            )<br><br>            # Log the generated SQL query for debugging or verification<br>            logger.info(&quot;query is : %s&quot;, query)<br><br>            # Open a cursor to execute the SQL query<br>            cursor = conn.connection.cursor()<br>            cursor.execute(query)  # Execute the query to create/migrate the table<br><br>            # Log success message after successful execution of the query<br>            logger.info(&quot;success execution of query: %s&quot;, query)<br><br>            # Close the cursor after query execution<br>            cursor.close()<br><br>    except Exception as e:<br>        # If an error occurs, log the error message<br>        logger.info(&quot;Error: %s&quot;, str(e))<br><br>    finally:<br>        # Dispose of the database engine, closing the connection after use<br>        engine.dispose()<br><br>    # Return True to indicate that the process completed successfully (errors are logged, but True is always returned)<br>    return True</pre><h4>Gold Layer Data processing</h4><p>The Gold layer integrates the two datasets based on the closest values of latitude and longitude. This final refinement produces a sophisticated dataset, combining temperature data and city information, ready for advanced analysis.</p><p><strong>Code -</strong>silver_to_gold.py :</p><pre>def migrate_table_to_gold(<br>    database: str,<br>    table_name: str,<br>    table_name_data: str,<br>    table_name_ref: str,<br>    schema_source: str,<br>    schema_destination: str,<br>) -&gt; bool:<br>    &quot;&quot;&quot;<br>    Migrate and merge two tables from the source schema to the gold schema (schema_destination) in a PostgreSQL database.<br><br>    Args:<br>        database (str): Name of the PostgreSQL database.<br>        table_name (str): Name of the target table in the gold schema.<br>        table_name_data (str): Name of the primary data table to be migrated from the source schema.<br>        table_name_ref (str): Name of the reference table to be merged with the data table.<br>        schema_source (str): Source schema where the data and reference tables reside.<br>        schema_destination (str): Destination schema where the merged table will be written.<br><br>    Returns:<br>        bool: Returns True if the migration and merging process succeeds.<br>    &quot;&quot;&quot;<br><br>    # Initialize a PostgresHandler instance to manage the connection to the database<br>    postgres_handler = PostgresHandler()<br><br>    # Retrieve the source tables from the source schema using the Postgres handler<br>    # df1: The primary data table; df2: The reference table for merging<br>    df1, df2 = get_source_tables(<br>        database,<br>        table_name_data,<br>        table_name_ref,<br>        schema_source,<br>        postgres_handler<br>    )<br><br>    # Rename columns in the reference table (df2) if needed<br>    # Assumed to standardize column names for compatibility with df1<br>    df2 = rename_columns(df2)<br><br>    # Ensure that the latitude (&#39;lat&#39;) and longitude (&#39;lon&#39;) columns in both dataframes are of type float64<br>    # This ensures consistent data types for merging on geographic coordinates<br>    df1, df2 = ensure_column_types_float64(df1, df2, [&#39;lat&#39;, &#39;lon&#39;])<br><br>    # Merge the two dataframes on &#39;lat&#39; and &#39;lon&#39; columns (geographic location)<br>    # This performs the data combination, likely using a join on these columns<br>    merged_table = merge_dataframes_on_lat_lon(df1, df2)<br><br>    # Add a primary key column to the merged dataframe, which will serve as the unique identifier in the target table<br>    merged_table = add_primary_key(merged_table)<br><br>    # Write the merged dataframe to the destination schema in the PostgreSQL database<br>    return write_dataframe_to_postgres(<br>        merged_table,              # The merged table data<br>        database,                  # The database name<br>        schema_destination,        # The destination schema (gold)<br>        table_name,                # The final table name<br>        postgres_handler           # The Postgres handler to manage database operations<br>    )</pre><p>Now we have clean data ready to be exploited. Our next step is to create the docker image of this pipeline.</p><h3>Build a Docker Image</h3><p>This section provides a Docker file along with instructions for building and running the associated Docker image. Here is a description of the essential components and steps.</p><h4>Download Docker Desktop</h4><p>Visit the official <a href="https://www.docker.com/products/docker-desktop/">Docker Desktop website</a> and download the appropriate version for your operating system (Windows/Mac).</p><h4>DockerFile code</h4><pre># Use the official Python 3.11 slim image as the base<br>FROM python:3.11-slim-bullseye<br><br># Set environment variables<br>ENV PYTHONUNBUFFERED=1 \\<br>    PYTHONDONTWRITEBYTECODE=1 \\<br>    PIP_NO_CACHE_DIR=off \\<br>    PIP_DISABLE_PIP_VERSION_CHECK=on \\<br>    PIP_DEFAULT_TIMEOUT=100 \\<br>    POETRY_HOME=&quot;/opt/poetry&quot; \\<br>    POETRY_VIRTUALENVS_IN_PROJECT=true \\<br>    POETRY_NO_INTERACTION=1 \\<br>    PYSETUP_PATH=&quot;/opt/pysetup&quot; \\<br>    VENV_PATH=&quot;/opt/pysetup/.venv&quot;<br><br># Add Poetry and project paths to the PATH variable<br>ENV PATH=&quot;$POETRY_HOME/bin:$VENV_PATH/bin:$PATH&quot;<br><br># Install essential dependencies<br>RUN buildDeps=&quot;build-essential&quot; \\<br>    &amp;&amp; apt-get update \\<br>    &amp;&amp; apt-get install --no-install-recommends -y \\<br>        curl \\<br>        vim \\<br>        netcat \\<br>    &amp;&amp; apt-get install -y --no-install-recommends $buildDeps \\<br>    &amp;&amp; rm -rf /var/lib/apt/lists/*<br><br># Set Poetry version and install it<br>ENV POETRY_VERSION=1.4.1<br>SHELL [&quot;/bin/bash&quot;, &quot;-o&quot;, &quot;pipefail&quot;, &quot;-c&quot;]<br>RUN curl -sSL &lt;https://install.python-poetry.org&gt; | POETRY_HOME=${POETRY_HOME} python3 - --version ${POETRY_VERSION} &amp;&amp; \\<br>    chmod a+x /opt/poetry/bin/poetry<br><br># Create a user and set up the working directory<br>RUN groupadd -g 1500 poetry &amp;&amp; \\<br>    useradd -m -u 1500 -g poetry poetry<br><br># Copy project files into the /app directory<br>COPY --chown=poetry:poetry ./ /app<br><br># Switch to the poetry user and set the working directory<br>USER poetry<br>WORKDIR /app<br><br># Install project dependencies using Poetry<br>RUN poetry install --only main<br><br># Expose port 8000<br>EXPOSE 8000<br><br># Define the entrypoint and default command<br>ENTRYPOINT [&quot;poetry&quot;, &quot;run&quot;, &quot;app&quot;]<br>CMD [&quot;--view&quot;, &quot;bronze&quot;]</pre><h4>Building the Docker Image locally</h4><p>To build the Docker image, execute the following command:</p><pre>docker build --no-cache -t gd-nasa-pipeline .</pre><h4>Adding Environment Variables</h4><p>We’ve provided a link to instructions on how to add environment variables to your container. Ensure that the specified environment variables (DB_HOST, DB_NAME, DB_USER, DB_PASS, DB_PORT) are correctly configured to match your database setup.</p><p><em>how to add environment</em> <em>variables: </em><a href="https://superuser.com/questions/1803976/how-to-add-an-environment-variable-to-a-container-in-docker-desktop"><em>here</em></a><em>.</em></p><pre>DB_HOST = &quot;your_host&quot;<br>DB_NAME = &quot;your_db_name&quot;<br>DB_USER = &quot;your_db_user&quot;<br>DB_PASS = &quot;your_db_pass&quot;<br>DB_PORT = 1234</pre><h4>Testing the Pipeline</h4><p>We’ve included an image demonstrating the successful creation and testing of our data pipeline using Docker containers. The image shows the pipeline execution with the <strong>--view bronze</strong> command.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WSW__xUNndBIH25ag_gcuA.png" /></figure><p>Our Docker image is now created and can be used.</p><h3>Conclusion</h3><p>As we conclude this chapter of our series about data pipelines using Medallion Architecture, several key points and essential notions have come to the forefront:</p><ul><li>The Medallion Architecture, with its three distinctive layers — Bronze, Silver, and Gold.</li><li>The integration of Amazon S3, CSV files, and PostgreSQL database.</li><li>The orchestration prowess of Apache Airflow ensuring that the data flow remains coordinated and up-to-date.</li><li>Building docker images.</li></ul><p>As we move forward to subsequent chapters like exploring orchestration with Airflow, building APIs with FastAPI, and deploying the entire NASA API using Terraform on Google Cloud Platform.</p><p>Each step is a progression, bringing us closer to a fully functional and scalable Data Mesh implementation.</p><p>For more articles of this kind you can visite the Gnomon Digital medium <a href="https://medium.com/gnomondigital">publications</a> or <a href="https://www.gnomondigital.com/">website</a>.</p><p><em>Next chapter &gt; </em><a href="https://medium.com/gnomondigital/part-2-4-orchestrating-a-data-pipeline-with-airflow-c20a615e9b2b"><em>Part 2/4 — Orchestrating a Data Pipeline with Airflow</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a14b983866a1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/gnomondigital/part-1-4-build-etl-pipelines-of-data-domain-with-medallion-architecture-a14b983866a1">Part 1/4 — Build ETL Pipelines of Data Domain with Medallion Architecture</a> was originally published in <a href="https://medium.com/gnomondigital">Gnomon Digital</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cloudflare: A Solution for a Faster, Safer Website]]></title>
            <link>https://medium.com/gnomondigital/cloudflare-a-solution-for-a-faster-safer-website-f84586c6f5de?source=rss----07d683c09d9f---4</link>
            <guid isPermaLink="false">https://medium.com/p/f84586c6f5de</guid>
            <category><![CDATA[cloudflare]]></category>
            <category><![CDATA[governance]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Ghiles Yahiatene]]></dc:creator>
            <pubDate>Tue, 13 Aug 2024 11:25:28 GMT</pubDate>
            <atom:updated>2025-02-19T18:14:41.870Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/819/1*LRMh2srdWOGe2_Ib7_ptkA.jpeg" /></figure><h3><strong>Table of Contents</strong></h3><p>· <a href="#96a2">Introduction</a><br>· <a href="#016b">Key Features of Cloudflare</a><br>· <a href="#383e">Easy Setup of Cloudflare</a><br>· <a href="#c8db">Our Experience with Cloudflare</a><br>· <a href="#401c">Our Advice</a><br>· <a href="#91bf">Conclusion and Resources</a></p><h3>Introduction</h3><p>Founded in 2009, <a href="https://www.cloudflare.com/"><strong>Cloudflare</strong></a> is an online service designed to enhance the performance and security of company websites. Think of it as a super assistant that makes your site faster and safer. It’s crucial because it can shield your site from online attacks and help your pages load more quickly for your visitors. Cloudflare quickly evolved to become a leader in web performance and security services.</p><h4>What Makes Cloudflare Special</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DQpVo9jwzlcmprIq2mMXuw.png" /><figcaption>source : <a href="https://blog.cloudflare.com/speed-week-2023-network-performance-update">https://blog.cloudflare.com/speed-week-2023-network-performance-update</a></figcaption></figure><p>When choosing a Content Delivery Network provider, performance is a crucial factor. The graph above, which compares the performance of Cloudflare and other entities between July 2022 and May 2023, provides compelling evidence explaining why Cloudflare stands out as the best choice. Here are the detailed reasons why Cloudflare stands out and what benefits it brings to clients:</p><ul><li><strong>Superior Performance</strong>: Cloudflare consistently ranks highest in the percentage of networks where it is the fastest, growing from around 30% to 40% over the past year. This means faster loading times for websites and applications, thereby improving user experience, reducing bounce rates, and increasing conversions and sales.</li><li><strong>Reliability</strong>: With minimal fluctuations in performance, Cloudflare ensures that your content is delivered quickly and reliably, guaranteeing constant service availability, maintaining user trust, and allowing businesses to operate without interruption.</li><li><strong>Continuous Improvement</strong>: The steady upward trend in performance shows that Cloudflare is always optimizing and getting better, This allows clients to benefit from the latest technological advancements and optimizations without having to switch providers, ensuring top-notch performance and increased competitiveness.</li><li><strong>Market Leadership</strong>: Cloudflare’s strong and improving performance, especially compared to competitors like Akamai, highlights its leadership in the CDN market, This offers clients additional assurance of quality and reliability, enhancing their reputation with end users.</li></ul><h3>Key Features of Cloudflare</h3><h4><a href="https://www.cloudflare.com/application-security/">Application Security</a></h4><p>One of Cloudflare’s major strengths is the importance it places on web application security. It offers tools to detect malicious bot traffic, customizable rules to filter incoming traffic, SSL certificates to encrypt data, and a web application firewall to protect against threats.</p><h4><a href="https://www.cloudflare.com/network-services/">Network Services</a></h4><p>The majority of individuals and organizations turn to Cloudflare for its features that accelerate content delivery, optimize images, and ensure fast traffic routing. Additional options support high availability, video hosting, and provide network-level protections. How is this possible? In fact, Cloudflare’s CDN stores copies of your site on servers around the world, helping to load pages faster for visitors, no matter where they are located.</p><h4><a href="https://www.cloudflare.com/zero-trust/">Zero Trust Services</a></h4><p>Cloudflare’s Zero Trust services adopt a security model that does not trust any user or device by default. They include secure access to internal applications without a VPN, web browsing isolation to protect against threats, and email security features to guard against phishing and malware.</p><h4><a href="https://developers.cloudflare.com/">Developer Platform, Insights and AI</a></h4><p>This platform offers tools and resources to create and deploy applications. This includes quick start guides, hosting options for static sites, practical examples, and tutorials. Command-line tools and a runtime environment support development, while detailed analytics and logs provide valuable insights. Additionally, Cloudflare integrates artificial intelligence capabilities, such as the AI Gateway and Vectorize, as well as Workers AI, enabling the development of intelligent applications and the integration of AI features.</p><h3>Easy Setup of Cloudflare</h3><p>Is it easy to set up Cloudflare? Yes, it really is. Just follow these steps:</p><h4>Step 1: Create an Account</h4><p>To get started, visit the Cloudflare website and create an account using your email address. It’s free.</p><h4>Step 2: Add Your Website</h4><p>Once your account is created, you can add your website by entering its address (URL). Cloudflare will then analyze your site and guide you through the next steps.</p><h4>Step 3: Configure DNS Settings</h4><p>Cloudflare will ask you to update your domain’s DNS settings. This may seem technical, but they provide clear instructions. You will need to copy some information from Cloudflare and paste it into your domain settings with your domain provider.</p><h3>Our Experience with Cloudflare</h3><p>At <a href="https://www.gnomondigital.com/">Gnomon Digital</a>, our official website was experiencing performance issues, particularly with page load times, which negatively impacted the user experience. To address these problems, we decided to turn to Cloudflare.</p><h4>Positive Points</h4><p>We appreciated the ease of integrating Cloudflare with our existing infrastructure. Subsequently, several improvements were observed, particularly:</p><ul><li>Reduced Page Load Times: The time it takes for pages to load has significantly decreased.</li><li>Enhanced Security: The DDoS protection and other security features have been very effective.</li><li>User-Friendly DNS Management: The DNS management dashboard is intuitive and easy to use, reducing errors and management time.</li></ul><h4>Negative Points</h4><p>However, we also encountered some challenges:</p><ul><li>Dashboard Errors: When modifying firewall rules, there is often a delay of several seconds before the changes are applied.</li><li>Performance and Security Graphs: These graphs do not always load correctly, sometimes requiring a page refresh.</li><li>Limitations of the Free Version: The free version is quite limited in terms of the Web Application Firewall, with only 5 rules available. To fully leverage Cloudflare’s potential, upgrading to the paid version is inevitable.</li></ul><h4>Did It Help Us and Do We Recommend It?</h4><p>Overall, Cloudflare has greatly helped improve the performance and security of our website. The benefits far outweigh the minor inconveniences we encountered. Therefore, we highly recommend the use of Cloudflare to other website administrators looking to enhance their site’s performance and security.</p><h3>Our Advice</h3><ul><li>First, you need to assess the specific needs of your site in terms of performance and security, as well as your own needs, to determine if Cloudflare’s features align with and are suitable for your objectives.</li><li>Be prepared to update your domain’s DNS settings to point to Cloudflare’s name servers. However, always prioritize security by backing up your current DNS settings so you can restore them quickly if necessary.</li><li>Familiarize yourself with Cloudflare’s offerings, including the CDN, WAF, and SSL/TLS encryption. Understand how to configure and use these features effectively.</li><li>Regularly review the information collected by Cloudflare’s monitoring tools to identify unusual activities. Make the necessary adjustments to maintain optimal performance and security.</li></ul><h3>Conclusion and Resources</h3><p>In summary, Cloudflare makes your site faster, safer, and more reliable. It protects against attacks, improves page load times, and ensures your websites stays online even in case of issues. so we highly recommend it. Don’t hesitate to share also your experiences with us.</p><p><em>We hope you enjoyed reading the article! Be sure to visit our </em><a href="https://medium.com/gnomondigital"><em>Gnomon Digital</em> <em>account</em></a><em> to read other interesting articles.</em></p><h4>Links to Additional Guides and Tutorials</h4><p>To learn more, here are some useful resources:</p><ul><li><a href="https://developers.cloudflare.com/learning-paths/get-started/">Cloudflare Getting Started Guide</a></li><li><a href="https://community.cloudflare.com/">Cloudflare Community Forum</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f84586c6f5de" width="1" height="1" alt=""><hr><p><a href="https://medium.com/gnomondigital/cloudflare-a-solution-for-a-faster-safer-website-f84586c6f5de">Cloudflare: A Solution for a Faster, Safer Website</a> was originally published in <a href="https://medium.com/gnomondigital">Gnomon Digital</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>