<?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 Abdulmajeed Alroumi on Medium]]></title>
        <description><![CDATA[Stories by Abdulmajeed Alroumi on Medium]]></description>
        <link>https://medium.com/@alroumi.abdulmajeed?source=rss-4f2f77d947cf------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*mp6kpW3x0SnhA0h6.jpg</url>
            <title>Stories by Abdulmajeed Alroumi on Medium</title>
            <link>https://medium.com/@alroumi.abdulmajeed?source=rss-4f2f77d947cf------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 19:00:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@alroumi.abdulmajeed/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How I Built My First Agent-to-Agent (A2A) AI: Manga Localization, On-Chain]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@alroumi.abdulmajeed/how-i-built-my-first-agent-to-agent-a2a-ai-manga-localization-on-chain-4c3ee4acbf50?source=rss-4f2f77d947cf------2"><img src="https://cdn-images-1.medium.com/max/1456/0*RrLEhDN4CJqHWLRW.png" width="1456"></a></p><p class="medium-feed-snippet">The wild part first</p><p class="medium-feed-link"><a href="https://medium.com/@alroumi.abdulmajeed/how-i-built-my-first-agent-to-agent-a2a-ai-manga-localization-on-chain-4c3ee4acbf50?source=rss-4f2f77d947cf------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@alroumi.abdulmajeed/how-i-built-my-first-agent-to-agent-a2a-ai-manga-localization-on-chain-4c3ee4acbf50?source=rss-4f2f77d947cf------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c3ee4acbf50</guid>
            <dc:creator><![CDATA[Abdulmajeed Alroumi]]></dc:creator>
            <pubDate>Mon, 13 Jul 2026 05:59:21 GMT</pubDate>
            <atom:updated>2026-07-13T05:59:21.624Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[From Real-Time Data to Decision Support: A Roadmap for AI-Native Airline Operations]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@alroumi.abdulmajeed/from-real-time-data-to-decision-support-a-roadmap-for-ai-native-airline-operations-bd5eaadb4a55?source=rss-4f2f77d947cf------2"><img src="https://cdn-images-1.medium.com/max/1672/1*Hh0g8VrO19lfR3HYcZ6pOw.png" width="1672"></a></p><p class="medium-feed-snippet">The more interesting opportunity is how AI can support real-time operational and commercial decisions.</p><p class="medium-feed-link"><a href="https://medium.com/@alroumi.abdulmajeed/from-real-time-data-to-decision-support-a-roadmap-for-ai-native-airline-operations-bd5eaadb4a55?source=rss-4f2f77d947cf------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@alroumi.abdulmajeed/from-real-time-data-to-decision-support-a-roadmap-for-ai-native-airline-operations-bd5eaadb4a55?source=rss-4f2f77d947cf------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd5eaadb4a55</guid>
            <dc:creator><![CDATA[Abdulmajeed Alroumi]]></dc:creator>
            <pubDate>Sat, 02 May 2026 13:33:33 GMT</pubDate>
            <atom:updated>2026-05-02T13:33:33.124Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Improving LLM Reasoning with DPO: From Concept to End-to-End Pipeline]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@alroumi.abdulmajeed/improving-llm-reasoning-with-dpo-from-concept-to-end-to-end-pipeline-831859889ebb?source=rss-4f2f77d947cf------2"><img src="https://cdn-images-1.medium.com/max/1536/1*lPqComf3ErYACNIoFb19lw.png" width="1536"></a></p><p class="medium-feed-link"><a href="https://medium.com/@alroumi.abdulmajeed/improving-llm-reasoning-with-dpo-from-concept-to-end-to-end-pipeline-831859889ebb?source=rss-4f2f77d947cf------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@alroumi.abdulmajeed/improving-llm-reasoning-with-dpo-from-concept-to-end-to-end-pipeline-831859889ebb?source=rss-4f2f77d947cf------2</link>
            <guid isPermaLink="false">https://medium.com/p/831859889ebb</guid>
            <dc:creator><![CDATA[Abdulmajeed Alroumi]]></dc:creator>
            <pubDate>Wed, 08 Apr 2026 08:23:37 GMT</pubDate>
            <atom:updated>2026-04-08T08:23:37.532Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[ZenML, the Orchestrator Behind LLMOps]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@alroumi.abdulmajeed/zenml-the-orchestrator-behind-llmops-b04d2b636f44?source=rss-4f2f77d947cf------2"><img src="https://cdn-images-1.medium.com/max/2400/0*BAg2tMMHnQyjQ2I6.png" width="2400"></a></p><p class="medium-feed-snippet">Introduction</p><p class="medium-feed-link"><a href="https://medium.com/@alroumi.abdulmajeed/zenml-the-orchestrator-behind-llmops-b04d2b636f44?source=rss-4f2f77d947cf------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@alroumi.abdulmajeed/zenml-the-orchestrator-behind-llmops-b04d2b636f44?source=rss-4f2f77d947cf------2</link>
            <guid isPermaLink="false">https://medium.com/p/b04d2b636f44</guid>
            <dc:creator><![CDATA[Abdulmajeed Alroumi]]></dc:creator>
            <pubDate>Fri, 22 Aug 2025 16:59:56 GMT</pubDate>
            <atom:updated>2025-08-22T16:59:56.951Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Building Smart Agents with Google Cloud Agent Builder — A Step-by-Step Guide]]></title>
            <link>https://medium.com/@alroumi.abdulmajeed/building-smart-agents-with-google-cloud-agent-builder-a-step-by-step-guide-d31959754c04?source=rss-4f2f77d947cf------2</link>
            <guid isPermaLink="false">https://medium.com/p/d31959754c04</guid>
            <dc:creator><![CDATA[Abdulmajeed Alroumi]]></dc:creator>
            <pubDate>Mon, 14 Apr 2025 11:37:07 GMT</pubDate>
            <atom:updated>2025-04-14T11:37:07.086Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Building Smart Agents with Google Cloud Agent Builder — A Step-by-Step Guide</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8QdGEZVW_28Igvuu" /></figure><h3>Introduction: GCP Lands in Saudi Arabia — Why It Matters</h3><p>In a significant move that marks a new era of cloud computing in the Middle East, <strong>Google Cloud Platform (GCP)</strong> has officially launched its services in <strong>Saudi Arabia</strong>. This is more than just a technological milestone — it’s a game changer for startups, enterprises, government entities, and individual developers who now have access to world-class infrastructure with lower latency and full compliance to local data residency regulations.</p><p>As businesses increasingly shift to cloud-native architectures, the demand for smart, automated, and scalable digital solutions is surging. Among the many powerful tools that GCP offers, <strong>Agent Builder</strong> stands out as a must-know platform for creating intelligent conversational agents (chatbots, voice assistants, etc.) with minimal coding effort. Whether you’re streamlining customer service or building next-gen digital assistants, Agent Builder makes it easier than ever.</p><p>This blog will walk you through how to create your own agent using <strong>Google Cloud’s Agent Builder</strong>, with clear visuals and a practical, real-world approach. Let’s dive in.</p><ol><li>Introduction to Agent</li><li>What is Agent Builder in GCP?</li><li>How to create Agent builder in GCP (step-by-step)</li><li>Conclusion</li></ol><h3>Introduction to Agent</h3><p>Imagine having a digital teammate, one that never sleeps, answers instantly, understands your questions, and can perform tasks on your behalf. That, in essence, is what an <strong>agent</strong> is in the world of artificial intelligence.</p><p>In technical terms, an agent is a virtual, AI-powered entity that interacts with users using natural language. But in practice, it’s much more than that. It’s the helpful bot that tracks your lost order, the assistant that helps you book flights, and increasingly, the AI brain behind your favorite smart apps.</p><p>In the age of <strong>Large Language Models (LLMs)</strong> like GPT and PaLM, agents have become even more intelligent. Powered by LLMs, modern agents are not just keyword matchers ,they understand context, carry conversations across multiple turns, learn user preferences, and even reason through problems. Think of them as the front-end persona of much deeper AI systems, capable of interfacing with APIs, databases, or even other agents.</p><p>Agents today can:</p><ul><li><strong>Interpret and respond</strong> to human language (text or voice)</li><li><strong>Make decisions</strong> based on goals, rules, or previous context</li><li><strong>Perform actions</strong> like retrieving information, submitting forms, or triggering backend workflows</li><li><strong>Learn and adapt</strong> based on new input</li></ul><p>And the beauty? You don’t need to build all this from scratch. Tools like <strong>Google Cloud’s Agent Builder</strong> make it incredibly easy to create such intelligent assistants visually and rapidly. You can define what the agent knows, how it speaks, what actions it takes, and where it lives — be it on your website, app, or messaging platform.</p><p>So before we dive into how to build one, keep this in mind: an agent is not just a chatbot. It’s your AI-powered interface to the digital world.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Sii8n4rTAMB6lu_W" /></figure><h3>What is Agent Builder in GCP?</h3><p><strong>Agent Builder</strong> is part of GCP’s Dialogflow CX suite — a platform designed to help you create powerful and intuitive conversational experiences. Unlike traditional bot-building frameworks that require complex coding, Agent Builder provides a visual flow-based interface that simplifies intent mapping, context handling, and response generation.</p><p>Whether you’re developing a simple FAQ bot or a complex multi-turn dialogue agent, Agent Builder allows you to:</p><ul><li>Design conversations using drag-and-drop flows</li><li>Handle natural language understanding (NLU)</li><li>Integrate with external APIs</li><li>Connect to platforms like websites, WhatsApp, Messenger, and more</li></ul><h3>How to Create Agent Builder in GCP (Step-by-Step)</h3><p>Below is a visual and descriptive guide to building your first agent from scratch using GCP Agent Builder.</p><h4>Step 1: Go to Agent Builder</h4><p>From the Google Cloud Console, simply type “Agent Builder” in the search bar at the top. Once it appears in the results, click on it to open the Agent Builder interface.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K9u_F3UNn2gKeAisvDTZhA.png" /></figure><h4>Step 2: Create a New Agent</h4><p>Once you’re inside the Agent Builder interface, click on the <strong>“CREATE APP”</strong> button under the “Apps” section to start building a new agent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/262/1*w8tvfRlfwxojaeQpiLE4Xw.png" /></figure><h4>Step 3: Choose the App Type</h4><p>After clicking “Create App,” you’ll be prompted to select the type of application you want to build. Each type has a distinct use case depending on the data source and interaction goals.</p><p>Here’s a quick breakdown of the options:</p><ul><li><strong>Search for your website</strong>: Ideal for helping users navigate and search through public websites or internal documentation hosted on platforms like BigQuery or Google Cloud Storage.</li><li><strong>Media search</strong>: Best suited for media-rich applications. It enables users to search across image, video, and audio libraries.</li><li><strong>Healthcare search</strong>: Tailored for healthcare-related data (e.g., medical records or guidelines). It emphasizes data security and compliance.</li><li><strong>Search for commerce</strong>: Designed for retail environments to help users search product catalogs using the Retail Search API.</li><li><strong>Custom search</strong>: Offers full flexibility by allowing you to connect to multiple data sources like BigQuery, Google Workspace, or Cloud Storage. This is ideal if you want full control over your data and how it’s queried.</li></ul><p>For most general-purpose virtual agents, “Search for your website” or “Custom search” are the go-to options.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZW7TKRWR3rX0yh205mPo-A.png" /></figure><h4>Step 4: Configure Your App Settings</h4><p>After selecting the type of agent you’d like to build (e.g., “Search for your website”), the next step is configuring your application settings.</p><p>Here’s what you’ll see:</p><ul><li><strong>Enterprise edition features</strong>: Enables high-performance capabilities such as:</li></ul><blockquote><strong>Extractive answers</strong> pulled verbatim from your documents</blockquote><blockquote><strong>Image-based search</strong> using image queries</blockquote><blockquote><strong>Website search</strong> with low-latency indexing. This is essential if you’re building an agent that relies heavily on precise document responses or rich media search.</blockquote><ul><li><strong>Advanced LLM features</strong>: Activates enhanced AI capabilities like:</li></ul><blockquote><strong>Search summarization</strong>: Summarizes long responses or pages for quicker understanding</blockquote><blockquote><strong>Follow-up queries</strong>: Maintains context through multiple user inputs, making conversations more natural</blockquote><p>Finally, name your app and company. These names help identify your agent and personalize the responses or branding.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OSO7O5D7mjWjg_sf6uH8SQ.png" /></figure><h4>Step 5: Create and Connect a Data Store</h4><p>Now that the agent’s configuration is ready, you need to provide it with data. Click on <strong>“CREATE DATA STORE”</strong> to begin. This data store is the backbone of your agent’s knowledge — it’s where the documents, websites, and structured data you’ll use for answering queries live.</p><p>This step is critical for search-based or knowledge-based agents, as it allows your agent to retrieve relevant, accurate, and real-time answers based on indexed content.</p><p>You can later specify the type of data source (e.g., web URLs, documents from Cloud Storage, or BigQuery tables) that you want your agent to tap into.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/615/1*nmF2GUZrYQ3aQoiWVIDMJQ.png" /></figure><h4>Step 6: Select Your Data Source</h4><p>In this step, you’ll choose the type of data your agent will connect to. GCP gives you several powerful options:</p><ul><li><strong>Website Content</strong>: Crawls and indexes data from public URLs</li><li><strong>BigQuery</strong>: Connects to structured analytics and business data</li><li><strong>Cloud Storage</strong>: Lets you upload and query files like PDFs or text</li><li><strong>API</strong>: Pulls data dynamically via an API call</li><li><strong>Cloud SQL / Firestore / Bigtable / Spanner / AlloyDB</strong>: Useful for highly structured databases across different use cases</li></ul><p>Choose the source that best fits where your data currently lives. For example, if you’re building an internal knowledge bot, Cloud Storage or BigQuery are often ideal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1021/1*182QYyDZebjOiHkROErlMg.png" /></figure><h4>Step 7: Import and Structure the Data</h4><p>After selecting your data source (e.g., Cloud Storage), you need to define what kind of data you’re importing. You’ll be presented with options such as:</p><ul><li><strong>Unstructured documents</strong> (PDF, HTML, TXT)</li><li><strong>Structured data</strong> (JSONL)</li><li><strong>Structured media data</strong> (JSONL with media)</li><li><strong>Linked unstructured docs</strong> with metadata</li><li><strong>Structured FAQ</strong> for chatbot-style agents</li><li><strong>Healthcare data</strong> for medical use cases</li></ul><p>Select what best fits your dataset. For general-purpose knowledge agents, unstructured documents are often the go-to.</p><p>Also choose the <strong>synchronization frequency</strong>:</p><ul><li><strong>One-time</strong>: Best for static documents</li><li><strong>Periodic</strong>: Use if your data is regularly updated and you want the agent to stay in sync</li></ul><p>Then, point to your file or folder using a Cloud Storage URI (e.g., gs://your-bucket-name/...).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gu3p1iTdkLRE-ju9g0THqQ.png" /></figure><h4>Step 8: Finalize Your Data Store Configuration</h4><p>In this step, you finalize your data store setup:</p><ul><li><strong>Location</strong>: Choose the region closest to your users for optimal performance. Since GCP has a data center in <strong>Dammam</strong>, Saudi Arabia, select <strong>me-central2</strong> for lower latency, regional compliance, and faster response times.</li><li><strong>Data store name</strong>: Give it a unique, meaningful name. This ID will be generated and <strong>cannot be changed later</strong>, so choose carefully.</li><li><strong>Access Control (Optional)</strong>: You can enable access control if you’re handling sensitive documents.</li><li><strong>Document Processing Options</strong>: Customize how documents are parsed, tokenized, or handled in the backend.</li><li><strong>Gen AI Options</strong>: Enable or tweak LLM capabilities related to summarization, chat-based querying, or relevance ranking.</li></ul><p>Once everything is filled in, click <strong>CREATE</strong> to complete the data store setup.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OWXZQCgZ0pBZASM8B-AlxQ.png" /></figure><h4>Step 9: Document Parsing and Chunking Configuration</h4><p>Before you hit the final “CREATE,” you’ll want to configure how your documents are processed.</p><ul><li><strong>Document Parser</strong>:</li></ul><blockquote><strong>Digital Parser</strong>: Best for clean, structured text (e.g., HTML, PDFs with embedded text)</blockquote><blockquote><strong>OCR Parser</strong>: Use this when your documents are scanned or image-based PDFs</blockquote><blockquote><strong>Layout Parser</strong>: Ideal for documents where formatting and layout carry meaning (e.g., tables, invoices)</blockquote><ul><li><strong>Chunking</strong>: You can also choose to <strong>enable advanced chunking configuration</strong> if you want to control how your document is broken into segments for indexing and retrieval. Once set, this cannot be changed later.</li></ul><p>This step ensures your agent will understand and retrieve content as accurately and efficiently as possible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/1*UlDEzCOLfxeZXCQiab1NOA.png" /></figure><h4>Step 10: Advanced Chunking Options</h4><p>Chunking refers to how documents are broken into pieces or “chunks” for easier retrieval and semantic understanding by LLMs. When you enable <strong>Advanced Chunking</strong>, you can:</p><ul><li><strong>Set a chunk size limit</strong> (in tokens): This determines how much content each chunk contains. A typical size like <strong>500 tokens</strong> balances context and performance.</li><li><strong>Include ancestor headings in chunks</strong>: Useful when you want to preserve section titles or hierarchies for more contextual responses.</li></ul><p>Proper chunking boosts the accuracy of answer generation by helping the AI retrieve the most relevant content slices.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/415/1*uH3sWlcIX3lVsEYjo0T3gA.png" /></figure><h4>Step 11: Verify Your Data Store Setup</h4><p>Once the data store is created, you’ll be directed to a dashboard overview. Here you can verify the following:</p><ul><li><strong>Type</strong>: Confirms whether your data is unstructured or structured</li><li><strong>Region</strong>: Should reflect your selected location (e.g., me-central2 for Saudi Arabia)</li><li><strong>Serving state</strong>: Should be <strong>Enabled</strong> if your data store is live</li><li><strong>Last document import</strong>: Shows the most recent ingestion timestamp</li><li><strong>Exclude from Gen AI</strong>: Indicates whether the data is accessible by Gen AI features</li></ul><p>You can also navigate to <strong>Documents</strong>, <strong>Activity</strong>, and <strong>Processing Config</strong> to dive deeper into your data’s health and configuration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/538/1*FXPUb21UQ6nYuifTfvrT8A.png" /></figure><h4>Step 12: Test Your Agent in Preview Mode</h4><p>Now it’s time to see your agent in action. Head to the <strong>Preview</strong> tab from the sidebar. This is where you can simulate user interactions by typing queries into the search bar.</p><p>This feature lets you:</p><ul><li>Verify how your agent retrieves answers</li><li>Check if document indexing is working as expected</li><li>Evaluate LLM summarization and follow-up behavior (if enabled)</li></ul><p>It’s a powerful sandbox to catch errors, fine-tune responses, and validate the agent before going live.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qH42Ph6I195z6Y-FQWsibw.png" /></figure><h4>Step 13: Choose and Tune Your Language Model</h4><p>Under the <strong>Configurations</strong> tab, you can specify which <strong>Large Language Model (LLM)</strong> powers your summarization and interaction logic. This is where you select from the latest <strong>Gemini models</strong> provided by Google.</p><p>Options include:</p><ul><li><strong>Stable</strong> (default)</li><li><strong>Gemini 2.0 Flash 1 (NEW)</strong> — optimized for fast and accurate Q&amp;A</li><li><strong>Gemini 1.5 Flash / Pro / Pro 2</strong> — offers larger context windows and refined summarization</li></ul><p>You can also:</p><ul><li>Set the <strong>number of top results</strong> used to build a summary</li><li>Toggle between different models to evaluate performance in real time</li></ul><p>This is one of the most powerful parts of Agent Builder, enabling fine control over how smart and responsive your assistant can be.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_hhpd8o1V86aNT3a-X67nQ.png" /></figure><p>Still in the <strong>UI</strong> tab under <strong>Configurations</strong>, you’ll find options to tailor the user search experience. You can choose from three types:</p><ul><li><strong>Search</strong>: Traditional search results with no LLM summarization</li><li><strong>Search with an Answer</strong>: Adds a generative summary above search results (great for quick insights)</li><li><strong>Search with Follow-ups</strong>: Enables conversational AI with generative summaries and context-aware follow-up questions</li></ul><p>For AI-rich applications, “Search with Follow-ups” delivers the most intuitive and chat-like experience.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*38Xuv66tVArCsDgQ_X_aGQ.png" /></figure><h4>Step 15: Customize the Summary and Suggestions</h4><p>Still in the <strong>UI Configuration</strong> section, you can fine-tune how the summary appears and behaves.</p><p>Key options include:</p><ul><li><strong>Customize the summary</strong>: You can instruct the LLM to adjust tone, verbosity, or format. Example: “Make responses friendly and concise.”</li><li><strong>Summary language</strong>: Set the language for generated summaries. Use <strong>Auto-detect</strong> or choose a specific one like Arabic.</li><li><strong>Enable related questions</strong>: Let the system offer follow-up questions to guide the user journey.</li><li><strong>Ignore ‘no answer’ summaries</strong>: Prevents showing a default “no answer” message if the system can’t find results.</li></ul><p>These settings ensure your assistant’s output feels aligned with your brand voice and user expectations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/475/1*knn2lP8_vFzLrdzts2HXEQ.png" /></figure><h4>Step 16: Deploy and Experience Your Agent</h4><p>With everything set up — from data ingestion to UI configuration — your agent is now ready to go live!</p><p>Here’s what deployment looks like:</p><ul><li><strong>Real queries in action</strong>: Start asking your agent real-world questions just like an end-user would.</li><li><strong>Fallback behavior</strong>: If the model can’t generate a summary, the system automatically returns traditional search results and helpful follow-up suggestions (as shown below).</li><li><strong>Live data integration</strong>: The agent pulls content directly from your configured data store — whether PDF documents, structured tables, or websites.</li></ul><p>This final step gives you and your users the full AI-powered search experience you’ve built — resilient, dynamic, and informative.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*JjYrQyDcdhKyvg2jR05M1Q.png" /></figure><h3>Conclusion</h3><p>The arrival of Google Cloud in Saudi Arabia isn’t just a technical upgrade ,it’s a signal for the region to take bold steps toward innovation and automation. With tools like Agent Builder, building intelligent, scalable, and localized virtual assistants has never been more accessible.</p><p>Whether you’re a product manager, developer, or business owner, understanding how to build and deploy smart agents is now a critical skill in your digital transformation toolkit.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d31959754c04" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[البحث الدلالي والتوليد المدعوم بالاسترجاع (RAG)]]></title>
            <link>https://medium.com/@alroumi.abdulmajeed/%D8%A7%D9%84%D8%A8%D8%AD%D8%AB-%D8%A7%D9%84%D8%AF%D9%84%D8%A7%D9%84%D9%8A-%D9%88%D8%A7%D9%84%D8%AA%D9%88%D9%84%D9%8A%D8%AF-%D8%A7%D9%84%D9%85%D8%AF%D8%B9%D9%88%D9%85-%D8%A8%D8%A7%D9%84%D8%A7%D8%B3%D8%AA%D8%B1%D8%AC%D8%A7%D8%B9-rag-01391f52406b?source=rss-4f2f77d947cf------2</link>
            <guid isPermaLink="false">https://medium.com/p/01391f52406b</guid>
            <dc:creator><![CDATA[Abdulmajeed Alroumi]]></dc:creator>
            <pubDate>Sun, 02 Feb 2025 06:30:06 GMT</pubDate>
            <atom:updated>2025-02-02T06:30:06.315Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>الفهرس:</strong></h3><ol><li>مقدمة</li><li>البحث الدلالي (Semantic Search) و RAG</li></ol><ul><li>Dense Retrieval</li><li>إعادة الترتيب (Reranking)</li><li>RAG</li></ul><p>3. تفاصيل تقنية</p><ul><li>Dense Retrieval</li><li>إعادة الترتيب (Reranking)</li><li>تجزئة النصوص الطويلة (Chunking)</li></ul><p>4. RAG: أمثلة عملية</p><ul><li>باستخدام API</li><li>باستخدام نموذج محلي</li></ul><p>5. الخلاصة</p><h3>مقدمة:</h3><p>النماذج اللغوية، أو اللي نسميها <strong>Language Models</strong>، غيرت بشكل كبير الطريقة اللي نبحث فيها عن المعلومات. قبل كان البحث يعتمد بشكل أساسي على مطابقة الكلمات المفتاحية، يعني إذا كتبت كلمة معينة، النظام يطابقها مع النصوص اللي تحتوي على نفس الكلمة. لكن مع التطور صار عندنا شيء اسمه <strong>البحث الدلالي (Semantic Search)</strong>، واللي يعتمد على فهم المعنى الحقيقي وراء استفسارك، مو مجرد مطابقة كلمات.</p><p><strong>RAG (التوليد المدعوم بالاسترجاع)</strong> يعتبر من أهم التطورات في هذا المجال. الفكرة منه إنه يدمج بين استخدام النماذج اللغوية الكبيرة لاسترجاع وثائق دقيقة من مصادر خارجية، وتوليد إجابات تعتمد على المعلومات المسترجعة.</p><h4>مثال بسيط:</h4><p>لما تسأل سؤال على الشات بوت، مثل: <em>“وش أكبر كوكب في النظام الشمسي؟”</em>، الشات بوت يستخدم <strong>RAG</strong> لاسترجاع المعلومة من قاعدة بيانات موثوقة (مثل معلومة تقول إن المشتري هو أكبر كوكب)، وبعدين يولد إجابة دقيقة: <em>“أكبر كوكب في النظام الشمسي هو المشتري.”</em></p><h3><strong>البحث الدلالي Semantic search و RAG:</strong></h3><p>تم تطوير ثلاث طرق لاستخدام نماذج اللغة في البحث. فيه ثلاث أنواع رئيسية:</p><ol><li>Dense Retrieval</li><li>اعادة ترتيب ( Reranking )</li><li>RAG</li></ol><p>راح نشرح كل وحده منها شرح مبسط:</p><h3>Dense Retrieval:</h3><p>هنا النظام أول شيء يحوّل استعلامات البحث والوثائق إلى أرقام رياضية نسميها <strong>Embeddings</strong>، واللي تمثل النصوص بطريقة يفهمها الكمبيوتر كمعاني وعلاقات. بعدها، النظام يقارن بين <strong>Embeddings</strong> للاستعلام و<strong>Embeddings</strong> للوثائق، ويطلع الوثائق اللي تكون قريبة أو متشابهة مع الاستعلام.</p><p>الميزة هنا إن النظام ما يعتمد فقط على الكلمات المطابقة، بل يفهم المعنى الحقيقي وراء استفسارك، وهذا يخليه يرجع نتائج أكثر صلة واستفادة، حتى لو ما كانت الكلمات متطابقة حرفياً.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*s_EcvAR--hvj-kfY.png" /></figure><p><strong>Reranking:</strong></p><p>هنا في فقرة Reranking الي تعتبر اعادة ترتيب ياخذ نتيجة البحث الأولية ويقيمها من حيث الصلة والهدف يعيد ترتيب النتايج بحيث تظهر الأكثر صلة اولا وهنا يحسن الجودة من خلال انه يراعي السياق والمعنى</p><p>يعني مثال:</p><p>طرحت سؤال لشات بوت, كيف اتعلم البرمجة ؟</p><p>الي بيصير هنا تشات بوت بيطلع لك نتائج</p><p>“اشترك في دورات برمجة عبر الإنترنت”</p><p>“تعريف البرمجة وأهميتها”</p><p>“أفضل لغات البرمجة للمبتدئين”</p><p>“تاريخ البرمجة وتطورها”</p><p>راح ياخذ التشات بوت الردود هذي ويقيم مدى صلتها بالسؤال ويعيد ترتيب الاجابة</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*gfNOR7AgjsyIQnXJ.png" /></figure><p><strong>RAG:</strong></p><p>لما التشات بوت يولد الاجابة هنا يجمع بين توليد الاجابة و نموذج اللغوي الي هي text generation</p><p>وهنا يقدم استجابات للاستفسارات عن طريق استرجاع البيانات الي لها علاقه واستخدامها لإنشاء رد وبهذي الطريقة يقلل من الأخطاء مثل Hallucination الهلوسة</p><p>الان بعد ان اخذنا فكرة مبسطة عن كل وحده منهم, راح ندخل في تفاصيل .</p><h4>شرح مفهوم <strong>Embeddings</strong> في البحث:</h4><p>الـ <strong>Embeddings</strong> مثل ما ذكرنا، هي طريقة لتحويل النصوص إلى أرقام تُعبّر عن معانيها بطريقة يفهمها الكمبيوتر. تقدر تتخيلها كنقاط موزعة في فضاء متعدد الأبعاد. النصوص اللي لها معاني قريبة تكون نقاطها قريبة من بعض، والنصوص اللي تختلف في المعنى تكون بعيدة.</p><h4>كيف يتم استخدامها في البحث؟</h4><ol><li>لما يدخل المستخدم استعلام (مثل كلمة أو جملة)، يتم تحويل الاستعلام إلى <strong>Embedding</strong>.</li><li>النظام يقارن هذا <strong>Embedding</strong> مع <strong>Embeddings</strong> النصوص المخزنة في الأرشيف.</li><li>يبحث عن أقرب النقاط في High dimension space (يعني الوثائق الأقرب من حيث المعنى).</li></ol><h4>تقسيم المستندات (Chunking):</h4><p>إذا عندنا مستند طويل، نقطع النص إلى أجزاء صغيرة تسمى <strong>Chunks</strong> (مثل فقرات أو جمل). كل جزء يتم تحويله إلى <strong>Embedding</strong>، ونجمع كل هذه الـ <strong>Embeddings</strong> في قاعدة بيانات تُسمى <strong>Vector Database</strong>.</p><h4>التطبيق باستخدام Dense Retrieval:</h4><p>الآن، بنشوف كيف نطبق هذا المفهوم باستخدام كود:</p><pre>text = &quot;&quot;&quot;فيلم إنترستيلر هو فيلم خيال علمي ملحمي صدر عام 2014، كتبه وأخرجه وأنتجه كريستوفر نولان.يشارك في بطولته ماثيو ماكونهي، آن هاثاواي، جيسيكا تشاستين، بيل إيروين، إلين بورستين، مات ديمون، ومايكل كين.تدور أحداث الفيلم في مستقبل بائس حيث تكافح البشرية للبقاء، ويتبع مجموعة من رواد الفضاء الذين يسافرون عبر ثقب دودي بالقرب من زحل بحثًا عن منزل جديد للبشرية.كتب الأخوان كريستوفر وجوناثان نولان السيناريو، والذي كانت أصوله في نص طوره جوناثان في عام 2007.كان الفيزيائي النظري في معهد كالتيك والحائز على جائزة نوبل في الفيزياء عام 2017 كيب ثورن منتجًا تنفيذيًا، وعمل كمستشار علمي، وكتب كتابًا مرتبطًا بعنوان &quot;علم إنترستيلر&quot;.قام المصور السينمائي هويت فان هويتما بتصوير الفيلم على فيلم سينمائي 35 مم بتنسيق بانافيجن أنامورفيك وIMAX 70 مم.بدأ التصوير الرئيسي في أواخر عام 2013 وتم في ألبرتا، آيسلندا، ولوس أنجلوس.يستخدم فيلم إنترستيلر تأثيرات عملية ومصغرة واسعة النطاق، وقامت شركة دابل نيغاتيف بإنشاء تأثيرات رقمية إضافية.عرض فيلم إنترستيلر لأول مرة في 26 أكتوبر 2014 في لوس أنجلوس.في الولايات المتحدة، تم إصداره أولاً على فيلم، ثم توسع إلى أماكن تستخدم أجهزة عرض رقمية.حقق الفيلم إجمالي إيرادات عالمية تزيد عن 677 مليون دولار (و773 مليون دولار مع إعادة الإصدارات اللاحقة)، مما يجعله عاشر أعلى فيلم تحقيقًا للإيرادات في عام 2014.حصل على إشادة لأدائه، وإخراجه، والسيناريو، والموسيقى التصويرية، والتأثيرات البصرية، والطموح، والمواضيع، والعمق العاطفي.كما تلقى الثناء من العديد من علماء الفلك لدقته العلمية وتصويره للفيزياء الفلكية النظرية.منذ عرضه الأول، اكتسب فيلم إنترستيلر متابعة قوية، ويُعتبر الآن من قبل العديد من خبراء الخيال العلمي واحدًا من أفضل أفلام الخيال العلمي على الإطلاق.تم ترشيح إنترستيلر لخمس جوائز في حفل توزيع جوائز الأوسكار السابع والثمانين، وفاز بجائزة أفضل تأثيرات بصرية، وتلقى العديد من الجوائز الأخرى.&quot;&quot;&quot;</pre><p>بعدها نستخدم تقنية Chunking الي هي تقطيع النص</p><p>عشان تسهيل عمليه Embeddings</p><pre><br>import nltknltk.download(&#39;punkt&#39;)from nltk.tokenize import sent_tokenizechunks = sent_tokenize(text, language=&#39;arabic&#39;)chunks = [chunk.strip() for chunk in chunks if chunk.strip()]for idx, chunk in enumerate(chunks):    print(f&quot;الجزء رقم {idx+1}:\n{chunk}\n&quot;)</pre><p>بما أننا بنستخدم OpenAI في الحاله راح نستدعي المكتبه واكيد api key</p><pre>import openai<br># أدخل مفتاح OpenAI API الخاص بك هنا<br><br>openai.api_key = &#39;YOUR_OPENAI_API_KEY&#39;</pre><p>عملية Embedding وهنا فيه خيارات كثيرة منها وتقدر تستخدم أي نوع على حسب use case حقتك</p><p>في هذا الرابط كل Embeddings</p><p>https://huggingface.co/spaces/mteb/leaderboar</p><p>d</p><pre><br>embeddings = []batch_size = 10  for i in range(0, len(chunks), batch_size):    batch = chunks[i:i+batch_size]    response = openai.Embedding.create(        input=batch,        engine=&#39;text-embedding-ada-002&#39;    )    batch_embeddings = [data[&#39;embedding&#39;] for data in response[&#39;data&#39;]]    embeddings.extend(batch_embeddings)</pre><p>الخطوة الي بعدها راح نبني فهرس بحث ونستخدم Faiss</p><pre>import faissimport numpy as npembeddings = np.array(embeddings).astype(&#39;float32&#39;)dimension = embeddings.shape[1]  index = faiss.IndexFlatL2(dimension)index.add(embeddings) </pre><p>Faiss هو اختصار Facebook AI Similarity Search عبارة عن مكتبة مفتوحة المصدر وتستخدم للبحث بكفاءة عالية وبشكل سريع ويعتبر كويس لما يكون عندنا عدد كبير من Embeddings</p><p>الخطوة الرابعة وهي الي راح نجري البحث ومشاهدة النتائج</p><pre>def search(query, top_k=3):    response = openai.Embedding.create(        input=[query],        engine=&#39;text-embedding-ada-002&#39;    )    query_embedding = np.array(response[&#39;data&#39;][0][&#39;embedding&#39;]).astype(&#39;float32&#39;)        distances, indices = index.search(np.array([query_embedding]), top_k)        print(f&quot;استعلام البحث: &#39;{query}&#39;\n&quot;)    for i in range(top_k):        idx = indices[0][i]        distance = distances[0][i]        print(f&quot;النتيجة رقم {i+1} (المسافة: {distance}):\n{chunks[idx]}\n&quot;)</pre><p>هنا نبحث عن اقرب top_k في الفهرس</p><p>يعني مثلا انت سالت سؤال وتبي تسترجع اجابات ,نحط 3 راح يسترجع ثلاث اجابات</p><p>مثال:</p><p><strong>استعلام المستخدم:</strong> “ما هي جوائز فيلم إنترستيلر؟”</p><p><strong>top_k = 2</strong></p><p><strong>نتائج البحث:</strong></p><p><strong>النتيجة 1:</strong> “تم ترشيح إنترستيلر لخمس جوائز في حفل توزيع جوائز الأوسكار السابع والثمانين، وفاز بجائزة أفضل تأثيرات بصرية، وتلقى العديد من الجوائز الأخرى.”</p><p><strong>النتيجة 2:</strong> “حصل على إشادة لأدائه، وإخراجه، والسيناريو، والموسيقى التصويرية، والتأثيرات البصرية، والطموح، والمواضيع، والعمق العاطفي.”</p><h3>التعامل مع النصوص الطويلة وتجزيئها</h3><p>لما نتعامل مع نصوص طويلة جدًا، تواجهنا مشكلة تتعلق بحدود النماذج اللغوية، مثل عدد الكلمات أو الرموز اللي يمكن معالجتها في وقت واحد. إذا حاولت تعالج نص طويل كامل، راح تتجاوز هذه الحدود، وبالتالي ما يقدر النموذج يعالج النص بالكامل.في الصورة</p><p>1. تقسيم بالأحرف (Character Split):</p><ul><li><strong>كيف يعمل؟</strong>النص يتم تقسيمه كل 15 حرف. كل جزء يحتوي على 15 حرف فقط، ويتقدم خطوة خطوة بدون تداخل.</li><li><strong>المشكلة:</strong>هذي الطريقة ممكن تقطع الكلمات وتفصل المعنى، يعني المعنى قد يضيع لأن بعض الكلمات تكون ناقصة أو مقسومة.</li></ul><h4>2. تقسيم بالتوكينز بدون تداخل (Token Split):</h4><ul><li><strong>كيف يعمل؟</strong>النص يتم تقسيمه إلى أجزاء بناءً على التوكينز (وحدة اللغة، مثل الكلمات أو العبارات). كل جزء يحتوي على 5 توكينز، وينتهي عند آخر توكين ليبدأ جزء جديد مباشرةً.</li><li><strong>الميزة:</strong>يحافظ على النص ككلمات كاملة.</li><li><strong>المشكلة:</strong>ما يكون فيه سياق بين الأجزاء لأن كل جزء مستقل تمامًا عن اللي قبله.</li></ul><h4>3. تقسيم بالتوكينز مع تداخل (Token Split with Overlap):</h4><ul><li><strong>كيف يعمل؟</strong>النص يتم تقسيمه كل 5 توكينز، لكن يكون فيه تداخل بين الأجزاء. يعني، التوكين الأخير من الجزء الأول يتكرر كأول توكين في الجزء الثاني.</li><li><strong>الميزة:</strong>يساعد في الحفاظ على السياق بين الأجزاء. كل جزء يحتوي على جزء بسيط من اللي قبله، مما يعطي المعنى استمرارية.</li></ul><h3>إعادة الترتيب (Reranking)</h3><p>واحدة من الطرق المهمة اللي تطور قدرات البحث في نماذج اللغة هي إعادة الترتيب. هالخطوة تجي كمرحلة ثانية بعد البحث الأولي وتساعد في ترتيب النتائج بشكل أفضل.</p><h4>1. المرحلة الأولى — البحث الأولي:</h4><p>النظام يسوي بحث أولي في الأرشيف (مثل ملايين المستندات) باستخدام كلمات مفتاحية، بحث دلالي (Dense)، أو خليط بينهم.النتائج اللي تطلع تكون مرتبة بشكل مبدئي لكنها ممكن ما تكون مثالية.</p><h4>2. المرحلة الثانية — إعادة الترتيب:</h4><p>هنا يجي دور نماذج اللغة المتقدمة مثل <strong>BERT</strong>. يعيد ترتيب النتائج حسب صلتها بالسؤال اللي كتبه المستخدم.<strong>الهدف: إنك تشوف النتائج اللي فعلاً تهمك أول شيء.</strong></p><h4>3. النتائج النهائية:</h4><p>بعد الترتيب، تطلع النتائج النهائية مرتبة من الأكثر صلة إلى الأقل.هالشي يخلي البحث دقيق وأفضل للمستخدم.</p><h4>وين يستخدم؟</h4><p>زي اللي سوته <strong>مايكروسوفت Bing</strong>، أضافوا خطوة إعادة الترتيب كنموذج لغة في المرحلة الأخيرة، وهذا حسن نتائج البحث بشكل كبير باستخدام الذكاء الصناعي.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*P4wye9mPXrmWQad3.png" /></figure><p><strong>:إعادة الترتيب باستخدام OpenAI (Reranking Example)</strong></p><p>إعادة الترتيب خطوة بسيطة لكن قوية لتحسين ترتيب نتائج البحث باستخدام نماذج اللغة. هنا نقدر ندخل استعلام مع قائمة نتائج مبدئية، والنظام يعيد ترتيبها بحيث تكون النتائج الأكثر صلة في الأعلى.</p><p>نشوف مثال بسيط بالكود</p><pre>def keyword_and_reranking_search(query, top_k=3, num_candidates=10):    print(&quot;Input question:&quot;, query)    bm25_scores = bm25.get_scores(bm25_tokenizer(query))    top_n = np.argpartition(bm25_scores, -num_candidates)[-num_candidates:]    bm25_hits = [{&#39;corpus_id&#39;: idx, &#39;score&#39;: bm25_scores[idx]} for idx in top_n]    bm25_hits = sorted(bm25_hits, key=lambda x: x[&#39;score&#39;], reverse=True)        print(&quot;\nTop-3 BM25 hits:&quot;)    for hit in bm25_hits[0:top_k]:        print(&quot;\t{:.3f}\t{}&quot;.format(hit[&#39;score&#39;], texts[hit[&#39;corpus_id&#39;]].replace(&quot;\n&quot;, &quot; &quot;)))    docs = [texts[hit[&#39;corpus_id&#39;]] for hit in bm25_hits]    print(f&quot;\nTop-{top_k} hits by Reranking (from {len(bm25_hits)} BM25 hits):&quot;)    results = openai.Rerank.create(query=query, documents=docs, top_n=top_k)    for result in results[&#39;results&#39;]:        print(&quot;\t{:.3f}\t{}&quot;.format(result[&#39;relevance_score&#39;], result[&#39;document&#39;]))أول شي نستخدم خوارزمية BM25 عشان نطلع أفضل 10 نتائج مبدئية بناءً على الكلمات المفتاحية، بعدين نرسل هالنتائج لـ Reranking API مع الاستعلام عشان يعيد ترتيبها حسب صلتها بالسؤال. بعدها، نعرض النتائج الأولية اللي جابها BM25 والنتائج اللي تم إعادة ترتيبها (Reranked) عشان نشوف الفرق والتحسين في الترتيب.</pre><p>أول شي نستخدم خوارزمية <strong>BM25</strong> عشان نطلع أفضل 10 نتائج مبدئية بناءً على الكلمات المفتاحية اللي كتبها المستخدم. بعدين، نرسل هالنتائج <strong>Reranking API</strong> مع الاستعلام، والهدف إنه يعيد ترتيبها حسب صلتها بالسؤال. بعد انتهاء العملية، نعرض النتائج المبدئية اللي طلعها BM25 ونقارنها بالنتائج اللي تمت إعادة ترتيبها (Reranked) عشان نشوف الفرق والتحسين.</p><h4>كيف تعمل نماذج إعادة الترتيب (Reranking Models)؟</h4><ul><li>نماذج إعادة الترتيب تعتمد غالبًا على <strong>LLMs (نماذج اللغة الكبيرة)</strong>، وتستخدم طريقة <strong>cross-encoder</strong>.</li><li>الاستعلام والنتائج يتم تقديمهم معًا للنموذج، بحيث يقدر النموذج يقارن النصوص بنفس الوقت ويعطي درجة صلة لكل نتيجة (درجة من 0 إلى 1، حيث 0 = غير ذات صلة و1 = ذات صلة عالية).</li><li>النموذج يعالج الوثائق كلها كدفعة وحدة، لكن التقييم لكل وثيقة يتم بشكل مستقل.</li></ul><p>بعد ما يحسب النموذج الدرجات، يتم ترتيب النتائج بترتيب جديد حسب الصلة. هذي الطريقة تُعرف باسم <strong>monoBERT</strong>، وهي موضحة في ورقة بحثية بعنوان:<em>“Multi-stage document ranking with BERT”.</em></p><h4><strong>معايير تقييم الاسترجاع</strong> (<strong>Retrieval Evaluation Metrics</strong>)</h4><p>لتقييم جودة البحث الدلالي (<strong>Semantic Search Quality</strong>)، نحتاج <strong>أرشيف نصوص</strong> (<strong>Text Archive</strong>)، <strong>مجموعة استعلامات</strong> (<strong>Set of Queries</strong>)، و<strong>أحكام صلة</strong> (<strong>Relevance Judgments</strong>) تحدد وش الوثائق اللي فعلاً مرتبطة بكل استعلام. نقارن بين نظامين بأننا نرسل نفس الاستعلام ونشوف أفضل ثلاث نتائج لكل واحد. لو <strong>نظام 1</strong> جاب نتيجتين صحيحتين ونظام 2 جاب وحدة، نظام 1 أفضل. لكن لو النظامين جابوا نفس عدد النتائج الصحيحة بس بترتيب مختلف؟ هنا الترتيب يصنع الفرق. مثلاً لو النتيجة الصحيحة في أول مركز، بتكون أهم وأفضل من لو كانت في المركز الثالث. مقياس <strong>Mean Average Precision (MAP)</strong> يجي هنا كحل، بحيث يعطينا رقم يقيّم جودة ترتيب النتائج، ويركز على وضع النتائج الصحيحة في المراكز الأولى. نحسب <strong>متوسط الدقة (Average Precision)</strong> لكل استعلام، ثم نحسب المتوسط لجميع الاستعلامات في الاختبار. النتيجة النهائية تعطينا تقييم للنظام، وكل ما كان النظام يجيب النتائج الصحيحة في المراكز الأولى، كل ما كان تقييمه أعلى.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*QuaGLB4HGkuq3jhe.png" /></figure><p>عند تقييم نظام البحث لاستعلام معين، نركز على حساب الدقة للوثائق ذات الصلة فقط. إذا كانت هناك وثيقة واحدة ذات صلة ووضعت في المركز الأول، يحصل النظام على درجة كاملة <strong>1.0</strong> لأن الدقة عند المركز الأول تكون مثالية. أما إذا وُضعت الوثيقة الصحيحة في مركز متأخر (مثل المركز الثالث)، يتم تقليل الدرجة لأن النظام أعطى الأولوية لوثائق غير ذات صلة، مما يؤدي إلى عقوبة على الدقة. في حالة وجود عدة وثائق ذات صلة، يتم حساب الدقة عند كل مركز يحتوي على وثيقة ذات صلة، ثم نحسب <strong>متوسط الدقة (Average Precision)</strong> لهذه الوثائق، مع التركيز فقط على المراكز التي تحتوي على نتائج صحيحة. بشكل عام، تكون الدقة أعلى عندما يتم وضع الوثائق ذات الصلة في المراكز الأولى، بينما يؤدي ترتيب الوثائق غير ذات الصلة قبل الوثائق الصحيحة إلى تقليل التقييم النهائي للنظام.</p><p>الحين بعد ما فهمنا <strong>الدقة عند k</strong> و<strong>متوسط الدقة (Average Precision)</strong>، نقدر نقيّم نظام البحث على كل الاستعلامات الموجودة في مجموعة الاختبار. <strong>MAP</strong> أو <strong>Mean Average Precision</strong> هو مقياس ناتجه رقم واحد، يحسب متوسط الدقة لكل استعلام، وبكذا يسهّل علينا مقارنة أداء الأنظمة المختلفة.</p><p><strong>مثال بسيط:</strong>لو عندنا 3 استعلامات، وكل استعلام فيه دقة مختلفة:</p><ul><li>استعلام 1: الدقة 0.8</li><li>استعلام 2: الدقة 0.6</li><li>استعلام 3: الدقة 1.0</li></ul><p>نحسب الـ <strong>MAP</strong> بأخذ متوسط الدقة:</p><p>MAP=(0.8+0.6+1.0)3=0.8MAP = \frac{(0.8 + 0.6 + 1.0)}{3} = 0.8MAP=3(0.8+0.6+1.0)​=0.8</p><p>يعني أداء النظام في المتوسط جيد بنسبة 80%.</p><p><strong>ليش اسمها “mean” و”average”؟</strong>لأنهم نفس الشي، لكن <strong>MAP</strong> أسهل وأحلى من “average average precision”.</p><p><strong>مقياس ثاني مهم:</strong>عندنا بعد مقياس اسمه <strong>nDCG</strong> (<strong>Normalized Discounted Cumulative Gain</strong>)، هذا شوي أدق لأنه ما يعتبر الصلة مجرد “ذات صلة” أو “غير ذات صلة” بس، لا، يقدر يفرّق بين النتائج اللي صلتها أقوى من غيرها.</p><p><strong>مثال:</strong>لو نتيجتين وحدة صلتها عالية والثانية أقل، <strong>nDCG</strong> يقيّمها بشكل مختلف ويعطي درجات أدق للنظام اللي يجيب النتيجة الأهم في أول المراكز.</p><p><strong>الخلاصة:MAP مقياس بسيط يعطينا صورة عامة عن أداء النظام بناءً على متوسط الدقة لكل استعلام، بينما nDCG يعطيك دقة أكبر إذا كانت النتائج لها درجات صلة مختلفة.</strong></p><h3><strong>RAG (استرجاع مدعوم بالتوليد):</strong></h3><p>RAG هو نظام يدمج بين <strong>الاسترجاع (Retrieval)</strong> و<strong>التوليد (Generation)</strong>. السبب وراه هو إن نماذج اللغة الكبيرة (LLMs) زي <strong>GPT</strong> أحيانًا تعطي إجابات خاطئة أو “تتخيل” معلومات غير صحيحة (Hallucinations).</p><p>بدل ما نعتمد على النموذج لوحده، نضيف خطوة لاسترجاع معلومات صحيحة من مصادر محددة، وبعدها نستخدم هذي المعلومات كنقطة أساس للنموذج عشان يولد إجابات تكون دقيقة ومبنية على المصادر الصحيحة.</p><h4>خطوة 1: البحث عن معلومات</h4><p>لما المستخدم يطرح سؤال، النظام يبدأ بالبحث في قاعدة بيانات أو مصدر معلومات معين (زي مستندات الشركة، كتاب، أو أي مصدر موثوق). الهدف هو استرجاع البيانات الأكثر صلة بالسؤال.</p><h4>خطوة 2: التوليد المدعوم بالمعلومات</h4><p>بعد استرجاع المعلومات ذات الصلة، يتم إرسالها للنموذج مع السؤال. النموذج يستخدم هالمعلومات كمرجع لتوليد إجابة تكون دقيقة ومبنية على البيانات اللي تم استرجاعها.</p><p>بهالطريقة، RAG يجمع بين قوة الاسترجاع ودقة التوليد لتقديم أجوبة أكثر موثوقية وفعالية</p><p>.<strong>مثال بسيط:</strong></p><ul><li><strong>السؤال:</strong> “ما هو أكبر كوكب في النظام الشمسي؟”</li><li><strong>الخطوة الأولى (البحث):</strong> النظام يسترجع معلومة من قاعدة بيانات تقول: “أكبر كوكب هو المشتري”.</li><li><strong>الخطوة الثانية (التوليد):</strong> النموذج يستخدم هالمعلومة ويجاوب: “أكبر كوكب في النظام الشمسي هو المشتري.”</li></ul><p><strong>وين نستخدم RAG؟</strong></p><ul><li><strong>الدردشة مع بياناتك:</strong> مثل إنك تسأل النظام أسئلة عن بيانات داخل شركتك، أو كتاب، أو أي مصدر محدد.</li><li><strong>محركات البحث الذكية:</strong> زي محركات البحث الحديثة (مثل Bing AI وGoogle Gemini) اللي تلخص النتائج أو تجاوب على الأسئلة مباشرة مع ذكر المصادر.</li></ul><p><strong>تحويل نظام بحث إلى RAG:</strong>نظام البحث يصير RAG لما نضيف نموذج لغة في نهاية عملية البحث. بعد البحث واسترجاع الوثائق الأكثر صلة، نرسلها للنموذج مع السؤال، والنموذج يولد الإجابة بناءً على السياق. هذا الشيء يقلل الأخطاء ويضمن إن الإجابات مبنية على مصادر واضحة.</p><p><strong>الخلاصة:RAG يحل مشكلة الإجابات الخاطئة في نماذج اللغة الكبيرة عن طريق دمج البحث مع التوليد. النظام يسترجع المعلومات الصحيحة أولًا، ثم يعتمد عليها النموذج لإعطاء إجابات دقيقة وموثوقة. هذا يخلي الأنظمة أكثر دقة وفائدة سواء للمستخدمين العاديين أو للشركات.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*AXFerZbmW3nGmz59.png" /></figure><p><strong>RAG (استرجاع مدعوم بالتوليد) مع مثال باستخدام كود :</strong></p><p><strong>البحث (Retrieval):</strong>نستخدم البحث بالتضمين لاستخراج أفضل الوثائق للإجابة.</p><p><strong>التوليد المدعوم (Grounded Generation):</strong>نعطي الوثائق المسترجعة للنموذج مع السؤال عشان يولد الإجابة.</p><pre>query = &quot;What is capital of Saudi Arabia&quot;results = search(query)docs_dict = [{&#39;text&#39;: text} for text in results[&#39;texts&#39;]]response = co.chat(    message=query,    documents=docs_dict)print(response.text)</pre><pre>النتيجة &quot;Riyadh&quot;</pre><h4>مثال باستخدام نموذج محلي:</h4><p>إذا نبغى نعمل نفس الشي بدون API خارجي، نستخدم نماذج محلية. الكود أدناه يوضح الخطوات:</p><p>اول شي نحمل النموذج التوليدي</p><pre>from langchain import LlamaCppllm = LlamaCpp(    model_path=&quot;Phi-3-mini-4k-instruct-fp16.gguf&quot;,    n_gpu_layers=-1,    max_tokens=500,    n_ctx=2048,    seed=42,    verbose=False)</pre><p>ثانيا نحميل نموذج Embedding وانشاء قاعدة بيانات</p><pre>from langchain.embeddings.huggingface import HuggingFaceEmbeddingsfrom langchain.vectorstores import FAISSembedding_model = HuggingFaceEmbeddings(model_name=&#39;thenlper/gte-small&#39;)db = FAISS.from_texts(texts, embedding_model)</pre><p>اعداد Prompt لتوليد</p><p>طبعا هنا راح تكون عبارة عن خطوات تعطيها LLM بحيث يولد الاجابة الي تبيها</p><p>الكود راح يعطي فكرة افضل</p><pre>from langchain import PromptTemplatetemplate = &quot;&quot;&quot;&lt;|user|&gt;Relevant information:{context}Provide a concise answer to the following question using the relevant information provided above:{question}&lt;|end|&gt;&lt;|assistant|&gt;&quot;&quot;&quot;prompt = PromptTemplate(    template=template,    input_variables=[&quot;context&quot;, &quot;question&quot;])</pre><p>اخيرا اعداد نظام RAG وتشغيله</p><pre>from langchain.chains import RetrievalQArag = RetrievalQA.from_chain_type(    llm=llm,    chain_type=&#39;stuff&#39;,    retriever=db.as_retriever(),    chain_type_kwargs={        &quot;prompt&quot;: prompt    },    verbose=True)result = rag.invoke(&#39;ًWhat is the capital of Saudi Arabia&#39;)print(result)</pre><p><strong>الخلاصة:</strong></p><p>تقنيات البحث باستخدام نماذج اللغة تطورت بشكل كبير، وانتقلنا من البحث التقليدي القائم على الكلمات المفتاحية إلى البحث الدلالي (Semantic Search) اللي يفهم المعنى الحقيقي للاستعلامات. ومن خلال RAG (التوليد المدعوم بالاسترجاع)، قدرنا نحسّن دقة النماذج اللغوية ونقلل من مشكلة الهلوسة عبر استرجاع معلومات دقيقة من مصادر موثوقة قبل توليد الإجابة.</p><p><strong>المرجع:</strong></p><p>1. Natural Language Processing with Transformers</p><p>2.	Multi-Stage Document Ranking with BERT paper</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=01391f52406b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Conquer Your Fear of Failure: Practical Strategies to Break Free from Judgment and Build Lasting…]]></title>
            <link>https://medium.com/@alroumi.abdulmajeed/conquer-your-fear-of-failure-practical-strategies-to-break-free-from-judgment-and-build-lasting-2e22d6941a68?source=rss-4f2f77d947cf------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e22d6941a68</guid>
            <dc:creator><![CDATA[Abdulmajeed Alroumi]]></dc:creator>
            <pubDate>Mon, 30 Sep 2024 07:21:18 GMT</pubDate>
            <atom:updated>2024-09-30T07:46:36.767Z</atom:updated>
            <content:encoded><![CDATA[<h3>Conquer Your Fear of Failure: Practical Strategies to Break Free from Judgment and Build Lasting Confidence</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zd9smXIjF8tkgR4GAv67uw.png" /></figure><p>For many of us, it isn’t the situation itself — it’s the fear of being judged by others. We worry about people’s opinions, their critical eyes, and what our “failure” might mean in the minds of those who watch from the sidelines. Underneath this fear often lies something even deeper: our ego. We carry an internal image of ourselves that we want to protect at all costs, and the fear of failure isn’t just about disappointing others — it’s about shattering that carefully constructed image.</p><p>Our ego is delicate, and the thought of failure threatens to crack it wide open, exposing vulnerabilities we’d rather hide. We fear appearing weak, incompetent, or “less-than” in any way. When we imagine failing, we aren’t just afraid of the outcome itself; we’re terrified of what that outcome might reveal about us, not only to others but to ourselves. Our ego becomes a shield, and anything that risks breaking it can feel like an existential threat.</p><p>Yet, what are we actually giving up when we allow this fear of judgment and ego protection to steer our actions? Why do we allow other people’s opinions and our own pride to dictate our choices, our character, and our potential growth? When we prioritize protecting our ego over genuine experiences, we miss the chance to grow and become better versions of ourselves</p><h4>Why Are We So Afraid of Judgment?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dLs937tYIuTTBZ0bSbOrrw.png" /></figure><p>Think back to the last time you hesitated to do something out of fear — something you truly wanted. You probably imagined the scenario unfolding in your head with a critical audience. Maybe you pictured the interviewer’s disappointed nod, the subtle judgment in a friend’s eyes, or even the amused chuckle of a stranger. Our minds have a fascinating way of inflating these possibilities until we genuinely start believing that our worth, in some way, depends on the approval of others.</p><p>But it’s not just about their judgment. There’s also our ego, the image of ourselves that we desperately try to protect. Imagine standing at the edge of something new — a job opportunity, starting a business, or even a simple hobby like painting. In that moment, it isn’t just the fear of what others might say that holds us back; it’s also our fear of confronting our own limitations. We fear discovering that we aren’t as talented, capable, or “special” as we imagined. The ego, so carefully built up over the years, whispers: <em>If you fail, you’ll have to face the truth about yourself, and that’s terrifying.</em></p><p>Adding to that fear is our tendency to compare ourselves to others. We see friends, colleagues, or even strangers on social media effortlessly excelling, and we think to ourselves: <em>What if I try and I don’t measure up? What if I’m not as good as them?</em> Comparison becomes a powerful obstacle. It’s not just about failing; it’s about failing while others seem to be effortlessly succeeding. And that, to our fragile ego, feels like confirmation that we’re simply not enough.</p><p>From a young age, many of us are conditioned to seek validation. As children, we learn to feel good when praised and to feel lesser when criticized. A teacher gives us a gold star, a parent smiles approvingly, and we feel worthy. On the other hand, a scolding or a critical comment cuts deep, making us question our value. Somewhere along the line, we begin to equate our successes with our worth as individuals, creating a dangerous connection between our achievements and our self-esteem. This link makes any failure not just an event but a perceived statement about our identity.</p><p>Take, for example, a young artist who loves to paint. They spend hours at home perfecting their craft, feeling a sense of peace and joy. One day, they decide to share their work at a local art show. Before they even enter their piece, though, fear hits them. They see other artists’ work — more detailed, more vibrant, more “professional.” The voice in their head says, <em>What if my art isn’t good enough? What if people laugh at it?</em> It’s not just the fear of a critique that paralyzes them; it’s the fear of what that judgment will do to the image they’ve held onto — the belief that they might be talented. They fear that their ego will shatter under the weight of comparison, leaving them feeling exposed.</p><p>So why do we let these imagined judgments, our fragile egos, and constant comparisons define our character?</p><p>The truth is, our ego often becomes a barrier to growth. We fear appearing vulnerable, lacking, or imperfect, so we play it safe. We avoid risks that could help us grow, all in an effort to protect that internal image. But the irony is that true growth — real, meaningful transformation — comes precisely from stepping into discomfort, from being willing to face judgment, and from letting go of comparisons. Our character is not defined by perfection but by our willingness to try, to stumble, and to rise again despite the fear. When we begin to see that our value doesn’t lie in flawless success but in the courage to engage fully with life, we open ourselves up to experiences that genuinely build who we are.</p><h4>But What If We Shifted the Perspective?</h4><p>Instead of focusing on how others might perceive our failures, imagine if we instead concentrated on who we might become through those experiences. I recently had a moment of realization while facing a challenge of my own — a certification exam that I needed for work. I remember sitting in my car for an hour before the test, heart pounding, lost in a maze of negative thoughts: <em>What if I fail? What will people think of me? Will they see me as incompetent or incapable?</em> My mind was entirely consumed by other people’s potential judgments. It wasn’t until much later, as I reflected on that moment, that I realized how misguided my focus had been.</p><p>I never once asked myself: <em>What will I learn from this experience, whether I pass or fail?</em> I had been so worried about how others would see me that I didn’t give any consideration to who I might become as a result of simply trying.</p><p>It’s important to recognize that each of us has our own journey, and within that journey lies the unique battle we face to conquer our fears. For some, that battle is against their ego, the part of them that wants to protect their sense of self from any perceived vulnerability. For others, it might be battling through a tangle of mixed emotions uncertainty, doubt, and insecurity all tied together. Whatever the specific nature of the struggle, it is <em>our own battle</em>, and it’s crucial to focus on it. The more you understand and engage with your personal battle, the more equipped you become to shift your perspective from fear of failure to a mindset of growth.</p><p>This shift in perspective can be incredibly liberating. No matter the result, whether we succeed or fail, the experience itself contributes to our growth. We evolve by facing fears, learning from setbacks, and pushing ourselves beyond our comfort zones. When we start to see life as a process of becoming better rather than proving ourselves as “the best,” the fear of judgment begins to loosen its grip.</p><p>It is in focusing on our own battle , whether it’s calming our anxious thoughts, confronting our fragile ego, or learning to stop comparing ourselves to others, that we unlock the possibility for true transformation. The journey isn’t about showing the world our best; it’s about genuinely becoming better through each step, each challenge, and each risk we take.</p><h4>Growth Mindset vs Fixed Mindset</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*INrPYY155NPNe_eks_eeIQ.png" /></figure><p>A <em>growth mindset</em> is the belief that our abilities can improve with effort, learning, and persistence. It’s also about understanding that while we cannot always control the outcome, we can control how we react to it. People with a growth mindset know that they aren’t defined by a single success or failure. Instead, they see each experience — whether a win or a loss — as a valuable opportunity to grow.</p><p>One key to adopting a growth mindset is to detach your sense of self-worth from the results of any particular challenge. The result — whether it’s passing a test, getting a job, or nailing a presentation — does not define who you are as a human being. You grow by facing fears, by learning from every experience, and by understanding that you are always in a state of becoming better. It’s about embracing the process and making each new challenge exciting — an opportunity to learn something new rather than a moment to prove your value.</p><p>When you approach challenges with the mindset that you are not trying to be “the best,” you free yourself from the fear of losing. You’re there to learn, to experience, and to improve. And most importantly, you don’t let the judgments of others define who you are. Their opinions are just that — opinions, not reflections of your true potential.</p><p>A <em>fixed mindset</em> is the belief that abilities are static — you either have talent, or you don’t. People with a fixed mindset avoid risks because failure, to them, means exposing their limitations. They fear that any setback will prove they aren’t good enough.</p><h4>Trying to Be Better, Not the Best</h4><p>One of the core realizations I had from this experience was the difference between striving to be <em>better</em> versus trying to be <em>the best</em>. Being the best implies comparison — it’s an exhausting race against others, an unattainable pursuit for perfection, and an invitation to a constant cycle of anxiety. When we feel like we need to be the best, we put unnecessary pressure on ourselves. Every failure seems catastrophic, and every setback feels like a blow to our very identity.</p><p>But when we aim to be better — just a bit better than we were yesterday — the focus shifts inward. It becomes about personal progress, about self-improvement, about the small, everyday victories that, over time, make a meaningful difference. This mindset doesn’t mean you don’t strive for excellence; it just means that excellence is something you chase at your own pace, on your own terms, without the burden of unrealistic expectations.</p><h4>See Who You Will Become</h4><p>When facing a challenge, whether big or small, a simple shift in focus can make all the difference. Instead of asking, <em>How will others see me if I fail?</em>, try asking, <em>Who will I become if I try?</em> The answer to that question is infinitely more meaningful. Trying is always an act of courage. Whether the outcome is what we hoped for or not, each experience adds to our resilience, adaptability, and self-knowledge.</p><h4>Victim Identity: Breaking Free from Self-Limiting Beliefs</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mcISWYlX7X2D5qqJaxODLg.png" /></figure><p>Another major factor that can prevent people from embracing challenges is what’s known as a <em>victim identity</em>. A victim identity is when a person sees themselves primarily as a victim of circumstances — believing that life is happening <em>to</em> them rather than seeing themselves as an active participant with power to influence their own path. This identity often comes with a mindset that says, <em>“Why bother trying? Life is just unfair to me.”</em></p><p>People who adopt a victim identity tend to focus on all the reasons why something won’t work rather than why it could. This way of thinking is often rooted in repeated setbacks or difficult experiences that leave someone feeling powerless. Over time, these feelings solidify into a fixed belief that they have no control over their outcomes, which naturally makes taking risks and facing fears feel impossible.</p><p>However, embracing a <em>growth mindset</em> helps dismantle this victim identity by shifting focus from what’s out of one’s control to what <em>is</em> within one’s control. You may not be able to control every outcome or circumstance, but you can always control how you choose to react. Growth comes from making that choice — to refuse to let the past dictate the future, to take each setback as a stepping stone rather than a stopping point, and to see every challenge as an opportunity to learn rather than a predetermined defeat. Letting go of victim identity is liberating because it opens the door to growth, change, and a renewed sense of personal power.</p><h4>Conclusion</h4><p>Conquering the fear of failure isn’t about eliminating fear altogether — it’s about changing our relationship with it. The fear of judgment, the desire to protect our ego, and the internal battle against comparison all point to one simple truth: we are terrified of what failure might reveal about us. But the growth mindset offers an antidote to this fear by showing us that our worth isn’t tied to outcomes, external validation, or perceived perfection. Instead, our worth lies in our ability to keep learning, adapting, and striving to be just a little better than we were yesterday.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e22d6941a68" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring Advanced Arabic Text Summarization with Python, Transformers, and Large Language Models…]]></title>
            <link>https://medium.com/@alroumi.abdulmajeed/exploring-advanced-arabic-text-summarization-with-python-transformers-and-large-language-models-c9c637046827?source=rss-4f2f77d947cf------2</link>
            <guid isPermaLink="false">https://medium.com/p/c9c637046827</guid>
            <dc:creator><![CDATA[Abdulmajeed Alroumi]]></dc:creator>
            <pubDate>Wed, 24 Jul 2024 11:21:28 GMT</pubDate>
            <atom:updated>2024-07-24T11:21:28.413Z</atom:updated>
            <content:encoded><![CDATA[<h3>Exploring Advanced Arabic Text Summarization with Python, Transformers, and Large Language Models (LLMs)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oUJGV5LI4GNkcYs1-w-3TA.jpeg" /></figure><ol><li>Introduction</li><li>Explanation of the Diagram</li><li>Code illustration</li><li>Conclusion</li></ol><h3>Introduction</h3><p>Text summarization, a key facet of Natural Language Processing (NLP), has evolved dramatically over the years, driven by groundbreaking advancements in AI models. Initially, the field was dominated by models like GPT-2 and BERT, which laid the foundation for understanding text at scale. These were soon followed by more specialized models such as T5 and Pegasus, each designed to improve how machines generate concise summaries from extensive text data.</p><p>However, the real transformation in NLP came with the development of Large Language Models (LLMs). Building on the capabilities of their predecessors, LLMs represent a significant leap forward, offering deeper contextual understanding and greater precision in tasks such as text summarization. This shift is particularly impactful for complex languages like Arabic, known for its rich linguistic structure and contextual depth.</p><p>In this blog post, we will explore the sophisticated ecosystem of these models, from GPT-2 and BERT to the latest LLMs, and their role in advancing Arabic text summarization. We’ll begin with a Lucid diagram that visually details each step of the summarization process, enhanced by these powerful models. Following this visual guide, we will delve into the actual Python code that implements these theories in practical applications.</p><p>Whether you’re just curious about NLP or are deep into developing AI-driven applications, this post will provide a clear and comprehensive look at how modern AI is revolutionizing the way we process and summarize text, making it more accessible and insightful than ever before.</p><h3>Explanation of the Diagram</h3><p>The below diagram serves as a visual roadmap for the Arabic text summarization process, beginning with the “Start” symbol, a blue oval that marks the initiation of the process. This simple visual cue signifies the beginning of a series of sophisticated operations that will transform raw text into a concise summary.</p><p>As we move from the start, the first major step is the input of the Arabic text document, represented by a red parallelogram. This shape is traditionally used to denote inputs and outputs, emphasizing the entry point where the raw text is fed into the system. Following the input, the “Load Document” step occurs, illustrated by a green rectangle. This action involves using the SinglePDFLoader function to read and load the document’s text into the system, preparing it for processing. It&#39;s crucial as it ensures that the text is accessible and ready for subsequent steps.</p><p>Next, the “Merge Text” step also uses a green rectangle to symbolize the merging of text from potentially multiple documents. This merging is vital for creating a unified text block from multiple sources, facilitating a smoother summarization process. Once the text is merged, it undergoes a validation check through the “Validate Configuration” step, where the system confirms that all settings and configurations of the language model are correctly set. This step is crucial for preventing errors during the processing phase and is also depicted by a green rectangle.</p><p>The workflow then advances to a more critical phase of “Tokenization and Prompt Creation,” shown in a yellow rectangle, which reflects its importance in the summarization process. Here, the text is broken down into manageable chunks, and prompts are created for each segment. These prompts will guide the language model in generating accurate and relevant summaries for each text piece.</p><p>Following the preparation of the text, the diagram leads us into the “Map Phase,” where each chunk of text is independently processed to generate individual summaries. This phase is crucial as it demonstrates the ‘map’ part of the MapReduce approach, handling the task by dividing it into smaller, manageable components. The “Reduce Phase” then takes over, depicted in the same yellow to maintain visual continuity, where these individual summaries are combined into a comprehensive final summary. This phase illustrates the ‘reduce’ part of MapReduce, highlighting the consolidation of data into a meaningful output.</p><p>The process culminates with the “Output Final Summary” step, where the completed summary is presented, signified by a red parallelogram to match the input symbol, emphasizing its role as the final output of the process. Finally, the “End” symbol, another blue oval, marks the conclusion of the summarization process, indicating that the workflow has been successfully executed from start to finish.</p><p>This diagram not only serves as a guide to the sequential steps involved but also educates on the functionality of each component, providing a clear understanding of how advanced computational models are employed to simplify complex text summarization tasks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*H_sc5Teryg0OcF2xP4dtSw.png" /></figure><h3>Code illustration</h3><pre>from transformers import AutoTokenizer, AutoModelForSeq2SeqLM<br>import time<br><br><br>tokenizer = AutoTokenizer.from_pretrained(&#39;Load Embedding&#39;)<br>model = AutoModelForSeq2SeqLM.from_pretrained(&#39;Load Embedding&#39;)</pre><p><strong>Import and Setup</strong>: The script starts by importing necessary modules and loading pre-defined tokenizer and model. This setup is crucial for processing Arabic text correctly.</p><pre>def validate_llm_dict(llm_dict):<br>    required_keys = [&#39;name&#39;, &#39;context_window&#39;, &#39;llm model&#39;]<br>    for key in required_keys:<br>        if key not in llm_dict:<br>            raise ValueError(f&quot;Key {key} missing from llm_dict&quot;)<br>    return llm_dict<br><br>def SinglePDFLoader(file, clean=False):<br>    # Placeholder for actual PDF loading logic<br>    return f&quot;Loaded content from {file}&quot;<br><br>def merge_context(docs):<br>    return &quot; &quot;.join(docs)<br><br>def chunk_and_prompt(text, lang=&#39;en&#39;):<br>    # Simulate chunking text and creating prompts for Arabic<br>    return [text[i:i+500] for i in range(0, len(text), 500)]<br><br>def get_summary_prompt(context, bullet_points=False, arabic=False):<br>    if bullet_points:<br>        return f&quot;قم بتلخيص النص التالي في نقاط:\n{context}&quot;<br>    else:<br>        return f&quot;قم بتلخيص النص التالي:\n{context}&quot;</pre><p><strong>Utility Functions</strong>: Several functions such as validate_llm_dict, SinglePDFLoader, and merge_context provide foundational operations, from validating model configuration to preparing text for summarization.</p><pre>class Summarizer:<br>    def __init__(self, llm_dict: dict, tokenizer=AutoTokenizer.from_pretrained(&#39;casperhansen/mixtral-instruct-awq&#39;)):<br>        self._tokenizer = tokenizer  <br>        self._docs = None<br>        self._llm_dict = validate_llm_dict(llm_dict)<br>        <br>    def get_text(self):<br>        return merge_context(self._docs)<br><br>    def map_reduce(self, text, lang=&#39;en&#39;):<br>        prompts = chunk_and_prompt(text, lang=lang)<br>        summaries = []<br>        for prompt in prompts:<br>            inputs = tokenizer(prompt, return_tensors=&quot;pt&quot;, padding=True, truncation=True, max_length=512)<br>            outputs = model.generate(inputs[&#39;input_ids&#39;], max_length=150, min_length=40, length_penalty=2.0, num_beams=4, early_stopping=True)<br>            summary = tokenizer.decode(outputs[0], skip_special_tokens=True)<br>            summaries.append(summary)<br>        return &#39; &#39;.join(summaries)<br><br>    def summarize(self, summary_type=&#39;paragraph&#39;, lang=&#39;en&#39;):<br>        text = self.get_text()<br>        if summary_type == &#39;bullet_points&#39;:<br>            prompt = get_summary_prompt(text, bullet_points=True, arabic=(lang == &#39;ar&#39;))<br>        else:<br>            prompt = get_summary_prompt(text, arabic=(lang == &#39;ar&#39;))<br>        return self.map_reduce(prompt, lang=lang)<br><br>    def set_document(self, file_path):<br>        self._docs = SinglePDFLoader(file=file_path, clean=False)</pre><p><strong>Summarizer Class</strong>: This class is the core of the script. It initializes with configurations for the tokenizer and model, loads documents, and performs the summarization:</p><ul><li><strong>Initialization</strong>: Takes a dictionary for model configuration and a tokenizer. It ensures flexibility by validating the model’s configuration and setting up the tokenizer for text processing.</li><li><strong>Text Processing and Summarization</strong>: Implements methods to merge document text, generate prompts, and use a map-reduce approach for summarizing text, which allows handling large datasets efficiently.</li></ul><pre>if __name__ == &quot;__main__&quot;:<br>    llm_config = {<br>        &#39;name&#39;: &#39;Loadembedding&#39;,<br>        &#39;context_window&#39;: 2048,<br>        &#39;llm&#39;: model # Load LLM model<br>    }<br>    summarizer = Summarizer(llm_dict=llm_config)<br>    summarizer.set_document(&#39;example.pdf&#39;)<br>    print(summarizer.summarize(summary_type=&#39;bullet_points&#39;, lang=&#39;ar&#39;))</pre><p><strong>Example Usage</strong>: Demonstrates how to use the Summarizer class by specifying a model configuration, loading a document, and summarizing it.</p><h3>Conclusion</h3><p>As we’ve explored in this blog, the journey of text summarization has evolved dramatically with the advent of sophisticated NLP technologies.</p><p>The script provided offers a practical demonstration of how these technologies can be applied to create a summarization tool that is not only effective but also adaptable to various languages and tasks. By integrating pre-trained models and custom tokenizers, the script is capable of handling the complexities of the Arabic language, which is renowned for its rich linguistic features.</p><p><strong>Reference</strong>:</p><p>Hugging Face’s Transformer Documentation</p><p>Dean, J., and Ghemawat, S. (2004). “MapReduce: Simplified Data Processing on Large Clusters.” <em>OSDI’04: Sixth Symposium on Operating System Design and Implementation.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c9c637046827" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kolmogorov-Arnold Networks: A Flexible Alternative to Multi-Layer Perceptrons]]></title>
            <link>https://medium.com/@alroumi.abdulmajeed/kolmogorov-arnold-networks-a-flexible-alternative-to-multi-layer-perceptrons-56c2278f0378?source=rss-4f2f77d947cf------2</link>
            <guid isPermaLink="false">https://medium.com/p/56c2278f0378</guid>
            <dc:creator><![CDATA[Abdulmajeed Alroumi]]></dc:creator>
            <pubDate>Mon, 27 May 2024 19:53:05 GMT</pubDate>
            <atom:updated>2024-05-27T19:53:05.305Z</atom:updated>
            <content:encoded><![CDATA[<ol><li>Introduction</li><li>What is MLP?</li><li>MLPs issues</li><li>The role of KANs</li><li>Advantages of KAN</li><li>Edges vs Neurons and how edges create difference ?</li><li>Conclusion</li></ol><h3>Introduction</h3><p>In Transformer architectures, for example, the majority of parameters are often in the feedforward and attention layers rather than in the initial embedding layers. These parameters are responsible for the heavy lifting in terms of learning from the data, adjusting weights, and ultimately determining the output based on input features. They are termed “non-embedding” because they do not directly contribute to embedding input data but rather process the data post-embedding. This can cause issues with MLPs that we will explain in the blog later.</p><p>While the universal approximation theorem guarantees that MLPs can approximate any function, it does not specify how many neurons are necessary. In practice, this often means that larger networks with more hidden units are required, which can lead to inefficiencies and interpretability issues.</p><p>The paper introduces Kolmogorov-Arnold Networks (KANs) as a promising alternative to MLPs. KANs are inspired by the Kolmogorov-Arnold representation theorem. Like MLPs, KANs have fully-connected structures, but with a key difference: instead of placing fixed activation functions on neurons (nodes), KANs place learnable activation functions on the connections (edges) between neurons. Each weight in KANs is a learnable function called a spline, which allows for more flexibility and accuracy. This design change leads to KANs having no traditional linear weight matrices, making them more efficient. We will explain how KANs achieve this efficiency and flexibility.</p><h3>What is MLPs Multi-Layer Perceptrons?</h3><p>Multi-layer perceptrons (MLPs) are advanced neural networks that consist of multiple layers of neurons, each performing nonlinear transformations to enhance predictive accuracy. By stacking multiple neurons within layers and employing several hidden layers with nonlinear activation functions, MLPs can handle complex, nonlinear data patterns that single-layer perceptrons cannot. This structure allows MLPs to make sophisticated predictions and understand intricate data relationships. They use backpropagation and gradient descent to optimize weights and minimize errors, balancing the need for specialization on training data with the ability to generalize to new data. MLPs are powerful tools in modern deep learning, capable of modeling complex functions and improving prediction accuracy across various applications. As an example, Imagine you want to predict whether a student will pass or fail a course based on their study hours and past grades. The input features are the number of study hours per week (e.g., 10 hours) and past grades (e.g., 85 out of 100). The output is the probability of passing the course (e.g., 0.9 or 90%). The MLP structure consists of an input layer with 2 neurons (one for each input feature: study hours and past grades), a hidden layer with 3 neurons (to capture complex patterns in the data) using the ReLU activation function, and an output layer with 1 neuron (to produce the probability of passing) using the Sigmoid activation function. In the forward pass, the input features are fed into the input layer, transformed by the neurons in the hidden layer using weights, biases, and the ReLU activation function, and then passed to the output layer where the sigmoid function produces the final probability. During backpropagation, the network’s prediction is compared to the actual result (whether the student passed or failed), the error is calculated, and backpropagation adjusts the weights and biases in the network to reduce this error. This process is repeated for many iterations (epochs) until the network learns to make accurate predictions. This simple example illustrates how an MLP can take input features, transform them through hidden layers, and produce a prediction, learning from data to improve its accuracy, making MLPs powerful tools for various predictive tasks.</p><p>Below is diagram illustrations:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/967/1*qzGOKk7K3NOzWd7q9pytyg.png" /><figcaption>Simple MLPs structure</figcaption></figure><h3>MLPs issues</h3><p><strong>Interpretability Issue</strong>: MLPs are not easily interpretable. You can’t easily understand which input features led to a particular output. In our simple example above, you cannot track whether it is the past grades or study hours that caused a particular output. This is problematic for applications where understanding the decision-making process is crucial, such as in healthcare and finance.</p><p><strong>Function Approximation Strength and Challenge</strong>: MLPs can approximate any function, making them very flexible and powerful for various tasks. However, they often require a large number of parameters to do this efficiently, which can lead to potential overfitting and high computational costs. Referring back to our previous example, if we add more parameters, it may result in these issues, making the model more complex and harder to manage.</p><h3>The Role of KANs</h3><p>Kolmogorov-Arnold Networks (KANs) are introduced as a promising alternative to Multi-Layer Perceptrons (MLPs) to address some of their key limitations. KANs are inspired by the Kolmogorov-Arnold representation theorem and bring a novel approach to neural network design</p><p>In traditional MLPs, fixed activation functions are applied at the neurons (nodes). This means that each neuron in the hidden layers applies a predetermined non-linear transformation (such as ReLU, Sigmoid, or Tanh) to its inputs. While this approach has been effective, it has limitations in terms of flexibility and the ability to capture complex relationships in the data as we explained above. While KANs introduce a significant innovation by placing learnable activation functions on the connections (edges) between neurons instead of on the neurons themselves. KANs offers the below which will server as major asset compared to that of MLPs:</p><ul><li><strong>Learnable Activation Functions on Edges</strong>: Unlike MLPs, KANs place the learnable activation functions on the connections (edges) between neurons. This means each connection adapts based on the data to transform the input more effectively.</li><li><strong>Sum Operation on Nodes</strong>: Neurons (nodes) in KANs simply sum the incoming signals without applying additional nonlinear functions.</li><li><strong>How They Work</strong>: In KANs, the transformation is done on the connections themselves. Each connection has its own learnable function that adapts based on the data, while the neurons just sum the incoming signals.</li></ul><h3>Advantages of KAN</h3><ul><li><strong>Enhanced Flexibility</strong>:</li><li>The ability to learn activation functions for each connection allows KANs to model more complex patterns in the data. This flexibility can lead to better performance on tasks that require capturing intricate relationships.</li><li><strong>Improved Interpretability</strong>:</li><li>By using learnable functions on edges, KANs can offer better insights into how the network transforms inputs to outputs. Each function on an edge can be analyzed to understand its contribution, providing more transparency than fixed activation functions on nodes.</li><li><strong>Efficient Parameter Usage</strong>:</li><li>KANs can achieve high accuracy with fewer parameters. This efficiency helps in reducing the risk of overfitting and lowers computational costs, making KANs more scalable for large datasets and complex tasks.</li></ul><h3>Edges vs Neurons and how edges create difference ?</h3><p>In traditional neural networks like MLPs, neurons (nodes) are the points where inputs are processed using a fixed activation function (like ReLU or Sigmoid). They combine the weighted inputs and apply the activation function to produce an output. As an example, Imagine a neuron as a small factory that takes in raw materials (inputs), processes them in a fixed way (activation function), and outputs a product (result).</p><p>Now, for the edges. In KANs, the edges (connections) between neurons are more significant. Instead of just having weights, these edges have learnable activation functions. This means that the way data is transformed as it travels from one neuron to another is flexible and can adapt based on the data. As an example, Think of an edge as a smart road that can change not just in width (weight) but also in how it directs traffic (learnable function). The road can adjust its path and influence based on the needs, making the transportation of materials (data) more efficient and tailored.</p><p>Below is an illustration:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*MK64gAcWPWMkIAius1XtBA.png" /></figure><p>In the above simple illustration, traditional neural networks like Multi-Layer Perceptrons (MLPs), the activation functions applied at each neuron (node) are fixed. For example, common activation functions like ReLU or Sigmoid are predefined and do not change during training. In contrast, Kolmogorov-Arnold Networks (KANs) introduce a significant innovation by placing learnable activation functions on the connections (edges) between neurons. This change makes KANs more flexible and powerful.</p><p>In MLPs, Each neuron processes data using a fixed activation function. This limits the ability of the network to adapt to different kinds of data transformations. While KANs, The activation functions on the edges are learnable, meaning they can adapt based on the data. This allows the network to find the best possible way to transform the data for the task at hand. As an example, Imagine you are trying to teach a robot to recognize objects. If the robot’s vision system uses fixed filters (like fixed activation functions), it might struggle to adapt to new objects or environments. However, if the filters are learnable, the robot can adjust its vision to better recognize a wide variety of objects in different settings.</p><p>Now for the question? I was wondering how does learnable function adapt ?In KANs, the learnable functions on edges are often implemented as spline functions. Splines can adapt their shape based on the data, making them an excellent choice for learnable functions. They can provide smooth transformations and are computationally efficient to optimize. So, Each connection from the input neurons to the hidden neuron, and from the hidden neuron to the output neuron, has a learnable spline function. These spline functions are parameterized by control points, which will be adjusted during training.</p><h3>Conclusion</h3><p>The key innovation in KANs is the use of learnable functions on the edges (connections) between neurons, implemented as spline functions. These learnable functions allow the network to adapt and transform the data more effectively than fixed activation functions in traditional MLPs. By adjusting the control points of the splines during training, KANs can optimize these transformations to improve performance and accuracy. This flexibility in data transformation is what makes KANs a powerful alternative to traditional neural networks</p><p><strong>Reference</strong>: <a href="https://arxiv.org/abs/2404.19756">https://arxiv.org/abs/2404.19756</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=56c2278f0378" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unlocking Code Secrets with LLM4Decompile: A Cybersecurity Game-Changer]]></title>
            <link>https://medium.com/@alroumi.abdulmajeed/unlocking-code-secrets-with-llm4decompile-a-cybersecurity-game-changer-54831c48ff69?source=rss-4f2f77d947cf------2</link>
            <guid isPermaLink="false">https://medium.com/p/54831c48ff69</guid>
            <dc:creator><![CDATA[Abdulmajeed Alroumi]]></dc:creator>
            <pubDate>Tue, 26 Mar 2024 06:31:26 GMT</pubDate>
            <atom:updated>2024-03-26T06:31:26.663Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IRPP5dZ_8os5yduZ9iDv1g.png" /></figure><p>In the world of making and protecting computer programs, there’s a tricky challenge that pops up quite often. Imagine you’re given a book written in a secret code, but you don’t have the key to understand it directly. Your job is to figure out what the original story was, without any direct clues. This is a bit like what happens in the world of computer security when experts try to understand a program’s secret inner workings without having the instructions that were used to create it. This task is known as decompilation, and it’s like solving a really tough puzzle.</p><p>Why is this important, especially in cybersecurity? Well, sometimes, bad guys hide nasty things in programs, and security experts need to find and understand these hidden bits to keep computers and data safe. Decompiling helps them see the hidden parts, understand how harmful programs work, and figure out how to protect against them. It’s a critical step in stopping hackers and making sure our digital world is secure.</p><p>But this puzzle-solving is super hard. That’s where AI, or artificial intelligence, comes in, especially the smart tools such as Large Language Models (LLMs). These AI brains have recently shown they can be a big help. They’re like having a super-smart detective that can help translate the secret code back into a story we can all understand, making this tough job a bit easier for those looking to keep our digital spaces safe. In this Blog we will go through the below:</p><ol><li>The Challenge of Decompilation</li><li>LLM4Decompile to the Rescue</li><li>Pipeline</li><li>Code illustration</li><li>Conclusion</li></ol><h3>The Challenge of Decompilation</h3><p>At its core, decompilation involves translating binary code (the 1s and 0s that computers understand) back into human-readable source code. Traditional tools have made strides but often fall short in producing code that’s easily understandable by humans, particularly struggling with details like variable names and program structure that get lost in translation.</p><h3>LLM4Decompile to the Rescue</h3><p>In an exciting development, researchers have introduced LLM4Decompile an open-source project leveraging the power of LLMs specifically for decompilation. This tool isn’t just another addition to the toolbox; it represents a significant leap forward. It’s like having a multilingual literary genius who can not only translate our complex book accurately but also beautifully preserve the essence of the original text.</p><p>LLM4Decompile ranges from models with 1 billion to 33 billion parameters, trained on a massive dataset comprising C source code and its corresponding assembly code. This ensures the model understands both the high-level structure and nuances of programming languages</p><h3>Pipeline</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cNTci8wg5qQeqNmDtUnG1Q.png" /></figure><p>In the above image, the LLM4Decompile pipeline:</p><ol><li><strong>Start with Source Code (src): </strong>You have a recipe written in a language you understand (source code in C), like instructions to make a cake.</li><li><strong>Compile:</strong> You translate the recipe into another language (binary code), which only the kitchen appliances (computer) can understand.</li><li><strong>Disassemble:</strong> Now, someone else comes along who doesn’t understand this new language and tries to translate it back into a common language (assembly code). However, it’s still not as easy to understand as the original recipe.</li><li><strong>Decompile:</strong> This person then takes a shot at translating the still-hard-to-read language back into a friendly recipe format (source code in C again). It looks a lot like the original recipe, but some words might be different or the instructions slightly changed.</li><li><strong>Recompile (Eval): </strong>To make sure this new recipe still works, they try to translate it back into the kitchen appliance language (binary code). If the appliances accept it without errors, it means the new recipe is likely written correctly.</li><li><strong>Test and Run (Re-executability):</strong> Finally, you cook the dish following the new recipe to make sure it tastes right (running the program). If the meal turns out great, you know the translation was good and the original recipe’s instructions were kept intact.</li></ol><h3>Code illustration</h3><pre>import subprocess<br>import os<br>import re<br><br>digit_pattern = r&#39;\b0x[a-fA-F0-9]+\b&#39;# binary codes in Hexadecimal<br>zeros_pattern = r&#39;^0+\s&#39;#0s<br>OPT = [&quot;O0&quot;, &quot;O1&quot;, &quot;O2&quot;, &quot;O3&quot;]<br>fileName = &#39;path/to/file&#39;<br>with open(fileName+&#39;.c&#39;,&#39;r&#39;) as f:#original file<br>    c_func = f.read()<br>for opt_state in OPT:<br>    output_file = fileName +&#39;_&#39; + opt_state<br>    input_file = fileName+&#39;.c&#39;<br>    compile_command = f&#39;gcc -c -o {output_file}.o {input_file} -{opt_state} -lm&#39;#compile the code with GCC on Linux<br>    subprocess.run(compile_command, shell=True, check=True)<br>    compile_command = f&#39;objdump -d {output_file}.o &gt; {output_file}.s&#39;#disassemble the binary file into assembly instructions<br>    subprocess.run(compile_command, shell=True, check=True)<br>    <br>    input_asm = &#39;&#39;<br>    with open(output_file+&#39;.s&#39;) as f:#asm file<br>        asm= f.read()<br>    asm = asm.split(&#39;Disassembly of section .text:&#39;)[-1].strip()<br>    for tmp in asm.split(&#39;\n&#39;):<br>        tmp_asm = tmp.split(&#39;\t&#39;)[-1]#remove the binary code<br>        tmp_asm = tmp_asm.split(&#39;#&#39;)[0].strip()#remove the comments<br>        input_asm+=tmp_asm+&#39;\n&#39;<br>    input_asm = re.sub(zeros_pattern, &#39;&#39;, input_asm)<br>    before = f&quot;# This is the assembly code with {opt_state} optimization:\n&quot;#prompt<br>    after = &quot;\n# What is the source code?\n&quot;#prompt<br>    input_asm_prompt = before+input_asm.strip()+after<br>    with open(fileName +&#39;_&#39; + opt_state +&#39;.asm&#39;,&#39;w&#39;,encoding=&#39;utf-8&#39;) as f:<br>        f.write(input_asm_prompt)</pre><p>Then use LLM4Decompile to translate the assembly instructions into C:</p><pre>from transformers import AutoTokenizer, AutoModelForCausalLM<br>import torch<br><br>model_path = &#39;arise-sustech/llm4decompile-1.3b&#39;<br>tokenizer = AutoTokenizer.from_pretrained(model_path)<br>model = AutoModelForCausalLM.from_pretrained(model_path,torch_dtype=torch.bfloat16).cuda()<br><br>with open(fileName +&#39;_&#39; + opt_state +&#39;.asm&#39;,&#39;r&#39;) as f:#original file<br>    asm_func = f.read()<br>inputs = tokenizer(asm_func, return_tensors=&quot;pt&quot;).to(model.device)<br>with torch.no_grad():<br>    outputs = model.generate(**inputs, max_new_tokens=512)<br>c_func_decompile = tokenizer.decode(outputs[0][len(inputs[0]):-1])</pre><p>The provided code automates the process of decompiling C code using an AI model, specifically the LLM4Decompile model hosted on HuggingFace. Here’s a breakdown of the code into its main components and steps:</p><p><strong>Preparation and Assembly Code Extraction</strong></p><ol><li>Importing necessary modules: subprocess for executing shell commands, os for interacting with the operating system, and re for regular expression operations.</li><li>Pattern Definitions:</li></ol><ul><li>digit_pattern: A regular expression to identify hexadecimal numbers (binary codes in Hexadecimal).</li><li>zeros_pattern: A regular expression to identify leading zeros.</li></ul><ol><li>Optimization Levels: Defines the various optimization levels (O0, O1, O2, O3) that can be applied during the compilation of C code with GCC.</li><li>File Handling:</li></ol><ul><li>Opens the original C file to read the source code.</li><li>Iterates through each optimization level, compiling and disassembling the code to generate assembly instructions.</li></ul><ol><li>Compilation and Disassembly:</li></ol><ul><li>For each optimization level, it compiles the C code into an object file using GCC with the specified optimization level.</li><li>It then uses objdump to disassemble the compiled object file, extracting the assembly instructions.</li></ul><ol><li>Assembly Code Cleaning:</li></ol><p>. Splits the disassembled code to isolate the .text section, which contains the actual assembly instructions.</p><p>. Cleans up the assembly code by removing binary codes and comments.</p><p>. Applies regex to remove leading zeros and formats the assembly code for the AI model, pre-pending a prompt indicating the optimization level used.</p><p>. Writing to File: Saves the cleaned assembly code with prompts to a new file, preparing it for decompilation.</p><p><strong>Decompilation with LLM4Decompile</strong></p><ol><li>Model Setup:</li></ol><p>Initializes the tokenizer and model from the LLM4Decompile pre-trained model available on HuggingFace, ensuring the model is loaded onto a GPU for acceleration.</p><p>3. Loading Assembly Code for Decompilation:</p><p>Reads the prepared assembly code file.</p><p>Tokenizes the assembly code, converting it into a format suitable for the model.</p><p>3. Generating Source Code:</p><p>Feeds the tokenized assembly code to the model.</p><p>The model generates tokens representing the decompiled C code.</p><p>Decodes the generated tokens back into human-readable C code.</p><p>Conclusion</p><h3>Conclusion</h3><p>Decompilation stands at the crossroads of complexity and necessity, especially for cybersecurity where it’s crucial for dissecting and neutralizing threats. The LLM4Decompile tool marks a significant leap forward, blending AI’s analytical prowess with human ingenuity to peel back the layers of compiled code. Imagine effortlessly cracking open a sophisticated cyber threat to reveal its secrets and vulnerabilities — this is the kind of breakthrough that can transform cyber defense strategies. With AI-driven tools like LLM4Decompile, the future of software decompilation isn’t just promising; it’s a game-changer for developers and security professionals alike.</p><p><strong>References</strong>:</p><p><a href="https://huggingface.co/arise-sustech/llm4decompile-1.3b?text=%23+This+is+the+assembly+code+with+O0+optimization%3A%0A%3Cfunc0%3E%3A%0Aendbr64%0Alea++++%28%25rdi%2C%25rsi%2C1%29%2C%25eax%0Aretq%0A%23+What+is+the+source+code%3F">arise-sustech/llm4decompile-1.3b · Hugging Face</a></p><p><a href="https://github.com/albertan017/LLM4Decompile?tab=readme-ov-file">https://github.com/albertan017/LLM4Decompile?tab=readme-ov-file</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=54831c48ff69" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>