<?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 Andy Yang on Medium]]></title>
        <description><![CDATA[Stories by Andy Yang on Medium]]></description>
        <link>https://medium.com/@ai-data-drive?source=rss-5140c0782d6f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*PLQOoPlL4HONwQv1AXUj9w.jpeg</url>
            <title>Stories by Andy Yang on Medium</title>
            <link>https://medium.com/@ai-data-drive?source=rss-5140c0782d6f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 18:24:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ai-data-drive/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[AI Coding Showdown: 6 Tools × 8 Models — The Ultimate Frontend Generation Test]]></title>
            <link>https://medium.com/@ai-data-drive/ai-coding-showdown-6-tools-8-models-the-ultimate-frontend-generation-test-6eeb754ff753?source=rss-5140c0782d6f------2</link>
            <guid isPermaLink="false">https://medium.com/p/6eeb754ff753</guid>
            <category><![CDATA[cursor]]></category>
            <category><![CDATA[claude]]></category>
            <category><![CDATA[trae]]></category>
            <category><![CDATA[vibe-coding]]></category>
            <dc:creator><![CDATA[Andy Yang]]></dc:creator>
            <pubDate>Sat, 28 Jun 2025 08:45:44 GMT</pubDate>
            <atom:updated>2025-06-28T08:45:44.140Z</atom:updated>
            <content:encoded><![CDATA[<h3>AI Coding Showdown: 6 Tools × 8 Models — The Ultimate Frontend Generation Test</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3OM93-4htSVygX-UHLSG5Q.jpeg" /></figure><p><em>Which AI coding assistant reigns supreme? A comprehensive comparison of Cursor, Windsurf, Trae, Replit, Lovable, and Bolt.new</em></p><h3>Introduction</h3><p>In the current AI wave, AI-powered coding has undoubtedly become the hottest battleground. The competition is fierce, with numerous contestants including Cursor, Windsurf, Trae, Replit, Lovable, Bolt.new, v0, and other coding agents. Behind these tools lies the driving force of large language models like Anthropic Claude, OpenAI GPT, Google Gemini, and DeepSeek R1, whose code generation capabilities are the core engine powering these coding agents.</p><p>So as of June 2025, how do these AI coding tools actually perform? What are the differences in code generation capabilities between different models? Through a real-world case study, I tested various AI coding products with different code generation models to provide you with an intuitive, qualitative impression of their performance.</p><h3>The Challenge: Building “My MBTI AI Friends Circle”</h3><p>Here’s the test case I used: Generate a high-fidelity design prototype for an app called “My MBTI AI Friends Circle.” Simply put, it’s an app where I have AI friends with different MBTI personalities, and whenever I post about my life, they respond according to their personality traits, providing emotional support.</p><p>Here’s the prompt I used:</p><pre>I want to develop a Chinese AI personal emotional companion app with the following features:<br>​<br>1. Users can use this app to record their thoughts, plans, todos, emotions, links they&#39;ve seen, and other life moments. It uses cards + timeline for interaction. So it&#39;s primarily an AI diary app.<br>​<br>2. The system has a series of AI agents with different MBTI personalities who will respond to users&#39; records based on their MBTI personality traits.<br>​<br>3. Users can add different AI agents as their followers.<br>​<br>4. Users can share their records and AI agents&#39; responses.<br>​<br>5. Through these responses and sharing, provide emotional companionship to users.<br>​<br>Now I need to output high-fidelity prototypes. Please help me complete the prototype design for all interfaces through the following approach, ensuring these prototype interfaces can be directly used for development:<br>​<br>1. User Experience Analysis: First analyze the main functions and user needs of this app, determine core interaction logic<br>​<br>2. Product Interface Planning: As a product manager, define key interfaces and ensure reasonable information architecture<br>​<br>3. High-Fidelity UI Design: As a UI designer, design interfaces that closely follow real iOS/Android design specifications, using modern UI elements for good visual experience.<br>​<br>4. HTML Prototype Implementation: Use HTML + Tailwind CSS (or Bootstrap) to generate all prototype interfaces, and use FontAwesome (or other open-source UI components) to make interfaces more refined and closer to real app design. Split code files and maintain clear structure:<br>​<br>5. Each interface should be stored as an independent HTML file, such as home.html, profile.html, settings.html<br>​<br>- index.html serves as the main entry point, not directly writing all interface HTML code, but using iframe to embed these HTML fragments, and display all pages directly tiled on the index page rather than navigation links.<br>​<br>- Reality Enhancement:<br>​<br>- Interface dimensions should simulate iPhone 15 Pro, with rounded corners to make it look more like a real phone interface.<br>​<br>- Use real UI images rather than placeholder images (can choose from Unsplash, Pexels, Apple official UI resources).<br>​<br>- Add top status bar (simulate iOS status bar) and include app navigation bar (similar to iOS bottom TabBar).<br>​<br>Please generate complete HTML code in the design-trae-DeepSeekR1 folder according to the above requirements, ensuring it can be used for actual development.</pre><p>I then generated different code using various AI coding products and models:</p><ul><li><strong>Products tested</strong>: Cursor, Trae, Replit, Lovable, v0, Bolt.new</li><li><strong>Models tested</strong>: claude-3.5-sonnet, claude-3.7-sonnet, claude-4-sonnet, gemini-2.5-flash, gemini-2.5-pro, o3, gpt-4.1, deepseek-r1</li></ul><h3>Results &amp; Analysis</h3><h3>Cursor</h3><h4>claude-3.5-sonnet</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ejuIOqojxBuN4Ar1.png" /></figure><p><strong>Cursor + claude-3.5-sonnet:</strong></p><ul><li><strong>Functionality</strong>: Accurately implements requirements, though there’s a broken page that shouldn’t exist</li><li><strong>UI</strong>: Basic complete interface, but icons don’t meet requirements and need web materials</li><li><strong>Design</strong>: Simple, plain aesthetic</li></ul><p><em>Verdict: Standard delivery, like a basic shell. </em><strong><em>Score: 60/100</em></strong></p><h4>claude-4-sonnet</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*toyF_2KUYRPgQJEw.png" /></figure><p><strong>Cursor + claude-4-sonnet — This is impressive:</strong></p><ul><li><strong>Functionality</strong>: Very accurate implementation. The “Create” tab, for example, is feature-complete with post types and mood options</li><li><strong>UI</strong>: Complete interface with rich materials</li><li><strong>Design</strong>: Beautiful and polished</li></ul><p><em>Verdict: Highly complete, ready for direct frontend implementation. Premium delivery. </em><strong><em>Score: 90/100</em></strong></p><h4>gemini-2.5-pro</h4><p>The result showed only one page without implementing the required “direct tiling.” After manual page switching:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KGmoCLXI5qy5ppbY.png" /></figure><p><strong>Cursor + gemini-2.5-pro:</strong></p><ul><li><strong>Functionality</strong>: Barely adequate implementation. Basic functions present but failed to implement “direct tiling” — major deduction</li><li><strong>UI</strong>: Basic complete interface with acceptable icons</li><li><strong>Design</strong>: Simple and plain</li></ul><p><em>Verdict: Basic delivery with major flaws. </em><strong><em>Score: 59/100</em></strong></p><h4>o3</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AHJIyeau8fDIpBeg.png" /></figure><p><strong>Cursor + o3:</strong></p><ul><li><strong>Functionality</strong>: Accurately implements requirements</li><li><strong>UI</strong>: Basic complete interface with good icons</li><li><strong>Design</strong>: Clean and minimalist</li></ul><p><em>Verdict: Very clean basic delivery, better than claude-3.5-sonnet. </em><strong><em>Score: 70/100</em></strong></p><h3>Trae</h3><h4>claude-3.5-sonnet</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kisZiZDUUOIvH8Lu.png" /></figure><p><strong>Trae + claude-3.5-sonnet — Now this is impressive:</strong></p><ul><li><strong>Functionality</strong>: Accurately implements requirements</li><li><strong>UI</strong>: Complete interface with rich materials</li><li><strong>Design</strong>: Beautiful, though slightly less polished than claude-4-sonnet</li></ul><p><em>Verdict: Refined basic delivery. </em><strong><em>Score: 80/100</em></strong></p><h4>claude-3.7-sonnet</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ju5nE2xBS627exzR.png" /></figure><p><strong>Trae + claude-3.7-sonnet — Surprisingly, 3.7 performed worse than 3.5:</strong></p><ul><li><strong>Functionality</strong>: Failed to implement “direct tiling” — major deduction</li><li><strong>UI</strong>: Complete interface with good icons</li><li><strong>Design</strong>: Beautiful aesthetic</li></ul><p><em>Verdict: Refined delivery with major flaws. </em><strong><em>Score: 59/100</em></strong></p><h4>claude-4-sonnet</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1f9wbkVYaYiAxf64.png" /></figure><p><strong>Trae + claude-4-sonnet — Also impressive:</strong></p><ul><li><strong>Functionality</strong>: Very accurate implementation. The “Create” tab is feature-complete with post types, moods, and attachments</li><li><strong>UI</strong>: Complete interface with rich materials</li><li><strong>Design</strong>: Beautiful and polished</li></ul><p><em>Verdict: Similar to Cursor + claude-4-sonnet. Highly complete, ready for direct frontend implementation. Premium delivery. </em><strong><em>Score: 90/100</em></strong></p><h4>gemini-2.5-pro</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*th6x1gyWqxgsosGL.png" /></figure><p><strong>Trae + gemini-2.5-pro — Very mediocre:</strong></p><ul><li><strong>Functionality</strong>: Barely adequate. Basic functions present but no “direct tiling” — major deduction</li><li><strong>UI</strong>: Basic complete interface with missing icons</li><li><strong>Design</strong>: Plain and simple</li></ul><p><em>Verdict: Basic shell with major flaws. </em><strong><em>Score: 50/100</em></strong></p><h4>DeepSeek R1</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gmikVepPtBpL3zgX.png" /></figure><p>No “direct tiling” implementation, and clicking tabs showed incorrect pages.</p><p><strong>Trae + DeepSeek R1 — Poor performance:</strong></p><ul><li><strong>Functionality</strong>: Inadequate implementation. Basic functions incomplete, no “direct tiling”</li><li><strong>UI</strong>: Incomplete basic interface, no icons</li><li><strong>Design</strong>: Crude</li></ul><p><em>Verdict: Poor quality shell with major flaws. </em><strong><em>Score: 40/100</em></strong></p><h3>Cloud-Based Solutions</h3><p>The following tools (Replit, Lovable, v0, Bolt.new) are cloud-based products that operate directly in the browser.</p><h4>Replit</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Oo5OGjatPkBitp8R.png" /></figure><p><strong>Replit + Unknown Model:</strong></p><ul><li><strong>Functionality</strong>: No “direct tiling” implementation — major deduction</li><li><strong>UI</strong>: Basic complete interface with acceptable icons</li><li><strong>Design</strong>: Crude</li></ul><p><em>Verdict: Basic delivery with major flaws. </em><strong><em>Score: 50/100</em></strong></p><h4>Lovable</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NpmQllnBezFf86Uj.png" /></figure><p><strong>Lovable + Unknown Model — Stunning:</strong></p><ul><li><strong>Functionality</strong>: Very accurate implementation. The “Create” tab is feature-complete with post types, moods, and privacy settings</li><li><strong>UI</strong>: Very complete interface with rich materials</li><li><strong>Design</strong>: Beautiful and polished</li></ul><p><em>Verdict: Even better than claude-4-sonnet. High-quality premium delivery. Highly complete, ready for direct frontend implementation. </em><strong><em>Score: 95/100</em></strong></p><h4>v0</h4><p>v0–1.5-md</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*R8XLv5Vp2pQgbqED.png" /></figure><p><strong>v0 + v0–1.5-md:</strong></p><ul><li><strong>Functionality</strong>: Barely adequate. Basic functions present but no “direct tiling” — major deduction</li><li><strong>UI</strong>: Basic complete interface with missing icons</li><li><strong>Design</strong>: Clean and minimalist</li></ul><p><em>Verdict: Basic shell with major flaws but decent style. </em><strong><em>Score: 55/100</em></strong></p><p>v0–1.5-lg</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pBfU11L6bZSQRdj-.png" /></figure><p><strong>v0 + v0–1.5-lg — Similar to Cursor + claude-3.5-sonnet:</strong></p><ul><li><strong>Functionality</strong>: Accurately implements requirements</li><li><strong>UI</strong>: Basic complete interface, but icons need web materials</li><li><strong>Design</strong>: Clean and minimalist</li></ul><p><em>Verdict: Standard delivery without the flaws of Cursor + claude-3.5-sonnet. </em><strong><em>Score: 65/100</em></strong></p><h4>Bolt.new</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CBFl2NkOhKSmhBYd.png" /></figure><p><strong>Bolt.new + Unknown Model — Very poor:</strong></p><ul><li><strong>Functionality</strong>: Failed to implement requirements</li><li><strong>UI</strong>: Missing and compressed elements</li><li><strong>Design</strong>: Crude</li></ul><p><em>Verdict: Poor quality shell with major flaws. </em><strong><em>Score: 40/100</em></strong></p><h3>Final Rankings</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A03hYfuimnN0OZSaSfKxtA.png" /></figure><h3>Key Takeaways</h3><p>While this evaluation is based on a single use case focused on frontend code generation with only one test per configuration (introducing some randomness), it provided valuable insights for my subsequent frontend development:</p><h3>🏆 The Winners</h3><ol><li><strong>Lovable</strong> emerges as the surprise champion with a perfect 95/100 score</li><li><strong>Claude-4-sonnet</strong> consistently delivers excellence across both Cursor and Trae (90/100)</li><li><strong>Trae + claude-3.5-sonnet</strong> offers impressive results (80/100)</li></ol><h3>📊 Model Performance Rankings</h3><ol><li><strong>claude-4-sonnet</strong>: The gold standard for complex frontend generation</li><li><strong>claude-3.5-sonnet</strong>: Solid performance, especially with Trae</li><li><strong>o3</strong>: Clean and reliable results</li><li><strong>gemini-2.5-pro</strong>: Inconsistent, often missing key requirements</li><li><strong>deepseek-r1</strong>: Struggles with complex UI requirements</li></ol><h3>🛠️ Platform Insights</h3><p><strong>For Local Development:</strong></p><ul><li><strong>Claude-4-sonnet is the clear winner</strong> — the model makes all the difference</li><li><strong>Cursor vs Trae</strong>: Minimal difference; both are excellent platforms for Claude-4</li></ul><p><strong>For Cloud-Based Development:</strong></p><ul><li><strong>Lovable is the standout choice</strong> — delivering premium results without the need for local setup</li><li><strong>v0</strong> shows promise but needs improvement</li><li><strong>Replit</strong> and <strong>Bolt.new</strong> lag behind significantly</li></ul><h3>🎯 The Model vs. Platform Debate</h3><p>This comparison reinforces a crucial insight: <strong>the underlying model matters more than the platform</strong>. Claude-4-sonnet consistently delivered superior results regardless of whether it ran on Cursor or Trae, while weaker models struggled even on robust platforms.</p><h3>💡 Practical Recommendations</h3><ul><li><strong>For Professional Development</strong>: Use Claude-4-sonnet on either Cursor or Trae</li><li><strong>For Quick Prototyping</strong>: Lovable offers the fastest path to impressive results</li><li><strong>For Budget-Conscious Projects</strong>: Trae + claude-3.5-sonnet provides excellent value</li><li><strong>Avoid</strong>: Gemini-2.5-pro for complex UI tasks, and DeepSeek R1 for production work</li></ul><p>This evaluation demonstrates that we’re entering a new era where AI coding assistants can generate production-ready frontend code. The gap between AI-generated prototypes and developer-crafted interfaces is rapidly closing, with top performers like Lovable and Claude-4-sonnet combinations already delivering impressive, deployment-ready results.</p><p><em>The AI coding revolution is here, and choosing the right tool-model combination can dramatically accelerate your development workflow. Choose wisely! 🚀</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6eeb754ff753" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tracking the AI Revolution: A Data-Driven Journey Through Open-Source LLM Trends]]></title>
            <link>https://medium.com/@ai-data-drive/tracking-the-ai-revolution-a-data-driven-journey-through-open-source-llm-trends-7a9840eef864?source=rss-5140c0782d6f------2</link>
            <guid isPermaLink="false">https://medium.com/p/7a9840eef864</guid>
            <category><![CDATA[ollama]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[vibe-coding]]></category>
            <category><![CDATA[streamlit]]></category>
            <dc:creator><![CDATA[Andy Yang]]></dc:creator>
            <pubDate>Thu, 26 Jun 2025 14:47:29 GMT</pubDate>
            <atom:updated>2025-06-26T14:47:29.670Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M9nu0ChFqMS-tJnSv-gPeA.png" /></figure><p>The world of Large Language Models (LLMs) is expanding at an explosive rate. New models are released almost daily, each with unique capabilities and a growing community of users. As an AI enthusiast, I found myself captivated by this rapid evolution. But beyond the headlines, I wanted to understand the real trends. Which models are gaining traction? Which are fading away? To answer these questions, I embarked on a project to systematically track and analyze the burgeoning ecosystem of open-source models on Ollama.</p><p>Visit the final app: <a href="https://ollama-models-analysis.streamlit.app/">https://ollama-models-analysis.streamlit.app</a></p><h3>The “Why”: A Quest for Clarity in a Booming Field</h3><p>My motivation was simple: to replace speculation with data. Ollama has become a major hub for running and sharing open-source LLMs locally. Its library is a dynamic, real-time reflection of what the community is excited about. By tracking metrics like pull counts (downloads) and likes, I could get a quantitative view of a model’s popularity and trajectory over time. This project is my attempt to build a public dashboard that not only satisfies my own curiosity but also provides a valuable resource for developers, researchers, and fellow AI enthusiasts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*z_dHg3ICAZym_IA1.png" /></figure><h3>The “How”: An Evolving Data Engineering Pipeline</h3><p>Building this system was a journey in itself, with the data architecture evolving from a simple script into a robust, cloud-native pipeline.</p><h3>Step 1: Scraping the Data</h3><p>The first step was to get the data. I wrote a Python script, scrape_ollama_models.py, that uses the requests and BeautifulSoup libraries to parse the Ollama models library page. Every day, a cron job triggers a shell script (fetch_ollama_data.sh) that runs the scraper. It meticulously extracts key information for each model:</p><ul><li><strong>Model Name:</strong> e.g., llama3</li><li><strong>Model Family:</strong> A derived field to group related models (e.g., llama)</li><li><strong>Pull Count:</strong> The total number of downloads, a primary metric for popularity.</li><li><strong>Tags:</strong> Information about different versions and quantizations.</li><li><strong>Description:</strong> The model’s brief introduction.</li></ul><h3>Step 2: The Data Storage Evolution</h3><p>How to store this time-series data was a critical decision that changed as the project grew.</p><h4>Phase 1: The Humble CSV</h4><p>Initially, I stored everything in a single CSV file, ollama_models.csv. This was easy to set up and inspect. However, as days turned into weeks, the file grew larger. Querying it for specific dates or performing aggregations became increasingly slow and inefficient. It was a good start, but it wasn&#39;t a scalable solution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rEHGeekDm4cGvbg4.png" /></figure><h4>Phase 2: Embracing Parquet and DuckDB</h4><p>To address the performance issues, I transitioned to a more professional data engineering setup. The key changes were:</p><ol><li><strong>Apache Parquet:</strong> I moved from CSV to Parquet, a columnar storage format. Parquet files are highly efficient for the type of analytical queries I needed to run, as you only need to read the columns you’re interested in.</li><li><strong>Date Partitioning:</strong> Instead of a single large file, I began partitioning the data by date, following a year=YYYY/month=MM/day=DD directory structure. This means each day&#39;s scraped data is stored in its own data.parquet file. This is a standard data lake pattern that dramatically speeds up queries on specific time ranges.</li><li><strong>DuckDB:</strong> To query this partitioned dataset, I integrated DuckDB. DuckDB is an in-memory analytical database that is incredibly fast and can directly query Parquet files (and even a collection of them) using standard SQL. My parquet_duckdb_storage.py module contains all the logic for writing new partitioned data and running complex queries across date ranges.</li></ol><p>This setup was a massive improvement, providing a scalable and high-performance local data warehouse.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kNL7L2EIAiCeTW_q.png" /></figure><h4>Phase 3: Migrating to the Cloud with Cloudflare R2</h4><p>While the partitioned Parquet setup was great, it lived only on my local machine. To make the data persistent, accessible from anywhere, and ready to power a public web application, I took the final step of migrating to cloud storage. I chose <strong>Cloudflare R2</strong>, an S3-compatible object storage service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uWMiguUwDE6jD3EQ.png" /></figure><p>The application now uses an environment variable (USE_R2) to switch between local and cloud mode. When enabled, the daily data partitions are uploaded to an R2 bucket. A metadata.json file, which keeps track of all available dates, is also synced to the cloud. This ensures the data is safe, and the visualization application can be deployed and run from anywhere, simply by providing the correct R2 credentials.</p><h3>The “What”: An Interactive Analysis Dashboard</h3><p>With a robust data pipeline in place, the final step was to bring the data to life. I built an interactive web application, visualize_models.py, using <strong>Streamlit</strong>, a fantastic Python framework for creating data apps.</p><p><a href="https://ollama-models-analysis.streamlit.app/">https://ollama-models-analysis.streamlit.app</a></p><p>The dashboard allows users to explore the Ollama model ecosystem in detail.</p><p><strong>Key Features:</strong></p><ol><li><strong>Interactive Date Range Selection:</strong> A slider allows you to select the time period you want to analyze, from the earliest collected data to the most recent</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KEi-XoLbonHshkDE.png" /></figure><p><strong>2. Top N Model Analysis:</strong> You can see charts of the top models and model families based on their total pull counts for the selected date. You can adjust how many “top” models you want to see.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*r39Qa7UChhL-grVN.png" /></figure><p><strong>3. Historical Popularity Trends:</strong> The most powerful feature is the ability to track a model family’s popularity over time. You can select one or more model families, and the application will plot their total pull counts across the entire historical dataset, revealing their growth trajectories.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ulPqdOKz-9_ED3Vr.png" /></figure><p><strong>4. Detailed Data Tables:</strong> Alongside every chart, there are detailed tables with the raw numbers, allowing for closer inspection of the data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*f28fqzctlQO_70Or.png" /></figure><p>This tool transforms a simple list of models into a dynamic and explorable dataset, offering clear insights into what’s currently trending in the open-source AI community.</p><h3>Conclusion</h3><p>This project was a fascinating journey from a simple question to a complete data application. It was an exercise in practical data engineering, evolving from a basic script to a scalable, cloud-based pipeline. The final dashboard provides a unique lens through which to view the fast-paced world of open-source LLMs. I plan to continue collecting this data and adding new features to the analysis tool. Feel free to check out the project and explore the trends for yourself!</p><p>One more thing: The whole app was built by <strong>vibe coding</strong> through Cursor without writing one line code by hand!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a9840eef864" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hands on LangChain: RAG]]></title>
            <link>https://medium.com/@ai-data-drive/hands-on-langchain-rag-dd639d0576f6?source=rss-5140c0782d6f------2</link>
            <guid isPermaLink="false">https://medium.com/p/dd639d0576f6</guid>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[langchain]]></category>
            <dc:creator><![CDATA[Andy Yang]]></dc:creator>
            <pubDate>Sun, 08 Jun 2025 08:32:05 GMT</pubDate>
            <atom:updated>2025-06-08T08:32:05.732Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*kdELJ7y2ARyUrXBS.png" /></figure><h3>RAG: Why RAG is Needed</h3><ul><li><a href="https://medium.com/@ai-data-drive/hands-on-langchain-models-part-1-3553624c84ec">Hands on LangChain: Models (Part 1)</a></li><li><a href="https://medium.com/@ai-data-drive/hands-on-langchain-memory-part-2-52d2eba9ba6d">Hands on LangChain: Memory(Part 2)</a></li><li><a href="https://medium.com/@ai-data-drive/hands-on-langchain-chains-part-3-b05ee7b097cc">Hands on LangChain: Chains (Part 3)</a></li></ul><p>In previous tutorials, we introduced how to dialogue with Large Language Models (LLMs) through LangChain’s PromptTemplate, ChatOpenAI, StrOutputParser, and other Runnable components to achieve a variety of GenAI (Generative AI) functionalities. LLMs are powerful and have given people a glimpse of AGI (Artificial General Intelligence). However, they also have their own shortcomings, mainly manifested in:</p><ul><li>The training data of LLMs has a cutoff time, hence lacking knowledge after that cutoff time. Below is the training data cutoff time for the Claude model online service on 20240730, which is April 2024. Therefore, it has no knowledge of Meta’s recent release of the Llama 3.1 model version.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iLYa-9twNzA_l88E.png" /></figure><ul><li>The training data of LLMs is mainly based on publicly available data that can be crawled, thus lacking private data. Especially in enterprise applications or personal assistant scenarios that require specific domain, internal, or private data, LLMs are inadequate. For example, Claude does not know who “Unrepentant Criminal Zhang San” is:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LE9skrrrzzF2PbWI.png" /></figure><p>When conversing with LLMs and requiring more timely, professional, and private data and information, RAG (Retrieval Augmented Generation) technology is needed. In simple terms, it is a method that provides the LLM with the required context through retrieval (which can be web search, database queries, document searches, knowledge graph searches, and other different technologies) to improve the quality of LLM output.</p><p>Some chatbots now have internet access and enhance LLMs with missing information by searching the web. For example, ChatGPT retrieves information from Bing search pages and nextplatform to get the latest version of the Llama model:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TTnkxkKtK59GoXdO.png" /></figure><p>For industry-specific or private information, we can provide documents to LLMs, and based on this information, they will have the relevant knowledge. For example, through my introduction, Claude got to know “Unrepentant Criminal Zhang San”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GUUBkvTerl-atKbS.png" /></figure><h3>RAG: Data Sources</h3><p>There are many data sources that can provide RAG to LLMs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rdIPeK1Z1uI3EqkJ.png" /></figure><p>Including:</p><ul><li><strong>Websites</strong>: Web pages. Results obtained from web searches or a direct URL.</li><li><strong>Docs</strong>: Documents. Including pdf, txt, excel, ppt, csv, epub, json, yaml, and various other document formats.</li><li><strong>Codes</strong>: Code. Software has swallowed the world, and code is everywhere. Code written in various programming languages such as C/C++, Python, Java, JavaScript, PHP, etc., can be provided to LLMs.</li><li><strong>DBs</strong>: Databases. Most enterprise data exists in various databases, and the operation of different systems such as business systems, ERP, CRM, and office automation depends on databases. The data in them can be used as context input for LLMs.</li><li><strong>Knowledge Graphs</strong>: Knowledge graphs. Businesses often build their own knowledge graphs for different businesses such as social networks, financial security, and asset management, storing complex dependency relationships between different business entities. It can also be a source of context for LLMs.</li><li><strong>Transcripts</strong>: Subtitles. Subtitle information of audio and video files can also be used as context input for LLMs, which is an important data source for analyzing non-structured data such as audio and video.</li><li><strong>Others</strong>: Etc., any information source that can obtain data can generate context needed by LLMs.</li></ul><h3>RAG: Working Principle</h3><p>Having provided external knowledge, how does RAG work? Below is the working principle diagram of the entire system:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kdELJ7y2ARyUrXBS.png" /></figure><p>The entire process can be divided into two stages, which are <strong>Indexing</strong> and <strong>Retrieval &amp; generation.</strong></p><p><strong>Indexing</strong>: It includes:</p><ul><li>Load: Document loading. Reading the original document, such as a large pdf, txt, or csv file of different formats. In LangChain, this can be achieved through <a href="https://python.langchain.com/v0.2/docs/concepts/#document-loaders">Document Loaders</a>.</li><li>Split: Document splitting. Splitting a large document into smaller data chunks because LLMs have input length limitations, so the entire document cannot be placed into the Prompt, hence the need to cut the large document into small pieces, and then index each piece. When a user asks a question, the most relevant data chunks are retrieved and spliced into context. Split can be implemented with LangChain’s <a href="https://python.langchain.com/v0.2/docs/concepts/#text-splitters">Text splitters</a>.</li><li>Embed: Transforming text into embedding. Embedding can be seen as a vector representation of a piece of text in the semantic space, which is a set of numbers representing the meaning of a piece of text. Since it is a vector representation, distances can be calculated to obtain the similarity between different texts, thus finding data chunks related to user input. This is a key to RAG implementation. The next chapter will expand on Embedding. LangChain provides a series of <a href="https://python.langchain.com/v0.2/docs/concepts/#embedding-models">Embedding models</a> to help users easily implement embedding.</li><li>Store: Embedding storage. Just like business order data needs to be stored in relational databases like MySQL for fast queries and operations, a large amount of data chunks also need a special database to store their embeddings. This special database for storing and retrieving embeddings is a vector database (<a href="https://python.langchain.com/v0.2/docs/concepts/#vector-stores">vector store/database</a>, embedding = vector).</li></ul><p><strong>Retrieval &amp; generation</strong>: It includes:</p><ul><li>Retrieve: Retrieving relevant text. Converting the user’s input question into an embedding, and then retrieving similar data chunks from the vector storage as input context for LLMs.</li><li>Generate: LLM generates an answer. Combining the context obtained above with the question into a Prompt and inputting it into the LLM to generate the final answer.</li></ul><p>The above is the entire process of RAG. Below we will implement a basic RAG through an actual example.</p><h3>RAG: Basic Implementation</h3><h3>Environment Preparation</h3><pre>import os<br>from dotenv import load_dotenv<br>​<br>from langchain.text_splitter import CharacterTextSplitter<br>from langchain_community.document_loaders import TextLoader<br>from langchain_openai import ChatOpenAI, OpenAIEmbeddings<br>​<br>load_dotenv()<br>​<br># set the directory for vector store<br>cur_dir = os.getcwd()<br>file_name = &quot;Top 20+ RAG Interview Questions&quot;<br>file_path = os.path.join(cur_dir, &quot;articles/RAG&quot;, file_name)<br>if not os.path.exists(file_path):<br>    raise FileNotFoundError(<br>        f&quot;The file {file_path} does not exist, please check it.&quot;<br>    )<br>​<br>vdb_dir = os.path.join(cur_dir, &#39;db&#39;, &#39;chroma_db&#39;)<br>os.makedirs(vdb_dir, exist_ok=True)<br>​</pre><p>First, we find an article introducing RAG: <a href="https://www.analyticsvidhya.com/blog/2024/04/rag-interview-questions/">Top 20+ RAG Interview Questions</a>, and place its content in the articles/RAG/Top 20+ RAG Interview Questions txt file. Then prepare a db/chroma_db folder as the working directory for the vector database to store embedding data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WME34oBtJcff3v01.png" /></figure><h3>Load: Loading</h3><p>Then use TextLoader to load this txt file:</p><pre># load<br>loader = TextLoader(file_path)<br>docs = loader.load()<br>​<br>type(docs), len(docs), type(docs[0]), type(docs[0].metadata), docs[0].metadata, type(docs[0].page_content), len(docs[0].page_content), docs[0].page_content[0:150]</pre><pre>(list,<br> 1,<br> langchain_core.documents.base.Document,<br> dict,<br> {&#39;source&#39;: &#39;/Users/yangls06/Documents/SyncSpace/work/learn-langchain/articles/RAG/Top 20+ RAG Interview Questions&#39;},<br> str,<br> 21162,<br> &#39;Top 20+ RAG Interview Questions\nurl:https://www.analyticsvidhya.com/blog/2024/04/rag-interview-questions/\n\nIntroduction\nRAG has been a game-changer in the developing fields of GenAI, Data Science, and AI. Because RAG models let machines produce more accurate, coherent, and consistent language with facts, they transform how humans engage with technology. RAG is bringing the idea of robots that can write unique content, engrossing product descriptions, and news pieces to life. Even with RAG’s increasing importance, prospective data scientists and AI enthusiasts still need access to comprehensive information. This article fills that knowledge gap by offering the top 20+ RAG interview questions.&#39;)</pre><p>After loading, we get an array of Document objects. Since only one file is loaded, there is only one Document in the array. The Document object includes:</p><ul><li>metadata: Metadata. It is a dict with a source member that stores the path of the file.</li><li>page_content: Document content. It is a string that stores the content of this document. This document includes 21169 characters, and the content is the entire text content of the web page.</li></ul><h3>Split: Splitting</h3><p>Then you can split the loaded document through CharacterTextSplitter:</p><pre>text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)<br>chunks = text_splitter.split_documents(docs)<br>type(chunks), len(chunks), type(chunks[0])</pre><pre>Created a chunk of size 1072, which is longer than the specified 1000<br>Created a chunk of size 1123, which is longer than the specified 1000<br>Created a chunk of size 1137, which is longer than the specified 1000<br>Created a chunk of size 1565, which is longer than the specified 1000<br>​<br>(list, 26, langchain_core.documents.base.Document)</pre><p>From the above code and running results, it can be seen:</p><ul><li>CharacterTextSplitter requires setting chunk_size (data chunk size) and chunk_overlap (data chunk overlap size).</li><li>After split_documents, what is obtained is still an array of Document, indicating that a chunk is also a Document.</li><li>There will be warning messages during the code run: Created a chunk of size 1072, which is longer than the specified 1000, indicating that chunk_size=1000 is not a hard constraint. The size of the chunks obtained is not exactly equal to 1000. From the source code, it is known that it is split by separator: str = &quot;\n\n&quot;:</li></ul><pre>class CharacterTextSplitter(TextSplitter):<br>    &quot;&quot;&quot;Splitting text that looks at characters.&quot;&quot;&quot;<br>​<br>    def __init__(<br>        self, separator: str = &quot;\n\n&quot;, is_separator_regex: bool = False, **kwargs: Any<br>    ) -&gt; None:<br>        &quot;&quot;&quot;Create a new TextSplitter.&quot;&quot;&quot;<br>        super().__init__(**kwargs)<br>        self._separator = separator<br>        self._is_separator_regex = is_separator_regex</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Si28mIn0XoUDIwgT.png" /></figure><pre>print(f&quot;chunk_sizes: {[len(chunk.page_content) for chunk in chunks]}&quot;)</pre><pre>chunk_sizes: [763, 698, 693, 974, 650, 621, 744, 526, 647, 684, 758, 974, 662, 991, 638, 1072, 1123, 873, 909, 948, 582, 1137, 681, 614, 1565, 585]</pre><p>From the above running results, it can be seen that the size of most data chunks is within 1000, and a few data chunks are longer than 1000. Below, check the specific data of each chunk:</p><pre>for idx, chunk in enumerate(chunks[0:3]):<br>    print(f&quot;\nsize of chunk {idx}: {len(chunk.page_content)}&quot;)<br>    print(f&quot;{&#39;-&#39; * 32}&quot;)<br>    print(chunk.page_content)<br>    print(f&quot;{&#39;-&#39; * 32}&quot;)</pre><pre>size of chunk 0: 763<br>--------------------------------<br>Top 20+ RAG Interview Questions<br>url:https://www.analyticsvidhya.com/blog/2024/04/rag-interview-questions/<br>​<br>Introduction<br>RAG has been a game-changer in the developing fields of GenAI, Data Science, and AI. Because RAG models let machines produce more accurate, coherent, and consistent language with facts, they transform how humans engage with technology. RAG is bringing the idea of robots that can write unique content, engrossing product descriptions, and news pieces to life. Even with RAG’s increasing importance, prospective data scientists and AI enthusiasts still need access to comprehensive information. This article fills that knowledge gap by offering the top 20+ RAG interview questions.<br>​<br>RAG Interview Questions<br>RAG Interview Questions for Beginners<br>------------------------------<br>​<br>size of chunk 1: 698<br>--------------------------------<br>Q1. What is Retrieval-Augmented Generation (RAG)?<br>A. Retrieval-Augmented Generation (RAG) is an approach that combines retrieval-based methods with generative models to enhance the performance of NLP tasks. In RAG, a retriever component first searches through a large corpus of documents to find relevant information based on the input query. Then, a generative model uses this retrieved information to generate a response or output. This two-step process allows RAG to leverage both the precision of retrieval methods and the flexibility of generative models. Therefore, it is particularly effective for tasks that require understanding and generating natural language based on external knowledge.<br>------------------------------<br>​<br>size of chunk 2: 693<br>--------------------------------<br>Q2. Can you explain the basic difference between RAG and traditional language models?<br>A. Traditional language models, like GPT-3, generate text based on the patterns and structures they have learned from training data. They cannot retrieve specific information from external sources but generate responses based on the input they receive.<br>On the other hand, RAG incorporates a retrieval component. It first searches for relevant information from a corpus of documents before generating a response. This allows RAG to access and utilize external knowledge. Thus making it more contextually aware and capable of providing more accurate and informative responses than traditional language models.<br>------------------------------</pre><p>It can be seen that separator: str = &quot;\n\n&quot; divides the original content into one question and answer. However, some answers are too long, exceeding the 1000-character limit 🚫, such as Q15:</p><pre>for idx, chunk in enumerate(chunks):<br>    if len(chunk.page_content) &gt; 1000:<br>        print(f&quot;\nsize of chunk {idx}: {len(chunk.page_content)}&quot;)<br>        print(f&quot;{&#39;-&#39; * 32}&quot;)<br>        print(chunk.page_content)<br>        print(f&quot;{&#39;-&#39; * 32}&quot;)<br>        break</pre><pre>size of chunk 15: 1072<br>--------------------------------<br>Q15. Can you explain how RAG models are trained?<br>A. RAG models are typically trained in two main stages: pre-training and fine-tuning.<br>Pre-training: In order to understand the underlying patterns, structures, and language representations of the generative model (such as a transformer-based architecture like GPT), developers train it on a sizable corpus of text data during the pre-training phase. Language modeling tasks, such as predicting the next word in a sequence based on the input text, are part of this phase.<br>Fine-tuning: After pre-training the model architecture, developers add the retriever component. They train the retriever to search through a dataset or document corpus for relevant information based on input queries. Then, they fine-tune the generative model on this retrieved data to generate contextually relevant and accurate responses.<br>This two-stage training approach allows RAG models to leverage the strengths of both retrieval-based and generative methods, leading to improved performance in natural language understanding and generation tasks.<br>------------------------------</pre><h3>Embed: Vectorization</h3><p>After splitting the document, it is necessary to embed the obtained chunk data to transform it into embedding. This requires the use of LangChain’s <a href="https://python.langchain.com/v0.1/docs/modules/data_connection/text_embedding/">Text embedding models</a>, such as the <a href="https://api.python.langchain.com/en/latest/embeddings/langchain_openai.embeddings.base.OpenAIEmbeddings.html">OpenAIEmbeddings</a> class.</p><pre>from langchain_openai import OpenAIEmbeddings<br>​<br>embeddings_model = OpenAIEmbeddings()<br>embeddings_model.model</pre><pre>&#39;text-embedding-ada-002&#39;</pre><p>In LangChain, OpenAIEmbeddings uses the text-embedding-ada-002 embedding model by default. According to OpenAI&#39;s <a href="https://openai.com/index/new-embedding-models-and-api-updates/">new embedding model announcement</a> on 20240125, it is recommended to use the better-performing, lower-priced upgraded model text-embedding-3-small; there is also a higher-performance but more expensive text-embedding-3-large version available. Let&#39;s use text-embedding-3-small to implement chunk embedding.</p><pre>embeddings_model = OpenAIEmbeddings(model=&quot;text-embedding-3-small&quot;)<br>embeddings = embeddings_model.embed_documents([<br>    &#39;dog&#39;, &#39;cat&#39;<br>])<br>len(embeddings), len(embeddings[0])</pre><pre>(2, 1536)</pre><pre>embeddings[0][0:10]</pre><pre>[0.05113774910569191,<br> -0.01870863139629364,<br> -0.004298428073525429,<br> 0.07271610200405121,<br> -0.007174310740083456,<br> -0.014693480916321278,<br> -0.0059395902790129185,<br> 0.005037412978708744,<br> 0.018954960629343987,<br> -0.01090618409216404]</pre><h3>Vector Store: Vector Database</h3><pre>from langchain_community.vectorstores import Chroma<br>​<br>embeddings_model = OpenAIEmbeddings(model=&quot;text-embedding-3-small&quot;)<br>​<br># create the vector store<br>rag_vdb_dir = os.path.join(vdb_dir, &#39;rag_topic&#39;)<br>​<br>if not os.path.exists(rag_vdb_dir):<br>    db = Chroma.from_documents(<br>        chunks, embeddings_model, persist_directory=rag_vdb_dir<br>    )<br>else:<br>    print(&quot;Vector store already exists for rag topic. No need to initialize.&quot;)</pre><p><a href="https://docs.trychroma.com/">Chroma</a> is an AI-native open-source vector database that can conveniently store and search embedding data. It has a very good <a href="https://python.langchain.com/v0.2/docs/integrations/vectorstores/chroma/">integration</a> with LangChain. This is its local storage file layout:</p><pre>! tree -h db</pre><pre>[  96]  [01;34mdb[0m<br>└── [  96]  [01;34mchroma_db[0m<br>    └── [ 128]  [01;34mrag_topic[0m<br>        ├── [ 192]  [01;34m39a9ce32-f089-4267-ab1d-7297511f482e[0m<br>        │   ├── [6.0M]  [00mdata_level0.bin[0m<br>        │   ├── [ 100]  [00mheader.bin[0m<br>        │   ├── [3.9K]  [00mlength.bin[0m<br>        │   └── [   0]  [00mlink_lists.bin[0m<br>        └── [508K]  [00mchroma.sqlite3[0m<br>​<br>3 directories, 5 files</pre><p>You can use the <a href="https://api.python.langchain.com/en/latest/vectorstores/langchain_community.vectorstores.chroma.Chroma.html#langchain_community.vectorstores.chroma.Chroma.get">get()</a> function to get all the data stored in the Chroma vector database. It will return a dictionary containing keys such as ids, embeddings, metadatas, documents, etc.:</p><pre>embeddings_stored = db.get()<br>type(embeddings_stored), len(embeddings_stored), embeddings_stored.keys(), embeddings_stored[&#39;ids&#39;], embeddings_stored[&#39;embeddings&#39;]</pre><pre>(dict,<br> 7,<br> dict_keys([&#39;ids&#39;, &#39;embeddings&#39;, &#39;metadatas&#39;, &#39;documents&#39;, &#39;uris&#39;, &#39;data&#39;, &#39;included&#39;]),<br> [&#39;00ad8dcd-31d0-4dcd-8ded-23f51f3a135f&#39;,<br>  &#39;0fce9646-bc90-43b3-a2c9-ed1280047d9f&#39;,<br>  &#39;1145787f-643b-403f-9a73-7643bbcede23&#39;,<br>  &#39;122c8ab3-0f79-47d6-9eaf-a4a74e47c084&#39;,<br>  &#39;16fd6bdd-fa37-4489-9e7c-7fcaa58e52b3&#39;,<br>  &#39;1a682023-b01e-4358-a3da-c7c9fc843e9c&#39;,<br>  &#39;20421c65-40d3-4677-9c50-2d83a32fca46&#39;,<br>  &#39;27929236-d98c-4cf7-876c-460c5b1a7620&#39;,<br>  &#39;3136e6f3-b1f2-4081-a456-961bf20c67af&#39;,<br>  &#39;3a0d5ae0-1d49-404e-908c-7cc6124008c8&#39;,<br>  &#39;3f67d47c-4c44-41b2-9d1d-34544b019795&#39;,<br>  &#39;441c0ad8-0d43-4fd0-9d4c-0621be202eb2&#39;,<br>  &#39;4a2dea60-0fec-4fc8-9a5f-6cc7e0c8143d&#39;,<br>  &#39;67ce524c-8a39-41c6-9466-d2559dbdefab&#39;,<br>  &#39;7170f954-222d-4a41-a249-621a6334d39c&#39;,<br>  &#39;740e28eb-36ad-46e8-bc07-7adf497e3a4f&#39;,<br>  &#39;79496290-be38-4b14-ac4d-356026c89a1e&#39;,<br>  &#39;8c9c4ede-4541-44b1-8333-909143f738e0&#39;,<br>  &#39;b578589d-22ed-4d87-94bc-e4fe4f097763&#39;,<br>  &#39;bde402b2-1427-4436-a4c8-e53cf30301e8&#39;,<br>  &#39;c9994c58-97af-46de-b4cf-ae2c7e07a6bb&#39;,<br>  &#39;cb7270f1-a0a5-4fda-93de-2b0f4b1f06e0&#39;,<br>  &#39;e3be3d52-4797-43e3-95a1-82d7575f4b68&#39;,<br>  &#39;e4f34df2-eb87-43b4-b060-9951d29ad871&#39;,<br>  &#39;eb37f3c1-ba36-4763-96c4-00e72bb06c46&#39;,<br>  &#39;fe92cc65-d20e-4a29-8fcb-9afb22d4135c&#39;],<br> None)</pre><p>From the above output, it can be seen that the embeddings field is None because the get() function includes an include parameter to specify the fields to be returned, and by default, only [“metadatas”, “documents”] are included, not embeddings (the ids are returned by default). You can pass specific ids and include to get specific information:</p><pre>embedding_fetched = db.get(ids=[&#39;00ad8dcd-31d0-4dcd-8ded-23f51f3a135f&#39;], include=[&#39;embeddings&#39;, &#39;documents&#39;, &#39;metadatas&#39;])<br>​<br>(<br>    len(embedding_fetched[&#39;embeddings&#39;][0]),<br>    embedding_fetched[&#39;embeddings&#39;][0][0:10],<br>    len(embedding_fetched[&#39;documents&#39;]),<br>    embedding_fetched[&#39;documents&#39;][0][0:100],<br>    embedding_fetched[&#39;metadatas&#39;][0]<br>)</pre><pre>(1536,<br> [-0.007388777565211058,<br>  0.058094266802072525,<br>  0.055785272270441055,<br>  -0.005974519532173872,<br>  0.0009286481654271483,<br>  -0.044517386704683304,<br>  -0.03283388167619705,<br>  -0.007019339129328728,<br>  -0.014061767607927322,<br>  0.019003013148903847],<br> 1,<br> &#39;Q6. What types of data sources are typically used in RAG systems?\nA. In RAG systems, various types o&#39;,<br> {&#39;source&#39;: &#39;/Users/yangls06/Documents/SyncSpace/work/learn-langchain/articles/RAG/Top 20+ RAG Interview Questions&#39;})</pre><h3>Retrieve: Retrieval</h3><p>After the documents are split into data chunks and the text is transformed into vectors and stored in the vector database, we can retrieve text that is semantically close based on user input:</p><pre>import os<br>from dotenv import load_dotenv<br>​<br>from langchain_openai import ChatOpenAI, OpenAIEmbeddings<br>from langchain_chroma import Chroma<br>​<br>load_dotenv()<br>​<br>cur_dir = os.getcwd()<br>vdb_dir = os.path.join(cur_dir, &#39;db&#39;, &#39;chroma_db&#39;)<br>rag_vdb_dir = os.path.join(vdb_dir, &#39;rag_topic&#39;)<br>​<br>embeddings_model = OpenAIEmbeddings(model=&quot;text-embedding-3-small&quot;)<br>db = Chroma(persist_directory=rag_vdb_dir, embedding_function=embeddings_model)<br>​<br>query = &quot;what is RAG? why do we need RAG? how does it work?&quot;<br>​<br># Retrieve relevant documents based on the query<br>retriever = db.as_retriever(<br>    search_type=&quot;similarity_score_threshold&quot;,<br>    search_kwargs={&quot;k&quot;: 3, &quot;score_threshold&quot;: 0.3},<br>)<br>relevant_chunks = retriever.invoke(query)<br>​<br># Display the relevant results with metadata<br>print(&quot;\n--- Relevant Chunks ---&quot;)<br># print(f&quot;type(relevant_chunks) = {type(relevant_chunks)}&quot;)<br>for i, chunk in enumerate(relevant_chunks, 1):<br>    # print(f&quot;type(chunk) = {type(chunk)}&quot;)<br>    print(f&quot;Chunk {i}:\n{chunk.page_content}\n&quot;)<br>    if chunk.metadata:<br>        print(f&quot;Source: {chunk.metadata.get(&#39;source&#39;, &#39;Unknown&#39;)}\n&quot;)</pre><pre>--- Relevant Chunks ---<br>Chunk 1:<br>Benefits of Using RAG in Various Fields: Healthcare: RAG-powered systems can assist medical professionals by pulling in information from medical journals and patient records to suggest diagnoses or treatments that are informed by the latest research. Customer Service: By retrieving company policies and customer histories, RAG allows service agents to offer personalized and accurate advice, improving customer satisfaction. Education: Teachers can leverage RAG-based tools to create custom lesson plans and learning materials that draw from a broad range of educational content, providing students with diverse perspectives. Additional Applications: Legal Aid: RAG systems can aid in legal research by fetching relevant case law and statutes to assist in drafting legal documents or preparing for cases. Translation Services: Combining RAG with translation models to provide context-aware translations that consider cultural nuances and idiomatic expressions by referencing bilingual text corpora. The utilization of RAG in these applications allows for outputs that are not just generated based on a static knowledge base but are dynamically informed by the most relevant and current data available, leading to more precise, informative, and trustworthy AI-generated content.<br>​<br>Source: /Users/yangls06/Documents/SyncSpace/work/learn-langchain/articles/RAG/What is Retrieval-Augmented Generation(RAG) in LLM and How it works?.txt<br>​<br>Chunk 2:<br>Q3. What are some common applications of RAG in AI?<br>A. RAG has various applications across different domains in AI, including: Question-Answering Systems: RAG may be used to create systems that provide a clear and precise response to a user’s inquiry after gathering pertinent facts from a sizable dataset or the internet. Information Retrieval: RAG may help increase the effectiveness and precision of information retrieval systems. This is done by helping to extract pertinent documents or information from a vast corpus using specific keywords or queries. Conversational Agents: RAG may improve their performance by giving conversational agents access to outside information sources. Additionally, it can also help them provide more insightful and contextually appropriate replies when conversing. Content Generation: RAG may produce logical and educational documents by gathering and combining information from various sources to create summaries, articles, and reports.<br>​<br>Source: /Users/yangls06/Documents/SyncSpace/work/learn-langchain/articles/RAG/Top 20+ RAG Interview Questions.txt<br>​<br>Chunk 3:<br>Top 20+ RAG Interview Questions<br>url:https://www.analyticsvidhya.com/blog/2024/04/rag-interview-questions/<br>​<br>Introduction<br>RAG has been a game-changer in the developing fields of GenAI, Data Science, and AI. Because RAG models let machines produce more accurate, coherent, and consistent language with facts, they transform how humans engage with technology. RAG is bringing the idea of robots that can write unique content, engrossing product descriptions, and news pieces to life. Even with RAG’s increasing importance, prospective data scientists and AI enthusiasts still need access to comprehensive information. This article fills that knowledge gap by offering the top 20+ RAG interview questions.<br>​<br>RAG Interview Questions<br>RAG Interview Questions for Beginners<br>​<br>Source: /Users/yangls06/Documents/SyncSpace/work/learn-langchain/articles/RAG/Top 20+ RAG Interview Questions.txt</pre><p>The above code points are:</p><ul><li>db = Chroma(persist_directory=rag_vdb_dir, embedding_function=embeddings_model): First, initialize a Chroma database instance through the storage directory of the vector data chunks and the embedding model;</li><li>retriever = db.as_retriever(search_type, search_kwargs): Then, turn the database instance into a retriever by setting the search type (similarity_score_threshold) and related parameters (top_k, score threshold, etc.).</li><li>relevant_chunks = retriever.invoke(query): Based on the user&#39;s question, retrieve the relevant chunks (satisfying the similarity score above the score threshold and the top_k results), which are still an array of Document.</li></ul><h3>Generate: Generate Responses</h3><p>After retrieving the relevant data chunks, combine them with the user’s question to form a Prompt and input it into the LLM model to generate the answer to the question:</p><pre>from langchain_core.messages import HumanMessage, SystemMessage<br>from langchain_openai import ChatOpenAI<br>​<br># Combine the query and the relevant chunk contents<br>combined_input = (<br>    &quot;Here is some context and source url that might help answer the question: &quot;<br>    + query<br>    + &quot;\n\nRelevant context(which starts with ### and ends with ###) and source url:\n&quot;<br>    + &quot;\n\n&quot;.join([f&quot;source_url:{chunk.metadata[&#39;origin_url&#39;]}\ncontent:###\n{chunk.page_content}\n###&quot; for chunk in relevant_chunks])<br>    + &quot;\n\nPlease provide an answer based only on the provided context. If the answer is not found in it, respond with &#39;I&#39;m not sure&#39;.&quot;<br>    + &quot; When providing an answer, include citations from the provided context to increase credibility.&quot;<br>    + &quot;\n\nAfter the answer, give three relative questions attractive to the user and output one by one in the format &#39;Relative question {#no}: {relative question}&#39;.&quot;<br>)<br>​<br># print(combined_input)<br>​<br># Create a ChatOpenAI model<br>model = ChatOpenAI(model=&quot;gpt-3.5-turbo&quot;)<br>​<br># Define the messages for the model<br>messages = [<br>    SystemMessage(content=&quot;You are a helpful assistant.&quot;),<br>    HumanMessage(content=combined_input),<br>]<br>​<br># Invoke the model with the combined input<br>result = model.invoke(messages)<br>​<br># Display the full result and content only<br>print(&quot;\n--- User Request ---&quot;)<br>print(query)<br>print(&quot;\n--- Generated Response ---&quot;)<br>print(result.content)</pre><pre>--- User Request ---<br>what is RAG? why do we need RAG? how does it work?<br>​<br>--- Generated Response ---<br>Retrieval-Augmented Generation (RAG) is a technique used in large language models (LLMs) to enhance their performance by retrieving relevant information from external sources and incorporating it into the generated content. This approach helps in producing more accurate, informative, and contextually appropriate outputs.<br>​<br>### Why do we need RAG?<br>RAG is particularly useful because it addresses the limitations of static knowledge bases in LLMs. Instead of relying solely on pre-existing, static data, RAG dynamically pulls in the most relevant and current information, making the generated content more precise and trustworthy. This is essential in scenarios where up-to-date information is critical, such as in healthcare, legal aid, and customer service (source: https://medium.com/@sahin.samia/what-is-retrieval-augmented-generation-rag-in-llm-and-how-it-works-a8c79e35a172).<br>​<br>### How does it work?<br>RAG operates by first retrieving pertinent documents or information based on a given query or context and then using this retrieved information to generate a response. This dual-step process ensures that the generated content is not only coherent but also enriched with the latest and most relevant data available (source: https://towardsai.net/p/l/a-complete-guide-to-rag).<br>​<br>Relative question 1: What are some common applications of RAG in AI?<br>​<br>Relative question 2: How does RAG improve the performance of conversational agents?<br>​<br>Relative question 3: What challenges does RAG address in the context of large language models?</pre><p>In the Prompt, we added the corresponding source_url in the background information and required the LLM to include citation information to increase the credibility of the answer; we also asked the LLM to provide three related questions for the user to further explore. The generated response from the LLM meets the requirements well. This is a basic function supported by AI search engines like Perplexity:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3V7FXEs_t-5SCPf2.png" /></figure><h3>Splitter: Splitting</h3><h4>CharacterTextSplitter</h4><p>After delving into loaders, let’s see how splitters affect the operation of RAG. In the previous examples, we used <a href="https://python.langchain.com/v0.2/docs/how_to/character_text_splitter/">CharacterTextSplitter</a> to split documents:</p><pre>import os<br>​<br>from langchain.text_splitter import CharacterTextSplitter<br>from langchain_community.document_loaders import TextLoader<br>from langchain_openai import ChatOpenAI, OpenAIEmbeddings<br>​<br>load_dotenv()<br>​<br># set the directory for vector store<br>cur_dir = os.getcwd()<br>file_name = &quot;Top 20+ RAG Interview Questions.txt&quot;<br>file_path = os.path.join(cur_dir, &quot;articles/RAG&quot;, file_name)<br>​<br>vdb_dir = os.path.join(cur_dir, &#39;db&#39;, &#39;chroma_db&#39;)<br>os.makedirs(vdb_dir, exist_ok=True)<br>​<br># load<br>loader = TextLoader(file_path)<br>docs = loader.load()<br>​<br>text_splitter = CharacterTextSplitter(chunk_size=500, chunk_overlap=0)<br>chunks = text_splitter.split_documents(docs)</pre><pre>Created a chunk of size 593, which is longer than the specified 500<br>Created a chunk of size 698, which is longer than the specified 500<br>Created a chunk of size 693, which is longer than the specified 500<br>Created a chunk of size 974, which is longer than the specified 500<br>Created a chunk of size 650, which is longer than the specified 500<br>Created a chunk of size 621, which is longer than the specified 500<br>Created a chunk of size 744, which is longer than the specified 500<br>Created a chunk of size 526, which is longer than the specified 500<br>Created a chunk of size 647, which is longer than the specified 500<br>Created a chunk of size 684, which is longer than the specified 500<br>Created a chunk of size 758, which is longer than the specified 500<br>Created a chunk of size 974, which is longer than the specified 500<br>Created a chunk of size 662, which is longer than the specified 500<br>Created a chunk of size 991, which is longer than the specified 500<br>Created a chunk of size 638, which is longer than the specified 500<br>Created a chunk of size 1072, which is longer than the specified 500<br>Created a chunk of size 1123, which is longer than the specified 500<br>Created a chunk of size 873, which is longer than the specified 500<br>Created a chunk of size 909, which is longer than the specified 500<br>Created a chunk of size 948, which is longer than the specified 500<br>Created a chunk of size 582, which is longer than the specified 500<br>Created a chunk of size 1137, which is longer than the specified 500<br>Created a chunk of size 681, which is longer than the specified 500<br>Created a chunk of size 614, which is longer than the specified 500<br>Created a chunk of size 1565, which is longer than the specified 500<br>Created a chunk of size 521, which is longer than the specified 500</pre><pre>def print_chunks_info(chunks, start=0, end=3):<br>    print(f&quot;split into {len(chunks)} chunks&quot;)<br>    print(f&quot;chunk_sizes: {[len(chunk.page_content) for chunk in chunks]}&quot;)<br>​<br>    for idx, chunk in enumerate(chunks[start:end]):<br>        print(f&quot;\nChunk {start+idx} -&gt; size: {len(chunk.page_content)}, metadata: {chunk.metadata}&quot;)<br>        print(f&quot;{&#39;-&#39; * 32}&quot;)<br>        print(chunk.page_content)<br>        print(f&quot;{&#39;-&#39; * 32}&quot;)<br>​<br>print_chunks_info(chunks)</pre><pre>split into 83 chunks<br>chunk_sizes: [106, 12, 498, 81, 61, 49, 491, 156, 338, 354, 322, 477, 173, 64, 495, 89, 56, 492, 71, 371, 372, 62, 463, 55, 491, 99, 48, 493, 141, 449, 308, 71, 499, 12, 389, 69, 491, 100, 340, 442, 207, 65, 497, 74, 134, 384, 339, 212, 68, 494, 20, 433, 104, 219, 298, 354, 319, 381, 207, 444, 303, 199, 53, 494, 33, 263, 477, 395, 74, 499, 106, 57, 499, 56, 402, 355, 275, 304, 225, 10, 496, 13, 62]<br>​<br>Chunk 0 -&gt; size: 106, metadata: {&#39;source&#39;: &#39;/Users/yangls06/Documents/SyncSpace/work/learn-langchain/articles/RAG/Top 20+ RAG Interview Questions.txt&#39;, &#39;start_index&#39;: 0}<br>--------------------------------<br>Top 20+ RAG Interview Questions<br>url: https://www.analyticsvidhya.com/blog/2024/04/rag-interview-questions/<br>--------------------------------<br>​<br>Chunk 1 -&gt; size: 12, metadata: {&#39;source&#39;: &#39;/Users/yangls06/Documents/SyncSpace/work/learn-langchain/articles/RAG/Top 20+ RAG Interview Questions.txt&#39;, &#39;start_index&#39;: 108}<br>--------------------------------<br>Introduction<br>--------------------------------<br>​<br>Chunk 2 -&gt; size: 498, metadata: {&#39;source&#39;: &#39;/Users/yangls06/Documents/SyncSpace/work/learn-langchain/articles/RAG/Top 20+ RAG Interview Questions.txt&#39;, &#39;start_index&#39;: 121}<br>--------------------------------<br>RAG has been a game-changer in the developing fields of GenAI, Data Science, and AI. Because RAG models let machines produce more accurate, coherent, and consistent language with facts, they transform how humans engage with technology. RAG is bringing the idea of robots that can write unique content, engrossing product descriptions, and news pieces to life. Even with RAG’s increasing importance, prospective data scientists and AI enthusiasts still need access to comprehensive information. This<br>------------------------------</pre><p>From the above code and running results, it can be seen:</p><ul><li>CharacterTextSplitter requires setting chunk_size (data chunk size) and chunk_overlap (data chunk overlap size).</li><li>After split_documents, what is obtained is still an array of Document, indicating that a chunk is also a Document.</li><li>There will be warning messages during the code run: Created a chunk of size 1072, which is longer than the specified 1000, indicating that chunk_size=1000 is not a hard constraint. The size of the chunks obtained is not exactly equal to 1000. From the source code, it is known that it is split by separator: str = &quot;\n\n&quot;:</li></ul><pre>class CharacterTextSplitter(TextSplitter):<br>    &quot;&quot;&quot;Splitting text that looks at characters.&quot;&quot;&quot;<br>​<br>    def __init__(<br>        self, separator: str = &quot;\n\n&quot;, is_separator_regex: bool = False, **kwargs: Any<br>    ) -&gt; None:<br>        &quot;&quot;&quot;Create a new TextSplitter.&quot;&quot;&quot;<br>        super().__init__(**kwargs)<br>        self._separator = separator<br>        self._is_separator_regex = is_separator_regex</pre><p>You can also set add_start_index=True to display the starting position start_index of the text in the original text in the metadata of each data chunk:</p><pre>text_splitter = CharacterTextSplitter(chunk_size=100, chunk_overlap=0, add_start_index=True)<br>chunks = text_splitter.split_documents(docs)<br>print_chunks_info(chunks)</pre><pre>Created a chunk of size 106, which is longer than the specified 100<br>Created a chunk of size 593, which is longer than the specified 100<br>Created a chunk of size 698, which is longer than the specified 100<br>Created a chunk of size 693, which is longer than the specified 100<br>Created a chunk of size 974, which is longer than the specified 100<br>Created a chunk of size 650, which is longer than the specified 100<br>Created a chunk of size 621, which is longer than the specified 100<br>Created a chunk of size 744, which is longer than the specified 100<br>Created a chunk of size 526, which is longer than the specified 100<br>Created a chunk of size 647, which is longer than the specified 100<br>Created a chunk of size 684, which is longer than the specified 100<br>Created a chunk of size 758, which is longer than the specified 100<br>Created a chunk of size 974, which is longer than the specified 100<br>Created a chunk of size 662, which is longer than the specified 100<br>Created a chunk of size 991, which is longer than the specified 100<br>Created a chunk of size 638, which is longer than the specified 100<br>Created a chunk of size 1072, which is longer than the specified 100<br>Created a chunk of size 1123, which is longer than the specified 100<br>Created a chunk of size 873, which is longer than the specified 100<br>Created a chunk of size 909, which is longer than the specified 100<br>Created a chunk of size 948, which is longer than the specified 100<br>Created a chunk of size 582, which is longer than the specified 100<br>Created a chunk of size 1137, which is longer than the specified 100<br>Created a chunk of size 681, which is longer than the specified 100<br>Created a chunk of size 614, which is longer than the specified 100<br>Created a chunk of size 1565, which is longer than the specified 100<br>Created a chunk of size 521, which is longer than the specified 100</pre><pre>split into 29 chunks<br>chunk_sizes: [106, 593, 61, 698, 693, 974, 650, 621, 744, 526, 647, 684, 758, 974, 662, 991, 638, 1072, 1123, 873, 909, 948, 582, 1137, 681, 614, 1565, 521, 62]<br>​<br>Chunk 0 -&gt; size: 106, metadata: {&#39;source&#39;: &#39;/Users/yangls06/Documents/SyncSpace/work/learn-langchain/articles/RAG/Top 20+ RAG Interview Questions.txt&#39;, &#39;start_index&#39;: 0}<br>--------------------------------<br>Top 20+ RAG Interview Questions<br>url: https://www.analyticsvidhya.com/blog/2024/04/rag-interview-questions/<br>--------------------------------<br>Chunk 1 -&gt; size: 593, metadata: {&#39;source&#39;: &#39;/Users/yangls06/Documents/SyncSpace/work/learn-langchain/articles/RAG/Top 20+ RAG Interview Questions.txt&#39;, &#39;start_index&#39;: 108}<br>--------------------------------<br>Introduction<br>RAG has been a game-changer in the developing fields of GenAI, Data Science, and AI. Because RAG models let machines produce more accurate, coherent, and consistent language with facts, they transform how humans engage with technology. RAG is bringing the idea of robots that can write unique content, engrossing product descriptions, and news pieces to life. Even with RAG’s increasing importance, prospective data scientists and AI enthusiasts still need access to comprehensive information. This article fills that knowledge gap by offering the top 20+ RAG interview questions.<br>--------------------------------<br>Chunk 2 -&gt; size: 61, metadata: {&#39;source&#39;: &#39;/Users/yangls06/Documents/SyncSpace/work/learn-langchain/articles/RAG/Top 20+ RAG Interview Questions.txt&#39;, &#39;start_index&#39;: 703}<br>--------------------------------<br>RAG Interview Questions<br>RAG Interview Questions for Beginners<br>------------------------------</pre><p>You can set a custom separator to implement different splitting logic, such as using \n or .</p><pre>text_splitter = CharacterTextSplitter(separator=&#39;\n&#39;, chunk_size=500, chunk_overlap=0, add_start_index=True)<br>chunks = text_splitter.split_documents(docs)<br>print_chunks_info(chunks)</pre><pre>Created a chunk of size 580, which is longer than the specified 500<br>Created a chunk of size 648, which is longer than the specified 500<br>Created a chunk of size 585, which is longer than the specified 500<br>Created a chunk of size 564, which is longer than the specified 500<br>Created a chunk of size 591, which is longer than the specified 500<br>Created a chunk of size 635, which is longer than the specified 500<br>Created a chunk of size 512, which is longer than the specified 500<br>Created a chunk of size 592, which is longer than the specified 500<br>Created a chunk of size 572, which is longer than the specified 500<br>Created a chunk of size 515, which is longer than the specified 500<br>Created a chunk of size 528, which is longer than the specified 500<br>Created a chunk of size 606, which is longer than the specified 500<br>Created a chunk of size 556, which is longer than the specified 500<br>Created a chunk of size 510, which is longer than the specified 500</pre><pre>split into 55 chunks<br>chunk_sizes: [119, 580, 111, 648, 338, 481, 431, 480, 585, 56, 564, 371, 435, 463, 55, 591, 48, 635, 449, 380, 512, 459, 592, 340, 442, 273, 572, 134, 384, 339, 281, 515, 433, 324, 298, 458, 438, 431, 379, 303, 253, 528, 263, 477, 470, 606, 57, 556, 402, 355, 275, 304, 236, 510, 62]<br>​<br>Chunk 0 -&gt; size: 119, metadata: {&#39;source&#39;: &#39;/Users/yangls06/Documents/SyncSpace/work/learn-langchain/articles/RAG/Top 20+ RAG Interview Questions.txt&#39;, &#39;start_index&#39;: -1}<br>--------------------------------<br>Top 20+ RAG Interview Questions<br>url: https://www.analyticsvidhya.com/blog/2024/04/rag-interview-questions/<br>Introduction<br>--------------------------------<br>Chunk 1 -&gt; size: 580, metadata: {&#39;source&#39;: &#39;/Users/yangls06/Documents/SyncSpace/work/learn-langchain/articles/RAG/Top 20+ RAG Interview Questions.txt&#39;, &#39;start_index&#39;: 121}<br>--------------------------------<br>RAG has been a game-changer in the developing fields of GenAI, Data Science, and AI. Because RAG models let machines produce more accurate, coherent, and consistent language with facts, they transform how humans engage with technology. RAG is bringing the idea of robots that can write unique content, engrossing product descriptions, and news pieces to life. Even with RAG’s increasing importance, prospective data scientists and AI enthusiasts still need access to comprehensive information. This article fills that knowledge gap by offering the top 20+ RAG interview questions.<br>--------------------------------<br>Chunk 2 -&gt; size: 111, metadata: {&#39;source&#39;: &#39;/Users/yangls06/Documents/SyncSpace/work/learn-langchain/articles/RAG/Top 20+ RAG Interview Questions.txt&#39;, &#39;start_index&#39;: -1}<br>--------------------------------<br>RAG Interview Questions<br>RAG Interview Questions for Beginners<br>Q1. What is Retrieval-Augmented Generation (RAG)?<br>------------------------------</pre><p>Using \n as the separator instead of the default \n\n results in more data chunks being split, with a finer granularity. You can further use .?! punctuation marks that indicate the end of a sentence as a separator to split at the sentence level:</p><pre>text_splitter = CharacterTextSplitter(<br>    separator=&#39;[.?!]&#39;, is_separator_regex=True,<br>    chunk_size=500, chunk_overlap=0,<br>    add_start_index=True, keep_separator=&#39;end&#39;)<br>chunks = text_splitter.split_documents(docs)<br>print_chunks_info(chunks)</pre><pre>split into 49 chunks<br>chunk_sizes: [480, 491, 496, 493, 251, 378, 366, 390, 495, 489, 444, 439, 465, 415, 417, 495, 449, 384, 376, 376, 376, 438, 335, 442, 387, 465, 393, 460, 449, 494, 438, 473, 416, 481, 435, 376, 359, 319, 449, 494, 401, 492, 497, 431, 479, 355, 470, 427, 494]<br>​<br>Chunk 0 -&gt; size: 480, metadata: {&#39;source&#39;: &#39;/Users/yangls06/Documents/SyncSpace/work/learn-langchain/articles/RAG/Top 20+ RAG Interview Questions.txt&#39;, &#39;start_index&#39;: 0}<br>--------------------------------<br>Top 20+ RAG Interview Questions<br>url: https://www.analyticsvidhya.com/blog/2024/04/rag-interview-questions/<br>​<br>Introduction<br>RAG has been a game-changer in the developing fields of GenAI, Data Science, and AI. Because RAG models let machines produce more accurate, coherent, and consistent language with facts, they transform how humans engage with technology. RAG is bringing the idea of robots that can write unique content, engrossing product descriptions, and news pieces to life.<br>--------------------------------<br>Chunk 1 -&gt; size: 491, metadata: {&#39;source&#39;: &#39;/Users/yangls06/Documents/SyncSpace/work/learn-langchain/articles/RAG/Top 20+ RAG Interview Questions.txt&#39;, &#39;start_index&#39;: 481}<br>--------------------------------<br>Even with RAG’s increasing importance, prospective data scientists and AI enthusiasts still need access to comprehensive information. This article fills that knowledge gap by offering the top 20+ RAG interview questions.<br>​<br>RAG Interview Questions<br>RAG Interview Questions for Beginners<br>​<br>Q1. What is Retrieval-Augmented Generation (RAG)?<br>A. Retrieval-Augmented Generation (RAG) is an approach that combines retrieval-based methods with generative models to enhance the performance of NLP tasks.<br>--------------------------------<br>Chunk 2 -&gt; size: 496, metadata: {&#39;source&#39;: &#39;/Users/yangls06/Documents/SyncSpace/work/learn-langchain/articles/RAG/Top 20+ RAG Interview Questions.txt&#39;, &#39;start_index&#39;: 973}<br>--------------------------------<br>In RAG, a retriever component first searches through a large corpus of documents to find relevant information based on the input query. Then, a generative model uses this retrieved information to generate a response or output. This two-step process allows RAG to leverage both the precision of retrieval methods and the flexibility of generative models. Therefore, it is particularly effective for tasks that require understanding and generating natural language based on external knowledge.<br>​<br>Q2.<br>------------------------------</pre><p>The above results show that Chunk 0 and Chunk 1 are the first and second paragraphs of the article, respectively; Chunk 2 + Chunk 3 together are the third paragraph, which is first split by \n\n, and then split by \n and &quot; &quot; to get the result.</p><p>In addition to the CharacterTextSplitter and RecursiveCharacterTextSplitter introduced above, LangChain also provides a variety of Splitters for different purposes:</p><ul><li>Token-based <a href="https://python.langchain.com/v0.2/docs/how_to/split_by_token/">TokenTextSplitter</a></li><li>Convenient for splitting markdown files <a href="https://python.langchain.com/v0.2/docs/how_to/markdown_header_metadata_splitter/">MarkdownHeaderTextSplitter</a></li><li>Used for splitting Json files <a href="https://python.langchain.com/v0.2/docs/how_to/recursive_json_splitter/">RecursiveJsonSplitter</a></li><li>…</li></ul><p>You can choose freely according to your own needs.</p><h3>Retriever</h3><p>Through the above introduction, we have learned about different types of Loaders (loaders) and Splitters (splitters) in LangChain. As an indispensable part of RAG, are there also multiple implementations of Retrievers (retrievers)?</p><h4>search_type: Search Type</h4><p>Let’s review the Retriever in RAG through the code:</p><pre>import os<br>from langchain_community.vectorstores import Chroma<br>​<br>embeddings_model = OpenAIEmbeddings(model=&quot;text-embedding-3-small&quot;)<br>​<br># create the vector store<br>cur_dir = os.getcwd()<br>vdb_dir = os.path.join(cur_dir, &#39;db&#39;, &#39;chroma_db&#39;)<br>rag_vdb_dir = os.path.join(vdb_dir, &#39;rag_articles&#39;)<br>​<br>if not os.path.exists(rag_vdb_dir):<br>    db = Chroma.from_documents(<br>        chunks, embeddings_model, persist_directory=rag_vdb_dir<br>    )<br>else:<br>    print(&quot;Vector store already exists for rag topic. No need to initialize.&quot;)<br>​<br>embeddings_model = OpenAIEmbeddings(model=&quot;text-embedding-3-small&quot;)<br>db = Chroma(persist_directory=rag_vdb_dir, embedding_function=embeddings_model)<br>​<br>query = &quot;what is RAG? why do we need RAG? how does it work?&quot;<br>​<br># Retrieve relevant documents based on the query<br>retriever = db.as_retriever(<br>    search_type=&quot;similarity_score_threshold&quot;,<br>    search_kwargs={&quot;k&quot;: 3, &quot;score_threshold&quot;: 0.3},<br>)<br>relevant_chunks = retriever.invoke(query)<br>​<br># Display the relevant results with metadata<br>print(&quot;\n--- Relevant Chunks ---&quot;)<br># print(f&quot;type(relevant_chunks) = {type(relevant_chunks)}&quot;)<br>for i, chunk in enumerate(relevant_chunks, 1):<br>    # print(f&quot;type(chunk) = {type(chunk)}&quot;)<br>    print(f&quot;Chunk {i}:\n{chunk.page_content}\n&quot;)<br>    if chunk.metadata:<br>        print(f&quot;Source: {chunk.metadata.get(&#39;source&#39;, &#39;Unknown&#39;)}\nOrigin_url: {chunk.metadata.get(&#39;origin_url&#39;, &#39;Unknown&#39;)}\n&quot;)</pre><pre>Vector store already exists for rag topic. No need to initialize.<br>​<br>--- Relevant Chunks ---<br>Chunk 1:<br>Benefits of Using RAG in Various Fields: Healthcare: RAG-powered systems can assist medical professionals by pulling in information from medical journals and patient records to suggest diagnoses or treatments that are informed by the latest research. Customer Service: By retrieving company policies and customer histories, RAG allows service agents to offer personalized and accurate advice, improving customer satisfaction. Education: Teachers can leverage RAG-based tools to create custom lesson plans and learning materials that draw from a broad range of educational content, providing students with diverse perspectives. Additional Applications: Legal Aid: RAG systems can aid in legal research by fetching relevant case law and statutes to assist in drafting legal documents or preparing for cases. Translation Services: Combining RAG with translation models to provide context-aware translations that consider cultural nuances and idiomatic expressions by referencing bilingual text corpora. The utilization of RAG in these applications allows for outputs that are not just generated based on a static knowledge base but are dynamically informed by the most relevant and current data available, leading to more precise, informative, and trustworthy AI-generated content.<br>​<br>Source: articles/RAG/What is Retrieval-Augmented Generation(RAG) in LLM and How it works?.txt<br>Origin_url: https://medium.com/@sahin.samia/what-is-retrieval-augmented-generation-rag-in-llm-and-how-it-works-a8c79e35a172<br>​<br>Chunk 2:<br>Q3. What are some common applications of RAG in AI? A. RAG has various applications across different domains in AI, including: Question-Answering Systems: RAG may be used to create systems that provide a clear and precise response to a user’s inquiry after gathering pertinent facts from a sizable dataset or the internet. Information Retrieval: RAG may help increase the effectiveness and precision of information retrieval systems. This is done by helping to extract pertinent documents or information from a vast corpus using specific keywords or queries. Conversational Agents: RAG may improve their performance by giving conversational agents access to outside information sources. Additionally, it can also help them provide more insightful and contextually appropriate replies when conversing. Content Generation: RAG may produce logical and educational documents by gathering and combining information from various sources to create summaries, articles, and reports.<br>​<br>Source: articles/RAG/Top 20+ RAG Interview Questions.txt<br>Origin_url: https://www.analyticsvidhya.com/blog/2024/04/rag-interview-questions/<br>​<br>Chunk 3:<br>A Complete Guide to RAG url: https://towardsai.net/p/l/a-complete-guide-to-rag<br>​<br>If you haven’t heard about RAG from your refrigerator yet, you surely will very soon, so popular this technique has become. Surprisingly, there is a lack of complete guides that consider all the nuances (like relevance assessment, combating hallucinations, etc. ), instead of just fragmented pieces. Based on our experience, I have compiled a guide that covers this topic thoroughly.<br>​<br>Image by DALL-E 3 So, why do we need RAG?<br>​<br>You could use LLM models like ChatGPT to create horoscopes (which it does quite successfully), or for something more practical (like work). However, there is a problem: companies typically have a multitude of documents, rules, regulations, etc., about which ChatGPT knows nothing, of course.<br>​<br>What can be done?<br>​<br>There are two options: retrain the model with your data or use RAG.<br>​<br>Source: articles/RAG/A Complete Guide to RAG.txt<br>Origin_url: https://towardsai.net/p/l/a-complete-guide-to-rag</pre><p>Through the code retriever = db.as_retriever(search_type, search_kwargs), it is visible: LangChain turns a vector database instance into a retriever through the as_retriever function, and the search type (similarity_score_threshold) and related parameters (top_k, score threshold, etc.) can be set.</p><p>The search type search_type in addition to being set to &quot;similarity_score_threshold&quot;, which is &quot;similarity search above the score threshold&quot;, through the setting of search_kwargs={&quot;k&quot;: 3, &quot;score_threshold&quot;: 0.3}, we expect to obtain the three most similar embeddings with a similarity score above 0.3.</p><p>In addition to similarity_score_threshold, search_type also supports similarity and mmr. Below is the interface documentation for as_retriever:</p><pre>def as_retriever(self, **kwargs: Any) -&gt; VectorStoreRetriever:<br>     &quot;&quot;&quot;Return VectorStoreRetriever initialized from this VectorStore.<br>​<br>        Args:<br>            search_type (Optional[str]): Defines the type of search that<br>                the Retriever should perform.<br>                Can be &quot;similarity&quot; (default), &quot;mmr&quot;, or<br>                &quot;similarity_score_threshold&quot;.<br>            search_kwargs (Optional[Dict]): Keyword arguments to pass to the<br>                search function. Can include things like:<br>                    k: Amount of documents to return (Default: 4)<br>                    score_threshold: Minimum relevance threshold<br>                        for similarity_score_threshold<br>                    fetch_k: Amount of documents to pass to MMR algorithm (Default: 20)<br>                    lambda_mult: Diversity of results returned by MMR;<br>                        1 for minimum diversity and 0 for maximum. (Default: 0.5)<br>                    filter: Filter by document metadata<br>​<br>        Returns:<br>            VectorStoreRetriever: Retriever class for VectorStore.<br>     &quot;&quot;&quot;<br><br>retriever = db.as_retriever()<br>print(f&quot;retriever&#39;s default search_type: {retriever.search_type}, default search_kwargs: {retriever.search_kwargs}&quot;)<br>print(f&quot;retriever&#39;s default allowed_search_types: {retriever.allowed_search_types}&quot;)<br></pre><pre>retriever&#39;s default search_type: similarity, default search_kwargs: {}<br>retriever&#39;s default allowed_search_types: (&#39;similarity&#39;, &#39;similarity_score_threshold&#39;, &#39;mmr&#39;)</pre><p>From the above running results, it can be seen that the default search type of Retriever is similarity (search directly by similarity), and currently, only similarity, similarity_score_threshold, and mmr are allowed as search types.</p><pre>results = db.similarity_search_with_score(query, k=5)<br>print(f&quot;similarity_search_with_score returns {len(results)} results.&quot;)<br>print(f&quot;first result:\n {results[0]}&quot;)<br>print(f&quot;last result:\n {results[-1]}&quot;)<br>print(f&quot;all results:&quot;)<br>for doc, sim in results:<br>    print(f&quot;  similarity: {sim}, Document length: {len(doc.page_content)}&quot;)</pre><pre>similarity_search_with_score returns 5 results.<br>first result:<br> (Document(metadata={&#39;origin_url&#39;: &#39;https://medium.com/@sahin.samia/what-is-retrieval-augmented-generation-rag-in-llm-and-how-it-works-a8c79e35a172&#39;, &#39;source&#39;: &#39;articles/RAG/What is Retrieval-Augmented Generation(RAG) in LLM and How it works?.txt&#39;}, page_content=&#39;Benefits of Using RAG in Various Fields: Healthcare: RAG-powered systems can assist medical professionals by pulling in information from medical journals and patient records to suggest diagnoses or treatments that are informed by the latest research. Customer Service: By retrieving company policies and customer histories, RAG allows service agents to offer personalized and accurate advice, improving customer satisfaction. Education: Teachers can leverage RAG-based tools to create custom lesson plans and learning materials that draw from a broad range of educational content, providing students with diverse perspectives. Additional Applications: Legal Aid: RAG systems can aid in legal research by fetching relevant case law and statutes to assist in drafting legal documents or preparing for cases. Translation Services: Combining RAG with translation models to provide context-aware translations that consider cultural nuances and idiomatic expressions by referencing bilingual text corpora. The utilization of RAG in these applications allows for outputs that are not just generated based on a static knowledge base but are dynamically informed by the most relevant and current data available, leading to more precise, informative, and trustworthy AI-generated content.&#39;), 0.6014071106910706)<br>last result:<br> (Document(metadata={&#39;origin_url&#39;: &#39;https://www.analyticsvidhya.com/blog/2024/04/rag-interview-questions/&#39;, &#39;source&#39;: &#39;articles/RAG/Top 20+ RAG Interview Questions.txt&#39;}, page_content=&#39;Q13. What challenges does RAG solve in natural language processing? A. RAG addresses several challenges in natural language processing, including: Context Understanding: RAG’s retrieval component allows it to understand and consider the context of a query, leading to more coherent and meaningful responses than traditional language models. Information Retrieval: By leveraging retrieval-based methods, RAG can efficiently search through large datasets or document corpora to retrieve relevant information, improving the accuracy and relevance of generated responses. Bias and Misinformation: As discussed earlier, RAG can help mitigate bias and misinformation by prioritizing credible sources and validating retrieved information, enhancing the reliability of the generated content. Personalization: RAG can be adapted to personalize responses based on user preferences or historical interactions by retrieving and utilizing relevant information from previous interactions or user profiles.&#39;), 0.707072913646698)<br>all results:<br>  similarity: 0.6014071106910706, Document length: 1278<br>  similarity: 0.6469900608062744, Document length: 974<br>  similarity: 0.6886522173881531, Document length: 887<br>  similarity: 0.6946591734886169, Document length: 758<br>  similarity: 0.707072913646698, Document length: 991</pre><p>Below, introduce the <a href="https://www.kaggle.com/code/marcinrutecki/rag-mmr-search-in-langchain">MMR</a> search type, which stands for Maximal Marginal Relevance. MMR is an algorithm used in fields such as text summarization, information retrieval, and recommendation systems, aiming to select a set of elements (such as documents, sentences, or items) that are not only highly relevant to the query or user interests but also diverse from each other. The MMR algorithm calculates the similarity between candidate elements and the elements in the current set, and selects elements that increase diversity while maintaining relevance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0tCPAlzTdvJoxhiF.png" /></figure><p>Different from similarity and similarity_score_threshold which only consider the relevance of the retrieval results to the user input, mmr also considers the diversity of the results. If there are data chunks in the vector database that are close to the text and all have a high relevance to the user input, there will be a lot of redundancy in the retrieval results. Using MMR will eliminate this redundancy and make the results diverse while relevant.</p><pre>retriever = db.as_retriever(<br>    search_type=&quot;mmr&quot;,<br>    search_kwargs={&quot;k&quot;: 3},<br>)<br>relevant_chunks = retriever.invoke(query)<br>​<br># Display the relevant results with metadata<br>print(&quot;\n--- Relevant Chunks ---&quot;)<br># print(f&quot;type(relevant_chunks) = {type(relevant_chunks)}&quot;)<br>for i, chunk in enumerate(relevant_chunks, 1):<br>    # print(f&quot;type(chunk) = {type(chunk)}&quot;)<br>    print(f&quot;Chunk {i}:\n{chunk.page_content}\n&quot;)<br>    if chunk.metadata:<br>        print(f&quot;Source: {chunk.metadata.get(&#39;source&#39;, &#39;Unknown&#39;)}\nOrigin_url: {chunk.metadata.get(&#39;origin_url&#39;, &#39;Unknown&#39;)}\n&quot;)</pre><pre>--- Relevant Chunks ---<br>Chunk 1:<br>Benefits of Using RAG in Various Fields: Healthcare: RAG-powered systems can assist medical professionals by pulling in information from medical journals and patient records to suggest diagnoses or treatments that are informed by the latest research. Customer Service: By retrieving company policies and customer histories, RAG allows service agents to offer personalized and accurate advice, improving customer satisfaction. Education: Teachers can leverage RAG-based tools to create custom lesson plans and learning materials that draw from a broad range of educational content, providing students with diverse perspectives. Additional Applications: Legal Aid: RAG systems can aid in legal research by fetching relevant case law and statutes to assist in drafting legal documents or preparing for cases. Translation Services: Combining RAG with translation models to provide context-aware translations that consider cultural nuances and idiomatic expressions by referencing bilingual text corpora. The utilization of RAG in these applications allows for outputs that are not just generated based on a static knowledge base but are dynamically informed by the most relevant and current data available, leading to more precise, informative, and trustworthy AI-generated content.<br>​<br>Source: articles/RAG/What is Retrieval-Augmented Generation(RAG) in LLM and How it works?.txt<br>Origin_url: https://medium.com/@sahin.samia/what-is-retrieval-augmented-generation-rag-in-llm-and-how-it-works-a8c79e35a172<br>​<br>Chunk 2:<br>A Complete Guide to RAG url: https://towardsai.net/p/l/a-complete-guide-to-rag<br>​<br>If you haven’t heard about RAG from your refrigerator yet, you surely will very soon, so popular this technique has become. Surprisingly, there is a lack of complete guides that consider all the nuances (like relevance assessment, combating hallucinations, etc. ), instead of just fragmented pieces. Based on our experience, I have compiled a guide that covers this topic thoroughly.<br>​<br>Image by DALL-E 3 So, why do we need RAG?<br>​<br>You could use LLM models like ChatGPT to create horoscopes (which it does quite successfully), or for something more practical (like work). However, there is a problem: companies typically have a multitude of documents, rules, regulations, etc., about which ChatGPT knows nothing, of course.<br>​<br>What can be done?<br>​<br>There are two options: retrain the model with your data or use RAG.<br>​<br>Source: articles/RAG/A Complete Guide to RAG.txt<br>Origin_url: https://towardsai.net/p/l/a-complete-guide-to-rag<br>​<br>Chunk 3:<br>The Fusion of Retrieval-Based and Generative Models RAG is fundamentally a hybrid model that seamlessly integrates two critical components. Retrieval-based methods involve accessing and extracting information from external knowledge sources such as databases, articles, or websites. On the other hand, generative models excel in generating coherent and contextually relevant text. What distinguishes RAG is its ability to harmonize these two components, creating a symbiotic relationship that allows it to comprehend user queries deeply and produce responses that are not just accurate but also contextually rich.<br>​<br>Deconstructing RAG’s Mechanics To grasp the essence of RAG LLM, it’s essential to deconstruct its operational mechanics. RAG operates through a series of well-defined steps.<br>​<br>Source: articles/RAG/What is Retrieval-Augmented Generation (RAG)?.txt<br>Origin_url: https://www.analyticsvidhya.com/blog/2023/09/retrieval-augmented-generation-rag-in-ai/</pre><p>Borrowing the analyze_list_overlap function from <a href="https://www.kaggle.com/code/marcinrutecki/rag-mmr-search-in-langchain">RAG: MMR Search in LangChain</a>, let’s analyze the overlap between the retrieval results of similarity and mmr:</p><pre>def analyze_list_overlap(list1, list2):<br>    &quot;&quot;&quot;<br>    Analyzes the overlap between the content of two lists of documents and prints the counts<br>    of common and unique documents. Includes detailed debugging information.<br>​<br>    Parameters:<br>    list1 (list): First list of document objects, each having a &#39;page_content&#39; attribute.<br>    list2 (list): Second list of document objects, each having a &#39;page_content&#39; attribute.<br>    &quot;&quot;&quot;<br>​<br>    # Remove duplicate documents within each list<br>    unique_list1 = list({doc.page_content: doc for doc in list1}.values())<br>    unique_list2 = list({doc.page_content: doc for doc in list2}.values())<br>​<br>    # Extract sets of document contents<br>    content_set1 = {doc.page_content for doc in unique_list1}<br>    content_set2 = {doc.page_content for doc in unique_list2}<br>​<br>    # Print sets for debugging<br>    print(f&quot;Total unique documents in list 1: {len(unique_list1)}&quot;)<br>    print(f&quot;Total unique documents in list 2: {len(unique_list2)}&quot;)<br>    print(f&quot;Content set 1: {len(content_set1)} unique documents&quot;)<br>    print(f&quot;Content set 2: {len(content_set2)} unique documents&quot;)<br>​<br>    # Determine common and unique contents<br>    common_contents = content_set1.intersection(content_set2)<br>    unique_contents_list1 = content_set1 - content_set2<br>    unique_contents_list2 = content_set2 - content_set1<br>​<br>    # Count the number of common and unique contents<br>    common_count = len(common_contents)<br>    unique_to_list1_count = len(unique_contents_list1)<br>    unique_to_list2_count = len(unique_contents_list2)<br>​<br>    # Print the counts for clarity<br>    print(f&quot;Common documents: {common_count}&quot;)<br>    print(f&quot;Unique to list 1: {unique_to_list1_count}&quot;)<br>    print(f&quot;Unique to list 2: {unique_to_list2_count}&quot;)</pre><pre>retriever = db.as_retriever(<br>    search_type=&quot;mmr&quot;,<br>    search_kwargs={&quot;k&quot;: 5},<br>)<br>relevant_chunks_mmr = retriever.invoke(query)<br>​<br>retriever = db.as_retriever(<br>    search_type=&quot;similarity&quot;,<br>    search_kwargs={&quot;k&quot;: 5},<br>)<br>relevant_chunks_similarity = retriever.invoke(query)<br>​<br>analyze_list_overlap(relevant_chunks_similarity, relevant_chunks_mmr)</pre><pre>Total unique documents in list 1: 5<br>Total unique documents in list 2: 5<br>Content set 1: 5 unique documents<br>Content set 2: 5 unique documents<br>Common documents: 2<br>Unique to list 1: 3<br>Unique to list 2: 3</pre><p>The analysis shows that there are 5 relevant chunks obtained by similarity and mmr methods, among which only 2 have the same content, and the other 3 are different, reflecting the difference between MMR retrieval results and simple similarity searches.</p><h3>MultiQueryRetriever</h3><p><a href="https://python.langchain.com/v0.2/docs/how_to/MultiQueryRetriever/">MultiQueryRetriever</a> is a new type of retriever developed by LangChain. In natural language processing, we often encounter a problem: directly searching by the queried text may not yield good results, due to the accuracy of the wording in the query text, which can lead to differences in retrieval results.</p><p>At this time, MultiQueryRetriever comes into play. Its working principle is to use a large language model (LLM) to refine and abstract the user’s input query from different perspectives, generating several similar query texts, and then taking all the unique union of the query results to form a larger, potentially relevant document set.</p><p>Through this multi-angle query method, MultiQueryRetriever can effectively solve the problem of the original query text being not accurately described, providing us with a richer and more in-depth set of retrieval results.</p><pre>from langchain.retrievers.multi_query import MultiQueryRetriever<br>from langchain_openai import ChatOpenAI<br>​<br>llm = ChatOpenAI(temperature=0)<br>retriever_multi_query = MultiQueryRetriever.from_llm(<br>    retriever=db.as_retriever(),<br>    llm=llm<br>)<br>​<br># Set logging for the queries<br>import logging<br>​<br>logging.basicConfig()<br>logging.getLogger(&quot;langchain.retrievers.multi_query&quot;).setLevel(logging.INFO)<br>​<br>relevant_chunks = retriever_multi_query.invoke(query)<br>len(relevant_chunks)</pre><pre>INFO:langchain.retrievers.multi_query:Generated queries: [&#39;1. Can you explain the concept of RAG and its significance?&#39;, &#39;2. What are the reasons for utilizing RAG and how does it function?&#39;, &#39;3. Why is RAG important and what are the mechanics behind its operation?&#39;]<br>​<br>6</pre><p>It can be seen that MultiQueryRetriever breaks down the original query into 3 related questions and then obtains 6 different chunks in total.</p><p>To avoid the LLM-generated related questions from being inaccurate, we can set include_original=True to include the original question, so as not to miss out on possible information:</p><pre>retriever_multi_query = MultiQueryRetriever.from_llm(<br>    retriever=db.as_retriever(),<br>    llm=llm, include_original=True<br>)<br>relevant_chunks = retriever_multi_query.invoke(query)<br>len(relevant_chunks)</pre><pre>INFO:langchain.retrievers.multi_query:Generated queries: [&#39;1. What is the purpose of RAG and why is it important?&#39;, &#39;2. Can you explain the concept of RAG and its significance?&#39;, &#39;3. How does RAG function and what are its benefits?&#39;]<br>​<br>7</pre><h3>Generation: Conversation Generation</h3><h4>One off: One Round of Conversation</h4><p>Integrating the different stages of RAG and technologies discussed above, we can achieve a complete RAG conversation:</p><pre>import os<br>from dotenv import load_dotenv<br>from langchain_community.vectorstores import Chroma<br>from langchain_core.messages import HumanMessage, SystemMessage<br>from langchain.retrievers.multi_query import MultiQueryRetriever<br>from langchain_openai import ChatOpenAI<br>​<br>load_dotenv()<br>​<br># vector store<br>cur_dir = os.getcwd()<br>vdb_dir = os.path.join(cur_dir, &#39;db&#39;, &#39;chroma_db&#39;)<br>rag_vdb_dir = os.path.join(vdb_dir, &#39;rag_articles&#39;)<br>​<br>if not os.path.exists(rag_vdb_dir):<br>    db = Chroma.from_documents(<br>        chunks, embeddings_model, persist_directory=rag_vdb_dir<br>    )<br>else:<br>    print(&quot;Vector store already exists for rag topic. No need to initialize.&quot;)<br>​<br>embeddings_model = OpenAIEmbeddings(model=&quot;text-embedding-3-small&quot;)<br>db = Chroma(persist_directory=rag_vdb_dir, embedding_function=embeddings_model)<br>​<br># Retriever<br>query = &quot;what is RAG? why do we need RAG? how does it work?&quot;<br>llm = ChatOpenAI(temperature=0)<br>retriever_multi_query = MultiQueryRetriever.from_llm(<br>    retriever=db.as_retriever(<br>        search_type=&quot;mmr&quot;,search_kwargs={&quot;k&quot;: 5}<br>    ), llm=llm<br>)<br>relevant_chunks = retriever_multi_query.invoke(query)<br>​<br>​<br># Generation<br>combined_input = (<br>    &quot;Here is some context and source url that might help answer the question: &quot;<br>    + query<br>    + &quot;\n\nRelevant context(which starts with ### and ends with ###) and source url:\n&quot;<br>    + &quot;\n\n&quot;.join([f&quot;source_url:{chunk.metadata[&#39;origin_url&#39;]}\ncontent:###\n{chunk.page_content}\n###&quot; for chunk in relevant_chunks])<br>    + &quot;\n\nPlease provide an answer based only on the provided context. If the answer is not found in it, respond with &#39;I&#39;m not sure&#39;.&quot;<br>    + &quot; When providing an answer, include citations from the provided context to increase credibility.&quot;<br>    + &quot;\n\nAfter the answer, give three relative questions attractive to the user and output one by one in the format &#39;Relative question {#no}: {relative question}&#39;.&quot;<br>)<br>​<br>​<br># Create a ChatOpenAI model<br>model = ChatOpenAI(model=&quot;gpt-4o&quot;)<br>​<br># Define the messages for the model<br>messages = [<br>    SystemMessage(content=&quot;You are a helpful assistant.&quot;),<br>    HumanMessage(content=combined_input),<br>]<br>​<br># Invoke the model with the combined input<br>result = model.invoke(messages)<br>​<br># Display the full result and content only<br>print(&quot;\n--- User Request ---&quot;)<br>print(query)<br>print(&quot;\n--- Generated Response ---&quot;)<br>print(result.content)</pre><pre>Vector store already exists for rag topic. No need to initialize.</pre><pre>INFO:langchain.retrievers.multi_query:Generated queries: [&#39;1. Can you explain the concept of RAG and its significance?&#39;, &#39;2. What are the reasons for utilizing RAG and how does it function?&#39;, &#39;3. Why is RAG important and what are the mechanics behind its operation?&#39;]<br>​<br>--- User Request ---<br>what is RAG? why do we need RAG? how does it work?<br>​<br>--- Generated Response ---<br>### What is RAG?<br>​<br>RAG, or Retrieval-Augmented Generation, is a hybrid model that integrates retrieval-based methods with generative models. Retrieval-based methods involve accessing and extracting information from external knowledge sources such as databases, articles, or websites. Generative models, on the other hand, excel in generating coherent and contextually relevant text. RAG harmonizes these two components to deeply comprehend user queries and produce responses that are accurate and contextually rich (source_url: https://www.analyticsvidhya.com/blog/2023/09/retrieval-augmented-generation-rag-in-ai/).<br>​<br>### Why do we need RAG?<br>​<br>RAG is necessary because traditional language models like ChatGPT do not inherently have access to specific or updated knowledge within a company&#39;s documents, rules, regulations, or the latest information from external sources. To address this, RAG can be used instead of retraining the model with new data, which allows for more dynamic and current information retrieval and generation (source_url: https://towardsai.net/p/l/a-complete-guide-to-rag). Additionally, RAG systems can ensure the retrieved information is up-to-date by regularly updating their databases or document corpora with the latest information from reputable sources (source_url: https://www.analyticsvidhya.com/blog/2024/04/rag-interview-questions/).<br>​<br>### How does RAG work?<br>​<br>RAG operates through a series of well-defined steps by combining retrieval-based methods and generative models. This integration allows RAG to access relevant external information and generate responses that are not just based on a static knowledge base but are dynamically informed by the most current and relevant data available. This results in more precise, informative, and trustworthy AI-generated content (source_url: https://www.analyticsvidhya.com/blog/2023/09/retrieval-augmented-generation-rag-in-ai/). One particular advantage of RAG is that it permits continuous updates and revisions of its data sources, unlike traditional fine-tuning, which embeds data into the model’s architecture (source_url: https://www.superannotate.com/blog/rag-explained).<br>​<br>Relative question 1: How can RAG improve customer service interactions?<br>​<br>Relative question 2: What are the ethical considerations in using RAG?<br>​<br>Relative question 3: Can you explain the differences between RAG and traditional fine-tuning?</pre><p>The above example integrates Chroma vector storage, MultiQuery + MMR retrieval, and answer generation with citations and related questions, thus running through a complete RAG.</p><h4>Multi-Turn: Multi-Round Conversation</h4><p>The above example only involves one round of conversation, and in reality, we often have multi-round conversations with AI on a topic, which involves how to add <a href="https://python.langchain.com/v0.2/docs/how_to/qa_chat_history_how_to/">chat history</a>:</p><pre>from langchain.chains import create_history_aware_retriever, create_retrieval_chain<br>from langchain.chains.combine_documents import create_stuff_documents_chain<br>from langchain_core.prompts import MessagesPlaceholder<br>​<br># Create a ChatOpenAI model<br>llm = ChatOpenAI(model=&quot;gpt-4o&quot;)<br>​<br># Contextualize question prompt<br># This system prompt helps the AI understand that it should reformulate the question<br># based on the chat history to make it a standalone question<br>contextualize_q_system_prompt = (<br>    &quot;Given a chat history and the latest user question &quot;<br>    &quot;which might reference context in the chat history, &quot;<br>    &quot;formulate a standalone question which can be understood &quot;<br>    &quot;without the chat history. Do NOT answer the question, just &quot;<br>    &quot;reformulate it if needed and otherwise return it as is.&quot;<br>)<br>​<br># Create a prompt template for contextualizing questions<br>contextualize_q_prompt = ChatPromptTemplate.from_messages(<br>    [<br>        (&quot;system&quot;, contextualize_q_system_prompt),<br>        MessagesPlaceholder(&quot;chat_history&quot;),<br>        (&quot;human&quot;, &quot;{input}&quot;),<br>    ]<br>)<br>​<br># Create a history-aware retriever<br># This uses the LLM to help reformulate the question based on chat history<br>history_aware_retriever = create_history_aware_retriever(<br>    llm, retriever_multi_query, contextualize_q_prompt<br>)<br>​<br># Answer question prompt<br># This system prompt helps the AI understand that it should provide concise answers<br># based on the retrieved context and indicates what to do if the answer is unknown<br>qa_system_prompt = (<br>    &quot;You are an assistant for question-answering tasks. Use &quot;<br>    &quot;the following pieces of retrieved context to answer the &quot;<br>    &quot;question. If you don&#39;t know the answer, just say that you &quot;<br>    &quot;don&#39;t know. Use three sentences maximum and keep the answer &quot;<br>    &quot;concise.&quot;<br>    &quot;\n\n&quot;<br>    &quot;{context}&quot;<br>    &quot;When providing an answer, include citations(source url if possible) &quot;<br>    &quot;from the provided context to increase credibility.&quot;<br>    &quot;After the answer, give three relative questions attractive to the user &quot;<br>    &quot;and output one by one in the format &#39;Relative question #no: relative-question&#39;.&quot;<br>)<br>​<br># Create a prompt template for answering questions<br>qa_prompt = ChatPromptTemplate.from_messages(<br>    [<br>        (&quot;system&quot;, qa_system_prompt),<br>        MessagesPlaceholder(&quot;chat_history&quot;),<br>        (&quot;human&quot;, &quot;{input}&quot;),<br>    ]<br>)<br>​<br># Create a chain to combine documents for question answering<br># `create_stuff_documents_chain` feeds all retrieved context into the LLM<br>question_answer_chain = create_stuff_documents_chain(llm, qa_prompt)<br>​<br># Create a retrieval chain that combines the history-aware retriever and the question answering chain<br>rag_chain = create_retrieval_chain(history_aware_retriever, question_answer_chain)<br>​<br>​<br># Function to simulate a continual chat<br>def continual_chat():<br>    print(&quot;Start chatting with the AI! Type &#39;exit&#39; to end the conversation.&quot;)<br>    chat_history = []  # Collect chat history here (a sequence of messages)<br>    while True:<br>        query = input(&quot;You: &quot;)<br>        if query.lower() == &quot;exit&quot;:<br>            break<br>        # Process the user&#39;s query through the retrieval chain<br>        result = rag_chain.invoke({&quot;input&quot;: query, &quot;chat_history&quot;: chat_history})<br>        # Display the AI&#39;s response<br>        print(f&quot;AI: {result[&#39;answer&#39;]}&quot;)<br>        print(f&quot;{&#39;-&#39; * 100}\n&quot;)<br>        # Update the chat history<br>        chat_history.append(HumanMessage(content=query))<br>        chat_history.append(SystemMessage(content=result[&quot;answer&quot;]))<br>​<br>continual_chat()</pre><pre>Start chatting with the AI! Type &#39;exit&#39; to end the conversation.<br>You: What is RAG?<br>INFO:langchain.retrievers.multi_query:Generated queries: [&#39;1. Can you provide information on RAG?&#39;, &#39;2. What does RAG stand for?&#39;, &#39;3. Could you explain the concept of RAG?&#39;]<br>AI: RAG (Retrieval-Augmented Generation) is a hybrid AI model that combines retrieval-based methods with generative models. It accesses and extracts information from external knowledge sources like databases and articles, then generates contextually relevant and coherent text based on the retrieved information. This enables RAG to produce accurate, informative, and contextually rich responses.<br>​<br>Relative question #1: How does RAG ensure the information it retrieves is up-to-date?<br>Relative question #2: What types of data can RAG utilize?<br>Relative question #3: What are some ethical considerations when using RAG systems?<br><br>----------------------------------------------------------------------------------------------------<br>You: What types of data can RAG utilize?<br>INFO:langchain.retrievers.multi_query:Generated queries: [&#39;1. How does Retrieval-Augmented Generation (RAG) make use of different types of data?&#39;, &#39;2. In what ways can Retrieval-Augmented Generation (RAG) leverage various data types?&#39;, &#39;3. What are the different kinds of data that Retrieval-Augmented Generation (RAG) can utilize effectively?&#39;]<br>AI: RAG can utilize a diverse range of data sources, including structured data from databases, unstructured text from documents and articles, and potentially even data from other modalities like images and videos. This versatility allows RAG to retrieve and integrate information from various external knowledge sources to enhance the accuracy and relevance of its generated responses.<br>​<br>Relative question #1: How does RAG ensure the information it retrieves is up-to-date?<br>Relative question #2: What are some ethical considerations when using RAG systems?<br>Relative question #3: How does RAG differ from traditional language models?<br><br>----------------------------------------------------------------------------------------------------<br>You: How does RAG ensure the information it retrieves is up-to-date?<br>INFO:langchain.retrievers.multi_query:Generated queries: [&#39;1. What methods does Retrieval-Augmented Generation (RAG) use to verify the freshness of the information it retrieves?&#39;, &#39;2. How does Retrieval-Augmented Generation (RAG) maintain the currency of the retrieved information?&#39;, &#39;3. In what ways does Retrieval-Augmented Generation (RAG) ensure that the information it retrieves is current and relevant?&#39;]<br>AI: RAG ensures the information it retrieves is up-to-date by regularly updating its external data sources, either through automated processes or periodic batch updates. Developers can configure the retrieval component to prioritize recent publications or updates, and implement continuous monitoring and updating mechanisms to refresh the data sources. This approach helps maintain the relevance and accuracy of the responses generated by the system ([source](https://www.k2view.com/what-is-retrieval-augmented-generation)).<br>​<br>Relative question #1: What are some ethical considerations when using RAG systems?<br>Relative question #2: How does RAG differ from traditional language models?<br>Relative question #3: What are the key advantages of using RAG in customer service applications?<br><br>----------------------------------------------------------------------------------------------------<br>You: exit</pre><p>The entire process includes:</p><ul><li>Using create_history_aware_retriever to construct a Retriever that is aware of the conversation history. It uses LLM to combine the conversation history and the current question to produce a more appropriate query for retrieving the vector database.</li><li>Using create_stuff_documents_chain to create a document-based QA chain.</li><li>Using create_retrieval_chain to combine create_history_aware_retriever and create_stuff_documents_chain, achieving a complete RAG based on chat history.</li></ul><h3>Summary</h3><p>In this article, we have learned what RAG is and how to implement RAG using LangChain. It can be appreciated that LangChain provides components such as Embedding, Vector Store, Splitter, Retriever, and Generation, making it easy to implement RAG.</p><p>RAG is a rich and evolving technology, and there are many topics that have not been discussed here, including:</p><ul><li>Reranker</li><li>Graph RAG</li><li>Multimodal RAG</li><li>…</li></ul><p>Worth further exploration!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dd639d0576f6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vibe Coding: A Practical Guide to Building LLM Analytics Tools Through Conversation]]></title>
            <link>https://medium.com/@ai-data-drive/vibe-coding-a-practical-guide-to-building-llm-analytics-tools-through-conversation-1914f0fed1d9?source=rss-5140c0782d6f------2</link>
            <guid isPermaLink="false">https://medium.com/p/1914f0fed1d9</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[vibe-coding]]></category>
            <dc:creator><![CDATA[Andy Yang]]></dc:creator>
            <pubDate>Mon, 24 Mar 2025 12:34:47 GMT</pubDate>
            <atom:updated>2025-03-24T12:34:47.235Z</atom:updated>
            <content:encoded><![CDATA[<h3>What is Vibe Coding?</h3><p>Vibe coding is a revolutionary approach to software development that’s transforming how we build applications. Instead of writing code line by line, vibe coding allows you to describe what you want to build in natural language, and AI tools generate the code for you.</p><p>As defined by Andrej Karpathy (who coined the term in February 2025), vibe coding is when you “fully give in to the vibes, embrace exponentials, and forget that the code even exists.” It represents a fundamental shift in the development process — from manual coding to guiding AI through the creation process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nvNKJU7FhMnSwGf8hH43cw.jpeg" /></figure><h3>Why Vibe Coding Matters</h3><p>Vibe coding democratizes software development. You no longer need years of programming experience to build functional applications. Whether you’re a seasoned developer looking to accelerate your workflow or a complete novice with an idea, vibe coding makes software creation accessible to everyone.</p><p>Key benefits include:</p><ul><li><strong>Speed</strong>: Build applications in hours instead of weeks</li><li><strong>Accessibility</strong>: Create software without specialized technical knowledge</li><li><strong>Iteration</strong>: Test and refine ideas quickly</li><li><strong>Focus on outcomes</strong>: Concentrate on what you want to achieve rather than implementation details</li></ul><h3>The Vibe Coding Methodology</h3><p>Before diving into my specific experience, let’s outline the general approach to vibe coding that anyone can follow:</p><h3>1. Define Your Project Goal</h3><p>Start with a clear vision of what you want to build. Focus on outcomes rather than technical implementation.</p><h3>2. Choose Your AI Coding Assistant</h3><p>Select from tools like Cursor AI, Repl.it, WindSurf, Lovable, Bolt.new or some others based on your needs.</p><h3>3. Describe Your Requirements in Natural Language</h3><p>Communicate what you want to build using everyday language, not technical specifications.</p><h3>4. Guide, Don’t Code</h3><p>Act as a project manager rather than a programmer — describe what isn’t working, ask questions about implementation options, and direct the AI through conversation, not by editing code yourself.</p><h3>5. Test Against Real-World Scenarios</h3><p>Run the generated code with actual data and check if it handles edge cases. When issues arise, describe the problem to the AI rather than debugging yourself.</p><h3>6. Build in Layers</h3><p>Start with a minimal viable product, then gradually add sophistication — ask for one complete feature at a time rather than trying to perfect everything at once.</p><h3>7. Deploy and Maintain</h3><p>Set up automated processes for running, updating, and backing up your application.</p><h3>Vibe Coding Hands-on: Building an LLM Analytics Platform</h3><p>Now let’s look at a real example of vibe coding in action. I’ll share my experience building an LLM analytics platform through conversation with Cursor AI, with no manual coding required.</p><h3>Initial Goal</h3><p>My goal was to build a comprehensive LLM analytics website by web scraping data from Ollama. The project would collect model information (names, descriptions, pull counts, and parameters) and transform this raw data into meaningful visualizations and insights about the open-source LLM ecosystem.</p><p>It looks like as following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Qd6R8iyQcZAjvB1m.png" /></figure><h3>Iteration 1: From Analytics Concept to Data Collection</h3><p>In our initial conversation, I described my analytics vision: “<strong>I want to scrape the open source LLMs’ usage info from ollama website…to get model name, introduction, pulls, parameters and save the infos into a csv file.</strong>”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_l2NztY6A6EzMeQs.png" /></figure><p>The AI immediately understood this was about more than just scraping — it was about building the foundation for analytics — and generated a complete Python script with:</p><ul><li>Request handling to fetch the webpage</li><li>BeautifulSoup for HTML parsing</li><li>Functions to extract each required field</li><li>CSV output formatting for further analysis</li><li>…</li></ul><p>When I pointed out that “BeautifulSoup is never used in the python code. why?”, the AI explained it had incorrectly assumed an API endpoint and quickly pivoted to a proper web scraping approach, showing how vibe coding allows for real-time clarification and correction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5kx6zbhvHSFFH-Jd.png" /></figure><h3>Iteration 2: Tackling HTML Structure Challenges</h3><p>After testing, I discovered the HTML selectors weren’t working with the actual webpage structure. Instead of debugging the code myself, I simply shared a snippet of the actual HTML:</p><pre>html<br>​<br>Copy<br>​<br>&lt;ul role=&quot;list&quot; class=&quot;grid grid-cols-1&quot;&gt;<br>    &lt;li x-test-model=&quot;&quot; class=&quot;flex items-baseline border-b border-neutral-200 py-6&quot;&gt;<br>      &lt;!-- More HTML structure --&gt;<br>      &lt;span x-test-search-response-title=&quot;&quot;&gt;llama3.3&lt;/span&gt;<br>      &lt;!-- Description, tags, etc. --&gt;<br>      &lt;span x-test-pull-count=&quot;&quot;&gt;322.9K&lt;/span&gt;<br>    &lt;/li&gt;<br>&lt;/ul&gt;</pre><p>I told the AI: “you can use this info to fix the extracting process.” The AI immediately understood the site’s structure and updated the code accordingly — no HTML/CSS knowledge required on my part.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JmGdfy2AJohsmV2F.png" /></figure><h3>Iteration 3: Adding Intelligence with Data Categorization</h3><p>To enable deeper analytics, I needed more structured data. I asked to “add a model_family field which extracts from the model_name field” and to “add a fetch_date field with ‘yyyymmdd’ format to keep tracking history.”</p><p>The AI implemented both features, even creating a sophisticated regex-based function to extract model families like “llama” from names like “llama3.3” by:</p><ul><li>Finding version numbers in model names</li><li>Getting the part before version numbers</li><li>Cleaning up non-alphabetic characters</li></ul><p>This categorization was critical for my analytics goals, allowing me to analyze trends by model family rather than just individual models, and the time dimension enabled trend analysis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_ez4352pD1p1-kKY.png" /></figure><h3>Iteration 4: Building Interactive Analytics Dashboards</h3><p>The core of my project was visualization and analytics. When I asked to “visualize the top 10 model and top 10 model_family using steamlite with the saved csv data,” the AI:</p><ol><li>Generated a complete Streamlit dashboard with interactive charts</li><li>Created visualizations for both individual models and model families</li><li>Added statistical summaries showing total pulls, average pulls, and other metrics</li><li>Implemented proper data formatting and styling for clarity</li></ol><p>The analytics dashboard made insights immediately accessible. To enhance interactivity, I requested a “slider to change the N of Top N, to give user more interaction with the data viz.” The AI implemented this feature, allowing users to dynamically adjust the analysis scope from 10 to 50 top models in increments of 5.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*il2joAS1uXcScTvW.png" /></figure><h3>Iteration 5: Enabling Trend Analytics</h3><p>For true analytics value, I needed to track changes over time. I requested to “save_to_csv: not just write the latest fetch_date’s data, use a update logic which save the fetch history.” The AI transformed the platform into a trend analytics system that:</p><ol><li>Preserves data from all previous runs</li><li>Updates only the current date’s data</li><li>Maintains a chronological record of changes</li><li>Creates visualizations showing trends over time</li></ol><p>I then asked to “provide a slider along the fetch_date, enabling users to see the history,” and the AI implemented a time-slider interface showing how model popularity changed over time — turning static data into dynamic trend analysis.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SFywx2zINV_QL9Ki.png" /></figure><h3>Iteration 6: Production Analytics Platform Features</h3><p>In the final key iterations, I asked to add features that would make this a production-ready analytics platform:</p><ol><li><strong>Automated data collection</strong>: “Add a daily fetch crontab to get the latest data.” The AI created a shell script with proper environment handling and scheduling.</li><li><strong>Data backup</strong>: “Add function to sync the ollama_models.csv to my icloud’s data folder.” The AI added cloud backup to ensure data persistence.</li><li><strong>Scheduled updates</strong>: “How to change the crontab to let the script run hourly?” The AI provided the exact crontab syntax for more frequent data collection.</li></ol><h3>The Transformation</h3><p>What began as a concept for LLM analytics evolved into a full-featured analytics platform with:</p><ul><li>Automated data collection</li><li>Historical trend analysis</li><li>Interactive visualizations</li><li>Cloud backup</li><li>Sophisticated data categorization</li><li>Statistical summaries</li></ul><p>All of this was accomplished through natural conversation with an AI assistant — no coding required on my part. I simply described the analytics capabilities I wanted at each step, and the AI handled the implementation details, allowing me to focus on the insights rather than the technical implementation.</p><h3>Tips for Effective Vibe Coding</h3><ol><li><strong>Be specific</strong>: The more detailed your description, the better the AI can match your intention</li><li><strong>Think in outcomes</strong>: Focus on what you want to achieve, not how to code it</li><li><strong>Iterate incrementally</strong>: Start simple and add complexity in steps</li><li><strong>Provide feedback</strong>: Tell the AI when something isn’t working as expected so it can fix issues</li><li><strong>Test frequently</strong>: Run the code after each significant change to catch issues early</li><li><strong>Version control</strong>: Use git commits to track meaningful improvements and changes</li></ol><h3>The Future of Vibe Coding</h3><p>Vibe coding is still evolving, but it’s already changing how we approach software development. As AI models improve, we can expect:</p><ul><li>More complex applications built entirely through natural language</li><li>Better understanding of requirements and context</li><li>Lower barriers to entry for software development</li><li>New workflows that blend human creativity with AI implementation</li></ul><h3>Getting Started with Vibe Coding</h3><p>Ready to try vibe coding yourself? Here’s how to begin:</p><ol><li><strong>Choose a simple project</strong>: Start with something small and well-defined</li><li><strong>Select an AI coding assistant</strong>: Pick a tool that supports natural language code generation</li><li><strong>Describe your project</strong>: Be clear and detailed about what you want to build</li><li><strong>Iterate and refine</strong>: Work with the AI to improve the implementation</li><li><strong>Learn and expand</strong>: Use each project to build your vibe coding skills</li></ol><h3>Conclusion</h3><p>Vibe coding represents a paradigm shift in software development — from writing every line of code to describing functionality and guiding AI implementation. While it may not replace traditional coding for all use cases, it offers an exciting new approach that makes software development more accessible and efficient.</p><p>By embracing vibe coding, you can transform your ideas into working software faster than ever before, regardless of your technical background. The future of programming is increasingly conversational, and the most powerful programming language might just be the one you’re already fluent in: natural language.</p><p>So give vibe coding a try — describe your idea, guide the AI, and watch your vision come to life without writing a single line of code yourself.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1914f0fed1d9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[AI Protocol] MCP: The Perfect Bridge Between AI and Local Resources]]></title>
            <link>https://medium.com/@ai-data-drive/ai-protocol-mcp-the-perfect-bridge-between-ai-and-local-resources-26055f59cde5?source=rss-5140c0782d6f------2</link>
            <guid isPermaLink="false">https://medium.com/p/26055f59cde5</guid>
            <category><![CDATA[agents]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[tools]]></category>
            <dc:creator><![CDATA[Andy Yang]]></dc:creator>
            <pubDate>Wed, 19 Mar 2025 23:34:09 GMT</pubDate>
            <atom:updated>2025-03-19T23:34:09.799Z</atom:updated>
            <content:encoded><![CDATA[<h3>0. Preface</h3><p>I’ve recently noticed that AI-related protocols are quietly emerging. Today, I’d like to introduce the Model Context Protocol (MCP) proposed by Claude AI.</p><p>As AI technology continues to develop, more and more applications are beginning to interact with local resources (such as databases, file systems, etc.). However, such interactions need to ensure data security and control, and MCP was born for this purpose. Let’s understand how MCP works and how it helps AI applications better connect with local services.</p><h3>1. Why: Why Do We Need MCP?</h3><p>With the development of artificial intelligence technology, AI applications are now able to provide increasingly complex functions. For example, AI tools like Claude can help us quickly analyze data, generate text content, and even automate daily tasks. But to maximize the potential of these AI tools, they need to interact safely and efficiently with local services (such as databases, file systems, etc.).</p><p>However, traditional connection methods may bring some security risks. For instance, we might worry: if AI applications directly access data stored locally, will sensitive information be leaked? Or, how can we ensure that AI programs only operate within authorized boundaries and don’t overstep?</p><p>This is where MCP (Model Context Protocol) comes into play. MCP is an open protocol that establishes secure, controlled connections between AI applications and local services, ensuring that data and operations are conducted in a secure environment.</p><h3>2. What: What Exactly is MCP?</h3><p>MCP (Model Context Protocol) is a standardized communication protocol that allows for secure data interaction between AI applications and local or remote resources. Its design philosophy is to provide a lightweight, flexible connection method through a client-server architecture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RZXyUTz79JBonywfXucFvA.png" /></figure><p>In the MCP architecture, there are the following important roles:</p><ul><li>MCP Host: Host applications such as Claude Desktop, IDEs, or AI tools that want to access resources via MCP.</li><li>MCP Client: These protocol clients maintain one-to-one connections with MCP servers.</li><li>MCP Server: Lightweight programs that expose specific functionalities through the MCP protocol, accessing local or remote resources.</li><li>Local Resources: Such as databases, files, or services that MCP servers can securely access.</li></ul><p>MCP’s goal is to ensure that AI applications can only access local resources through authorized interfaces, thereby safeguarding data privacy and security through a clear protocol.</p><h3>3. How: How Does MCP Work?</h3><p>MCP implements data interaction through a client-server architecture. Simply put, the host application connects to one or more local services (servers) through the MCP protocol and securely performs queries and operations.</p><p>Here’s how MCP works:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4d8lzLeBcqmAXQKQ_7urbw.png" /></figure><ul><li>Connection Establishment: When you start an application like Claude Desktop, it automatically discovers and connects to configured MCP servers.</li><li>Protocol Handshake: When a user makes a request (for example, requesting to query data from a database), the application negotiates with the server through the MCP protocol to ensure that the server has the capability to fulfill the request.</li><li>Data Query and Response: Through the MCP protocol, the application can query local or remote resources, obtaining data that has gone through strict security controls or executing corresponding operations.</li><li>Most importantly, MCP guarantees that only authorized operations can be executed. For example, Claude Desktop can only access and query a database through interfaces defined by the protocol and cannot directly access unauthorized data in the database. This way, users have complete control over the operational permissions and data access permissions of AI applications.</li></ul><h3>4. Example: Connecting to a Local SQLite Database via MCP</h3><p>To better understand how MCP works, we can look at a specific example: using MCP to connect to a local SQLite database in Claude Desktop. Here are the operational steps and related code to give you a direct sense of how MCP interacts with local services.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*URWa-rrAtHLaZWGeN_DCNw.png" /></figure><h3>Step 1: Create an SQLite Database</h3><p>First, we need to create an SQLite database locally and populate it with some data. We can use the following command-line code to create an SQLite database named test.db and create a products table in it, inserting some product information.</p><pre># Create a new SQLite database<br>sqlite3 ~/test.db &lt;&lt;EOF<br>CREATE TABLE products (<br>    id INTEGER PRIMARY KEY,<br>    name TEXT,<br>    price REAL<br>);<br>INSERT INTO products (name, price) VALUES<br> (&#39;Widget&#39;, 19.99),<br> (&#39;Gadget&#39;, 29.99),<br> (&#39;Gizmo&#39;, 39.99),<br> (&#39;Smart Watch&#39;, 199.99),<br> (&#39;Wireless Earbuds&#39;, 89.99),<br> (&#39;Portable Charger&#39;, 24.99),<br> (&#39;Bluetooth Speaker&#39;, 79.99),<br> (&#39;Phone Stand&#39;, 15.99),<br> (&#39;Laptop Sleeve&#39;, 34.99),<br> (&#39;Mini Drone&#39;, 299.99),<br> (&#39;LED Desk Lamp&#39;, 45.99),<br> (&#39;Keyboard&#39;, 129.99),<br> (&#39;Mouse Pad&#39;, 12.99),<br> (&#39;USB Hub&#39;, 49.99),<br> (&#39;Webcam&#39;, 69.99),<br> (&#39;Screen Protector&#39;, 9.99),<br> (&#39;Travel Adapter&#39;, 27.99),<br> (&#39;Gaming Headset&#39;, 159.99),<br> (&#39;Fitness Tracker&#39;, 119.99),<br> (&#39;Portable SSD&#39;, 179.99);</pre><h3>Step 2: Configure Claude Desktop to Connect to MCP</h3><p>Next, we configure MCP in Claude Desktop, telling it to connect to the local SQLite database. We need to edit Claude Desktop’s configuration file, adding the configuration information for the SQLite database server.</p><p>Open Claude Desktop’s configuration file:</p><pre>code ~/Library/Application\\ Support/Claude/claude_desktop_config.json</pre><p>Add the MCP server configuration to the file, replacing YOUR_USERNAME with your actual username:</p><pre>{<br>  &quot;mcpServers&quot;: {<br>    &quot;sqlite&quot;: {<br>      &quot;command&quot;: &quot;uvx&quot;,<br>      &quot;args&quot;: [&quot;mcp-server-sqlite&quot;, &quot;--db-path&quot;, &quot;/Users/YOUR_USERNAME/test.db&quot;]<br>    }<br>  }<br>}</pre><p>Save the configuration file and restart Claude Desktop.</p><h3>Step 3: Interact with the MCP Server</h3><p>Now, Claude Desktop is configured and ready to interact with the local SQLite database. Next, you can enter the following request in Claude Desktop to query data from the local database:</p><pre>Can you connect to my SQLite database and tell me what products are available, and their prices?</pre><p>Claude Desktop will automatically establish a connection with the SQLite server through the MCP protocol, execute SQL queries, and return a list of all products and their prices. For example, you might see a return result like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Bvtzf3iNZ8147g27.png" /></figure><p>Through this example, we can see how MCP works in a local environment, ensuring that Claude Desktop can perform controlled operations with the database through a secure protocol when interacting with the database.</p><h3>Step 4: Add More Complex Queries</h3><p>Once the basic configuration is complete, you can also have Claude Desktop execute more complex query operations. For example, you can ask Claude Desktop to query all products priced above $50:</p><pre>Can you tell me which products are priced above $50?</pre><p>Claude Desktop will send a query request to the SQLite database through the MCP protocol and return the results that meet the conditions.</p><pre>Here are the products priced above $50:<br>1. Smart Watch - $199.99<br>2. Wireless Earbuds - $89.99<br>3. Bluetooth Speaker - $79.99<br>4. Portable SSD - $179.99<br>5. Gaming Headset - $159.99</pre><p>Through this operation, you can see that MCP remains efficient and secure even when executing more complex data queries.</p><h3>MCP vs Function Calling</h3><p>The Model Context Protocol (MCP) developed by Anthropic and OpenAI’s Function Calling feature represent two innovative approaches to enhancing the interaction capabilities of large models. Below is a detailed comparison of their functionality, application scenarios, and underlying architecture.</p><h3>Overview</h3><ul><li><strong>MCP</strong>. MCP is an open standard designed to facilitate secure bidirectional connections between AI systems and various data sources. Its goal is to integrate AI with existing data infrastructure (such as content repositories and business tools) by providing a universal protocol, thereby eliminating information silos.</li><li><strong>Function Calling</strong>. Function calling allows OpenAI’s models to dynamically call specific functions based on the context of user prompts. This feature enables models to independently execute operations or obtain data, making them more interactive and efficient.</li></ul><h3>Key Components</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UMeJ0hla_JH7HomxFmj-jg.png" /></figure><h3>Functionality</h3><p><strong>MCP Features</strong></p><ul><li>Provides SDKs and server support for developers to create MCP servers.</li><li>Allows integration with popular enterprise systems like Google Drive, Slack, and GitHub.</li><li>Designed to improve the relevance of AI responses by connecting directly to real-time data sources.</li></ul><p><strong>OpenAI Function Calling Features:</strong></p><ul><li>Models can intelligently decide when to call functions based on user prompts.</li><li>Developers define functions in a structured format, including names, descriptions, and parameters.</li><li>Models return a JSON object indicating the function to be called and its necessary parameters.</li></ul><h3>Summary</h3><p>Both MCP and Function Calling significantly enhance the capabilities of AI models. MCP focuses on creating a standardized method for AI systems to connect with multiple data sources, promoting interoperability and integration convenience. OpenAI’s Function Calling, on the other hand, emphasizes enabling models to perform specific tasks through defined functions, thereby enhancing their interactivity and operational range. Together, these innovations represent an important step toward more intelligent and powerful AI systems.</p><h3>Conclusion</h3><p>MCP provides a standardized, secure solution for interaction between AI applications and local services. By using MCP, developers can allow AI tools like Claude Desktop to securely connect and operate with local resources while ensuring data privacy and security. As AI technology continues to develop, MCP, as an open protocol, will provide flexible integration solutions for more applications. In the future, whether developing IDE tools, data analysis platforms, or enhanced AI assistants, MCP will be a key technology for achieving secure, controlled resource access.</p><p>If you are a developer, or are looking for a secure way to connect local services, try MCP. Whether it’s local database access or complex data analysis, MCP can provide strong support for your applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=26055f59cde5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Trae + Claude-3.7-Sonnet + A Magical Prompt = High-Fidelity App Design of Your Dreams]]></title>
            <link>https://medium.com/@ai-data-drive/trae-claude-3-7-sonnet-a-magical-prompt-high-fidelity-app-design-of-your-dreams-c63c5bd61500?source=rss-5140c0782d6f------2</link>
            <guid isPermaLink="false">https://medium.com/p/c63c5bd61500</guid>
            <category><![CDATA[ai-design]]></category>
            <category><![CDATA[claude]]></category>
            <category><![CDATA[design]]></category>
            <category><![CDATA[prompt]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Andy Yang]]></dc:creator>
            <pubDate>Mon, 17 Mar 2025 03:20:39 GMT</pubDate>
            <atom:updated>2025-03-17T03:20:39.622Z</atom:updated>
            <content:encoded><![CDATA[<h3>Foreword</h3><p>I’ve recently started a series of online conversations with friends about AI, covering topics such as impressive AI tools and use cases, how AI empowers work and industries, AI applications in family and education, personal opportunities created by AI, and whether we feel anxious about AI’s arrival. Last week, I had a nearly two-hour conversation with an old friend, which was incredibly engaging and left me wanting more. During our talk, we discussed how AI enhances product design, which prompted me to conduct deeper research afterward. The most inspiring insight came from a YouTube creator called “Peanut” and his <a href="https://youtu.be/1ZKe-dzbhqY?si=JMCLoKzLmShGHjo0">video</a>. Combined with my current toolset, I developed an excellent technical solution, which I’ll share below.</p><h3>Results</h3><p>Let’s cut to the chase and look at the results:</p><p><strong>App design similar to “Xiaohongshu” (RED)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*omBIlxn0FSdTmmyVqhXu6g.jpeg" /></figure><p><strong>Social App design for elderly users</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*81Gr0yzdp3wemvMw4myBZA.jpeg" /></figure><p><strong>MBTI Personality-based AI Companion App design</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4GUj_lMiGJLqlI-Fjt_7ZA.jpeg" /></figure><p>Impressive, right?</p><p>As a programmer who previously only used hand-drawn interface designs for products, I found these results absolutely stunning. I designed about a dozen products that had been lingering in my mind, most of them on the first try, which was even more shocking to me! 🤯</p><p>How did I achieve this?</p><h3>Tools: Trae + Claude-3.7-Sonnet</h3><p>The core technology is the <strong>Claude-3.7-Sonnet</strong> large language model. It’s Claude’s latest model with first-class capabilities in code generation and product design.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tw66RMYQbBgwnUb9s9KVCQ.png" /></figure><p><a href="https://www.trae.ai/">Trae</a> is an AI programming IDE similar to Cursor, launched by ByteDance. It’s powerful and feature-rich. The most attractive aspect is that it offers free, unlimited access to Claude-3.7-Sonnet (which is limited if you’re not a paying Claude user).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nlrYI4EhRBUfAtX837JEcQ.png" /></figure><p>After downloading and installing Trae, open the interface, switch to “<strong>Builder</strong>” mode (<strong>Chat</strong> mode is only for conversation; <strong>Builder</strong> allows you to generate/modify code through chat), and switch the model to “Claude-3.7-Sonnet”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*upFNK52KgAEyem8z20EsjA.png" /></figure><h3>The Magical Prompt: The Soul of Design Generation</h3><p>Here’s the magical prompt that generates app designs:</p><pre>I want to develop an app [xxx/similar to xxx/for a specific user group xxx].<br><br>## Features section (optional)<br>It implements the following functions:<br>1. ...<br>2. ...<br>...<br><br>## Required specifications<br>Now I need high-fidelity prototype designs. Please help me complete the prototype design for all interfaces using the following approach, ensuring these prototype interfaces can be used directly for development:<br>1. User experience analysis: First analyze the main functions and user needs of this app to determine the core interaction logic<br>2. Product interface planning: As a product manager, define key interfaces and ensure reasonable information architecture<br>3. High-fidelity UI design: As a UI designer, design interfaces that adhere to iOS/Android design standards, using modern UI elements to create a good visual experience<br>4. HTML prototype implementation: Use HTML+Tailwind CSS (or Bootstrap) to generate all prototype interfaces, and use FontAwesome (or other open-source UI components) to make the interface more beautiful and close to a real app design. Split code files to maintain a clear structure:<br>5. Each interface should be stored as a separate HTML file, such as home.html, profile.html, settings.html<br> - index.html serves as the main entry point, not directly containing HTML code for all interfaces, but embedding these HTML fragments using iframes, and displaying all pages directly in the index page without link redirections.<br> - Realism enhancement:<br>    - Interface size should simulate iPhone 15 Pro, with rounded corners to make it look more like a real mobile interface.<br>    - Use real UI images rather than placeholder images (can be selected from Unsplash, Pexels, Apple official UI resources).<br>    - Add a top status bar (simulating iOS status bar) and include an app navigation bar (similar to iOS bottom TabBar).<br>    <br>Please follow the above requirements to generate complete HTML code in the design folder, ensuring it can be used for actual development.</pre><p>This prompt includes:</p><ul><li>App product features. This can be a single sentence like “an app similar to Xiaohongshu” or “a dating app for elderly users,” or you can list various functions you want.</li><li>Design requirements. These are the core constraints of the prompt:</li><li>First conduct user experience analysis and product interface planning to determine the content of the entire design.</li><li>High-fidelity UI design that complies with iOS/Android design standards.</li><li>Output HTML files using Tailwind CSS, FontAwesome, and other components to ensure beautiful interfaces.</li><li>Each interface is a separate HTML file, integrated in the entry index.html.</li><li>Interface elements requirement: simulate iPhone; use real UI images; include top status bar; include bottom TabBar navigation.</li><li>Output these design files to a design folder for later use.</li></ul><p>You can send this prompt directly to Trae AI, or save it to a prd.txt (Product Requirements Document) file and ask Trae AI to &quot;implement app design based on prd.txt.&quot;</p><p>Then Trae Builder will start producing design drafts file by file based on these product design requirements, as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6StBmhPtpgYHTsoIrkpUlA.png" /></figure><p>Finally, it will summarize all the generated content:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*G-WKNOUSmot9VdTiI2JxLw.png" /></figure><p>You can use “Accept All” to have the generated code written to corresponding files, then open the index.html design entry file directly in a browser to view the entire design:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*raZxdwIvUIvwRU1ug4BMsw.png" /></figure><p>These pages are realistic and beautiful. The text, icons, avatars, and images aren’t random placeholders but highly relevant to the app’s functionality, content, and style. They also have some interactivity — some areas can be clicked, pages can be scrolled down, tabs can be switched — making it feel like it could be published with just a bit more development. At the very least, you can show these to target users to get immediate product feedback.</p><p>If you find bugs or elements you’re not satisfied with, simply provide feedback to Trae through dialogue, and the code will be fixed in no time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B6WXjtssjEVgyyNxYsjLRg.png" /></figure><h3>Summary</h3><p>Through <strong>Trae + Claude-3.7-Sonnet + Design Generation Prompt</strong>, you can truly design a new product “in minutes,” allowing you to “see what you think.” This lowering of barriers greatly increases the possibility of turning ideas 💡 into action 🏃‍♂️, which is a tremendous empowerment for creative thinkers.</p><p>Perhaps the various ideas that once bounced around in your head have come back to life, attacking you again. Now’s the time!</p><p>With designs in hand, implementation is the next step. What surprises will AI bring us? Let’s take action and find out.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c63c5bd61500" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hacking OpenManus: Inside the World of AI Agents]]></title>
            <link>https://medium.com/@ai-data-drive/hacking-openmanus-inside-the-world-of-ai-agents-b18fe9aba571?source=rss-5140c0782d6f------2</link>
            <guid isPermaLink="false">https://medium.com/p/b18fe9aba571</guid>
            <category><![CDATA[agents]]></category>
            <category><![CDATA[prompt]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Andy Yang]]></dc:creator>
            <pubDate>Sun, 09 Mar 2025 14:06:10 GMT</pubDate>
            <atom:updated>2025-03-09T14:06:10.930Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Hacking OpenManus: Inside the World of AI Agents</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8FxSH5cpm9DPdRlKtwPDwg.jpeg" /></figure><h3>Preface</h3><p>This week, the AI Agent named Manus has attracted widespread attention due to its powerful functionality and flexible usage. However, the requirement of an invitation code to use Manus has deterred many developers and researchers. Fortunately, the open-source community has quickly responded with the OpenManus project, which achieves similar functions to Manus without the need for any invitation code.</p><p>OpenManus is an open-source project built by several members of the MetaGPT team in just three hours. By reading its code, we can gain an in-depth understanding of the framework design and implementation details of AI Agents. This is an excellent learning resource for developers who wish to build their own AI Agents.</p><h3>AI Agent Framework: Taking OpenManus as an Example</h3><h3>1. Overall Architecture</h3><p>OpenManus adopts a modular architectural design, comprising multiple core components:</p><pre>OpenManus<br>├── Agent (Proxy Layer)<br>│   ├── BaseAgent (Basic Abstract Class)<br>│   ├── ReActAgent (Think-Act Pattern)<br>│   ├── ToolCallAgent (Tool Calling Capability)<br>│   ├── PlanningAgent (Planning Capability)<br>│   ├── SWEAgent (Software Engineering Capability)<br>│   └── Manus (General Proxy)<br>├── LLM (Language Model Layer)<br>├── Memory (Memory Layer)<br>├── Tool (Tool Layer)<br>│   ├── BaseTool (Tool Base Class)<br>│   ├── PlanningTool (Planning Tool)<br>│   ├── PythonExecute (Python Execution)<br>│   ├── GoogleSearch (Search Tool)<br>│   ├── BrowserUseTool (Browser Tool)<br>│   └── ... (Other Tools)<br>├── Flow (Workflow Layer)<br>│   ├── BaseFlow (Basic Flow)<br>│   └── PlanningFlow (Planning Flow)<br>└── Prompt (Prompt Layer)</pre><p>This modular design ensures high code reusability, strong extensibility, and clear separation of responsibilities.</p><h3>2. LLM Component</h3><p>The LLM (Large Language Model) serves as the brain of the Agent, responsible for understanding user input, generating responses, and making decisions. OpenManus encapsulates the interaction with the language model through the LLM class:</p><pre>class LLM:<br>  _instances: Dict[str, &quot;LLM&quot;] = {}  # Singleton pattern implementation<br>  def __init__(<br>          self, config_name: str = &quot;default&quot;, llm_config: Optional[LLMSettings] = None<br>      ):<br>          if not hasattr(self, &quot;client&quot;):  # Initialize only once<br>              llm_config = llm_config or config.llm<br>              llm_config = llm_config.get(config_name, llm_config[&quot;default&quot;])<br>              self.model = llm_config.model<br>              self.max_tokens = llm_config.max_tokens<br>              self.temperature = llm_config.temperature<br>              self.client = AsyncOpenAI(<br>                  api_key=llm_config.api_key, base_url=llm_config.base_url<br>              )</pre><p>The LLM class provides two core methods:</p><ul><li>ask: Send a general conversation request.</li><li>ask_tool: Send a request with tool calling.</li></ul><pre>async def ask_tool(<br>    self,<br>    messages: List[Union[dict, Message]],<br>    system_msgs: Optional[List[Union[dict, Message]]] = None,<br>    timeout: int = 60,<br>    tools: Optional[List[dict]] = None,<br>    tool_choice: Literal[&quot;none&quot;, &quot;auto&quot;, &quot;required&quot;] = &quot;auto&quot;,<br>    temperature: Optional[float] = None,<br>    **kwargs,<br>):<br>    # Format messages<br>    if system_msgs:<br>        system_msgs = self.format_messages(system_msgs)<br>        messages = system_msgs + self.format_messages(messages)<br>    else:<br>        messages = self.format_messages(messages)<br>        <br>    # Send request<br>    response = await self.client.chat.completions.create(<br>        model=self.model,<br>        messages=messages,<br>        temperature=temperature or self.temperature,<br>        max_tokens=self.max_tokens,<br>        tools=tools,<br>        tool_choice=tool_choice,<br>        timeout=timeout,<br>        **kwargs,<br>    )</pre><h3>3. Memory Component</h3><p>The Memory component is responsible for storing and managing the Agent’s conversation history, ensuring the coherence of context:</p><pre>class Memory(BaseModel):<br>    &quot;&quot;&quot;Stores and manages the agent&#39;s conversation history.&quot;&quot;&quot;<br>    <br>    messages: List[Message] = Field(default_factory=list)<br>    <br>    def add_message(self, message: Union[Message, dict]) -&gt; None:<br>        &quot;&quot;&quot;Add a message to memory.&quot;&quot;&quot;<br>        if isinstance(message, dict):<br>            message = Message(**message)<br>        self.messages.append(message)<br>    <br>    def get_messages(self) -&gt; List[Message]:<br>        &quot;&quot;&quot;Get all messages in memory.&quot;&quot;&quot;<br>        return self.messages</pre><p>The Memory component is closely integrated with the Agent through the update_memory method of BaseAgent:</p><pre>def update_memory(<br>    self,<br>    role: Literal[&quot;user&quot;, &quot;system&quot;, &quot;assistant&quot;, &quot;tool&quot;],<br>    content: str,<br>    **kwargs,<br>) -&gt; None:<br>    &quot;&quot;&quot;Add a message to the agent&#39;s memory.&quot;&quot;&quot;<br>    message_map = {<br>        &quot;user&quot;: Message.user_message,<br>        &quot;system&quot;: Message.system_message,<br>        &quot;assistant&quot;: Message.assistant_message,<br>        &quot;tool&quot;: lambda content, **kw: Message.tool_message(content, **kw),<br>    }<br>if role not in message_map:<br>        raise ValueError(f&quot;Unsupported message role: {role}&quot;)<br>    msg_factory = message_map[role]<br>    msg = msg_factory(content, **kwargs) if role == &quot;tool&quot; else msg_factory(content)<br>    self.memory.add_message(msg)</pre><h3>4. Tools Component</h3><p>Tools are the interface through which the Agent interacts with the external world. OpenManus implements a flexible tool system based on BaseTool:</p><pre>class BaseTool(ABC, BaseModel):<br>    name: str<br>    description: str<br>    parameters: Optional[dict] = None<br>    async def __call__(self, **kwargs) -&gt; Any:<br>            &quot;&quot;&quot;Execute the tool with given parameters.&quot;&quot;&quot;<br>            return await self.execute(**kwargs)<br>        @abstractmethod<br>        async def execute(self, **kwargs) -&gt; Any:<br>            &quot;&quot;&quot;Execute the tool with given parameters.&quot;&quot;&quot;<br>        def to_param(self) -&gt; Dict:<br>            &quot;&quot;&quot;Convert tool to function call format.&quot;&quot;&quot;<br>            return {<br>                &quot;type&quot;: &quot;function&quot;,<br>                &quot;function&quot;: {<br>                    &quot;name&quot;: self.name,<br>                    &quot;description&quot;: self.description,<br>                    &quot;parameters&quot;: self.parameters,<br>                },<br>            </pre><p>The result of a tool execution is represented by the ToolResult class:</p><pre>class ToolResult(BaseModel):<br>    &quot;&quot;&quot;Represents the result of a tool execution.&quot;&quot;&quot;<br>    output: Any = Field(default=None)<br>    error: Optional[str] = Field(default=None)<br>    system: Optional[str] = Field(default=None)</pre><p>OpenManus provides several built-in tools, such as PlanningTool:</p><pre>class PlanningTool(BaseTool):<br>    &quot;&quot;&quot;<br>    A planning tool that allows the agent to create and manage plans for solving complex tasks.<br>    The tool provides functionality for creating plans, updating plan steps, and tracking progress<br>    &quot;&quot;&quot;<br>    name: str = &quot;planning&quot;<br>    description: str = _PLANNING_TOOL_DESCRIPTION<br>    parameters: dict = {<br>        &quot;type&quot;: &quot;object&quot;,<br>        &quot;properties&quot;: {<br>            &quot;command&quot;: {<br>                &quot;description&quot;: &quot;The command to execute. Available commands: create, update, list, get, set_active, mark_step, delete.&quot;,<br>                &quot;enum&quot;: [<br>                    &quot;create&quot;,<br>                    &quot;update&quot;,<br>                    &quot;list&quot;,<br>                    &quot;get&quot;,<br>                    &quot;set_active&quot;,<br>                    &quot;mark_step&quot;,<br>                    &quot;delete&quot;,<br>                ],<br>                &quot;type&quot;: &quot;string&quot;,<br>            },<br>            # Other parameters...<br>        },<br>        &quot;required&quot;: [&quot;command&quot;],<br>    }</pre><h3>5. Planning Component</h3><p>The Planning component is one of the core features of OpenManus, enabling the Agent to create and manage plans and break down complex tasks into manageable steps. The Planning component consists of two main parts:</p><ol><li>PlanningTool: Provides functions for creating, updating, and tracking plans.</li><li>PlanningAgent: Uses the PlanningTool to plan and execute tasks.</li></ol><pre>class PlanningAgent(ToolCallAgent):<br>    &quot;&quot;&quot;<br>    An agent that creates and manages plans to solve tasks.<br>    This agent uses a planning tool to create and manage structured plans,<br>    and tracks progress through individual steps until task completion.<br>    &quot;&quot;&quot;<br>    name: str = &quot;planning&quot;<br>    description: str = &quot;An agent that creates and manages plans to solve tasks&quot;<br>    system_prompt: str = PLANNING_SYSTEM_PROMPT<br>    next_step_prompt: str = NEXT_STEP_PROMPT<br>    available_tools: ToolCollection = Field(<br>        default_factory=lambda: ToolCollection(PlanningTool(), Terminate())<br>    )<br>    <br>    # Step execution tracker<br>    step_execution_tracker: Dict[str, Dict] = Field(default_factory=dict)<br>    current_step_index: Optional[int] = None</pre><p>The core methods of PlanningAgent include:</p><pre>async def think(self) -&gt; bool:<br>    &quot;&quot;&quot;Decide the next action based on plan status.&quot;&quot;&quot;<br>    prompt = (<br>        f&quot;CURRENT PLAN STATUS:\n{await self.get_plan()}\n\n{self.next_step_prompt}&quot;<br>        if self.active_plan_id<br>        else self.next_step_prompt<br>    )<br>    self.messages.append(Message.user_message(prompt))<br>    <br>    # Get the current step index<br>    self.current_step_index = await self._get_current_step_index()<br>    result = await super().think()<br>    # Associate tool calls with the current step<br>    if result and self.tool_calls:<br>        # ...association logic...<br>    return result</pre><h3>6. Flow Component</h3><p>The Flow component is used to manage the collaboration of multiple Agents to implement more complex task processing workflows:</p><pre>class BaseFlow(BaseModel, ABC):<br>    &quot;&quot;&quot;Base class for execution flows supporting multiple agents&quot;&quot;&quot;<br>    <br>    agents: Dict[str, BaseAgent]<br>    tools: Optional[List] = None<br>    primary_agent_key: Optional[str] = None<br>    <br>    @property<br>    def primary_agent(self) -&gt; Optional[BaseAgent]:<br>        &quot;&quot;&quot;Get the primary agent for the flow&quot;&quot;&quot;<br>        return self.agents.get(self.primary_agent_key)<br>    <br>    @abstractmethod<br>    async def execute(self, input_text: str) -&gt; str:<br>        &quot;&quot;&quot;Execute the flow with the given input&quot;&quot;&quot;</pre><p>PlanningFlow is a specific implementation of Flow for planning and executing tasks:</p><pre>class PlanningFlow(BaseFlow):<br>    &quot;&quot;&quot;A flow that manages planning and execution of tasks using agents.&quot;&quot;&quot;<br>    llm: LLM = Field(default_factory=lambda: LLM())<br>    planning_tool: PlanningTool = Field(default_factory=PlanningTool)<br>    executor_keys: List[str] = Field(default_factory=list)<br>    active_plan_id: str = Field(default_factory=lambda: f&quot;plan_{int(time.time())}&quot;)<br>    current_step_index: Optional[int] = None<br>    <br>    async def execute(self, input_text: str) -&gt; str:<br>        &quot;&quot;&quot;Execute the planning flow with agents.&quot;&quot;&quot;<br>        try:<br>            # Create the initial plan<br>            if input_text:<br>                await self._create_initial_plan(input_text)<br>                <br>            # Execute plan steps<br>            while await self._has_next_step():<br>                # Get the current step<br>                step_info = await self._get_current_step()<br>                <br>                # Select the appropriate executor<br>                executor = self.get_executor(step_info.get(&quot;type&quot;))<br>                <br>                # Execute the step<br>                result = await self._execute_step(executor, step_info)<br>                <br>                # Update the step status<br>                await self._update_step_status(step_info[&quot;index&quot;], &quot;completed&quot;)<br>                <br>            # Complete the plan<br>            return await self._finalize_plan()<br>            <br>        except Exception as e:<br>            # Handle exceptions<br>            return f&quot;Error executing flow: {str(e)}&quot;</pre><h3>Implementation of OpenManus: Key Code of Agents</h3><p>OpenManus’ Agents adopt a hierarchical architectural design, building from basic proxies to specialized proxies. This design ensures high code reusability, strong extensibility, and clear separation of responsibilities.</p><pre>BaseAgent (Abstract Base Class)<br>    └── ReActAgent (Think-Act Pattern)<br>        └── ToolCallAgent (Tool Calling Capability)<br>            ├── PlanningAgent (Planning Capability)<br>            ├── SWEAgent (Software Engineering Capability)<br>            └── Manus (General Proxy)</pre><h3>1. BaseAgent: Basic Abstract Class</h3><p>BaseAgent is the foundation of the entire framework, defining the core attributes and methods of the Agent:</p><pre>class BaseAgent(BaseModel, ABC):<br>    &quot;&quot;&quot;Abstract base class for managing agent state and execution.&quot;&quot;&quot;<br>    # Core attributes<br>    name: str = Field(..., description=&quot;Unique name of the agent&quot;)<br>    description: Optional[str] = Field(None, description=&quot;Optional agent description&quot;)<br>    <br>    # Prompts<br>    system_prompt: Optional[str] = Field(None, description=&quot;System-level instruction prompt&quot;)<br>    next_step_prompt: Optional[str] = Field(None, description=&quot;Prompt for determining next action&quot;)<br>    <br>    # Dependent components<br>    llm: LLM = Field(default_factory=LLM, description=&quot;Language model instance&quot;)<br>    memory: Memory = Field(default_factory=Memory, description=&quot;Agent&#39;s memory store&quot;)<br>    state: AgentState = Field(default=AgentState.IDLE, description=&quot;Current agent state&quot;)<br>    <br>    # Execution control<br>    max_steps: int = Field(default=10, description=&quot;Maximum steps before termination&quot;)<br>    current_step: int = Field(default=0, description=&quot;Current step in execution&quot;)</pre><h3>2. ReActAgent: Think-Act Pattern</h3><p>ReActAgent implements the &quot;Think-Act&quot; pattern, dividing the Agent&#39;s execution into two stages:</p><pre>class ReActAgent(BaseAgent, ABC):<br>    @abstractmethod<br>    async def think(self) -&gt; bool:<br>        &quot;&quot;&quot;Process the current state and decide the next action.&quot;&quot;&quot;<br>    @abstractmethod<br>    async def act(self) -&gt; str:<br>        &quot;&quot;&quot;Execute the decided actions.&quot;&quot;&quot;<br>    async def step(self) -&gt; str:<br>        &quot;&quot;&quot;Execute a single step: think and act.&quot;&quot;&quot;<br>        should_act = await self.think()<br>        if not should_act:<br>            return &quot;Thinking complete - no action needed&quot;<br>        return await self.act()</pre><h3>3. ToolCallAgent: Tool Calling Capability</h3><p>ToolCallAgent adds the ability to use tools to the Agent:</p><pre>class ToolCallAgent(ReActAgent):<br>    &quot;&quot;&quot;Base agent class for handling tool/function calls with enhanced abstraction&quot;&quot;&quot;<br>    <br>    available_tools: ToolCollection = ToolCollection(<br>        CreateChatCompletion(), Terminate()<br>    )<br>    tool_choices: Literal[&quot;none&quot;, &quot;auto&quot;, &quot;required&quot;] = &quot;auto&quot;<br>    <br>    async def think(self) -&gt; bool:<br>        # Get the LLM response and tool selection<br>        response = await self.llm.ask_tool(<br>            messages=self.messages,<br>            system_msgs=[Message.system_message(self.system_prompt)]<br>            if self.system_prompt<br>            else None,<br>            tools=self.available_tools.to_params(),<br>            tool_choice=self.tool_choices,<br>        )<br>        self.tool_calls = response.tool_calls<br>        <br>        # Process the response and tool calls<br>        # ...<br>        <br>    async def act(self) -&gt; str:<br>        # Execute tool calls<br>        results = []<br>        for command in self.tool_calls:<br>            result = await self.execute_tool(command)<br>            # Add tool response to memory<br>            # ...<br>            results.append(result)<br>        <br>        return &quot;\n\n&quot;.join(results)</pre><h3>4. PlanningAgent: Planning Capability</h3><p>PlanningAgent implements task planning and execution tracking:</p><pre>class PlanningAgent(ToolCallAgent):<br>    &quot;&quot;&quot;<br>    An agent that creates and manages plans to solve tasks.This agent uses a planning tool to create and manage structured plans,<br>    and tracks progress through individual steps until task completion.<br>    &quot;&quot;&quot;<br>    # Step execution tracker<br>    step_execution_tracker: Dict[str, Dict] = Field(default_factory=dict)<br>    current_step_index: Optional[int] = None<br>    async def think(self) -&gt; bool:<br>        &quot;&quot;&quot;Decide the next action based on plan status.&quot;&quot;&quot;<br>        prompt = (<br>            f&quot;CURRENT PLAN STATUS:\n{await self.get_plan()}\n\n{self.next_step_prompt}&quot;<br>            if self.active_plan_id<br>            else self.next_step_prompt<br>        )<br>        self.messages.append(Message.user_message(prompt))<br>        # Get the current step index<br>        self.current_step_index = await self._get_current_step_index()<br>        result = await super().think()<br>        # Associate tool calls with the current step<br>        if result and self.tool_calls:<br>            # ...association logic...<br>        return result<br></pre><h3>5. Manus: General Proxy</h3><p>Manus is the core proxy of OpenManus, integrating a variety of tools and capabilities:</p><pre>class Manus(ToolCallAgent):<br>    &quot;&quot;&quot;<br>    A versatile general-purpose agent that uses planning to solve various tasks.  This agent extends PlanningAgent with a comprehensive set of tools and capabilities,<br>    including Python execution, web browsing, file operations, and information retrieval<br>    to handle a wide range of user requests.<br>    &quot;&quot;&quot;<br>    name: str = &quot;manus&quot;<br>    description: str = &quot;A versatile general-purpose agent&quot;<br>    system_prompt: str = SYSTEM_PROMPT<br>    next_step_prompt: str = NEXT_STEP_PROMPT<br>    available_tools: ToolCollection = Field(<br>        default_factory=lambda: ToolCollection(<br>            PythonExecute(), GoogleSearch(), BrowserUseTool(), FileSaver(), Terminate()<br>        )<br>    )<br></pre><h3>The Important Role of Prompts in Building Agent Systems</h3><p>Prompts play a crucial role in building Agent systems, defining the behavior patterns of the Agent and guiding its decision-making process and tool usage.</p><h3>1. System Prompt: Defining the Agent’s Role and Capabilities</h3><p>The system prompt provides the Agent with a basic role definition and behavioral guidelines:</p><pre>SYSTEM_PROMPT = &quot;You are OpenManus, an all-capable AI assistant, aimed at solving any task presented by the user. You have various tools at your disposal that you can call upon to efficiently complete complex requests. Whether it&#39;s programming, information retrieval, file processing, or web browsing, you can handle it all.&quot;</pre><p>This prompt tells the Agent who it is, what it can do, and how it should act. In this way, we can shape the Agent’s “personality” and area of expertise.</p><h3>2. Planning Prompt: Guiding the Agent in Task Decomposition and Planning</h3><p>The planning prompt guides the Agent in breaking down complex tasks and creating execution plans:</p><pre>PLANNING_SYSTEM_PROMPT = &quot;&quot;&quot;<br>You are an expert Planning Agent tasked with solving complex problems by creating and managing structured plans.<br>Your job is:<br>1. Analyze requests to understand the task scope<br>2. Create clear, actionable plans with the `planning` tool<br>3. Execute steps using available tools as needed<br>4. Track progress and adapt plans dynamically<br>5. Use `finish` to conclude when the task is complete<br><br>Available tools will vary by task but may include:<br>- `planning`: Create, update, and track plans (commands: create, update, mark_step, etc.)<br>- `finish`: End the task when complete<br>Break tasks into logical, sequential steps. Think about dependencies and verification methods.<br>&quot;&quot;&quot;</pre><p>This prompt not only tells the Agent that its role is a planning expert but also details how it should use the planning tool to break down tasks, create plans, and track progress.</p><h3>3. Tool Usage Prompt: Guiding the Agent in Using Tools</h3><p>The tool usage prompt guides the Agent in selecting and using appropriate tools:</p><pre>NEXT_STEP_PROMPT = &quot;&quot;&quot;You can interact with the computer using PythonExecute, save important content and information files through FileSaver, open browsers with BrowserUseTool, and retrieve information using GoogleSearch.<br>PythonExecute: Execute Python code to interact with the computer system, data processing, automation tasks, etc.<br>FileSaver: Save files locally, such as txt, py, html, etc.<br>BrowserUseTool: Open, browse, and use web browsers. If you open a local HTML file, you must provide the absolute path to the file.<br>GoogleSearch: Perform web information retrieval<br>Based on user needs, proactively select the most appropriate tool or combination of tools. For complex tasks, you can break down the problem and use different tools step by step to solve it. After using each tool, clearly explain the execution results and suggest the next steps.<br>&quot;&quot;&quot;<br></pre><p>This prompt introduces the functions and use cases of each tool, helping the Agent choose the most suitable tool when facing different tasks.</p><h3>4. Dynamic Prompt Generation</h3><p>In OpenManus, prompts are not only static but can also be dynamically generated and parameterized. For example, in PlanningAgent, the system dynamically injects the current plan status into the prompt:</p><pre>async def think(self) -&gt; bool:<br>    &quot;&quot;&quot;Decide the next action based on plan status.&quot;&quot;&quot;<br>    prompt = (<br>        f&quot;CURRENT PLAN STATUS:\n{await self.get_plan()}\n\n{self.next_step_prompt}&quot;<br>        if self.active_plan_id<br>        else self.next_step_prompt<br>    )<br>    self.messages.append(Message.user_message(prompt))</pre><p>This dynamic prompt enables the Agent to make more appropriate decisions based on the current state.</p><h3>Summary</h3><p>Through the analysis of OpenManus code, we can see that a complete AI Agent framework should include the following key components:</p><ol><li>Agent: A hierarchical structure from basic proxies to specialized proxies, implementing different levels of capabilities</li></ol><ul><li>BaseAgent: Provides basic state management and execution loop</li><li>ReActAgent: Implements the Think-Act pattern</li><li>ToolCallAgent: Adds tool calling capabilities</li><li>Specialized proxies: Such as PlanningAgent, SWEAgent, and Manus</li></ul><p>2. LLM: Encapsulates interaction with the large language model, providing conversation and tool calling capabilities</p><ul><li>Supports general conversation and tool calling</li><li>Implements retry mechanisms and error handling</li><li>Supports streaming responses</li></ul><p>3. Memory: Manages conversation history and context</p><ul><li>Stores and retrieves messages</li><li>Maintains conversational context</li></ul><p>4. Tool: Provides an interface for interacting with the external world</p><ul><li>Basic tool abstraction</li><li>Multiple specialized tool implementations</li><li>Tool result processing</li></ul><p>5. Planning: Implements task planning and execution tracking</p><ul><li>Plan creation and management</li><li>Step status tracking</li><li>Dynamic plan adjustment</li></ul><p>6. Flow: Manages collaboration of multiple Agents</p><ul><li>Task assignment</li><li>Result integration</li><li>Flow control</li></ul><p>7. Prompt: Guides the Agent’s behavior and decision-making</p><ul><li>System prompt defines the role</li><li>Specialized prompts guide decision-making</li><li>Dynamic prompt generation</li></ul><p>OpenManus has a clear design philosophy and a well-structured codebase, making it an excellent example for learning AI Agent implementation. Its modular design allows developers to easily extend and customize their own proxies.</p><p>For developers who want to delve deeper into AI Agents or build their own Agent systems, OpenManus provides a great starting point. By studying its architecture and implementation, we can better understand the working principles and design philosophy of AI Agents.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b18fe9aba571" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[【AI启示录】2025 W10：读OPENMANUS代码，品AI AGENT系统]]></title>
            <link>https://medium.com/@ai-data-drive/ai%E5%90%AF%E7%A4%BA%E5%BD%95-2025-w10-%E8%AF%BBopenmanus%E4%BB%A3%E7%A0%81-%E5%93%81ai-agent%E7%B3%BB%E7%BB%9F-9ad337f6f889?source=rss-5140c0782d6f------2</link>
            <guid isPermaLink="false">https://medium.com/p/9ad337f6f889</guid>
            <category><![CDATA[prompt]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[agents]]></category>
            <dc:creator><![CDATA[Andy Yang]]></dc:creator>
            <pubDate>Sun, 09 Mar 2025 13:25:29 GMT</pubDate>
            <atom:updated>2025-03-09T13:25:29.571Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8FxSH5cpm9DPdRlKtwPDwg.jpeg" /></figure><h3>题记</h3><p>本周Manus这款AI Agent因其强大的功能和灵活的使用方式引起了广泛关注。然而，Manus需要邀请码才能使用，这让许多开发者和研究者望而却步。好消息是，开源社区迅速响应，推出了OpenManus项目，它不需要任何邀请码就能实现类似Manus的功能。</p><p>OpenManus是由MetaGPT团队的几位成员在短短3小时内构建的开源项目。通过阅读其代码，我们可以深入了解AI Agent的框架设计和实现细节，这对于想要构建自己的AI Agent的开发者来说是一个绝佳的学习资源。</p><h3>AI AGENT框架：以OPENMANUS为例</h3><h3>1. 整体架构</h3><p>OpenManus采用了模块化的架构设计，包含多个核心组件：</p><pre>OpenManus<br>├── Agent (代理层)<br>│   ├── BaseAgent (基础抽象类)<br>│   ├── ReActAgent (思考-行动模式)<br>│   ├── ToolCallAgent (工具调用能力)<br>│   ├── PlanningAgent (规划能力)<br>│   ├── SWEAgent (软件工程能力)<br>│   └── Manus (通用代理)<br>├── LLM (语言模型层)<br>├── Memory (记忆层)<br>├── Tool (工具层)<br>│   ├── BaseTool (工具基类)<br>│   ├── PlanningTool (规划工具)<br>│   ├── PythonExecute (Python执行)<br>│   ├── GoogleSearch (搜索工具)<br>│   ├── BrowserUseTool (浏览器工具)<br>│   └── ... (其他工具)<br>├── Flow (工作流层)<br>│   ├── BaseFlow (基础流程)<br>│   └── PlanningFlow (规划流程)<br>└── Prompt (提示词层)</pre><p>这种模块化设计使得代码复用性高、扩展性强，并且职责分离清晰。</p><h3>2. LLM组件</h3><p>LLM（大型语言模型）是Agent的大脑，负责理解用户输入、生成响应和决策。OpenManus通过 LLM 类封装了与语言模型的交互：</p><pre>class LLM:<br>    _instances: Dict[str, &quot;LLM&quot;] = {}  # 单例模式实现<br>​<br>    def __init__(<br>        self, config_name: str = &quot;default&quot;, llm_config: Optional[LLMSettings] = None<br>    ):<br>        if not hasattr(self, &quot;client&quot;):  # 只初始化一次<br>            llm_config = llm_config or config.llm<br>            llm_config = llm_config.get(config_name, llm_config[&quot;default&quot;])<br>            self.model = llm_config.model<br>            self.max_tokens = llm_config.max_tokens<br>            self.temperature = llm_config.temperature<br>            self.client = AsyncOpenAI(<br>                api_key=llm_config.api_key, base_url=llm_config.base_url<br>            )</pre><p>LLM类提供了两个核心方法：</p><ul><li>ask : 发送普通对话请求</li><li>ask_tool : 发送带工具调用的请求</li></ul><pre>async def ask_tool(<br>    self,<br>    messages: List[Union[dict, Message]],<br>    system_msgs: Optional[List[Union[dict, Message]]] = None,<br>    timeout: int = 60,<br>    tools: Optional[List[dict]] = None,<br>    tool_choice: Literal[&quot;none&quot;, &quot;auto&quot;, &quot;required&quot;] = &quot;auto&quot;,<br>    temperature: Optional[float] = None,<br>    **kwargs,<br>):<br>    # 格式化消息<br>    if system_msgs:<br>        system_msgs = self.format_messages(system_msgs)<br>        messages = system_msgs + self.format_messages(messages)<br>    else:<br>        messages = self.format_messages(messages)<br>        <br>    # 发送请求<br>    response = await self.client.chat.completions.create(<br>        model=self.model,<br>        messages=messages,<br>        temperature=temperature or self.temperature,<br>        max_tokens=self.max_tokens,<br>        tools=tools,<br>        tool_choice=tool_choice,<br>        timeout=timeout,<br>        **kwargs,<br>    )</pre><h3>3. Memory组件</h3><p>Memory组件负责存储和管理Agent的对话历史，使Agent能够保持上下文连贯性：</p><pre>class Memory(BaseModel):<br>    &quot;&quot;&quot;Stores and manages agent&#39;s conversation history.&quot;&quot;&quot;<br>    <br>    messages: List[Message] = Field(default_factory=list)<br>    <br>    def add_message(self, message: Union[Message, dict]) -&gt; None:<br>        &quot;&quot;&quot;Add a message to memory.&quot;&quot;&quot;<br>        if isinstance(message, dict):<br>            message = Message(**message)<br>        self.messages.append(message)<br>    <br>    def get_messages(self) -&gt; List[Message]:<br>        &quot;&quot;&quot;Get all messages in memory.&quot;&quot;&quot;<br>        return self.messages</pre><p>Memory组件与Agent紧密集成，通过BaseAgent的update_memory方法添加新消息：</p><pre>def update_memory(<br>    self,<br>    role: Literal[&quot;user&quot;, &quot;system&quot;, &quot;assistant&quot;, &quot;tool&quot;],<br>    content: str,<br>    **kwargs,<br>) -&gt; None:<br>    &quot;&quot;&quot;Add a message to the agent&#39;s memory.&quot;&quot;&quot;<br>    message_map = {<br>        &quot;user&quot;: Message.user_message,<br>        &quot;system&quot;: Message.system_message,<br>        &quot;assistant&quot;: Message.assistant_message,<br>        &quot;tool&quot;: lambda content, **kw: Message.tool_message(content, **kw),<br>    }<br>​<br>    if role not in message_map:<br>        raise ValueError(f&quot;Unsupported message role: {role}&quot;)<br>​<br>    msg_factory = message_map[role]<br>    msg = msg_factory(content, **kwargs) if role == &quot;tool&quot; else msg_factory(content)<br>    self.memory.add_message(msg)</pre><h3>4. Tools组件</h3><p>Tools是Agent与外部世界交互的接口。OpenManus实现了一个灵活的工具系统，以 BaseTool 为基础：</p><pre>class BaseTool(ABC, BaseModel):<br>    name: str<br>    description: str<br>    parameters: Optional[dict] = None<br>​<br>    async def __call__(self, **kwargs) -&gt; Any:<br>        &quot;&quot;&quot;Execute the tool with given parameters.&quot;&quot;&quot;<br>        return await self.execute(**kwargs)<br>​<br>    @abstractmethod<br>    async def execute(self, **kwargs) -&gt; Any:<br>        &quot;&quot;&quot;Execute the tool with given parameters.&quot;&quot;&quot;<br>​<br>    def to_param(self) -&gt; Dict:<br>        &quot;&quot;&quot;Convert tool to function call format.&quot;&quot;&quot;<br>        return {<br>            &quot;type&quot;: &quot;function&quot;,<br>            &quot;function&quot;: {<br>                &quot;name&quot;: self.name,<br>                &quot;description&quot;: self.description,<br>                &quot;parameters&quot;: self.parameters,<br>            },<br>        }</pre><p>工具执行结果通过 ToolResult 类表示：</p><pre>class ToolResult(BaseModel):<br>    &quot;&quot;&quot;Represents the result of a tool execution.&quot;&quot;&quot;<br>​<br>    output: Any = Field(default=None)<br>    error: Optional[str] = Field(default=None)<br>    system: Optional[str] = Field(default=None)</pre><p>OpenManus提供了多种内置工具，如 PlanningTool ：</p><pre>class PlanningTool(BaseTool):<br>    &quot;&quot;&quot;<br>    A planning tool that allows the agent to create and manage plans for solving complex tasks.<br>    The tool provides functionality for creating plans, updating plan steps, and tracking progress.<br>    &quot;&quot;&quot;<br>​<br>    name: str = &quot;planning&quot;<br>    description: str = _PLANNING_TOOL_DESCRIPTION<br>    parameters: dict = {<br>        &quot;type&quot;: &quot;object&quot;,<br>        &quot;properties&quot;: {<br>            &quot;command&quot;: {<br>                &quot;description&quot;: &quot;The command to execute. Available commands: create, update, list, get, set_active, mark_step, delete.&quot;,<br>                &quot;enum&quot;: [<br>                    &quot;create&quot;,<br>                    &quot;update&quot;,<br>                    &quot;list&quot;,<br>                    &quot;get&quot;,<br>                    &quot;set_active&quot;,<br>                    &quot;mark_step&quot;,<br>                    &quot;delete&quot;,<br>                ],<br>                &quot;type&quot;: &quot;string&quot;,<br>            },<br>            # 其他参数...<br>        },<br>        &quot;required&quot;: [&quot;command&quot;],<br>    }</pre><h3>5. Planning组件</h3><p>Planning组件是OpenManus的核心功能之一，它使Agent能够创建和管理计划，将复杂任务分解为可管理的步骤。Planning组件包括两个主要部分：</p><ol><li>PlanningTool ：提供计划创建、更新和跟踪的功能</li><li>PlanningAgent ：使用PlanningTool进行任务规划和执行</li></ol><pre>class PlanningAgent(ToolCallAgent):<br>    &quot;&quot;&quot;<br>    An agent that creates and manages plans to solve tasks.<br>​<br>    This agent uses a planning tool to create and manage structured plans,<br>    and tracks progress through individual steps until task completion.<br>    &quot;&quot;&quot;<br>​<br>    name: str = &quot;planning&quot;<br>    description: str = &quot;An agent that creates and manages plans to solve tasks&quot;<br>​<br>    system_prompt: str = PLANNING_SYSTEM_PROMPT<br>    next_step_prompt: str = NEXT_STEP_PROMPT<br>​<br>    available_tools: ToolCollection = Field(<br>        default_factory=lambda: ToolCollection(PlanningTool(), Terminate())<br>    )<br>    <br>    # 步骤执行跟踪器<br>    step_execution_tracker: Dict[str, Dict] = Field(default_factory=dict)<br>    current_step_index: Optional[int] = None</pre><p>PlanningAgent的核心方法包括：</p><pre>async def think(self) -&gt; bool:<br>    &quot;&quot;&quot;Decide the next action based on plan status.&quot;&quot;&quot;<br>    prompt = (<br>        f&quot;CURRENT PLAN STATUS:\n{await self.get_plan()}\n\n{self.next_step_prompt}&quot;<br>        if self.active_plan_id<br>        else self.next_step_prompt<br>    )<br>    self.messages.append(Message.user_message(prompt))<br>​<br>    # 获取当前步骤索引<br>    self.current_step_index = await self._get_current_step_index()<br>​<br>    result = await super().think()<br>​<br>    # 关联工具调用与当前步骤<br>    if result and self.tool_calls:<br>        # ...关联逻辑...<br>​<br>    return result</pre><h3>6. Flow组件</h3><p>Flow组件用于管理多个Agent的协作，实现更复杂的任务处理流程：</p><pre>class BaseFlow(BaseModel, ABC):<br>    &quot;&quot;&quot;Base class for execution flows supporting multiple agents&quot;&quot;&quot;<br>    <br>    agents: Dict[str, BaseAgent]<br>    tools: Optional[List] = None<br>    primary_agent_key: Optional[str] = None<br>    <br>    @property<br>    def primary_agent(self) -&gt; Optional[BaseAgent]:<br>        &quot;&quot;&quot;Get the primary agent for the flow&quot;&quot;&quot;<br>        return self.agents.get(self.primary_agent_key)<br>    <br>    @abstractmethod<br>    async def execute(self, input_text: str) -&gt; str:<br>        &quot;&quot;&quot;Execute the flow with given input&quot;&quot;&quot;</pre><p>PlanningFlow是一个具体的Flow实现，用于规划和执行任务：</p><pre>class PlanningFlow(BaseFlow):<br>    &quot;&quot;&quot;A flow that manages planning and execution of tasks using agents.&quot;&quot;&quot;<br>​<br>    llm: LLM = Field(default_factory=lambda: LLM())<br>    planning_tool: PlanningTool = Field(default_factory=PlanningTool)<br>    executor_keys: List[str] = Field(default_factory=list)<br>    active_plan_id: str = Field(default_factory=lambda: f&quot;plan_{int(time.time())}&quot;)<br>    current_step_index: Optional[int] = None<br>    <br>    async def execute(self, input_text: str) -&gt; str:<br>        &quot;&quot;&quot;Execute the planning flow with agents.&quot;&quot;&quot;<br>        try:<br>            # 创建初始计划<br>            if input_text:<br>                await self._create_initial_plan(input_text)<br>                <br>            # 执行计划步骤<br>            while await self._has_next_step():<br>                # 获取当前步骤<br>                step_info = await self._get_current_step()<br>                <br>                # 选择合适的执行者<br>                executor = self.get_executor(step_info.get(&quot;type&quot;))<br>                <br>                # 执行步骤<br>                result = await self._execute_step(executor, step_info)<br>                <br>                # 更新步骤状态<br>                await self._update_step_status(step_info[&quot;index&quot;], &quot;completed&quot;)<br>                <br>            # 完成计划<br>            return await self._finalize_plan()<br>            <br>        except Exception as e:<br>            # 处理异常<br>            return f&quot;Error executing flow: {str(e)}&quot;</pre><h3>OPENMANUS的实现：AGENT关键代码</h3><p>OpenManus的Agent采用了层次化的架构设计，从基础代理到专业代理逐层构建。这种设计使得代码复用性高、扩展性强，并且职责分离清晰。</p><pre>BaseAgent (抽象基类)<br>    └── ReActAgent (思考-行动模式)<br>        └── ToolCallAgent (工具调用能力)<br>            ├── PlanningAgent (规划能力)<br>            ├── SWEAgent (软件工程能力)<br>            └── Manus (通用代理)</pre><h3>1. BaseAgent：基础抽象类</h3><p>BaseAgent 是整个框架的基础，它定义了代理的核心属性和方法：</p><pre>class BaseAgent(BaseModel, ABC):<br>    &quot;&quot;&quot;Abstract base class for managing agent state and execution.&quot;&quot;&quot;<br>​<br>    # 核心属性<br>    name: str = Field(..., description=&quot;Unique name of the agent&quot;)<br>    description: Optional[str] = Field(None, description=&quot;Optional agent description&quot;)<br>    <br>    # 提示词<br>    system_prompt: Optional[str] = Field(None, description=&quot;System-level instruction prompt&quot;)<br>    next_step_prompt: Optional[str] = Field(None, description=&quot;Prompt for determining next action&quot;)<br>    <br>    # 依赖组件<br>    llm: LLM = Field(default_factory=LLM, description=&quot;Language model instance&quot;)<br>    memory: Memory = Field(default_factory=Memory, description=&quot;Agent&#39;s memory store&quot;)<br>    state: AgentState = Field(default=AgentState.IDLE, description=&quot;Current agent state&quot;)<br>    <br>    # 执行控制<br>    max_steps: int = Field(default=10, description=&quot;Maximum steps before termination&quot;)<br>    current_step: int = Field(default=0, description=&quot;Current step in execution&quot;)</pre><h3>2. ReActAgent：思考-行动模式</h3><p>ReActAgent 实现了”思考-行动”模式，将代理的执行分为两个阶段：</p><pre>class ReActAgent(BaseAgent, ABC):<br>    @abstractmethod<br>    async def think(self) -&gt; bool:<br>        &quot;&quot;&quot;Process current state and decide next action&quot;&quot;&quot;<br>​<br>    @abstractmethod<br>    async def act(self) -&gt; str:<br>        &quot;&quot;&quot;Execute decided actions&quot;&quot;&quot;<br>​<br>    async def step(self) -&gt; str:<br>        &quot;&quot;&quot;Execute a single step: think and act.&quot;&quot;&quot;<br>        should_act = await self.think()<br>        if not should_act:<br>            return &quot;Thinking complete - no action needed&quot;<br>        return await self.act()</pre><h3>3. ToolCallAgent：工具调用能力</h3><p>ToolCallAgent 为代理添加了使用工具的能力：</p><pre>class ToolCallAgent(ReActAgent):<br>    &quot;&quot;&quot;Base agent class for handling tool/function calls with enhanced abstraction&quot;&quot;&quot;<br>    <br>    available_tools: ToolCollection = ToolCollection(<br>        CreateChatCompletion(), Terminate()<br>    )<br>    tool_choices: Literal[&quot;none&quot;, &quot;auto&quot;, &quot;required&quot;] = &quot;auto&quot;<br>    <br>    async def think(self) -&gt; bool:<br>        # 获取LLM响应和工具选择<br>        response = await self.llm.ask_tool(<br>            messages=self.messages,<br>            system_msgs=[Message.system_message(self.system_prompt)]<br>            if self.system_prompt<br>            else None,<br>            tools=self.available_tools.to_params(),<br>            tool_choice=self.tool_choices,<br>        )<br>        self.tool_calls = response.tool_calls<br>        <br>        # 处理响应和工具调用<br>        # ...<br>        <br>    async def act(self) -&gt; str:<br>        # 执行工具调用<br>        results = []<br>        for command in self.tool_calls:<br>            result = await self.execute_tool(command)<br>            # 添加工具响应到内存<br>            # ...<br>            results.append(result)<br>        <br>        return &quot;\n\n&quot;.join(results)</pre><h3>4. PlanningAgent：规划能力</h3><p>PlanningAgent 实现了任务规划和执行跟踪：</p><pre>class PlanningAgent(ToolCallAgent):<br>    &quot;&quot;&quot;<br>    An agent that creates and manages plans to solve tasks.<br>​<br>    This agent uses a planning tool to create and manage structured plans,<br>    and tracks progress through individual steps until task completion.<br>    &quot;&quot;&quot;<br>​<br>    # 步骤执行跟踪器<br>    step_execution_tracker: Dict[str, Dict] = Field(default_factory=dict)<br>    current_step_index: Optional[int] = None<br>​<br>    async def think(self) -&gt; bool:<br>        &quot;&quot;&quot;Decide the next action based on plan status.&quot;&quot;&quot;<br>        prompt = (<br>            f&quot;CURRENT PLAN STATUS:\n{await self.get_plan()}\n\n{self.next_step_prompt}&quot;<br>            if self.active_plan_id<br>            else self.next_step_prompt<br>        )<br>        self.messages.append(Message.user_message(prompt))<br>​<br>        # 获取当前步骤索引<br>        self.current_step_index = await self._get_current_step_index()<br>​<br>        result = await super().think()<br>​<br>        # 关联工具调用与当前步骤<br>        if result and self.tool_calls:<br>            # ...关联逻辑...<br>​<br>        return result</pre><h3>5. Manus：通用代理</h3><p>Manus 是OpenManus的核心代理，它集成了多种工具和能力：</p><pre>class Manus(ToolCallAgent):<br>    &quot;&quot;&quot;<br>    A versatile general-purpose agent that uses planning to solve various tasks.<br>​<br>    This agent extends PlanningAgent with a comprehensive set of tools and capabilities,<br>    including Python execution, web browsing, file operations, and information retrieval<br>    to handle a wide range of user requests.<br>    &quot;&quot;&quot;<br>​<br>    name: str = &quot;manus&quot;<br>    description: str = &quot;A versatile general-purpose agent&quot;<br>​<br>    system_prompt: str = SYSTEM_PROMPT<br>    next_step_prompt: str = NEXT_STEP_PROMPT<br>​<br>    available_tools: ToolCollection = Field(<br>        default_factory=lambda: ToolCollection(<br>            PythonExecute(), GoogleSearch(), BrowserUseTool(), FileSaver(), Terminate()<br>        )<br>    )</pre><h3>PROMPT在构建AGENT系统中的重要作用</h3><p>Prompt在构建Agent系统中扮演着至关重要的角色，它不仅定义了Agent的行为模式，还指导了Agent的决策过程和工具使用方式。</p><h3>1. 系统Prompt：定义Agent的角色和能力</h3><p>系统Prompt为Agent提供了基本的角色定义和行为指南：</p><pre>SYSTEM_PROMPT = &quot;You are OpenManus, an all-capable AI assistant, aimed at solving any task presented by the user. You have various tools at your disposal that you can call upon to efficiently complete complex requests. Whether it&#39;s programming, information retrieval, file processing, or web browsing, you can handle it all.&quot;</pre><p>这个Prompt告诉Agent它是谁、能做什么，以及应该如何行动。通过这种方式，我们可以塑造Agent的”人格”和专业领域。</p><h3>2. 规划Prompt：指导Agent进行任务分解和规划</h3><p>规划Prompt指导Agent如何分解复杂任务并创建执行计划：</p><pre>PLANNING_SYSTEM_PROMPT = &quot;&quot;&quot;<br>You are an expert Planning Agent tasked with solving complex problems by creating and managing structured plans.<br>Your job is:<br>1. Analyze requests to understand the task scope<br>2. Create clear, actionable plans with the `planning` tool<br>3. Execute steps using available tools as needed<br>4. Track progress and adapt plans dynamically<br>5. Use `finish` to conclude when the task is complete<br>​<br>Available tools will vary by task but may include:<br>- `planning`: Create, update, and track plans (commands: create, update, mark_step, etc.)<br>- `finish`: End the task when complete<br>​<br>Break tasks into logical, sequential steps. Think about dependencies and verification methods.<br>&quot;&quot;&quot;</pre><p>这个Prompt不仅告诉Agent它的角色是一个规划专家，还详细说明了它应该如何使用规划工具来分解任务、创建计划并跟踪进度。</p><h3>3. 工具使用Prompt：指导Agent如何使用工具</h3><p>工具使用Prompt指导Agent如何选择和使用合适的工具：</p><pre>NEXT_STEP_PROMPT = &quot;&quot;&quot;You can interact with the computer using PythonExecute, save important content and information files through FileSaver, open browsers with BrowserUseTool, and retrieve information using GoogleSearch.<br>​<br>PythonExecute: Execute Python code to interact with the computer system, data processing, automation tasks, etc.<br>​<br>FileSaver: Save files locally, such as txt, py, html, etc.<br>​<br>BrowserUseTool: Open, browse, and use web browsers.If you open a local HTML file, you must provide the absolute path to the file.<br>​<br>GoogleSearch: Perform web information retrieval<br>​<br>Based on user needs, proactively select the most appropriate tool or combination of tools. For complex tasks, you can break down the problem and use different tools step by step to solve it. After using each tool, clearly explain the execution results and suggest the next steps.<br>&quot;&quot;&quot;</pre><p>这个Prompt详细介绍了每个工具的功能和使用场景，帮助Agent在面对不同任务时选择最合适的工具。</p><h3>4. 动态Prompt生成</h3><p>在OpenManus中，Prompt不仅是静态的，还可以动态生成和参数化。例如，在PlanningAgent中，系统会动态将当前计划状态注入到Prompt中：</p><pre>async def think(self) -&gt; bool:<br>    &quot;&quot;&quot;Decide the next action based on plan status.&quot;&quot;&quot;<br>    prompt = (<br>        f&quot;CURRENT PLAN STATUS:\n{await self.get_plan()}\n\n{self.next_step_prompt}&quot;<br>        if self.active_plan_id<br>        else self.next_step_prompt<br>    )<br>    self.messages.append(Message.user_message(prompt))</pre><p>这种动态Prompt使Agent能够根据当前状态做出更合适的决策。</p><h3>小结</h3><p>通过对OpenManus代码的分析，我们可以看到一个完整的AI Agent框架应该包含以下几个关键组件：</p><ol><li>Agent：从基础代理到专业代理的层次结构，实现不同级别的能力</li></ol><ul><li>BaseAgent：提供基础的状态管理和执行循环</li><li>ReActAgent：实现思考-行动模式</li><li>ToolCallAgent：添加工具调用能力</li><li>专业代理：如PlanningAgent、SWEAgent和Manus</li></ul><p>2. LLM：封装与大型语言模型的交互，提供对话和工具调用能力</p><ul><li>支持普通对话和工具调用</li><li>实现重试机制和错误处理</li><li>支持流式响应</li></ul><p>3. Memory：管理对话历史和上下文</p><ul><li>存储和检索消息</li><li>维护对话上下文</li></ul><p>4. Tool：提供与外部世界交互的接口</p><ul><li>基础工具抽象</li><li>多种专业工具实现</li><li>工具结果处理</li></ul><p>5. Planning：实现任务规划和执行跟踪</p><ul><li>计划创建和管理</li><li>步骤状态跟踪</li><li>动态调整计划</li></ul><p>6. Flow：管理多个Agent的协作</p><ul><li>任务分配</li><li>结果整合</li><li>流程控制</li></ul><p>7. Prompt：指导Agent的行为和决策</p><ul><li>系统Prompt定义角色</li><li>专业Prompt指导决策</li><li>动态Prompt生成</li></ul><p>OpenManus的设计思路清晰，代码结构合理，是学习AI Agent实现的优秀范例。它的模块化设计使得开发者可以轻松扩展和定制自己的代理。</p><p>对于想要深入了解AI Agent或构建自己的Agent系统的开发者来说，OpenManus提供了一个很好的起点。通过学习其架构和实现，我们可以更好地理解AI Agent的工作原理和设计思路。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9ad337f6f889" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Lies Behind DeepSeek’s Open Source Week? Deep Research Uncovers It All]]></title>
            <link>https://medium.com/@ai-data-drive/what-lies-behind-deepseeks-open-source-week-deep-research-uncovers-it-all-4d7fe583c907?source=rss-5140c0782d6f------2</link>
            <guid isPermaLink="false">https://medium.com/p/4d7fe583c907</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[deep-research]]></category>
            <category><![CDATA[deepseek]]></category>
            <dc:creator><![CDATA[Andy Yang]]></dc:creator>
            <pubDate>Thu, 06 Mar 2025 09:36:45 GMT</pubDate>
            <atom:updated>2025-03-06T09:37:02.672Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8FxSH5cpm9DPdRlKtwPDwg.jpeg" /></figure><p>Last week marked DeepSeek’s Open Source Week, during which DeepSeek has open-sourced a slew of projects in one go:</p><ul><li>FlashMLA (efficient attention decoding)</li><li>DeepEP (MoE/expert parallel communication library)</li><li>DeepGEMM (FP8 general matrix multiplication library)</li><li>DualPipe (bidirectional pipeline parallel algorithm)</li><li>EPLB (expert parallel load balancer)</li><li>3FS (high-performance distributed file system)</li><li>There’s also “One More Thing.”</li></ul><p>For someone who doesn’t have much understanding of LLM training and inference technology systems, it’s challenging to grasp the functions and significance of these projects.</p><p>Fortunately, this week, ChatGPT’s <strong>Deep Research</strong> feature was made available to me. It can help me conduct systematic and in-depth research on topics of interest and form easy-to-understand research reports. With its assistance, I’ve begun to gain some understanding of the originally hard-to-comprehend DeepSeek hardcore open-source projects.</p><h3>1. Basic Processes of LLM Training and Inference</h3><p>To understand the roles of these projects, it’s necessary to have a basic understanding of the training and inference processes of LLMs (Large Language Models).</p><p><strong>LLM Training Process</strong>:</p><p>This can be simply understood as the process of “<strong>teaching the model to speak</strong>.”</p><p>First, we prepare a vast amount of training data (such as tens of thousands of text documents). During training, data is fed into the model in batches. The model predicts outputs based on the inputs, and then compares the predicted results with the actual answers to calculate the loss (which basically indicates the degree of the model’s errors). Subsequently, the model adjusts its own parameters through backpropagation, much like a student improving their knowledge based on feedback from incorrect answers. This cycle of “seeing data -&gt; attempting to answer -&gt; correcting” is executed many, many times until the model’s predictions are as accurate as possible.</p><p>Due to the huge parameter scales of modern LLMs (possibly hundreds of billions of parameters), the memory and computing power of a single graphics card are often insufficient to complete the training. Therefore, it’s common to use multiple GPUs for collaborative training. One common method is data parallelism (each GPU processes different batches of data, with parameters synchronized periodically), as well as model parallelism (dividing the model into parts and distributing them across multiple GPUs) and pipeline parallelism (having different GPUs handle different layers of the model, processing data like an assembly line). The final output of training is a set of learned model parameters (like a well-trained “language expert”).</p><p><strong>LLM Inference Process</strong>:</p><p>This can be seen as the process of “<strong>the model applying what it has learned to answer questions</strong>.”</p><p>Once we have a well-trained large model, we can use it for inference (i.e., generating responses). Inference typically doesn’t require gradient updates anymore but instead involves fixed model parameters for forward computation.</p><p>Taking chatting with AI as an example: a user provides an input prompt, the model converts it into an internal vector representation, and then generates output text through a series of Transformer layers. The model often generates one word or character (i.e., a token) at a time, using each generated token as new input to continue generating the next one until the entire response is completed.</p><p>During this generation process, the model internally utilizes the attention mechanism learned during training to understand the context. For instance, given a long conversation history, the model will “focus on” the relevant parts to decide how to say the next sentence.</p><p>To accelerate inference, caching mechanisms are used in actual implementations (such as saving the “key-value pair” vectors that have been computed before, and reusing them directly the next time), so the model doesn’t have to process the entire input from scratch every time.</p><p>The goal of inference is to generate results as quickly and accurately as possible, as users expect low-latency responses. In summary, inference is the process of leveraging the model’s learned abilities to go from question -&gt; model’s thinking -&gt; providing an answer.</p><h3>2. The Positions and Roles of DeepSeek’s Open-Source Projects in LLM Training and Inference</h3><p>DeepSeek has released projects over five consecutive days during “Open Source Week,” covering various aspects from model computation to distributed communication and data storage. These projects respectively enhance the efficiency of different stages in LLM training or inference. Below, following the training/inference process, we’ll explain the position and role of each project:</p><p><strong>FlashMLA (Efficient Attention Decoding)</strong></p><p>It mainly functions during the inference stage. It optimizes the crucial “attention” calculation process when the model generates text, accelerating the model’s decoding response.</p><p>In simple terms, when the model predicts the next word based on existing content, FlashMLA makes this step run faster and more memory-efficient. This means that when users converse with chatbots, responses will be quicker and smoother.</p><p><strong>DeepEP (MoE/Expert Parallel Communication Library)</strong></p><p>It comes into play in distributed training scenarios, especially when using Mixture of Experts (MoE) models or expert parallel strategies. It is responsible for enhancing the efficiency of data exchange between multiple GPUs.</p><p>In other words, if different parts (experts) of the model are distributed across different GPUs, DeepEP acts like a high-speed channel between them, ensuring that each GPU quickly transfers the required data and reduces waiting time. This is crucial for the training and deployment of large models, preventing communication from becoming a bottleneck.</p><p><strong>DeepGEMM (FP8 General Matrix Multiplication Library)</strong></p><p>Its role spans the computational process of both training and inference. Most of the computations in LLMs can be reduced to matrix multiplication (such as tensor operations, fully connected layers, etc.). DeepGEMM provides a highly optimized matrix computation library, particularly targeting the low-precision FP8 data format.</p><p>During training, each batch of data undergoes forward propagation and backpropagation, which involve a large amount of matrix multiplication.</p><p>During inference, generating each word also requires matrix operations. DeepGEMM makes these fundamental computations more efficient.</p><p>Therefore, it enhances the model’s computational speed on GPUs and acts as an accelerator for the model’s “arithmetic core.”</p><p><strong>DualPipe (Bidirectional Pipeline Parallel Algorithm)</strong></p><p>It functions in the distributed training of large models, especially when involving pipeline parallelism. Ordinary pipeline parallel training places different layers of the model on multiple GPUs for sequential execution, which may lead to some GPUs being idle and waiting.</p><p>DualPipe, through its bidirectional pipeline design, achieves parallelism of computation and communication overlap, allowing forward computation and backward gradient computation to take place simultaneously on different pipelines. This significantly reduces the idle time of each GPU (referred to as “pipeline bubbles”) and improves overall training throughput.</p><p>For example, when training very large Transformers, DualPipe is equivalent to enabling data to flow bidirectionally through the model’s “assembly line,” maximizing the utilization of each GPU.</p><p><strong>EPLB (Expert Parallel Load Balancer)</strong></p><p>It comes into play during the training of Mixture of Experts (MoE) models. MoE models have many “expert” sub-models distributed across different devices, and different experts may have unbalanced loads (number of samples received).</p><p>If experts on some GPUs are frequently overloaded while others are idle, it will slow down the training. The role of EPLB is to dynamically balance this load. It monitors the workload of each expert and, through means such as replicating hot experts and replica scheduling, distributes the heavy computations to more GPUs, ensuring that each GPU bears a similar workload.</p><p>This helps avoid the “barrel effect” (where the slowest part limits the overall speed) in both training and deployment, allowing the expert modules of large models to be fully utilized.</p><p><strong>3FS (High-Performance Distributed File System)</strong></p><p>It functions at the level of data storage and retrieval, supporting processes such as training data loading and model persistence. Training LLMs requires reading a vast amount of data files, and conventional storage I/O often can’t keep up with the processing speed of GPUs.</p><p>3FS establishes a distributed storage system that leverages high-speed networks and SSDs, essentially equipping the AI cluster with an ultra-high-speed data read-write system. During training, 3FS can read data in parallel from many storage nodes, continuously feeding the computing nodes; during inference deployment, it can also efficiently load model files or process the massive logs produced by the model.</p><p>In short, 3FS ensures that the speed of “consuming data” is fast enough, preventing GPUs from being idle due to waiting for data, and serves as a guarantee for the underlying data supply.</p><h3>3. Goals and Implementation Methods of Each Project</h3><p>Next, we’ll introduce the specific problems each project was designed to address, its design goals, and how it achieves these goals.</p><p><strong>FlashMLA: Efficient Multi-Layer Attention Decoding Kernel</strong></p><p>The goal of FlashMLA is to achieve efficient multi-head attention computation during model inference decoding. For large language models, generating the next word at each step involves using the self-attention mechanism, which consumes a significant amount of video memory and computation. FlashMLA targets this bottleneck for optimization, especially accelerating inference in long-sequence and low-latency scenarios. It is specifically adapted for NVIDIA Hopper architecture GPUs (such as H100) to fully utilize the hardware features of these new GPUs.</p><p>The implementation of FlashMLA draws on the latest optimization techniques from academia. For example, it is inspired by the FlashAttention algorithm: FlashAttention reduces the complexity of attention computation to linear by decreasing the storage of intermediate results and using block-based computation, significantly reducing video memory usage. Building on this, FlashMLA introduces a technology called “Multi-Head Latent Attention (MLA),” which essentially applies a low-rank decomposition method to approximate the attention matrix.</p><p>To put it simply, if traditional attention is likened to a large warehouse full of information, FlashMLA is like finding a way to compress the warehouse, using a much smaller one to accomplish the same storage function. This not only saves space but also makes information retrieval faster. Thanks to more ingenious utilization of the GPU’s parallel capabilities and high-speed video memory, FlashMLA has been measured to achieve extremely impressive throughput on Hopper GPUs (such as processing thousands of GB of data internally per second). From the user’s perspective, its effect is to reduce response delay. For instance, when conversing with a chatbot, previously there might have been slight pauses when generating long responses. With FlashMLA optimization, the model can respond smoothly and quickly to long texts without stuttering. It’s as if the model’s brain has been upgraded, making it smarter and more efficient in understanding and generating language.</p><p><strong>DeepEP: Communication Acceleration Library for MoE/Expert Parallelism</strong></p><p>DeepEP targets the communication efficiency issue in large-scale distributed training. When models adopt a Mixture of Experts (MoE) structure, different expert modules may be located on different GPUs or nodes. Data flows frequently between these experts during each forward or backward computation, and communication delays and bandwidth bottlenecks can severely impact training speed. The goal of DeepEP is to increase the data transfer throughput between GPUs and reduce latency, making multi-GPU collaboration smoother, especially ensuring efficiency in scenarios like MoE that require frequent communication. It also supports low-precision communication (such as FP8), further reducing the amount of data transmitted.</p><p>In terms of implementation, DeepEP provides a set of customized high-speed communication kernels. Within a single machine, multiple GPUs are interconnected via NVLink; across servers, communication is done through RDMA (Remote Direct Memory Access) networks. DeepEP has designed two types of communication modes for different needs: one is high-throughput mode, suitable for batch-transferring large amounts of data (for example, during the model inference prefill phase, distributing a large number of inputs to different experts). DeepEP has optimized the data forwarding from NVLink to RDMA, allowing data transmission between different communication domains to approach the hardware bandwidth limit.</p><p>The other is low-latency mode, suitable for frequent interactions with small amounts of data (such as during the inference decoding phase, communicating with experts at each step). Here, DeepEP provides a pure RDMA extremely low-latency channel and uses a hook mechanism to overlap communication and computation, without occupying GPU computing unit resources.</p><p>In short, DeepEP is like building a highway between GPUs, ensuring that both large volumes of data (cargo) and small data packages (small Tensors) can travel quickly and smoothly. For example, without DeepEP, when your model has different experts on different machines collaborating, there might be a situation of “you wait for me, I wait for you” due to slow network speeds. With DeepEP, each expert is like being equipped with a high-speed conveyor belt, making the overall collaboration much smoother, thereby shortening training time or increasing service concurrency capabilities.</p><p><strong>DeepGEMM: FP8 General Matrix Multiplication Library</strong></p><p>The goal of DeepGEMM is to accelerate the basic computation in deep learning — matrix multiplication operations. Whether it’s the attention calculation in Transformers or the fully connected layers in feedforward networks, large-scale matrix multiplication is involved behind the scenes. NVIDIA GPUs themselves provide efficient matrix operation libraries (such as cuBLAS), but the DeepSeek team chose to customize DeepGEMM, particularly optimizing for <strong>low numerical precision (FP8)</strong>. This is because using lower precision can greatly enhance computation speed and save video memory, but it requires meticulous design to ensure that precision loss does not affect model performance.</p><p>In terms of implementation, DeepGEMM can be seen as a customized matrix computation engine. It supports standard GEMM operations and has made special optimizations for MoE scenarios. For example, in mixed expert models, there are often many small matrix multiplications (since each expert only processes a portion of the data); DeepGEMM may improve the overall utilization of these small matrix operations through means such as parallel scheduling or tensor merging. Additionally, due to the use of the FP8 data type, DeepGEMM employs specific quantization schemes and GPU tensor core instructions to fully leverage the advantages of the Hopper architecture. In actual performance, DeepGEMM can provide very high computation throughput. Its significance is equivalent to equipping the model with a <strong>“matrix computation accelerator.”</strong> For the training process, the cumulative saved computation time translates to a shorter training cycle; for inference, especially in scenarios with batch inference or concurrent requests, faster matrix computation means higher throughput and lower latency. To put it simply, if the model is likened to an accountant who needs to perform countless multiplication calculations, DeepGEMM is like giving this accountant a super high-speed calculator, enabling all multiplications to be completed as quickly as possible while ensuring correctness.</p><p><strong>DualPipe: Bidirectional Pipeline Parallel Algorithm</strong></p><p>Traditional large model training, if using pipeline parallelism, would segment different layers of the model across multiple GPUs, processing data in steps like a factory assembly line. The problem with this method is pipeline idling: when one end of the pipeline is busy (e.g., forward computation), the other end may be waiting (for backward gradients), resulting in underutilization of GPU resources. The design goal of DualPipe is to eliminate or reduce pipeline idling time (bubbles) and maximize the utilization of each GPU. It achieves this by introducing the concept of bidirectional parallelism, meaning that the model’s forward propagation and backward propagation can take place simultaneously at different stages. In other words, while some GPUs in the pipeline are performing forward computation for the nth batch of data, other GPUs can simultaneously perform backward computation for the (n-1)th batch of data. In this way, forward and backward computations flow in opposite directions through the pipeline without interfering with each other.</p><p>The implementation of DualPipe involves fine-grained scheduling of computation tasks and communication. It achieves complete overlap of computation and communication through an innovative pipeline design, meaning that the next step of computation is not blocked while transmitting gradients or activation values. This requires the division and scheduling of micro-batches in deep learning frameworks, allowing the forward and backward passes of different batches to be staggered. Additionally, DualPipe focuses on memory optimization, occupying less video memory compared to early pipeline parallel methods and reducing “bubble” time through decreased synchronization waits.</p><p>Imagine a factory assembly line where, in the past, one had to wait for a car chassis to be assembled before moving it to the next station to install the engine. Now, DualPipe is like opening two tracks on this line: one specifically for transporting cars being fitted with engines, and the other simultaneously returning with car frames that have already had their chassis installed, ensuring that both preceding and following processes are continuously active. For trainers, this means that when training a model of the same scale, DualPipe can significantly shorten the time per iteration, thereby accelerating convergence. In tests by the DeepSeek team, this improved pipeline has led to higher utilization of GPU clusters and a noticeable increase in overall training speed.</p><p><strong>EPLB: Expert Parallel Load Balancer</strong></p><p>In Mixture of Experts (MoE) models, how to evenly distribute the load to experts on different GPUs is a key challenge. DeepSeek’s introduction of EPLB (Expert Parallel Load Balancer) is precisely to address the issue of uneven expert loads. In simple terms, its goal is to keep every GPU “busy and balanced,” preventing any expert from being overloaded or idle. During model training, some experts may become hotspots due to being responsible for a large number of input samples. If these experts’ GPUs are continuously overloaded, not only will they themselves be slow, but they will also drag down the overall synchronization. EPLB avoids this situation by intelligently adjusting the deployment of experts.</p><p>The core idea of EPLB is dynamic replication and placement of experts. Specifically, when it is detected that some experts are handling far more samples than others, EPLB will replicate these “busy experts” and place their replicas on other idle GPUs. In this way, when a large number of samples need to be processed by this expert next time, multiple replicas can share the load in parallel, as if multiple experts have been invited to solve the problem together, naturally distributing the workload. At the same time, EPLB uses heuristic algorithms to decide which GPUs these replicated experts should be placed on, ensuring that the new load distribution is as balanced as possible. For example, it will try to place a group of related experts on the same machine node to reduce cross-node data communication overhead.</p><p>In terms of implementation, EPLB is integrated into DeepSeek’s training framework and automatically calculates an expert replication and placement plan based on the statistically tracked expert invocation frequency. This plan can be adjusted throughout the training process (since different experts may have different levels of activity at different training stages). Through EPLB, every GPU of the large model is utilized as evenly as possible, preventing situations where some cards are busy at 100% while others are idle waiting.</p><p>To put it metaphorically, if the MoE model is likened to a school, with different experts as teachers for different subjects, and students (data) seek answers from the corresponding teachers when they have questions, EPLB is like the principal allocating teaching resources based on the number of times each teacher is asked questions: if a particular subject is too popular and the classroom is overcrowded, an assistant is dispatched to help answer questions, or some students are diverted to another teacher with the same expertise. In this way, all classrooms are full but not overloaded, and the overall teaching progress is the fastest.</p><p><strong>3FS: High-Performance Distributed File System</strong></p><p>Training large models requires not only powerful computing and algorithms but also massive data read-write support. The birth goal of 3FS (Fire-Flyer File System) is to solve the data I/O bottleneck in AI training and inference. It is positioned as a high-performance distributed file system, aiming to fully utilize the capabilities of modern hardware (high-speed SSD drives and high-speed networks) to provide read-write throughput close to the hardware limit for AI tasks.</p><p>In large model training, it is often necessary to continuously read a vast amount of training samples from storage; if the storage can’t keep up, GPUs will be in a waiting state, causing resource waste. Similarly, when saving model checkpoints after training or loading large model files during inference services, high storage performance is also required.</p><p>The implementation of 3FS combines multiple advanced technologies: on one hand, it uses NVMe SSD clusters to store data, distributing the data across many storage nodes; on the other hand, it connects these nodes with RDMA high-speed networks, forming a file system with full-bandwidth parallel access.</p><p>In simple terms, 3FS turns traditional single-machine hard disk reading into “multiple people reading at the same time” — assuming there are hundreds of storage servers, each responsible for a small portion of the data, computing nodes in the AI training cluster can read data in parallel from these hundreds of servers, ultimately converging into an astonishing throughput of several TB per second.</p><p>In the tests published by DeepSeek, with a scale of 180 storage nodes and over 500 client nodes, the total read speed reached approximately 6.6 TiB/s, which is equivalent to reading tens of millions of pages of text content per second! Such high throughput allows even hundreds of billions of training data to be quickly traversed. In addition to high throughput, 3FS has also optimized data sorting, KV caching, and other application patterns (for example, providing a key-value cache read-write capability of 40 GiB per second) to accommodate different AI storage needs. For users, the existence of 3FS is transparent — training scripts read data as they normally would read files, but behind the scenes, 3FS schedules parallel I/O. Therefore, researchers/engineers don’t have to worry about issues like “hard disks not keeping up with GPUs” and can focus on model optimization.</p><p>To put it metaphorically, if training a large model is like burning boilers to smelt steel in a factory, 3FS is the feeder that continuously supplies materials, ensuring that the furnace doesn’t cool down due to waiting for materials. In summary, as an underlying facility, 3FS significantly enhances the efficiency of AI data processing, giving large-scale training and deployment a significant boost.</p><h3>4. One More Thing: An Overview of the DeepSeek-V3/R1 Inference System</h3><p>After open-sourcing the aforementioned multiple core technology projects over five consecutive days, covering areas such as model training, inference optimization, and file systems, and leaving the world in awe with a touch of Eastern mystery, on the sixth day, DeepSeek suddenly announced “One More Thing.” On March 1st, they exclusively released the technical long article “An Overview of the DeepSeek-V3/R1 Inference System” on their official Zhihu account. This article detailed the design details and optimization plans of DeepSeek’s self-developed high-performance inference system for large models and, for the first time, disclosed key data such as costs and benefits in large-scale deployment, sparking industry-wide discussion. The data in the article shows that, based on theoretical pricing, the daily profit margin of DeepSeek’s inference service is as high as <strong>545%</strong>, setting a new record for profitability in the global large model field. This unprecedented “transparent” disclosure showcased DeepSeek’s technical strength and commercial potential, also proving the possibility of achieving a profit-making closed loop in the large model business.</p><p><strong>Design Goals</strong></p><p>According to the official introduction, the design optimization goals of the DeepSeek-V3/R1 inference system are very clear: to pursue “higher throughput and lower latency.” In other words, to process more tokens per unit of time (increasing throughput) while minimizing the response latency of each request to enhance the interactive experience. This goal reflects that the system aims to provide high-concurrency, low-latency large model inference services while ensuring model performance, supporting the practical implementation of large language models.</p><p><strong>Core Technology Implementation</strong></p><p>To achieve the above performance goals, the DeepSeek-V3/R1 inference system has adopted a series of advanced technologies in architecture and engineering, mainly including:</p><ul><li><strong>Large-Scale Cross-Node Expert Parallelism (EP) and Batch Expansion</strong>: For the super large-scale MoE (Mixture-of-Experts) models used by DeepSeek, each layer has 256 experts but only activates 8 of them, making the model highly sparse. This means that a very large overall batch size is required to ensure that each expert has sufficient computational load. To this end, DeepSeek introduced expert parallelism across multiple machines and cards, splitting different “experts” to run on different GPUs, thereby significantly increasing the batch size that can be processed in parallel and fully utilizing the computing power of each card. The EP strategy not only improves the computational efficiency of matrix multiplication, significantly boosting throughput, but also, since each GPU is only responsible for the computation of a few experts, it reduces the memory bandwidth pressure and access latency of individual cards, achieving faster responses. For example, during the Prefill phase, DeepSeek used an EP cluster of 4 nodes (with 9 routing experts + 1 shared expert running on each card), and expanded to 18 nodes (with 2 routing experts + 1 shared expert per card) during the Decode phase, dynamically adjusting the scale of parallelism according to different stages to match the load requirements.</li><li><strong>Computation and Communication Overlap (Overlap) to Hide Communication Overhead</strong>: Large-scale distributed expert parallelism brings significant cross-node communication overhead. To prevent communication from becoming a bottleneck, DeepSeek carefully designed a mechanism for parallel computation and communication in the inference process: by using a “double batch” pipeline interleaving, one batch is computed while the other is being communicated, thus using computation time to mask communication latency. Specifically, during the Prefill phase, the system processes two batches of data simultaneously, with one batch undergoing forward computation while the data transfer for the other batch is carried out in parallel, hiding communication delays. During the Decode phase, due to different computation times for various parts, the attention component is split into two sub-stages, forming a total of 5 pipeline stages, allowing for full overlap of computation and communication. This computation/communication overlap strategy greatly reduces the pure waiting time for communication, overall improving the inference throughput rate.</li><li><strong>Global Load Balancing Optimization</strong>: In a large-scale cluster using a combination of data parallelism (DP) and expert parallelism (EP), if some GPUs bear excessive computational or communication loads, it will slow down the entire system, while other GPUs may be idle waiting, leading to resource waste. To address this, DeepSeek introduced dynamic load balancing algorithms for different levels of parallelism. In batch allocation, it ensures that the number and length of requests in different data parallel shards are as balanced as possible, ensuring that the attention computation and routing communication loads on each GPU are comparable, preventing individual nodes from slowing down due to overly long or numerous requests. In caching and decoding, it ensures that the KVCache cache usage and the number of sequences to be generated on each GPU are roughly equal, balancing the load of attention computation and result transmission. In expert allocation, for the issue of certain “heavyweight” experts being frequently activated, it adjusts the distribution of experts across different GPUs, preventing a few cards from always handling the most time-consuming experts, thus making the expert computation load on each card roughly equivalent. Through these strategies, the system achieves as balanced a load as possible for each GPU in terms of computation and communication, preventing the “barrel effect,” and fully extracting the overall computing power of the cluster. It’s worth mentioning that on the second day of Open Source Week, DeepSeek also open-sourced the DeepEP communication library. This is the industry’s first communication library for expert parallelism in MoE model training and inference, supporting NVLink and RDMA networks and compatible with low-precision FP8 communication. DeepEP effectively optimizes data transmission between multi-expert models, reducing communication latency and resource consumption, and improving the overall efficiency of MoE large model training and inference. This open-source tool is one of the key implementation foundations for the aforementioned EP parallel strategy, meaning that other researchers in the community can also use similar technologies to build and optimize their own MoE large models.</li></ul><p><strong>Performance and Cost Metrics</strong></p><p>Thanks to the above design, the DeepSeek-V3/R1 inference system has achieved outstanding performance and cost-effectiveness metrics. In actual deployment, each computing node equipped with 8 Nvidia H800 GPUs can process an average of approximately 73,700 input tokens and 14,800 output tokens per second. Under peak load, DeepSeek’s online service utilized about 278 nodes (an average of about 227 nodes) to provide inference services. Even with an estimated rental cost of $2 per GPU per hour, the daily operating cost is about $87,000. However, based on the pricing of DeepSeek R1 commercial services (charging $0.55 per million input tokens and $2.19 per million output tokens, etc.), theoretically, a daily income of about $5.62 million can be achieved, corresponding to an astonishing cost profit margin of <strong>545%</strong>. However, the official statement also acknowledged that this is an ideal estimate, and the actual revenue will be lower than the theoretical value due to DeepSeek V3’s low-price strategy, the proportion of free requests, and nighttime off-peak discounts. Nevertheless, such a high potential profit margin fully demonstrates the great success of this efficient inference system in reducing the cost of large model inference.</p><p>To ensure consistent inference quality with training, DeepSeek has also taken strict measures in terms of precision and data processing: the inference service uses the same numerical precision as model training, with matrix computation and routing communication using the FP8 format, and core attention computation and result aggregation communication using the BF16 format, maximizing the consistency of inference effects with training. In addition, the system utilizes disk KVCache caching to store part of the historical inference key-value pairs, with as high as 56.3% of input tokens directly hitting the cache within the statistical period, avoiding redundant computation and further reducing computing power consumption. In terms of cluster scheduling, DeepSeek has established a day-and-night resource allocation mechanism: during the daytime peak period, all nodes are used for online inference services, while during the nighttime off-peak period, the number of inference nodes is reduced, and idle GPUs are switched to model research and continued training to maximize hardware utilization. These engineering strategies enable DeepSeek to compress resource costs to the extreme while ensuring service performance.</p><p><strong>Impact and Significance for LLM Training and Inference</strong></p><p>What DeepSeek’s “One More Thing” release has showcased is not only the technical details of its own inference system but also a new paradigm for efficient large model inference to the industry. For the inference of large language models (LLMs), this solution has proven that through innovative parallel architectures and optimization strategies, inference throughput can be significantly increased, latency and costs can be reduced, thereby making it possible to run super large-scale models on conventional hardware investments. In other words, even sparse large models composed of hundreds of billions of parameters and numerous experts can be provided as online services in an economically feasible way. Many netizens have compared DeepSeek’s data with that of OpenAI and others, marveling at “a 545% profit margin — does this mean the services we used before had a lot of markup in their pricing?”. Indeed, the performance/cost ratio published by DeepSeek has set a new benchmark for the industry, showing that large model inference is not something only giants can afford, and small and medium-sized teams can also significantly reduce inference costs through technological innovation. As industry analysts have pointed out, DeepSeek’s open-source strategy and cost control capabilities are breaking the resource monopoly in the AI field, and the commercial feasibility of its technological approach has been verified — the profit-making closed loop of large models is moving from an ideal to reality.</p><p>For LLM training, DeepSeek’s expert parallel technology also has reference significance. Large model training is often limited by the memory and computing power of a single machine, and the EP approach provides a method for horizontally expanding model capacity: by splitting different experts to train collaboratively on multiple cards or even multiple machines, larger and more sparse models can be trained without exceeding the resource limits of a single machine. The DeepEP communication library and other tools provided during this Open Source Week offer infrastructure support for researchers to practice large-scale distributed training of MoE models. This means that the community can accelerate the development of high-performance, low-cost large models based on DeepSeek’s experience. As comments have stated, DeepSeek’s unreserved open-source of underlying technologies, and even the transparent sharing of profit data, demonstrate strong technical confidence. This is not only a victory for DeepSeek itself but also for the domestic AI industry. With these publicly available advanced technologies, more high-performance, low-cost large models will undoubtedly be trained and put into application in the future, promoting the popularization and development of artificial intelligence large models.</p><p>The industry generally believes that DeepSeek’s release this time is of milestone significance: it has proven to the industry that the threshold for large model training and deployment can be significantly reduced through technological innovation, accelerating the virtuous cycle development of the open-source large model ecosystem.</p><h3>5. Spring Has Come</h3><p>Through Open Source Week, DeepSeek has demonstrated to the world their profound engineering capabilities in building LLM training and inference systems. These innovations span the underlying aspects of computing systems such as computation, storage, communication, and algorithms, which are often considered weak links in Chinese technology. It can be seen that we are catching up and even surpassing in these areas, which is very inspiring. The spring scenery outside the window is in full bloom, with plum blossoms, cherry blossoms, peach blossoms, pear blossoms, and apricot blossoms… either in bloom or about to bloom, it’s springtime.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4d7fe583c907" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[AI Practice] Lessons in Cognitive Enhancement from DeepSeek-R1]]></title>
            <link>https://medium.com/@ai-data-drive/ai-practice-lessons-in-cognitive-enhancement-from-deepseek-r1-7f687eb64c32?source=rss-5140c0782d6f------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f687eb64c32</guid>
            <category><![CDATA[deepseek-r1]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Andy Yang]]></dc:creator>
            <pubDate>Sun, 26 Jan 2025 12:35:16 GMT</pubDate>
            <atom:updated>2025-01-26T12:35:16.920Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rWFAOtEn_8hJ_ne698UREg.jpeg" /></figure><h3>Prologue</h3><p>DeepSeek recently launched its R1 model, a large model similar to OpenAI’s o1, with enhanced reasoning capabilities. Unlike o1, which obscures the details of the machine’s thought process, R1 openly displays its thought process for all to see:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ketto-p1Y0appvegMZ4nWg.jpeg" /><figcaption>R1’s thinking process</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z0lTRxv5QppZAOe8mvHyRg.jpeg" /><figcaption>No thinking details of o1</figcaption></figure><p>Since AI can provide high-quality answers to any question from users (models at least at GPT-4’s level already surpass human averages on most evaluation sets), its thought process is highly worth studying for ordinary people like us. This sparked my curiosity about how AI tackles a question.</p><p>After engaging in numerous conversations with DeepSeek and observing its thought process for a long time, I conducted an experiment: asking the AI to summarize its thought process with the aim of deriving a general framework that could inspire my own thinking.</p><p>Here are the details.</p><h3>Step 1: Conversing with R1 to Experience Its Thought Process</h3><p>By interacting with DeepSeek in “DeepThink” mode:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tPFCWkuH2oY9-KdV3zFtNg.png" /></figure><p>You can observe its detailed thought process:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tbRk9zkXiUiUV3HV67-Ufw.jpeg" /></figure><p>When asking questions, it’s best to use English. From my observations, the same question in English generates longer thought processes and takes more time compared to asking in Chinese. For example, the question “What is Jenkins?” took DeepSeek R1 22 seconds to think, producing 5,153 English characters. Meanwhile, the Chinese version, “什么是Jenkins,” only took 5 seconds and resulted in 616 Chinese characters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7EZez--g1qzb6DcuD7tpPg.png" /></figure><p>To avoid random noise from a single observation, I conducted similar tests with other questions and found consistent results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*14SCHh-R6-qZ6DQ0ton3mQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JiYX2aoNJ1Mel1wkC_LuRQ.png" /></figure><p>Possible reasons might include:</p><ul><li>Chinese is more concise, so fewer tokens are generated.</li><li>The AI model’s primary language is English, with over 90% of training data in English, making it more suitable for reasoning.</li><li>English materials present reasoning processes more elaborately compared to Chinese, as evidenced by thicker English textbooks.</li></ul><p>Whatever the reason, it’s best to use English when interacting with AI.</p><h3>Step 2: Collecting R1’s Thought Process Data</h3><p>Engage in a series of dialogues with the AI and collect its thought process. For instance, due to my work involving Jenkins, a CI/CD (Continuous Integration/Deployment) tool, I asked DeepSeek R1 the following questions:</p><ul><li>What is Jenkins?</li><li>Give me a simple Python example using Jenkins for CI/CD.</li><li>Are there any alternatives to Jenkins for CI/CD?</li><li>Why do we need Jenkins or other CI/CD tools?</li></ul><p>I gathered these questions along with DeepSeek’s thought processes into a text file, forming “User Question” and “AI Thinking” reasoning pairs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*A267chlbjnQNa8y7.png" /></figure><h3>Step 3: Letting R1 Analyze Its Own Thought Process</h3><p>Next, I uploaded the reasoning pairs to R1 and prompted it to analyze as follows:</p><blockquote>Read the text of attachment file, which contains 4 User Question &amp; AI Thinking pairs. The AI Thinking parts are the results of thinking process of a smart AI system. I want to figure out how AI thinking works.</blockquote><blockquote>1. Can you read/research the text and decode the thinking process of AI？Output it in ‘Thinking Process’ part.<br>2. Figure out the system prompt of this AI. Output it in ‘System Prompt’ part.</blockquote><blockquote>Give the answer in markdown format.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G_q_WllwE1OThuATx8p_NQ.png" /></figure><p>R1’s analysis included the following stages:</p><ul><li>Question Parsing</li><li>Knowledge Retrieval</li><li>Structured Breakdown</li><li>Anticipation of User Needs</li><li>Verification and Expansion</li><li>Contextualization</li><li>Summarization</li></ul><p>Details are as follows (visualized with XMind from R1’s Markdown output):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1ztMNO3Mxerya4QBv92JOQ.png" /></figure><h3>Insights from AI’s Thought Process</h3><p>The framework above offered me several insights:</p><ul><li>Analyzing a problem should be based on thorough exploration of needs (especially latent ones) and sufficient knowledge background research (systematic knowledge retrieval).</li><li>Structured decomposition should consider the scenario, as different scenarios require unique approaches, underscoring the value of domain expertise.</li><li>It’s essential to design validation mechanisms to ensure outputs withstand scrutiny.</li><li>Outputs should provide context and examples to ensure comprehension.</li></ul><p>R1 also provided a guide for crafting prompts that enable AI to think effectively:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E2k507CNHC1NW3zS0HeiGw.png" /></figure><p>Upon further inquiry, R1 elaborated on the possible theoretical basis for this thought process:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kNl3RYYSlIzjSvXRcSbSRw.png" /></figure><p>These theoretical references can serve as reading materials for studying cognitive science.</p><h3>Conclusion</h3><p>AI’s reasoning process is truly fascinating. The framework above is merely a rough outline derived from a few examples. More reasoning data can be collected for deeper analysis, leading to a better understanding of our own thinking. This iterative exploration may pave the way for new methods in cognitive science research.</p><p>You can try it too.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f687eb64c32" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>