<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Israel Ilori on Medium]]></title>
        <description><![CDATA[Stories by Israel Ilori on Medium]]></description>
        <link>https://medium.com/@ogenepabo?source=rss-90839510598------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*i4KQLorMGPgkJkMS</url>
            <title>Stories by Israel Ilori on Medium</title>
            <link>https://medium.com/@ogenepabo?source=rss-90839510598------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 12:44:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ogenepabo/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How I Built an Agentic AI Workflow That Sends Heartfelt Love Notes]]></title>
            <link>https://medium.com/@ogenepabo/building-an-agentic-ai-workflow-a-workflow-that-sends-heartfelt-love-notes-8c6b8f2fdd5f?source=rss-90839510598------2</link>
            <guid isPermaLink="false">https://medium.com/p/8c6b8f2fdd5f</guid>
            <category><![CDATA[airflow]]></category>
            <category><![CDATA[orchestration]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Israel Ilori]]></dc:creator>
            <pubDate>Fri, 10 Oct 2025 05:16:07 GMT</pubDate>
            <atom:updated>2025-11-04T05:45:19.153Z</atom:updated>
            <content:encoded><![CDATA[<p><em>When you teach AI to write love notes, you end up learning about pipelines, feedback loops, and orchestration more than you ever expected.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9nQKGkNNZRmnQjfoPB3MFA.png" /><figcaption>When automation meets emotion</figcaption></figure><h3>Introduction: When Automation Meets Emotion</h3><p>It started as a lighthearted idea: “<em>What if an AI could automatically send thoughtful, emotionally resonant messages to my partner, not generic ones but messages that genuinely sound like me?”</em></p><p>On the surface, this might seem like a fun side project. But underneath, it reflects a deeper technical question that’s increasingly relevant to modern AI systems:</p><p><strong>How do you design Agentic AI workflows that can operate autonomously, contextually, and safely while maintaining quality and personality over time?</strong></p><p>In an age where we’re automating everything from financial forecasts to creative writing, this “love-note” project turned out to be a surprisingly powerful case study in <strong>real-world orchestration</strong>, <strong>retrieval-augmented generation (RAG)</strong>, and <strong>multi-agent design.</strong></p><p>Because building AI that’s reliable, safe, and contextualized for something as simple as monthly heartfelt messages is the same engineering challenge behind AI copilots, automated assistants, and enterprise chat workflows.</p><h3>Background: Why This Project Matters</h3><p>I’ve built AI systems in production for nearly a decade now, everything from model pipelines to MLOps architectures but most systems I’ve worked on have focused on <strong>accuracy</strong>, <strong>throughput</strong>, or <strong>cost efficiency.</strong></p><p>This one aimed for something different<strong>, Authenticity.</strong></p><p>The challenge wasn’t about optimizing a metric, it was about maintaining a <em>human</em> voice over time, even as the system ran automatically. That makes it a perfect example of the larger Agentic AI problem:</p><p><em>How can autonomous systems act on your behalf, over time, while still sounding like </em>you<em>?</em></p><p><strong>Here’s what I set out to build:</strong></p><ul><li>A multi-agent workflow where different AI agents collaborate to write, refine, and send a personalized message.</li><li>A RAG-powered context engine that learns my tone and style from past notes which I had sent.</li><li>A scheduling and delivery system that ensures notes go out automatically on specific dates, with no repeats and no loss of emotional tone.</li></ul><p><strong>The result:</strong><br> A fully autonomous, <strong>Agentic AI system</strong> that generates, evaluates, and delivers heartfelt messages each month powered by <strong>OpenAI LLMs</strong>, <strong>SendGrid</strong>, <strong>ChromaDB</strong>, <strong>Docker and Airflow</strong>.</p><h3>Approach &amp; Architecture</h3><p>At its core, the system is built around three ideas:</p><ol><li><strong>Multi-Agent Collaboration:</strong><br> Each agent has a clear, limited role (writer, evaluator, sender).<br> This makes behavior predictable and the pipeline auditable.</li><li><strong>Retrieval-Augmented Memory:</strong><br> Using ChromaDB as a vector store, the system “remembers” previous notes to maintain style and avoid repetition.</li><li><strong>Orchestrated Execution:</strong><br> The agents are coordinated through an explicit workflow: generation → evaluation → handoff → action.</li></ol><h3>System Architecture Overview</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QWQMEb2ZpsVNeU88sQtCfg.png" /><figcaption>The Agentic AI Workflow</figcaption></figure><h4><strong>Explanation</strong></h4><ul><li>The <strong>Heart Manager</strong> acts as the orchestrator, invoking three independent “writer” agents.</li><li>It collects all drafts, selects the most heartfelt one, and hands it off to the <strong>Love Email Manager</strong>.</li><li>The Email Manager uses three specialized tools:</li><li>Subject Writer → creates a catchy, loving subject.</li><li>HTML Converter → formats text for email rendering.</li><li>SendGrid API → sends the message reliably.</li><li>Finally, the message lands in the inbox — all autonomously.</li></ul><h3>RAG Data Flow</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*of7J2t3a9k59TL577bXW9A.png" /></figure><h4><strong>Explanation</strong></h4><ul><li>Old notes are embedded once and stored in <strong>ChromaDB</strong>.</li><li>Before each new message run, the workflow retrieves similar past notes for <strong>tone continuity</strong>.</li><li>The system “remembers” how it used to express love ensuring the AI doesn’t repeat itself or drift emotionally.</li><li>After sending, the note is written back into the vector store for future reference, thereby creating a <strong>self-evolving memory loop</strong>.</li></ul><h3>Core Workflow in Pseudocode</h3><pre># 1. Setup memory and load embeddings<br>collection = chromadb.get_or_create_collection(name=&quot;heartfelt_notes&quot;, embedding_function=openai_ef)<br><br># 2. Retrieve RAG context<br>context = retrieve_context(&quot;romantic heartfelt note&quot;)<br><br># 3. Generate drafts from 3 agents<br>romantic = run_agent(&quot;Romantic Agent&quot;, context)<br>cheeky   = run_agent(&quot;Cheeky Agent&quot;, context)<br>poetic   = run_agent(&quot;Poetic Agent&quot;, context)<br><br># 4. Pick the best one<br>best_note = pick_best([romantic, cheeky, poetic])<br><br># 5. Handoff to Email Manager<br>subject = generate_subject(best_note)<br>html    = convert_to_html(best_note)<br>send_email(subject, html)<br><br># 6. Save final note to memory<br>collection.add(documents=[best_note])</pre><h3>Scheduling and Execution</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3_W_E-rbmtPIt7EBfxABrQ.png" /></figure><ul><li>Scheduled for <strong>9:00 AM on the 1st day of every month</strong>.</li><li>Local Airflow (not MWAA) ensures full transparency and local debugging.</li><li>Logs capture OpenAI response times, SendGrid delivery confirmation, and trace metadata.</li><li>Ideal for hybrid local/prod testing before scaling to MWAA</li></ul><p>Initially, I considered a cron job or APScheduler, but eventually migrated to <a href="https://github.com/aws/aws-mwaa-local-runner"><strong>aws-mwaa-local-runner</strong></a><strong> (Airflow)</strong>, which mimics the behavior of <strong>prod-level AWS MWAA</strong> while providing full visibility into task logs and retries.</p><p><strong>Why Airflow?</strong></p><ul><li>Easy to test locally.</li><li>Integrates with .env secrets (OpenAI, SendGrid keys).</li><li>Built-in observability which allows me see every “love note run” and debug failures.</li></ul><pre>with DAG(<br>    dag_id=&quot;love_note_dag&quot;,<br>    schedule_interval=&quot;0 9 1 * *&quot;,<br>    start_date=datetime(2025, 1, 1),<br>    catchup=False,<br>) as dag:<br>    send_note = PythonOperator(<br>        task_id=&quot;send_love_note&quot;,<br>        python_callable=run_heartflow<br>    )</pre><p>This gives me a <strong>fully automated monthly loop </strong>every 1st of the month, the AI wakes up, retrieves past context, writes something heartfelt, evaluates, sends, and logs its success.</p><h3>Challenges &amp; Solutions</h3><h4>1. Endless Loops in the Agent Handoff</h4><p>At one point, the workflow would <em>never stop</em> because the Heart Manager kept “thinking,” repeatedly generating new drafts instead of handing one off.</p><p><strong>Why: </strong>the instructions weren’t explicit enough about <em>when</em> to stop or <em>how</em> to call the tools.</p><p><strong>Fix: </strong>I added hard “STOP” rules and explicit tool-call phrasing: <em>“Call the three agent tools exactly once. Handoff the best note to the Email Manager. Then stop.”</em></p><p>Once agents had explicit contracts, the loop disappeared.</p><h4>2. Context Drift in the RAG</h4><p>The first few runs included Valentine’s messages… even though it was July.</p><p><strong>Why: </strong>the vector retrieval pulled past Valentine-themed notes, biasing tone and phrasing.</p><p><strong>Fix: </strong>filtered out special-day terms.</p><pre>if not any(word in doc.lower() for word in [&quot;valentine&quot;, &quot;birthday&quot;, &quot;anniversary&quot;]):<br>    docs.append(doc)</pre><p>That simple filter restored everyday tone and reduced “context contamination.”</p><h4>3. Preventing Duplicates and Overfitting</h4><p>Early on, I noticed the AI reusing similar openings (“My dearest…”).<br> To prevent repetition:</p><ul><li>I hashed each note and stored it as a unique ID in ChromaDB.</li><li>Before sending, I queried for near-duplicates using cosine distance.</li></ul><pre>def is_duplicate(candidate):<br>    results = collection.query(query_texts=[candidate], n_results=1)<br>    return results[&quot;distances&quot;][0][0] &lt; 0.1</pre><p>No repeats since.</p><h4>4. Multi-Agent Coordination</h4><p>It’s easy to underestimate how tricky it is to make LLMs collaborate.<br> Each agent must:</p><ul><li>Understand its scope (what to do, what <em>not</em> to do).</li><li>Produce outputs consumable by others.</li><li>Avoid reasoning indefinitely.</li></ul><p>I solved this by structuring each as a <strong>ToolAgent</strong> using .as_tool().<br> This enforces strict I/O discipline: an agent only responds with what its tool definition allows. It’s like defining API boundaries between microservices, only that in here, the services are personas.</p><h4>5. The Subtle Art of Emotional Consistency</h4><p>This was the hardest part. AI can sound warm but hollow if it loses continuity. By feeding the top 3 most recent notes as context, tone consistency improved dramatically it started reusing idioms and emotional phrasing that sounded genuinely “me.” That’s <strong>RAG</strong> in this usecase both for <strong>knowledge retrieval</strong> and for <strong>emotional continuity.</strong></p><h3>Results</h3><p>Within a few test cycles, the workflow:</p><ul><li>Produced <strong>unique</strong>, heartfelt notes each month.</li><li>Maintained a consistent voice over time.</li><li>Handled <strong>holiday context switching</strong> (e.g., Valentine’s, birthdays) flawlessly.</li><li>Reduced runtime latency from ~45s to &lt;15s using smaller models (gpt-4o-mini).</li><li>Operated autonomously through Airflow with <strong>zero manual intervention.</strong></li></ul><p>And most importantly<em>, The messages being sent started to sound alot like me after about 20 iterations.</em></p><p>Mission accomplished. ❤️</p><h3>Lessons Learned</h3><h4>1. Explicit Instructions Beat Clever Prompts</h4><p>Agentic systems are about <strong>contracts</strong>. Define roles, dependencies, and stop conditions clearly.</p><h4>2. RAG isn’t Just for Facts</h4><p>Retrieval-Augmented Generation can preserve <strong>style, emotion, and personality.</strong></p><h4>3. Every Agent Needs Observability</h4><p>Adding trace() around each run was a lifesaver.</p><h4>4. Orchestration Is the Hard Part</h4><p>The hardest problem was making multiple AIs cooperate predictably under constraints.</p><h4>5. Emotional Intelligence Can Be Engineered</h4><p>Human-like empathy in text is reproducible by thoughtful memory design, retrieval capabilities, and tone conditioning.</p><h3>Closing Thoughts: From Love Notes to Production Pipelines</h3><p>What started as a playful experiment became a mini-version of what modern <strong>Agentic AI systems</strong> represent: multi-agent orchestration, context persistence, feedback loops, and safe execution boundaries.</p><p>It taught me that the difference between a one-off LLM script and a <strong>true AI workflow</strong> is structure. When you give AI agents:</p><ul><li>Clear roles,</li><li>Shared memory,</li><li>And controlled autonomy,</li></ul><p>…they can accomplish far more. In this case it’s sending heartfelt messages, in other cases it could be actually running production pipelines.</p><p>In the end, as much as it was about automating affection notes for my girlfriend, it’s equally about about designing <strong>autonomous systems that act with context, purpose, and reliability.</strong></p><p><em>If you enjoyed this breakdown, follow for more…</em></p><h3>References</h3><p>Ed Donner’s Agentic AI Course on Udemy — <a href="https://www.udemy.com/share/10dasB3@_I29T9pcvMVp6hhh0U9H3jZBdrs0MRZC06K2MZ1haVJ_HS6ALDg0iZNfNjZMyXVovA==/">https://www.udemy.com/share/10dasB3@_I29T9pcvMVp6hhh0U9H3jZBdrs0MRZC06K2MZ1haVJ_HS6ALDg0iZNfNjZMyXVovA==/</a></p><ul><li><a href="https://docs.trychroma.com/docs/overview/getting-started">Chroma Docs</a></li><li><a href="https://github.com/aws/aws-mwaa-local-runner">GitHub - aws/aws-mwaa-local-runner: This repository provides a command line interface (CLI) utility that replicates an Amazon Managed Workflows for Apache Airflow (MWAA) environment locally.</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c6b8f2fdd5f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Knowledge Graph: Transit Network Analysis Using Translink Data, and Gephi]]></title>
            <link>https://medium.com/@ogenepabo/knowledge-graph-transit-network-analysis-using-translink-data-and-gephi-bdc93993e5af?source=rss-90839510598------2</link>
            <guid isPermaLink="false">https://medium.com/p/bdc93993e5af</guid>
            <category><![CDATA[gephi]]></category>
            <category><![CDATA[network-analysis]]></category>
            <category><![CDATA[transportation]]></category>
            <category><![CDATA[knowledge-graph]]></category>
            <category><![CDATA[transport-technology]]></category>
            <dc:creator><![CDATA[Israel Ilori]]></dc:creator>
            <pubDate>Sun, 05 Oct 2025 05:27:54 GMT</pubDate>
            <atom:updated>2025-10-10T05:54:36.103Z</atom:updated>
            <content:encoded><![CDATA[<h3>Knowledge Graph: Transit Network Analysis Using Translink Data, Python and Gephi</h3><p>This research demonstrates how open transit data, combined with knowledge graph modeling and powerful network visualization tools like <strong>Gephi</strong>, can unlock insights about public transportation systems. I collected real-time data from Vancouver’s <strong>TransLink API</strong>, cleaned and transformed it using Python, and built a network graph that maps relationships between transit stops and routes. The graph analysis revealed patterns, vulnerabilities, and opportunities that can support data-informed transit planning.</p><h3>Introduction</h3><p>Public transit systems are complex networks that connect various parts of a city, facilitating daily commutes for millions of people. Understanding the intricacies of these networks is crucial for optimizing traffic flow, improving passenger experiences, and planning future urban development. This paper aims to unravel these complexities using a data-driven approach to network analysis and visualization.</p><h3>Data Collection</h3><p>The data was sourced from the local transit authority’s open API, which provides real-time information on bus routes, stops, schedules, and vehicle movements. An extensive data retrieval process was set up to query the API for various endpoints, collecting information about:</p><ul><li><strong>Bus Stops</strong>: Names, region, identifiers</li><li><strong>Active Buses</strong>: Vehicle IDs, destinations</li><li><strong>Bus Routes</strong>: Trip start and end locations</li></ul><p>Python scripts using requests and pandas handled data fetching and normalization. After parsing thousands of records, I created clean node-edge datasets:</p><ul><li><strong>Nodes</strong> = Transit Stops</li><li><strong>Edges</strong> = Routes between stops, with weights derived from frequency</li></ul><p>Each node was enriched with a region, and each edge included a Route ID and weight (number of buses).</p><h3>Data Preprocessing</h3><p>The raw data was subjected to rigorous cleaning and transformation to ensure accuracy and consistency. Python scripts were developed to automate these tasks, including:</p><ul><li>Parsing and normalizing JSON responses from the API</li><li>Merging data from multiple sources to align stops with routes</li><li>Calculating the weights of edges based on route frequency between stops</li></ul><h3>Network Graph Construction</h3><p>Using <strong>Pythons NetworkX</strong>, I modeled the transit network as a graph library, where nodes represent transit stops and edges represent bus routes connecting these stops. Each edge was assigned a weight proportional to the number of buses traveling that route, capturing the intensity of service.</p><h3>Visualization with Gephi</h3><p>Gephi was utilized to visualize the network graph. The nodes and edges datasets were imported into Gephi, where nodes were arranged using force-directed algorithms to reveal patterns in the network’s structure.</p><ul><li><strong>ForceAtlas2</strong> layout for spatial clustering</li><li>Node size: by degree (number of connected routes)</li><li>Color: by region/modularity class</li><li>Labels: Top stops by centrality</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uME9GWARHVlavk1IqyagAg.png" /></figure><h3>Descriptive Analytics</h3><p>Initial observations of the network topology showed:</p><h4>1. High-Degree Centrality Stops</h4><p>Hub nodes: Nodes like <strong>“Downtown Waterfront Station”</strong>, <strong>“Coquitlam Central Station”</strong>, and <strong>“Bridgeport Station”</strong> appear frequently and connect to many others, these are referred to as <em>hub nodes</em>. Their high node size and central position in the graph indicate high degree centrality.</p><h4>2. Regional Clusters and Modularity</h4><p>The network naturally forms <strong>regional clusters</strong> visible in color-coded communities from Gephi. As seen above,</p><ul><li><strong>Surrey/Langley</strong> forms one cluster.</li><li><strong>UBC/Vancouver/Downtown</strong> forms another.</li><li><strong>Maple Ridge/Coquitlam</strong> is separate.<br> This reveals <strong>geographical modularity</strong> in the transit system.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rtJdPJQ7sQLrA-sF44R_lQ.png" /><figcaption>Surrey/Langley</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BmEJo1oRl-0q-biK-cPScQ.png" /><figcaption>UBC/Vancouver/Downtown</figcaption></figure><h4>3. Peripheral Nodes</h4><p>Stops like <strong>“Ruskin”</strong>, <strong>“Bluewater”</strong>, or <strong>“Snug Cove”</strong> are peripheral with very few links. These likely represent <strong>edge-of-network zones</strong> with limited bus routes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J09o-PfbPOiFCe7EPJGpMw.png" /><figcaption>Snug Cove/Bluewater Peripheral Nodes</figcaption></figure><h4>4. Most Frequent Source — Target Pairs</h4><p>From the edges data, stops like&quot;Coquitlam Central Station&quot; → &quot;Haney Place Exchange&quot; and&quot;Guildford Exchange&quot; → &quot;Newton Exchange&quot;are repeated in different routes, indicating <strong>high-traffic corridors</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qCJ2VlvIm6w_KpxxFtZ1ig.png" /></figure><h4>5. Network Density</h4><p>The graph shows a <strong>sparse</strong> but <strong>strategically connected</strong> network — most stops are not universally connected but optimized through <strong>hub-and-spoke patterns</strong>, balancing coverage and efficiency.</p><h3>Inferential Analytics</h3><h4><strong>1. Regional Transit Equity Analysis</strong></h4><p>From the cluster sizes and number of routes, one can easily infer:</p><ul><li><strong>Urban centers </strong>such as<strong> Downtown, Surrey, Richmond</strong> are well-served.</li><li><strong>Outer regions </strong>like<strong> Bowen Island, Deep Cove</strong> have fewer connections.</li></ul><p>This points to <strong>transit inequality</strong> that can inform future expansions.</p><h4>2. Route Redundancy Risks</h4><p>Highly connected routes serve popular node pairs. An unexpected disruption on such a route could <strong>disproportionately affect access</strong>, suggesting the need for <strong>backup or alternate routing mechanisms</strong>.</p><h4>3. Student vs. Commuter Route Overlay</h4><p>Stops like <strong>“Brookswood Secondary School”</strong> or <strong>“Elgin Park Secondary”</strong> suggest <strong>school-specific routes</strong>, while stops like <strong>“Brentwood Station”</strong> or <strong>“Guildford Exchange”</strong> serve commuters. As a future step, one can model <strong>time-based demand profiles</strong> for optimization (e.g., peak student hours vs. general commute).</p><h3>Final Thoughts</h3><p>I carried out this project to bridge the gap between open source data and actionable transit intelligence. By turning raw bus routes into a knowledge graph, I highlighted how <strong>data science</strong>, <strong>network theory</strong>, and <strong>open tools</strong> can shape smarter cities.</p><h3>Conclusion</h3><p>The application of network analysis and visualization techniques yielded valuable insights into the operational characteristics of the transit network. This methodology can guide future enhancements in public transit services and contribute to more sustainable and efficient urban mobility solutions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bdc93993e5af" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Speaker Recommendation System: A Real-World GenAI Case Study Using Ollama, FAISS (RAG), LangChain…]]></title>
            <link>https://medium.com/@ogenepabo/speaker-recommendation-system-a-real-world-genai-case-study-using-ollama-faiss-rag-langchain-6e977bc03f2a?source=rss-90839510598------2</link>
            <guid isPermaLink="false">https://medium.com/p/6e977bc03f2a</guid>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[langchain]]></category>
            <category><![CDATA[recommendation-system]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[faiss]]></category>
            <dc:creator><![CDATA[Israel Ilori]]></dc:creator>
            <pubDate>Fri, 05 Sep 2025 04:30:03 GMT</pubDate>
            <atom:updated>2025-09-05T04:42:36.243Z</atom:updated>
            <content:encoded><![CDATA[<h3>Speaker Recommendation System: A Real-World GenAI Case Study Using Ollama, FAISS (RAG), LangChain, and Streamlit</h3><p>This article documents the technical process and architectural decisions behind building <strong>Speaker Scout</strong>, a GenAI-powered speakerrecommendation system developed entirely using <strong>LLMs (Meta LLaMA3 via Ollama)</strong>, <strong>FAISS vector search, LangChain</strong> and <strong>Streamlit UI</strong>.</p><p>While the platform solves a very real conference planning need, the project also served as a playful way for me to help my partner, who’s on the organizing team for a major PM conference reduce the time spent sifting through speaker bios. What started as a romantic gesture quickly evolved into a complete AI-powered RAG pipeline.</p><p>And yes, this project <em>absolutely</em> doubled as a crash course in GenAI tooling, vector databases, and user-centered AI design.</p><h4>Problem Context: “Sugar, I Got You.”</h4><p>My girlfriend was deep into planning a project management conference and lamented, <em>“Salt, this speaker stuff is giving me a headache. Too many bios, too little time.”</em></p><p>Of course, the inner nerd in me lit up. What if I could build her a tool that:</p><ul><li>Accepts <strong>conference themes</strong> + <strong>audience type</strong> as input</li><li>Retrieves the most relevant speakers from a curated dataset</li><li>Uses an LLM to explain <em>why</em> those speakers match</li><li>Allows for easy <strong>shortlisting</strong> and <strong>export</strong></li></ul><p><strong>Design Constraints:</strong></p><ul><li>100% open-source, no paid APIs</li><li>Local LLMs</li><li>Lightweight enough to run entire offline</li><li>Designed for practical GenAI learning</li></ul><p>Thus, <strong>Speaker Scout</strong> was born, built not just for her, but as a case study to explore the full RAG pipeline using local tooling.</p><h4>Architecture Overview</h4><p><strong>Tech Stack Overview</strong>:</p><ul><li>LLM Inference: Ollama + Meta LLaMA3</li><li>RAG Vector DB: FAISS</li><li>Embeddings: sentence-transformers (MiniLM)</li><li>Prompt Orchestration: LangChain</li><li>UI: Streamlit</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1016/1*VRWhN6CU865xn-eZ0VxjGw.png" /><figcaption>Model Architecture</figcaption></figure><h4>Dataset Preparation</h4><p>The speaker dataset was a subset of TED Talk presenters, filtered and cleaned into the following structure:</p><ul><li>Speaker</li><li>Speaker Message</li><li>Talk Duration</li><li>Presentation Materials</li><li>Audience Fit</li></ul><p>After dropping nulls and formatting the bios, the CSV was saved as pmi_speaker_inputs.csv.</p><h4>LangChain RAG Pipeline Implementation</h4><p>Step 1: FAISS Vector Store with LangChain</p><pre># Load and format data<br>df = pd.read_csv(&quot;data/pmi_speaker_inputs.csv&quot;)<br>docs = []<br>for idx, row in df.iterrows():<br>content = f&quot;Speaker: {row[&#39;Speaker&#39;]}\nMessage: {row[&#39;Speaker Message&#39;]}\nMaterials: {row[&#39;Presentation Materials&#39;]}&quot;<br>metadata = {&quot;Speaker&quot;: row[&#39;Speaker&#39;], &quot;id&quot;: idx}<br>docs.append(Document(page_content=content, metadata=metadata))<br><br># Create embeddings and vector store<br>embedding_model = SentenceTransformerEmbeddings(model_name=&quot;all-MiniLM-L6-v2&quot;)<br>vectorstore = FAISS.from_documents(docs, embedding_model)<br>vectorstore.save_local(&quot;data/lc_speaker_index&quot;)</pre><p>Step 2: Retrieval + LangChain Prompting</p><pre># Load vector index and embedding model<br>vectorstore = FAISS.load_local(&quot;data/lc_speaker_index&quot;, embedding_model)<br>retrieved_docs = vectorstore.similarity_search(query=theme_input, k=3)<br><br>llm = Ollama(model=&quot;llama3&quot;)<br><br># Define prompt template<br>template = &quot;&quot;&quot;<br>You are helping select speakers for a PMI conference on the theme: &quot;{theme}&quot;.<br><br>Here is a speaker&#39;s abstract:<br>{abstract}<br><br>1. Summarize why this speaker fits the theme.<br>2. Extract 2-3 keywords.<br>3. Suggest an audience question.<br>4. Rate the fit score (out of 10).<br><br>Return in markdown format.<br>&quot;&quot;&quot;<br>prompt = PromptTemplate(input_variables=[&quot;theme&quot;, &quot;abstract&quot;], template=template)<br>chain = LLMChain(llm=llm, prompt=prompt)<br><br># Run for each speaker<br>for doc in retrieved_docs:<br>response = chain.run({&quot;theme&quot;: theme_input, &quot;abstract&quot;: doc.page_content})<br>print(response)</pre><h4><strong>Streamlit UI</strong></h4><p>The frontend allowed users to:</p><ul><li>Input the theme and audience type</li><li>View results in interactive cards</li><li>Shortlist strong matches</li><li>Export selections as CSV or JSON</li></ul><p>Here&#39;s a sample screenshot:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/719/1*vrTS6G6OR_oF194pT4r7uw.png" /><figcaption>#Image 1</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/732/1*Em0jafyLFqLfI_s3NJAQOQ.png" /><figcaption>#Image 2</figcaption></figure><p>She especially liked the “Add to Shortlist” button</p><h4>Challenges &amp; Debugging Moments</h4><ul><li>❌ faiss-cpu refused to build under NumPy 2.x → solved with clean conda env</li><li>❌ Ollama model slowness on M1 → fixed with --num-thread 4</li><li>❌ Streamlit crashed with conflicting Python versions → used which python to ensure correct virtualenv</li><li>❌ LangChain deprecation issues → skipped in v1, reserved for LangGraph phase (next post)</li></ul><p>In each case, debugging was paired with late-night <em>Davids Herbal Tea</em> and playful encouragement.</p><h4>Outcomes</h4><ul><li>✅ Fully working <strong>local GenAI system</strong></li><li>✅ Learned RAG architecture end-to-end</li><li>✅ No paid APIs, fully portable</li><li>✅ Feedback from my partner: “Honestly, this saved me hours. We’re using this next year too.”</li></ul><h4>Next Post</h4><ul><li>Add LangGraph to simulate user workflows (e.g., onboarding, feedback loops)</li><li>Filter by speaker location, industry, experience level</li><li>Rank by Fit Score + Confidence + Diversity</li><li>UI polish with tags, pagination, and speaker photos</li></ul><h4>Reflections</h4><p>Projects like this remind me why I love AI. It wasn’t just about proving technical skill, it was about <strong>solving a real problem</strong>, <strong>supporting someone I care about</strong>, and doing it with <strong>tools I wanted to master</strong>.</p><p>Some people code for side projects. I code to say <em>“I got you”</em> — with FAISS, LLaMA3, LangChain and a shortlist button 😄</p><p>Now this goes more than just building RAG systems, scalability and resilient systems are core in any LLM Orchestration solution. So I have curated some intial performaance questions which I initially thought of:</p><p><strong>How would monitor retrieval quality and guard against query drift or hallucinations in RAG?</strong></p><p><em>In Speaker Scout, I implemented controlled input formatting (</em><em>theme + </em><em>audience) to anchor queries semantically. I manually evaluated top-k matches across themes and audiences to check for drift and low-relevance retrieval.</em></p><p><em>If deployed, I would track retrieval metrics such as cosine similarity distribution, variance of top-k scores, and user selection behavior to detect drift over time. I’d also monitor how often the same speaker appears for unrelated themes, which is a signal to revise chunking or retrain embeddings.</em></p><p><strong>How do you add rerankers, context window optimizers, and confidence scoring to minimize hallucinations?</strong></p><p><em>While Speaker Scout uses a single-pass LLM summarization (LLaMA3 via Ollama), I designed the system to modularize prompt flows via </em><em>LLMChain, enabling future insertion of a reranker LLM or score-based thresholds.</em></p><p><em>The prompt includes explicit speaker metadata (theme, audience, message, materials) to maximize relevance and reduce hallucinations. If this were scaled, I’d add a scoring mechanism to penalize hallucinations using rule-based checks (e.g., verifying the speaker name is mentioned) and optionally re-querying with a higher-confidence model or using a smaller reranker like Cohere Rerank.</em></p><p><strong>How do you chunk documents optimally, avoid semantic drift, and handle multilingual embeddings?</strong></p><p><em>In Speaker Scout, I processed unstructured speaker bios and presentation texts by chunking them into semantically meaningful units (e.g., “message”, “materials”). This avoided splitting ideas midstream, which reduces semantic drift.</em></p><p><em>I chose </em><em>all-MiniLM-L6-v2 for embeddings, which supports multilingual similarity and balances speed with accuracy. To further future-proof the pipeline, I designed it to accept pluggable embedding models so we can later swap in cross-lingual models like LaBSE if expanding beyond English contexts.</em></p><p><strong><em>✨ If you found this helpful or romantic (or both), give it a share!</em></strong></p><h4><strong>References</strong></h4><p><a href="https://www.kaggle.com/datasets/rounakbanik/ted-talks">https://www.kaggle.com/datasets/rounakbanik/ted-talks</a> — Dataset Source</p><ul><li><a href="https://docs.langchain.com/oss/python/langchain-overview">Overview - Docs by LangChain</a></li><li><a href="https://ollama.com/library/llama3">llama3</a></li><li><a href="https://docs.streamlit.io/develop/api-reference">API Reference - Streamlit Docs</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6e977bc03f2a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Structures & Algorithm — Arrays]]></title>
            <link>https://medium.com/@ogenepabo/data-structures-algorithm-arrays-90b4c1dbcaaf?source=rss-90839510598------2</link>
            <guid isPermaLink="false">https://medium.com/p/90b4c1dbcaaf</guid>
            <category><![CDATA[arrays]]></category>
            <category><![CDATA[data-structures]]></category>
            <dc:creator><![CDATA[Israel Ilori]]></dc:creator>
            <pubDate>Fri, 05 Sep 2025 02:43:23 GMT</pubDate>
            <atom:updated>2025-09-05T02:43:23.122Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Arrays in DSA Made Simple: Step-by-Step Sum Example</strong></h3><h4>Two Number Sum, Three Number Sum, Four Number Sum</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xsanuknNTuTxwRHI_x8OKw.png" /></figure><h3>Introduction to Array Sum Problems</h3><p>Array sum problems are staple challenges in algorithm learning, evolving in complexity from finding a pair of numbers to identifying quadruplets that meet a sum condition. These problems not only test your grasp of basic programming concepts but also your ability to think critically and apply efficient strategies.</p><h3>Two-Number Sum: The Foundation</h3><p>The two-number sum problem is our starting point. Given an array and a target sum, the task is to find any two numbers whose sum equals the target.</p><p><strong>Approach</strong>: Sort the array and use two pointers to search for a pair that meets the condition. This method leverages sorting to improve efficiency, leading to a time complexity of O(nlog(n)) and a space complexity of O(1).</p><p><strong>Code Walkthrough</strong>:</p><pre>def twoNumberSum(array, targetSum):<br>    array.sort()<br>    left = 0<br>    right = len(array) - 1<br>    while left &lt; right:<br>        currentSum = array[left] + array[right]<br>        if currentSum == targetSum:<br>            return [array[left], array[right]]<br>        elif currentSum &lt; targetSum:<br>            left += 1<br>        else:<br>            right -= 1<br>    return []</pre><ol><li>Sorting the array organizes our numbers, making it easier to navigate through them.</li><li>Initializing left and right pointers whereleft starts at the beginning, and right at the end of the sorted array.</li><li>Loop through by moving left and right pointers based on their sum compared to targetSum. If the sum is equal, return the pair. If less, move left rightward; if more, move right leftward.</li><li>If a pair is found, it’s returned; otherwise, an empty list signifies no such pair exists.</li></ol><h3>Learning with Two-Number Sum</h3><p>The key takeaway here is the power of sorting and two-pointer techniques. Sorting organizes our data, making it easier to navigate, while two pointers allow us to efficiently explore possible sums without redundant comparisons.</p><h3>Three-Number Sum: Adding Complexity</h3><p>Next, we tackle the three-number sum problem, where we look for triplets in an array whose sum matches a given target.</p><p><strong>Approach</strong>: Similar to the two-number sum, we sort the array first. Then, for each number, we use a modified two-pointer technique to find the other two numbers. This approach has a higher time complexity of O(n²) due to the nested loop but still maintains manageable space complexity, assuming O(n) for storing potential triplets.</p><h3>Learning with Three-Number Sum</h3><p>The introduction of a third number emphasizes the importance of iteration and careful pointer movement. This problem underlines the necessity of considering each element’s role in contributing to the target sum, showcasing the balance between iteration and efficient searching.</p><p><strong>Code Walkthrough</strong>:</p><pre>def threeNumberSum(arr, targetSum):<br>    arr.sort()<br>    triplets = []<br>    for i in range(len(arr) - 2):<br>        left = i + 1<br>        right = len(arr) - 1<br>        while left &lt; right:<br>            currentSum = arr[i] + arr[left] + arr[right]<br>            if currentSum == targetSum:<br>                triplets.append([arr[i], arr[left], arr[right]])<br>                left += 1<br>                right -= 1<br>            elif currentSum &lt; targetSum:<br>                left += 1<br>            else:<br>                right -= 1<br>    return triplets</pre><ol><li>Like the Two Number array, we start by sorting.</li><li>Iterate with a fixed point: The first number in each potential triplet is fixed by iterating through the array.</li><li>Two-Pointer search system: For each fixed point, we search for the other two numbers using a two-pointer approach similar to the two-number sum solution.</li><li>When a matching sum is found, the triplet is collected and added to the result list.</li></ol><h3>Four-Number Sum: The Challenge Peak</h3><p>Our final ascent is the four-number sum problem, where we seek quadruplets within an array that sum to a given target.</p><p><strong>Approach</strong>: After sorting the array, we iterate with two nested loops and apply a two-pointer search within the inner loop. This method requires careful management of four indices, pushing the time complexity to O(n³) for the naive approach but can be optimized further.</p><h3>Learning with Four-Number Sum</h3><p>The four-number sum problem highlights advanced iteration strategies and the importance of optimization. As we increase the number of target elements, the complexity grows, teaching us about the computational costs of nested iterations and the value of optimizing wherever possible.</p><p><strong>Code Walkthrough</strong>:</p><pre>def fourNumberSum(array, targetSum):<br>    quadruplets = []<br>    array.sort()<br>    for i in range(len(array) - 3):<br>        for j in range(i+1, len(array) - 2):<br>            left = j+1<br>            right = len(array) - 1<br>            while left &lt; right:<br>                fourSum = array[i] + array[j] + array[left] + array[right]<br>                if targetSum == fourSum:<br>                    quadruplets.append([array[i], array[j], array[left], array[right]])<br>                    left += 1<br>                    right -= 1<br>                elif targetSum &gt; fourSum:<br>                    left += 1<br>                else:<br>                    right -= 1<br>    return quadruplets</pre><ol><li>Sorting is the initial step for easier navigation.</li><li>Double Iteration for Two Fixed Points: We fix the first two numbers by iterating twice, narrowing down our search space.</li><li>Two-Pointer Search for the Remaining Pair: With two numbers fixed, we use the two-pointer approach to find the remaining pair.</li><li>Upon finding a matching sum, the quadruplet is collected and returned.</li></ol><h3>Conclusion: Growing Through Challenges</h3><p>Array sum problems, from two to four numbers, offer a progressive learning curve that sharpens our algorithmic thinking and problem-solving skills. Each step introduces new complexities and learning opportunities, from efficient data organization to advanced iteration techniques.</p><p>These problems are not just exercises in coding but lessons in thinking efficiently and strategically. As you master these challenges, you’ll find yourself better equipped to tackle even more complex problems, armed with a deeper understanding of algorithms and data structures.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=90b4c1dbcaaf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Scalable Systems using GCP Tools —Starter Guide]]></title>
            <link>https://medium.com/@ogenepabo/building-scalable-systems-using-gcp-tools-starter-guide-bb43292d25c8?source=rss-90839510598------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb43292d25c8</guid>
            <category><![CDATA[technical-writing]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Israel Ilori]]></dc:creator>
            <pubDate>Fri, 05 Sep 2025 02:26:22 GMT</pubDate>
            <atom:updated>2025-09-05T02:26:22.499Z</atom:updated>
            <content:encoded><![CDATA[<p>In the realm of scalable cloud architectures, the design and orchestration of components are important. Today, we’ll unravel a sophisticated system architecture that leverages Google Cloud’s robust suite of tools to orchestrate data flow from ingestion to reporting. This system is a blueprint for handling massive, diverse data streams, ensuring data integrity, and enabling advanced analytics.</p><p>Note: This is only a guide</p><h4><strong>System Architecture Overview</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JMkJv8TBRuCS9fYaGvF9AA.png" /></figure><p>The architecture presented is a multi-layered framework designed for high-throughput and resilience, integrating Pub/Sub messaging, stream and batch data processing, persistent storage solutions, and advanced data analysis and reporting tools. Here’s a breakdown of each component within the ecosystem.</p><p><strong>Ingestion Layer: The Data Gateway</strong></p><ul><li><strong>Pub/Sub Proxy</strong>: Utilizing Google Kubernetes Engine (GKE), we deploy a Pub/Sub proxy to facilitate the decoupling of data producers and consumers. GKE’s dynamic scaling and container orchestration capabilities ensure that our message throughput can adapt to fluctuating data volumes.</li><li><strong>Google Cloud Pub/Sub</strong>: Serving as a real-time messaging service, Pub/Sub allows us to implement asynchronous messaging that absorbs spikes in data flow without losing messages or requiring other services to be always available.</li><li><strong>Dataflow Collection Job</strong>: A Python-based Dataflow job subscribes to topics in Pub/Sub, acting as a data collection mechanism. Dataflow’s ability to handle both stream and batch processing empowers this architecture to manage varying data ingestion patterns.</li></ul><p><strong>Processing Layer: Data Transformation and Validation</strong></p><ul><li><strong>Dataflow Transformation Job</strong>: After initial collection, another Python-based Dataflow job is responsible for the transformation, enrichment, and validation of data. This is where the raw data is refined into a structured format suitable for analysis.</li></ul><p><strong>Storage Layer: Secure and Scalable Data Housing</strong></p><ul><li><strong>Cloud Storage Buckets</strong>: Segmented storage using Cloud Storage provides a highly available and global service to store large volumes of unstructured data.</li><li><strong>Cloud SQL</strong>: For structured data that requires relational database management, Cloud SQL is the service of choice, providing fully-managed SQL database instances.</li><li><strong>BigQuery Data Warehouse</strong>: Serving as the cornerstone of our analytics, BigQuery provides a serverless, highly scalable, and cost-effective multi-cloud data warehouse designed for business agility.</li></ul><p><strong>Reporting Layer: Turning Data into Decisions</strong></p><ul><li><strong>SQL Programming</strong>: Leveraging SQL’s powerful querying capabilities allows us to extract meaningful patterns and insights from our data within BigQuery.</li><li><strong>Looker &amp; Tableau</strong>: For data visualization and business intelligence, we integrate with Looker and Tableau, which offer comprehensive platforms for creating interactive and sharable reports and dashboards.</li><li><strong>BigQuery ML</strong>: Enabling machine learning capabilities within our data warehouse allows for predictive analytics and model building directly where our data resides, streamlining the process of turning insights into action.</li></ul><p><strong>Security: The Fortress of Data</strong></p><ul><li><strong>Cloud IAM</strong>: At every layer, Cloud IAM (Identity and Access Management) provides fine-grained access control, ensuring only authenticated and authorized entities can interact with the system’s components.</li></ul><p><strong>Conclusion</strong></p><p>This system architecture is a testament to the power of Google Cloud’s services, showcasing a cohesive and extensible pattern for modern data management. Each component plays a critical role in creating a pipeline that is not only performant but also resilient and secure. As technical solution architects, it is essential to understand the interplay between these services to craft solutions that can scale with the ever-growing demands of data-driven enterprises.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb43292d25c8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ethereum to Insights: With dbt and Python]]></title>
            <link>https://medium.com/@ogenepabo/ethereum-to-insights-with-dbt-and-python-3e6cd5c9c4ea?source=rss-90839510598------2</link>
            <guid isPermaLink="false">https://medium.com/p/3e6cd5c9c4ea</guid>
            <category><![CDATA[ethereum-blockchain]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[dbt]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Israel Ilori]]></dc:creator>
            <pubDate>Fri, 05 Sep 2025 01:52:31 GMT</pubDate>
            <atom:updated>2025-09-05T01:52:31.265Z</atom:updated>
            <content:encoded><![CDATA[<h4>Why this matters?</h4><p>In blockchain staking, numbers matter. Institutional clients, product managers, and compliance officers all depend on <strong>validator</strong> performance (a participant in Ethereum’s proof-of-stake system that locks up <strong>ETH</strong> to validate transactions and earns or loses rewards) data to make decisions. The catch is that raw Ethereum validator data is practically unusable out of the box.</p><ul><li>It arrives as <strong>massive, compressed JSON files</strong>, often several GBs each.</li><li>Validator records are <strong>messy. </strong>It contains duplicate keys, nulls, inconsistent types, and even negative values from slashing events (a penalty event where a validator loses some of its stake for malicious or negligent behavior).</li><li>Internal stakeholders need <strong>daily validator balances</strong> they can trust.</li></ul><p>The project began as a simple exercise to aggregate validator data. But the real business need was much bigger as it required building a <strong>reproducible, scalable, and trustworthy pipeline</strong> that transforms raw blockchain data into <strong>analytics stakeholders and clients can act on</strong>.</p><p>Business stakeholders be it executives, product managers, or clients don’t want your JSON outputs. They want <strong>trusted metrics.</strong> In this case-study using Blockchain data, a potential stakeholder would want to know:</p><ul><li>How much did each validator earn in staking rewards (the payouts validators receive for securing the network)??</li><li>What is the balance at the end of the day?</li><li>Can we trust these numbers for reporting, dashboards, and compliance?</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jXQ47A_VglShJ5rBaNQcIw.png" /></figure><p>This case study documents how I built a <strong>two-stage data pipeline</strong> — Python for block-level streaming aggregation and dbt for daily SQL modeling — to transform raw Ethereum data into <strong>reliable business-ready analytics</strong>.</p><p><strong>Architecture Diagram</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j29hU4BPk9UEGkQMsaVlFg.png" /><figcaption>Model Architecture</figcaption></figure><p>I chose the design because it balanced:</p><ul><li><strong>Python</strong> for control over raw, messy JSON.</li><li><strong>dbt</strong> for modular SQL transformations, testing, and lineage documentation.</li><li><strong>Postgres</strong> (via Docker) for reproducibility in a local test environment.</li></ul><h4>Phase 1: Python for Streaming Aggregation</h4><p>The first challenge was working<strong> </strong>with the gigabytes of data. A naïve approach was loading JSON into Pandas which crashed on multi-GB files. As an alternative, I built a <strong>streaming Python script</strong> that read line by line, updated per-block metrics in dictionaries, and accumulated global totals.</p><pre>with gzip.open(&quot;validators_data.jsonl.gz&quot;, &quot;rt&quot;) as f:<br>    for line in f:<br>        rec = json.loads(line)<br>        blk = rec[&quot;block_number&quot;]<br>        bal = int(rec[&quot;balance&quot;])<br>        eff = int(rec[&quot;validator&quot;][&quot;effective_balance&quot;])<br><br>        stats = per_block[blk]<br>        stats[&quot;total_balance&quot;] += bal<br>        stats[&quot;total_effective_balance&quot;] += eff</pre><p>Key trade-offs:</p><ul><li>2nd method: streaming with gzip and nested dictionaries → scalable, memory-safe, transparent.</li><li>1st method: Pandas (too memory-heavy), or pushing JSON directly into SQL (too costly to clean in database).</li></ul><p>This design was:</p><ul><li>Memory-safe → handled millions of records without crashing.</li><li>Transparent → simple dictionaries.</li><li>Verifiable → outputs tested against a strict verify.py harness.</li></ul><h4>Phase 2: dbt for Incremental, Trustworthy Analytics</h4><p>Where Python ensured raw correctness, <strong>dbt delivered business value </strong>by turning the pipeline into something stakeholders could actually use. It gave me a framework to:</p><ul><li>Clean and deduplicate raw rewards.</li><li>Incrementally aggregate daily totals and balances.</li><li>Enforce schema rules as data contracts.</li><li>Document models and lineage for transparency.</li></ul><h4>Staging Model — Cleaning the Raw Data</h4><p>The raw rewards table had duplicates and string-typed numbers.</p><pre>{{ config(materialized=&#39;view&#39;) }}<br><br>with raw as (<br>  select<br>    address,<br>    reward_type,<br>    mark as block_number,<br>    timestamp::timestamptz as event_time,<br>    (claimed_reward_numeric * power(10, claimed_reward_exp))::numeric as reward_amount<br>  from {{ source(&#39;ethereum&#39;,&#39;ethereum_rewards_raw&#39;) }}<br>  where type = &#39;rewards&#39;<br>    and address is not null<br>),<br><br>deduped as (<br>  select *,<br>         row_number() over (<br>            partition by address, reward_type, block_number<br>            order by event_time desc<br>         ) as rn<br>  from raw<br>)<br><br>select * <br>from deduped<br>where rn = 1</pre><p>Highlights:</p><ul><li>Casted raw text into timestamptz and numeric.</li><li>Computed real reward amounts using exponents.</li><li>Deduplicates on (address, reward_type, block_number).</li><li>Outputs clean records with event_date for downstream grouping.</li></ul><h4><strong>Mart Model — </strong>Incremental Daily Aggregates</h4><p>The mart model turned staging into <strong>daily totals and balances per validator</strong>.</p><pre>{{ config(materialized=&#39;incremental&#39;, unique_key=[&#39;address&#39;,&#39;event_date&#39;]) }}<br><br>with daily as (<br>  select<br>    address,<br>    date_trunc(&#39;day&#39;, event_time) as event_date,<br>    sum(reward_amount) as daily_reward<br>  from {{ ref(&#39;stg_ethereum_rewards&#39;) }}<br>  group by address, event_date<br>)<br><br>select<br>  address,<br>  event_date,<br>  daily_reward,<br>  sum(daily_reward) over (<br>    partition by address <br>    order by event_date<br>  ) as balance<br>from daily<br><br>{% if is_incremental() %}<br>  where event_date &gt; (select max(event_date) from {{ this }})<br>{% endif %}</pre><p>Highlights:</p><ul><li>Incremental model which computes new event_dates, avoiding full reloads.</li><li>Window function to calculate end-of-day balances for each validator.</li><li>Unique key enforcement so it has one row per (address, event_date).</li></ul><h4><strong>Testing &amp; Schema Enforcement</strong></h4><pre>version: 2<br><br>models:<br>  - name: ethereum_rewards_daily<br>    tests:<br>      - dbt_utils.unique_combination_of_columns:<br>          combination_of_columns: [&#39;address&#39;,&#39;event_date&#39;]<br>    columns:<br>      - name: address<br>        tests: [not_null]<br>      - name: event_date<br>        tests: [not_null]<br>      - name: daily_reward<br>        tests: [not_null]<br>      - name: balance<br>        tests: [not_null]</pre><p>Key wins:</p><ul><li>Staging models normalized schemas.</li><li>Mart models computed validator reward deltas.</li><li>Testing and documentation (dbt schema.yml) ensured data reliability.</li></ul><h4>Documentation &amp; Lineage</h4><p>dbt also gave transparency. With dbt docs generate, stakeholders could:</p><ul><li>See <strong>lineage graphs</strong>: raw → staging → marts.</li><li>Understand <strong>downstream dependencies</strong> on dashboards.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bqGT1TauNhH9Xp_-YeN2_Q.png" /></figure><h4>Lessons Learned</h4><ul><li>Precision matters → Rounding had to match verifier specs exactly.</li><li>Schema enforcement is essential → dbt tests acted as contracts with downstream teams.</li><li>Expect edge cases → negative rewards (slashing), nulls, and duplicates all had to be handled.</li><li>Reproducibility builds trust → Pipenv + Docker meant any engineer could reproduce the pipeline in minutes.</li></ul><h4>Conclusion</h4><p>This project was more than a technical exercise. It was about building trust in numbers.</p><ul><li>Python handled scale and raw correctness.</li><li>dbt layered on incremental models, schema enforcement, and documentation.</li><li>The result? a pipeline that decision-makers could depend on.</li></ul><p>My takeaway for Senior Data Engineers is our job isn’t just to build pipelines it’s to <strong>turn messy, high-volume data into insights the business can trust</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3e6cd5c9c4ea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Meta Llama3 Model: A simple guide to downloading to your Localhost]]></title>
            <link>https://medium.com/@ogenepabo/meta-llama3-model-a-simple-guide-to-downloading-to-your-localhost-ba086172bd0a?source=rss-90839510598------2</link>
            <guid isPermaLink="false">https://medium.com/p/ba086172bd0a</guid>
            <dc:creator><![CDATA[Israel Ilori]]></dc:creator>
            <pubDate>Sun, 28 Apr 2024 00:24:05 GMT</pubDate>
            <atom:updated>2024-04-28T02:48:23.595Z</atom:updated>
            <content:encoded><![CDATA[<p>I am writing this guide on how to download Meta’s Llama3 model simply because I spent some hours figuring it out with the unclear instructions from Meta’s official page and because, YouTube videos were not of much help either lol.</p><p>If you are reading this, I almost want to assume you know what Llama models are. However, if not, I still got you with this short summary. Meta’s Llama models are powerful tools used for various computational tasks, ranging from Data Analysis to Machine Learning, Natural Language Processing, Computer Vision, etc. More info can be found on Meta’s official page below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VOilABdIeK-GB7pRwdqEiA.png" /></figure><p><strong>Step 1:</strong> Visit Meta’s Llama page at <a href="https://llama.meta.com/llama3/">https://llama.meta.com/llama3/</a></p><p><strong>Step 2:</strong> Scroll/Search for the “Download Llama 3” button. It directs you to a webform. Fill in your details and you would get an email with the URL in your inbox. (There are other checkboxes for Llama 2, Meta Code Llama and a recommended option to download Llama Guard 2. If you check them, you end up getting an email with a different URL for each model).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5IRE8g-q1pDp0ofsq-Tl7g.png" /><figcaption>Meta Request Access to Llama GUI</figcaption></figure><p><strong>Step 3:</strong> In the email, you receive a link to the GitHub repo for Meta’s Llama models. You clone the repo into your local folder by clicking on “Code” drop-down and selecting which of the three options works best. I used VSCode (my python environment) to clone the repo as seen in the image below with the command:</p><pre>$ git clone repo_url</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C4l--uyZ3YKQPsB6SE95Tg.png" /></figure><p><strong>Step 4:</strong> Before installing any package, I generally like to install into a virtual environment (venv) first. (<a href="https://docs.python.org/3/library/venv.html">Link</a> on how to create and activate a <em>venv</em> in Python). Copy the pre-requisite package names, <em>wget</em> and <em>md5sum, </em>and add to the requirements.txt file in the root folder. Then install all packages at once. What better time to install them than now, because you would still install them later anyways. Other options to install packages are in the links below.</p><pre>$ pip install -r requirements.txt</pre><p><strong>Step 5:</strong> Once the <em>wget</em> and <em>md5sum </em>(or<em> md5sha1sum</em>) packages have been installed. Run the following command in your terminal/bash env to download the model to your localhost.</p><pre>$ ./download.sh</pre><p>It would prompt you to “Enter the URL from email:”. copy and paste the URL of the Llama model from your email and press enter. Press enter again to install all list of the model (i.e 8B, 70B) or select individual ones you require.</p><ul><li><a href="https://llama.meta.com/">Industry Leading, Open-Source AI | Llama</a></li><li><a href="https://docs.python.org/3/library/venv.html">venv - Creation of virtual environments</a></li><li><a href="https://brew.sh/">Homebrew</a></li><li><a href="https://conda.io/projects/conda/en/latest/user-guide/getting-started.html">Getting started with conda - conda 24.3.1.dev77 documentation</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ba086172bd0a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Harmonizing Data and Melody: A Data-Driven Analysis on Our Spotify Music Data]]></title>
            <link>https://medium.com/@ogenepabo/harmonizing-data-and-melody-a-data-driven-analysis-on-our-spotify-music-data-2857df0c243f?source=rss-90839510598------2</link>
            <guid isPermaLink="false">https://medium.com/p/2857df0c243f</guid>
            <dc:creator><![CDATA[Israel Ilori]]></dc:creator>
            <pubDate>Sat, 30 Dec 2023 21:24:14 GMT</pubDate>
            <atom:updated>2023-12-30T21:24:14.265Z</atom:updated>
            <content:encoded><![CDATA[<p>As a music enthusiast and data nerd, I’ve always been fascinated by what my Spotify streaming history might reveal about my listening preferences and habits. Thanks to the power of Python and the analytical capabilities of pandas, a playful exchange with my girlfriend revealed more than just melodies hidden within the data. In this post, I’ll share the insights gleaned from our Spotify listening history. The full code can be found in my <a href="https://github.com/tomiwa-ilori">GitHub repo</a>.</p><h4>Preparing the Data</h4><p>To kick things off, I loaded our Spotify streaming history in JSON format into a pandas DataFrame. This history contained details of every track we played over the past year, including the date and time of streaming, track names, artist names, and play durations. You can download yours by following the instructions <a href="https://support.spotify.com/ca-en/article/data-rights-and-privacy-settings/">here</a></p><h4>Data Description</h4><ul><li>Date and time of when the stream ended in UTC format (Coordinated Universal Time zone).</li><li>Name of “creator” for each stream (e.g. the artist name if a music track).</li><li>Name of items listened to or watched (e.g. title of music track or name of video).</li><li>“msPlayed”- Stands for how many mili-seconds the track was listened to.</li></ul><pre># read data into pandas dataframe<br>df_one = pd.read_json(&#39;StreamingHistory0.json&#39;)<br>df_two = pd.read_json(&#39;StreamingHistory1.json&#39;)<br>df_three = pd.read_json(&#39;StreamingHistory2.json&#39;)<br>df_four = pd.read_json(&#39;StreamingHistory3.json&#39;)<br><br># concatenate dataframes<br>df = pd.concat([df_one, df_two, df_three, df_four], ignore_index=True)<br><br># show first 5 rows of dataframe<br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*N-Vw2Fb51MakHX9yl76cRA.png" /><figcaption>first 5 rows of dataframe</figcaption></figure><h3>The Top Charts: Songs and Artists</h3><p><strong>Sugar</strong>: “It’s year end. I wonder what songs made it to our top listened songs this year?”</p><p><strong>Me:</strong> “Hmm! I wonder myself. I could do a quick analysis to confirm that.”</p><pre># get the total play count for songs in each year<br># convert endTime to datetime and extract year and month<br>df[&#39;endTime&#39;] = pd.to_datetime(df[&#39;endTime&#39;])<br>df[&#39;year&#39;] = df[&#39;endTime&#39;].dt.year<br>df[&#39;month&#39;] = df[&#39;endTime&#39;].dt.month<br><br># top 20 songs by play count each year<br>top_20_songs_year = df.groupby([&#39;year&#39;, &#39;trackName&#39;]).size().reset_index(name=&#39;playCount&#39;)<br>top_20_songs_year = top_20_songs_year.sort_values([&#39;year&#39;, &#39;playCount&#39;], ascending=[True, False])<br>top_20_songs_year = top_20_songs_year.groupby(&#39;year&#39;).head(20)<br><br># visualize top 20 Songs by year<br>for year in top_20_songs_year[&#39;year&#39;].unique():<br>    plt.figure(figsize=(10, 6))<br>    df_year = top_20_songs_year[top_20_songs_year[&#39;year&#39;] == year]<br>    df_year = df_year.sort_values(&#39;playCount&#39;, ascending=True)<br>    plt.barh(df_year[&#39;trackName&#39;], df_year[&#39;playCount&#39;], color=&#39;blue&#39;)<br>    plt.xlabel(&#39;Play Count&#39;)<br>    plt.ylabel(&#39;Track Name&#39;)<br>    plt.title(f&#39;Top 20 Songs in {year}&#39;)<br>    plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RpqEIg6fjj_zbZj5yk5eaw.png" /><figcaption>Top 20 Songs in 2023</figcaption></figure><p><strong>Me:</strong> “From the analysis, no surprises it’s been ‘Rain and Thunder Sounds for Sleep (Fall Asleep Fast)’. Those Rain Sounds have been a cozy backdrop to our bedtime chats lately.”</p><p><strong>Sugar:</strong> “Those rain sounds are so soothing! So I’d take it that sounds of nature has been helping us drift off to sleep through the year.”</p><p><strong>Sugar:</strong> But when we’re not listening to the sounds of a storm, which artist’s music fills our home the most?”</p><p><strong>Me:</strong> “Actually, it’s Apostle Emmanuel Iren who tops our list. His tracks was our musical compass this year, it set the tone for those thoughtful conversations we had, you know, even in the moments when we just sat in silence and enjoyed each other’s company.”</p><pre># display the top 20 artists, ranked according to the total number of times their songs have been played.<br>plt.title(&quot;Top 20 Artists by Number of Times Played&quot;)<br>df_artist_by_count = df[&quot;artistName&quot;].value_counts(ascending=False).head(20).sort_values(ascending=True)<br>df_artist_by_count.plot(kind=&quot;barh&quot;, figsize=(10,5), color=&quot;blue&quot;)<br>plt.xlabel(&quot;Play Count of Songs&quot;)<br>plt.ylabel(&quot;Artist Name&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zWa5qywyAs3eiUSd2YB3mg.png" /><figcaption>Top 20 Artists by Number of Times Played</figcaption></figure><p><strong>Sugar:</strong> Oh, I should’ve guessed! His music actually played alot in the background while we were working. Is there a way to also know what time of the day we listen to music the most?</p><p><strong>Me:</strong> Absolutely. I can pull that up.</p><pre># Convert endTime to a datetime column and extract the hour<br>df[&#39;hour&#39;] = pd.to_datetime(df[&#39;endTime&#39;]).dt.hour<br><br># Plot the distribution of streams across different hours of the day<br>df_distribution = df[&#39;hour&#39;].value_counts().sort_index()<br>df_distribution.plot(kind=&#39;bar&#39;)<br>plt.xlabel(&#39;Hour&#39;)<br>plt.ylabel(&#39;Number of Streams&#39;)<br>plt.title(&#39;Distribution of Streams Across Different Hours of the Day&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*N6BDluS4zuydOhAlOTxnSA.png" /><figcaption>Streams Across Different Hours of the Day</figcaption></figure><p><strong>Me:</strong> See here, the data shows we’re most in tune with our playlists when the rest of the world quiets down. Our music pattern peaks the most in the late hours of the morning and maintains a high altitude till mid-hours of the afternoon.</p><p><strong>Sugar: </strong>I guessed right haha! I remember we had music always in the background. Looking at our music, what do you think it says about the rhythm of our lives?”</p><pre># Fetch genres for tracks in the specific year<br>    genres_counter = Counter()<br>    for track in df_year[&#39;trackName&#39;]:<br>        # Search for the track to get track details<br>        track_data = sp.search(q=track, type=&#39;track&#39;)<br>        # Check if there are items returned in the search<br>        if track_data[&#39;tracks&#39;][&#39;items&#39;]:<br>            # Get the first track&#39;s details<br>            first_track = track_data[&#39;tracks&#39;][&#39;items&#39;][0]<br>            # Get the artist ID from the track&#39;s details<br>            artist_id = first_track[&#39;artists&#39;][0][&#39;id&#39;]<br>            # Get the artist&#39;s details, which includes genres<br>            artist_details = sp.artist(artist_id)<br>            # Update the counter with the genres of the current track<br>            genres_counter.update(artist_details[&#39;genres&#39;])<br>        else:<br>            print(f&quot;No results for {track}&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/841/1*iNhMebssMKo_Ea1qlaA-CQ.png" /><figcaption>Top Genres for 2023</figcaption></figure><p><strong>Me:</strong> Our top genres are a testament to our spirit, I’d say. With ‘naija worship’ leading the way, it’s clear we’ve leaned into songs that uplift and inspire us. It’s as if our days are infused with a blend of energetic songs and those that cause us to do a bit of reflection, don’t you think?</p><p><strong>Sugar:</strong> I would say so, the chart really shows that we listened to worship songs, three times the number of other categories. I guess music really is the soundtrack of our lives.</p><p><strong>Me:</strong> If I had to give our year a theme, it would be “Harmony in Diversity”. Our playlists were a blend of genres, artists, and moods that somehow fit together perfectly. Just like us.</p><p><strong>Sugar:</strong> What do you look forward to as we continue this musical journey?</p><p><strong>Me:</strong> To find new rhythms and melodies that resonate with our evolving story. Whether it’s the energetic beats of ‘afrobeats’ or the soul-stirring ‘nigerian pop’, I look forward to every discovery with you. Each track adds a new layer to the symphony of our days.</p><p><strong>Her:</strong> Aww, that’s sweet. And so true! Thank you for this little analysis, it’s like a time capsule of our year in music.</p><p><strong>Me:</strong> Anytime! It’s fun to look back at the melodies that defined our year. Here’s to another year of exploring music and making memories together!</p><h4><strong>Side Note — Tapping into the Rhythms of Our Music Genre with Spotipy</strong></h4><p>While Spotify’s streaming history provides a rich narrative of our listening patterns, one might notice that genre information isn’t directly available. But with a sprinkle of API magic and the Spotipy library, this gap is easily bridged.</p><p>Spotipy is a lightweight Python library that interacts with the Spotify Web API. With a few lines of code, you can authenticate with Spotify and access a universe of data — including the elusive genres of your favorite tracks. Here’s a brief on how I harnessed Spotipy to uncover the genre tapestry of our musical journey:</p><ol><li><strong>Authentication</strong>: First, I registered an application with Spotify to obtain the necessary credentials — a client ID and client secret. These keys are the first step to unlocking data through the Spotipy client.</li><li><strong>Fetching Track Details</strong>: Using Spotipy’s search function, I could retrieve details about each track we listened to. The beauty of this function lies in its ability to return a wealth of information, from album art to artist details.</li><li><strong>Discovering Genres</strong>: With the artist’s ID in hand, I dove deeper, fetching the artist’s info which includes the genres they’re associated with. This was the key step to mapping out the genres for our top tracks.</li><li><strong>Genre Analysis</strong>: Aggregating this data, I could then paint a picture of our genre diversity — seeing which styles dominated our airwaves and which ones were new entrants.</li></ol><p>In essence, Spotipy turned our streaming history into a colorful palette of genres, giving us another dimension to understand our musical preferences.</p><h4>Closing Notes</h4><p>Our Spotify data analysis has been a heartwarming and revealing endeavor. It’s a testament to how our shared love for music intertwines with our daily lives, highlighting our late-night musings and the soundtrack that accompanies our relationship’s quiet moments. It’s a melody of data that sings the songs of who we are together.</p><h3>References</h3><p><a href="https://python.plainenglish.io/bored-of-libraries-heres-how-to-connect-to-the-spotify-api-using-pure-python-bd31e9e3d88a">Bored of Libraries? Here’s How To Connect to the Spotify API Using Pure Python</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2857df0c243f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Build and Deploy a Semantic Search Engine with OpenAI’s LLM (text-ada-embedding) and…]]></title>
            <link>https://medium.com/@ogenepabo/how-to-build-and-deploy-a-semantic-search-engine-with-openais-llm-text-ada-embedding-and-482a7cfb897b?source=rss-90839510598------2</link>
            <guid isPermaLink="false">https://medium.com/p/482a7cfb897b</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Israel Ilori]]></dc:creator>
            <pubDate>Wed, 27 Dec 2023 19:26:58 GMT</pubDate>
            <atom:updated>2023-12-27T19:26:58.615Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to Build and Deploy a Semantic Search Engine with OpenAI’s LLM (text-ada-embedding) and Streamlit — Conversations with my Girlfriend</h3><h4>Introduction</h4><p>In this lighthearted and easy-to-follow guide, I’m excited to take my girlfriend (and you, dear reader!) on a delightful journey through the world of tech. We’ll be diving into the fascinating process of building a semantic search engine, leveraging the power of OpenAI’s Large Language Model (specifically, the text-ada-embedding), and bringing it to life via a web application using Streamlit. Whether you’re a seasoned coder or a curious newbie, this adventure is designed to be enjoyable and informative for everyone. So, let’s embark on this techy trek together, making complex concepts accessible and fun! 🚀💻🌟.</p><h4>Prerequisites</h4><p>Before we begin, ensure you have:</p><ul><li>Python 3.6 or higher installed.</li><li>Basic Python knowledge, particularly with data structures and web requests.</li><li>Familiarity with Streamlit, a Python library for creating web applications.</li></ul><h4>Setting Up the Environment</h4><ol><li><strong>Installing the necessary packages</strong>: create a <em>requirements.txt</em> file and fill with the following packages as seen below.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/257/1*3S81HjIA1LEhSr0Tb6vuog.png" /><figcaption><em>requirements.txt</em> file</figcaption></figure><p>In bash/linux shell, run <em>pip install -r requirements.txt</em> command to install the necessary dependencies. Optionally, you can create a <em>virtual environment (venv)</em>, <a href="https://uoa-eresearch.github.io/eresearch-cookbook/recipe/2014/11/20/conda/"><strong>link here</strong></a>, and run the command within <em>venv</em> to avoid conflicting packages between this project and other projects you might be working on.</p><p>We are installing the packages for the following reasons:openai for calling the text embedding model from OpenAI,streamlit for sharing our web app and making our search engine interactive, numpy for numerical operations, pandas for data handling, and tqdm for progress tracking in loops.</p><ul><li>Ensure all dependencies are correctly installed by importing them in a Python environment.</li></ul><pre># import the libraries<br>import openai<br>import numpy as np<br>import pandas as pd<br>from tqdm import tqdm<br>tqdm.pandas()</pre><p><strong>2. API Key Configuration</strong>: To use OpenAI’s text embedding model, you’ll need an API key, which is like a special password that lets you connect to OpenAI’s services. You can create your own API key by following the instructions on their website. Keep in mind, though, that to start using the text embedding services, there’s a minimum initial charge of $5. <a href="https://platform.openai.com/api-keys"><strong>Link</strong></a></p><h4>The Core of Semantic Search — Explained to my Girlfriend</h4><h4><strong>1. Conceptual Overview</strong></h4><p>Hi Sugar, let’s say you’re looking online for a place to eat pizza. You type in “pizza” but instead of getting pizza places, you get recipes to make pizza. This is what usually happens with regular search engines — they focus on the word ‘pizza’ but don’t understand you want a restaurant, not a recipe.</p><p>A semantic search engine is like a smarter version of this. It doesn’t just look at the word ‘pizza’. It tries to understand what you actually want — in this case, a place to eat pizza. It’s like having a friend who knows you’re looking for a restaurant, not a recipe, when you mention pizza.</p><p>Our project is to build this kind of smart search engine. It’s about making it understand what people really mean, not just the words they use. So, when you search for pizza next time, it’ll show you restaurants, knowing that’s what you’re probably looking for.</p><h4><strong>2. Brief on OpenAIs GPT Model</strong></h4><p>Hi Sugar, remember when we were watching that “Person of Interest” movie with the super-smart machine that could relate with and support humans? Well, there’s something similar in the world of technology, and it’s called OpenAI’s GPT ‘text-embedding-ada-002’ model. Let me break it down for you in a fun way.</p><p>So you have a friend who’s read every book, watched every movie, and knows almost everything you can think of. Now, whenever you ask them something, they give you really good answers, right? That’s kind of what this GPT model does.</p><p>It’s been trained by reading a huge amount of text, like studying. The model ‘studied’ by reading lots of internet contents, articles, websites, and books. This then helped it understand language. Now the cool part is, after understanding, it now creates text that sound very human-like using everything it has studied.</p><h4>3. Vector Tensor Operations</h4><p>Now finally, the last concept. So, as we live in British Columbia, and we regularly go on hikes (let me include a picture for our beloved readers, lol).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5apkYNZK1SAWO6mc_nHoqg.jpeg" /></figure><p>What if we’re looking for a new backpack for our hiking trip and then you type ‘durable hiking backpack’ into the search bar? Now, how does the website show us exactly what we’re looking for? This is where vector tensor operations come in. Think of them like a super smart shopping assistant in the digital world. When you search for something, this assistant needs to understand not just the words you type, but the meaning behind them. That’s what vector tensor operations help with.</p><h4><strong>Breaking It Down</strong></h4><ol><li><strong>Vectors for Words</strong>: Each word you type is turned into a ‘vector.’ It’s a little box that holds all the info about that word — what it means, how it’s used, and its relation to other words.</li><li><strong>Tensors — Grouping the Vectors</strong>: A tensor is like a bigger box that holds all these little word vectors. So when you type ‘durable hiking backpack’, each word is a small vector, and the tensor groups them into one big picture.</li><li><strong>Operations — Making Sense of It All</strong>: Now, the ‘operations’ part is where the magic happens. The system uses math (yes, math!, don’t you run away at the sight of math lol!) to compare your big tensor box with all the tensors of the backpacks available ((like counting and comparing the colors, sizes, and patterns of box to find the box most similar to yours). It tries to find the closest match based on color, size and pattern not just the box.</li><li><strong>Semantic Analysis</strong>: This is just a fancy way of saying ‘understanding the meaning.’ The system analyzes what you mean by ‘durable hiking backpack’ and finds the best results. So, it won’t show you a backpack meant for school kids but the rugged ones suitable for hiking.</li></ol><h3><strong>Now unto the Code Walkthrough </strong>🚀</h3><p>A step-by-step explanation of the Jupyter notebook, starting from importing libraries to processing data.</p><p>To illustrate the power and application of the semantic search concepts we’ve discussed, let’s embark on a fascinating project: building a semantic search engine tailored for exploring a dataset of global universities.</p><h4><strong>The key steps are outlined below:</strong></h4><p><strong>Data Collection and Processing</strong>: As opposed to building out an ETL pipeline, we simply use a University data from Kaggle. It has information about a global list of Universities. By analyzing the university name, our semantic search engine can gain deeper insight enhancing its ability to return accurate search results.</p><pre># read in dataset<br>data_input_path = &quot;data/world-universities.csv&quot;<br>df = pd.read_csv(data_input_path)<br>df.head()</pre><p><strong>Embedding the text (University names):</strong> Remember the openAI key that was created earlier, we utilize a getpass() library in Python which prompts users for a password without echoing. The getpass module provides a secure way to handle the password prompts where programs interact with the users via the terminal.</p><pre># prompt user for passkey<br>from getpass import getpass<br>openai_key = getpass()<br><br># set up the OpenAI client<br>client = openai.OpenAI(api_key = openai_key)<br><br># get model for embedding<br>text_embedding_model = &#39;text-embedding-ada-002&#39;<br><br># define a function to get the embeddings<br>def get_embedding(text, model=text_embedding_model):<br>   &quot;&quot;&quot;<br>   Retrieves the embedding for a given text using the specified model.<br><br>   Parameters:<br>   text (str): The input text to be embedded.<br>   model (str): The name of the model to use for embedding. Default is &#39;text-embedding-ada-002&#39;.<br><br>   Returns:<br>   list: The embedding vector for the input text.<br>   &quot;&quot;&quot;<br>   if &quot;\n&quot; in text:<br>      text = text.replace(&quot;\n&quot;, &quot; &quot;)<br>   return client.embeddings.create(input = [text], model=model).data[0].embedding<br><br># get the embeddings<br>df[&#39;ada_embeddings&#39;] = df[&#39;University&#39;].progress_apply(lambda x: get_embedding(x, model=text_embedding_model))<br><br># save the embeddings<br>df.to_csv(&#39;data/University_reviews.csv&#39;, index=False)</pre><p>As seen above, we developed a technique to obtain embeddings for our list of universities. After generating these embeddings, we then applied this method to capture the embeddings for each university, storing them in a new column. Subsequently, the complete dataset was exported in a new CSV file format. It’s important to note that in practical applications, opting for vector databases is a more effective strategy. This approach helps to circumvent limitations associated with Large Language Models (LLMs), such as the potential for hallucinations and the absence of long-term memory. For further information on Vector Databases, please refer to the reference section provided below.</p><h3>Streamlit Web Application Development — app.py</h3><p>To interact with our embeddings, we build a web app using streamlit.</p><pre># Set Title of the Web App<br>st.title(&quot;Search AI with OpenAI Embeddings&quot;)<br><br># Request the user to enter API key<br>user_secret = st.text_input(label = &quot;:green[OpenAI API Key]&quot;, <br>                            placeholder = &quot;Enter your OpenAI API Key Here&quot;, <br>                            type=&quot;password&quot;)</pre><p>Load the University embedded data from the saved file earlier.</p><pre># Define a function to load the data<br>@st.cache_data<br>def load_data():<br>    df = pd.read_csv(&quot;data/University_reviews.csv&quot;)<br>    return df<br><br>def search(query, df, n=4, pprint=True):<br><br>    # Select embedding to use for the query<br>    text_embedding_model = &#39;text-embedding-ada-002&#39;<br><br>    # Convert the embedding of the query to a numpy array<br>    df[&#39;ada_embeddings&#39;] = df.ada_embeddings.apply(eval).apply(np.array)</pre><p>Request a Search Query from the user and create a search button.</p><pre># Request the user to enter their search query<br>query = st.text_input(label = &quot;:green[Search Query]&quot;, <br>                            placeholder = &quot;Enter your search query here&quot;, <br>                            type=&quot;default&quot;)<br><br># Create a button to run the search<br>query_button = st.button(label = &quot;Search&quot;, type=&quot;primary&quot;)</pre><p>NB: The full code pipeline can be found in my <a href="https://github.com/tomiwa-ilori/semantic-search-engine-with-LLMs">github</a>.</p><p>To run the app.py file, from the bash shell, run the code below.</p><pre>streamlit run app.py</pre><p>If all dependencies have been installed properly, and there are no bugs (I heard you sigh a bit there!) you should see the below when you run the command above. Your system ip address and the port it is bound to. Also, your local browser should load up instantly with the interface.</p><pre>  You can now view your Streamlit app in your browser.<br><br>  Local URL: http://localhost:xxxx<br>  Network URL: http://192.xxx.1.xx:xx</pre><p>For a test, we passed the query “abu dhabi” and the result showed us the top 4 relative universities with close similarity to our query. The similarity score preceeds the result name.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*__FkuwkKKI8RoA02p9pAKA.png" /><figcaption>streamlit interactive interface</figcaption></figure><h3>Conclusion</h3><p>In conclusion, the development and deployment of this semantic search engine was a journey of discovery and growth. I hope, like my girl, you got to learn the power of language in the digital realm and the importance of understanding user intent.</p><p>And so, we wrap up our grand adventure in the whimsical world of semantic search engines. What a ride it’s been! The road ahead? It’s not just exciting; it’s a veritable yellow brick road of techy wonders! 🚀🌟🤖💫🎩</p><h3>References</h3><p><a href="https://platform.openai.com/docs/guides/embeddings/use-cases">https://platform.openai.com/docs/guides/embeddings/use-cases</a></p><ul><li><a href="https://www.elastic.co/enterprise-search/vector-search?utm_campaign=Google-NB-ESRE-Trials-AMER-NA&amp;utm_content=Nonbrand-Vector-B&amp;utm_source=google&amp;utm_medium=cpc&amp;device=c&amp;utm_term=vector%20search&amp;gad_source=1">Elasticsearch vector search - highly relevant, lightning fast search</a></li><li><a href="https://www.kaggle.com/">Kaggle: The World&#39;s AI Proving Ground</a></li><li><a href="https://docs.python.org/3/library/getpass.html">getpass - Portable password input</a></li><li><a href="https://stackoverflow.blog/2023/10/09/from-prototype-to-production-vector-databases-in-generative-ai-applications/">From prototype to production: Vector databases in generative AI applications</a></li><li><a href="https://www.pinecone.io/lp/vector-database/?utm_term=vector%20database&amp;utm_campaign=General&amp;utm_source=adwords&amp;utm_medium=ppc&amp;hsa_acc=3111363649&amp;hsa_cam=16569728076&amp;hsa_grp=135276647900&amp;hsa_ad=587750423880&amp;hsa_src=g&amp;hsa_tgt=kwd-1976865318&amp;hsa_kw=vector%20database&amp;hsa_mt=p&amp;hsa_net=adwords&amp;hsa_ver=3&amp;gad_source=1">Vector Database for Vector Search | Pinecone</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=482a7cfb897b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding The Foundational Block of Transformers in NLP]]></title>
            <link>https://medium.com/@ogenepabo/understanding-foundational-block-of-transformers-in-nlp-4881b8c29fb7?source=rss-90839510598------2</link>
            <guid isPermaLink="false">https://medium.com/p/4881b8c29fb7</guid>
            <dc:creator><![CDATA[Israel Ilori]]></dc:creator>
            <pubDate>Mon, 24 Apr 2023 22:40:55 GMT</pubDate>
            <atom:updated>2023-04-24T22:57:45.624Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, I will distill the novelty of transformers and summarize the underlying concepts behind each one of them. Before transformers can be explained, these concepts need to be understood first:</p><ul><li>Encoder-Decoder Framework</li><li>Attention Mechanism</li><li>Transfer Learning</li></ul><p><strong>The Encoder-Decoder Framework:</strong></p><p>The encoder-decoder framework has existed even before transformer models came into play. They are currently used in recurrent neural architectures such as LSTMs (Long-Short Term Memory).</p><ul><li>The encoder-decoder framework has a feedback loop within its network, allowing for the transmission of information from one point to another.</li><li>Words or character inputs are passed into the network, circulate through the network, and then output a hidden state vector.</li><li>The input circulates through the network via the loop in a series of steps until all parts of the input produce a hidden state.</li><li>The network passes information about its state at each point to the next operation in the sequence, aiding the tracking of information when predicting the final output.</li></ul><p>In summary, the encoder encodes information from the input sequence into a numerical form called the last hidden state, which is then passed to the decoder to generate the output sequence.</p><p><em>Limitation:</em> When the size of the input sequence is large, information at the start of the input sequence could potentially be lost to the decoder, resulting in some parts of the hidden state not being decoded for a prediction output.</p><p><strong>Attention Mechanism:</strong></p><p>The encoder produces a hidden state at each step for the decoder to access; however, when all these hidden states are used simultaneously, it creates a bottleneck for the decoder. A means to prioritize the hidden states is required. Attention comes into play here, as it allows the decoder to assign attention or weights to each hidden state at each decoding step. Through this prioritization using attention, attention-based models learn non-obvious relationships between words in a generated translation and those in a source sentence.</p><p><em>Limitation:</em> In modern-day NLP applications, there is an absence of large, labeled texts to start training from scratch. Hence, transfer learning is used in nearly all modern-day applications.</p><p><strong>Transfer Learning:</strong></p><p>Given training and compute resources, it is much cheaper to train custom models using fine-tuned models. The pre-trained models are trained on an original task, and then transfer learning is used to transfer the knowledge gained to more downstream tasks. This approach allows for faster computation times and improved efficiency in downstream tasks.</p><p><strong>Transformers — Explained</strong></p><p>Transformers are attention models that consider bidirectional flows of words when predicting an output.</p><ul><li>In contrast to feed-forward neural networks, transformers are bidirectional or, better still, non-directional.</li><li>They are unique due to their self-attention, which allows the representation of a sequence (or sentence) to be computed by relating different words in the same sequence.</li><li>This feature enables transformers to perform better, as they learn more about the sense of a language’s context.</li><li>The model architecture has an encoder-decoder structure — the encoder maps the input structure, and the decoder generates the output sequence, or prediction output.<br>- Within the encoder, it uses multi-head attention so that inputs from different representations can be run in parallel.<br>- In the decoder, it applies the same technique to enable the prediction outputs rendered to be dependent only on known inputs.</li></ul><p><strong>BERT — Explained</strong></p><p>Bi-directional Encoder Representations from Transformers (BERT) is pre-trained based on two main objectives:</p><ul><li>Randomly mask tokens and predict the original token based on the context of the unmasked token, a.k.a Masked Language Modeling (MLM).</li><li>Determine if one token would follow another, a.k.a Next Sentence Prediction (NSP).</li></ul><p>This approach allows for a two-way or bidirectional understanding of an input by considering its left and right context.</p><p><em>Architecture:</em></p><ul><li>Add a classification layer on top of the encoder output.</li><li>Multiply the output vectors by the embedding matrix, transforming them into the vocabulary dimension.</li><li>Calculate the probability of each word in the vocabulary with Softmax.</li></ul><p><strong>RoBERTa — Explained</strong></p><p>RoBERTa was developed through optimizing the hyperparameters used in training BERT. It has the same architecture as BERT, but during pre-training, it is only pre-trained with MLM.</p><p><em>Architecture:</em></p><ul><li>Longer training time and larger training data (10x from 16GB to 160GB).</li><li>Larger Batch Size from 256 to 8000 and bigger vocabulary size from 30k to 50k.</li><li>Longer sequences are used as input, but RoBERTa still has the maximum token limitation of 512 tokens, just like BERT.</li><li>Dynamic masking allows the masking pattern to be different every time a sequence is fed to the model, as opposed to BERT, which used the same masking pattern.</li></ul><p><strong>DistilBERT — Explained</strong></p><p>DistilBERT has the same architecture as BERT, but during pre-training, it is only pre-trained with MLM and uses knowledge distillation. It uses 40% less memory than BERT while being 60% faster.</p><p><em>Architecture:</em></p><ul><li>6 stacked encoder blocks.</li><li>To fine-tune itself for other tasks, BERT adds extra linear layers on top of the stacked encoders.</li><li>These extra layers are used to generate a specific output as per the task BERT is solving.</li><li>No token-type embeddings and pooling functionalities.</li><li>Same hyperparameters that RoBERTa uses, like larger batch size and dynamic masking.</li></ul><p><strong>LongFormer — Explained</strong></p><p>Because transformer models use self-attention when generating sequences, the longer the sequence in the document, the more expensive the transformer model becomes when processing due to quadratic scaling. LongFormer tackles this by using an attention mechanism that scales linearly (one-to-one).</p><p>To achieve this, it uses two attention windows:</p><ul><li>A local attention window: primarily used to build contextual representations.</li><li>A global attention window: builds full sequence representations for prediction.</li></ul><p><strong>BerTopic — Explained</strong></p><p>BerTopic generates topic representations through three steps:</p><ul><li>Each document is converted to its embedding representation using a pre-trained language model.</li><li>Before clustering these embeddings, the dimensionality of the resulting embeddings is reduced to optimize the clustering process.</li><li>Lastly, from the clusters of documents, topic representations are extracted using a custom class-based variation of TF-IDF.</li></ul><p>REFERENCES</p><ul><li><a href="https://arxiv.org/abs/1706.03762">Attention Is All You Need</a></li><li><a href="https://arxiv.org/abs/2004.05150">Longformer: The Long-Document Transformer</a></li><li><a href="https://www.oreilly.com/library/view/natural-language-processing/9781098136789/">Natural Language Processing with Transformers, Revised Edition</a></li><li><a href="https://arxiv.org/abs/1907.11692">RoBERTa: A Robustly Optimized BERT Pretraining Approach</a></li><li><a href="https://arxiv.org/abs/1910.01108">DistilBERT, a distilled version of BERT: smaller, faster, cheaper and lighter</a></li><li><a href="https://arxiv.org/abs/2203.05794">BERTopic: Neural topic modeling with a class-based TF-IDF procedure</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4881b8c29fb7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>