<?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 Sandeep Belgavi on Medium]]></title>
        <description><![CDATA[Stories by Sandeep Belgavi on Medium]]></description>
        <link>https://medium.com/@sandeep.b_41968?source=rss-73701b352c31------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*KcCk1kNXv_ozlWha</url>
            <title>Stories by Sandeep Belgavi on Medium</title>
            <link>https://medium.com/@sandeep.b_41968?source=rss-73701b352c31------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 15:30:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sandeep.b_41968/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[Vamana: The Graph Engine Powering Billion-Scale Vector Search]]></title>
            <link>https://medium.com/@sandeep.b_41968/vamana-the-graph-engine-powering-billion-scale-vector-search-0beaa9da8329?source=rss-73701b352c31------2</link>
            <guid isPermaLink="false">https://medium.com/p/0beaa9da8329</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[graph-theory]]></category>
            <category><![CDATA[vector-database]]></category>
            <dc:creator><![CDATA[Sandeep Belgavi]]></dc:creator>
            <pubDate>Sat, 13 Dec 2025 14:11:23 GMT</pubDate>
            <atom:updated>2025-12-13T14:11:23.280Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3GcNvvz_t8a1Qva6R_i0wQ.png" /><figcaption>Vamana Algorithm</figcaption></figure><p>As AI systems increasingly rely on <strong>high-dimensional embeddings</strong> to represent meaning, the challenge shifts from generating these vectors to retrieving them at scale. Brute-force searching billions of vectors is infeasible due to computational cost and the “curse of dimensionality.”</p><p>This article introduces <strong>Vamana</strong>, a graph-based <strong>Approximate Nearest Neighbor (ANN)</strong> algorithm that enables <strong>millisecond-scale vector search</strong> by transforming similarity retrieval into a navigable graph traversal problem.</p><h3>1. The Need for Speed: Why Brute Force Fails</h3><p>Modern applications like <strong>semantic search, RAG, and recommendations</strong> rely on dense vector embeddings. Stored in the billions, retrieving relevant vectors fast enough for real-time systems is a critical problem.</p><ul><li><strong>Naive exhaustive search</strong> is too slow.</li><li><strong>Traditional indexing methods</strong> (like KD-trees or inverted files) fail in high-dimensional spaces.</li></ul><p>Production systems must utilize ANN algorithms like Vamana to dramatically reduce search cost while maintaining high quality.</p><h3>2. From Distance to Graph Traversal: Vamana’s Core Concept</h3><p>Vamana takes a novel approach, modeling the high-dimensional embedding space as a <strong>directed proximity graph</strong>:</p><ul><li><strong>Nodes:</strong> Each vector is a node.</li><li><strong>Edges:</strong> Edges connect vectors that are close (but not redundantly close).</li></ul><p>This structure creates a highly interconnected “cosmic web” where <strong>similarity search becomes a fast graph traversal</strong> rather than continuous, costly distance calculations.</p><h3>3. The Core Innovation: Robust Pruning</h3><p>The efficiency of Vamana lies in its graph construction, utilizing <strong>robust pruning</strong> controlled by a <strong>diversity parameter, $\alpha$</strong>. This pruning process is the key to creating a highly navigable graph:</p><ul><li>It <strong>removes redundant edges</strong> that point to neighbors already reachable via a shorter path through another neighbor.</li><li>It <strong>preserves neighbors that offer directional diversity</strong>, effectively creating long-range shortcuts across the embedding space.</li></ul><p>This results in an <strong>Ultra-Metric structure</strong> — a highly navigable graph with a <strong>small diameter</strong> (few hops) and stable, low latency at billion-scale, ensuring high recall with bounded search cost.</p><h3>4. Search Algorithm: Greedy Traversal</h3><p>Querying the Vamana graph involves a <strong>greedy walk</strong> (a local search heuristic):</p><ol><li><strong>Initialization:</strong> Start the search at a predefined, strategically chosen <strong>entry point</strong>.</li><li><strong>Greedy Step:</strong> Continuously move to the <strong>neighboring node</strong> that is closest to the query vector.</li><li><strong>Termination:</strong> Stop when no closer neighbor exists within the current node’s local neighborhood.</li></ol><p>This stable traversal quickly converges to a strong <strong>approximation</strong> of the nearest neighbor set, offering high recall with minimal distance computations.</p><h3>5. Production Architecture: Speed Meets Scale</h3><p>Vamana is an <strong>in-memory ANN index</strong> optimized for microsecond-level query latency; it is not designed to be a durable database. To achieve persistence and massive scale, Vamana is paired with a distributed storage layer, most commonly <strong>Apache Cassandra®</strong>.</p><p>The <strong>Vamana Graph</strong> is leveraged as an <strong>In-memory ANN index</strong> (Approximate Nearest Neighbor), a core <strong>responsibility</strong> that delivers the crucial <strong>benefit</strong> of <strong>Ultra-low-latency similarity search</strong>. Conversely, <strong>Apache Cassandra®</strong> takes on the <strong>responsibility</strong> of being the <strong>System of record for embeddings</strong>, which provides the vital <strong>benefit</strong> of <strong>Durability and horizontal scale</strong> for the entire dataset.</p><p>This architectural separation ensures both resilience and speed — the core embeddings are durable, and the index is blazing fast.</p><h3>6. Real-World Applications</h3><p>Vamana-based vector search is foundational to modern AI infrastructure:</p><ul><li><strong>RAG (Retrieval-Augmented Generation):</strong> Instantly grounding large language models (LLMs) with relevant, up-to-date documents.</li><li><strong>Hyper-Personalized Recommendations:</strong> Real-time matching user preferences against massive catalogs (e.g., e-commerce, media).</li><li><strong>Anomaly Detection:</strong> Quickly identifying outliers in high-dimensional data streams.</li></ul><h3>7. Conclusion: Not Magic — An Elegant Graph</h3><p>Vamana proves that ultra-fast, billion-scale vector search is achievable through disciplined engineering and graph design. By transforming similarity search into a practical, navigable graph problem, Vamana makes massive retrieval predictable and reliable.</p><p><strong>The next time an AI system finds the right answer instantly: It’s the elegant mathematics of a very clever graph.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0beaa9da8329" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Triadic Axiom: Deconstructing LLM Performance Beyond Stochastic Benchmarks]]></title>
            <link>https://medium.com/redbus-in/the-triadic-axiom-deconstructing-llm-performance-beyond-stochastic-benchmarks-bf9572c4a185?source=rss-73701b352c31------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf9572c4a185</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[llm-as-a-judge]]></category>
            <category><![CDATA[generative-ai-solution]]></category>
            <category><![CDATA[google]]></category>
            <category><![CDATA[llm-evaluation]]></category>
            <dc:creator><![CDATA[Sandeep Belgavi]]></dc:creator>
            <pubDate>Sun, 30 Nov 2025 18:47:24 GMT</pubDate>
            <atom:updated>2025-12-02T06:25:47.990Z</atom:updated>
            <content:encoded><![CDATA[<p>The phenomenal capabilities of <strong>Large Language Models (LLMs)</strong> have solidified their role as a revolutionary technology across countless industries. However, moving an LLM application from a proof-of-concept to a reliable, production-ready system hinges entirely on rigorous, effective <strong>evaluation</strong>. This process is more intricate than traditional machine learning evaluation, demanding a shift in mindset to account for the generative, often open-ended nature of the output.</p><p>Effective LLM evaluation requires a holistic framework that integrates data quality, system-level assessment, and precise outcome definition.</p><h3>The Three Pillars of Effective LLM Evaluation</h3><p>A robust evaluation framework must be built on these three foundational principles:</p><h4>1. Data is the Foundation: Building a High-Quality Evaluation Dataset 🏗️</h4><p>The fundamental principle of “garbage in, garbage out” applies emphatically to LLM evaluation. The performance metrics you derive are only meaningful if the data they are tested on is a faithful representation of real-world usage.</p><ul><li><strong>Start with a Solid Foundation (Manually Crafted Data):</strong> Initially, <strong>domain experts</strong> must manually create a core set of diverse and relevant data points (prompts and desired outputs). This ensures that the first evaluations are testing the model on the most critical, high-value scenarios unique to your application.</li><li><strong>Embrace Continuous Improvement (Real-World Feedback):</strong> The evaluation dataset must be a <strong>living collection</strong>. As your application goes into production, continuously enrich the dataset with samples drawn from real <strong>user interactions and production logs</strong>. This ensures the evaluation framework adapts to evolving user behavior, emergent failure modes, and newly discovered edge cases.</li><li><strong>Explore Synthetic Data (Scaling Edge Case Testing):</strong> LLMs can be leveraged to generate <strong>synthetic data</strong>. This powerful technique allows you to rapidly scale the evaluation of specific, complex scenarios — such as rare legal queries or highly technical code snippets — that might be underrepresented in real user logs, allowing for thorough <strong>edge-case testing</strong> without waiting for real users to encounter them.</li></ul><h4>2. Look Beyond the Model: Evaluating the Entire System Architecture 🧩</h4><p>In practice, a successful LLM application is rarely just the model itself. It is often an intricate system that includes:</p><ul><li><strong>Prompt Engineering:</strong> The specific instructions and context given to the model.</li><li><strong>Data Augmentation:</strong> Techniques like <strong>Retrieval-Augmented Generation (RAG)</strong>, which inject relevant, up-to-date knowledge from external databases into the prompt.</li><li><strong>Input/Output Filters:</strong> Guardrails for safety, toxicity, or fact-checking.</li></ul><p>Therefore, evaluation must shift from assessing $P(output | model)$ to $P(output | entire \, system)$. Assessing the <strong>system’s overall performance</strong> ensures that components like the RAG pipeline’s document retrieval accuracy or the prompt template’s clarity are optimized alongside the core model weights.</p><h4>3. Define “Good” Precisely: Embracing Generative Nuance ✨</h4><p>Generative AI’s creative nature is its strength, but it complicates traditional evaluation. For a question, an LLM might produce ten different, equally valid, and high-quality answers. Traditional metrics based on matching a single “reference” answer will fail in this scenario, unfairly penalizing correct and innovative outputs.</p><p>Evaluation must begin with a <strong>clear, specific, and measurable definition of success</strong> for your use case. This definition needs to articulate:</p><ul><li><strong>Content Accuracy:</strong> Is the information factual and free of hallucinations?</li><li><strong>Style and Tone:</strong> Does the output meet the required tone (e.g., formal, friendly, technical)?</li><li><strong>Instruction Following:</strong> Did the model adhere to all constraints in the prompt (e.g., “Summarize in exactly three bullet points”)?</li></ul><h3>How to Evaluate LLMs: A Multi-faceted Approach</h3><p>Effective LLM evaluation requires combining three distinct methods to gain a complete picture of performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q6svD1bAoGNAbByBoL42Bw.png" /><figcaption>Evaluation Methodologies</figcaption></figure><h4>1. Computation-Based Methods (The Objective Baseline)</h4><p>These methods are most suitable for well-defined, narrow tasks (e.g., machine translation, summarization) where a high degree of lexical overlap is expected. Metrics like the <strong>BLEU score</strong> (Bilingual Evaluation Understudy) and <strong>ROUGE score</strong> (Recall-Oriented Understudy for Gisting Evaluation) measure the overlap of n-grams (sequences of words) between the generated text and a reference answer. <strong>Perplexity</strong> measures how well a language model predicts a sample of text. While indispensable for efficiency and objectivity, they should not be the sole basis for evaluation in generative tasks.</p><h4>2. Human Evaluation (The Gold Standard)</h4><p>For tasks requiring creativity, common sense, or adherence to complex stylistic guidelines, <strong>human judgment remains superior</strong>. A structured approach is key to maximizing its value:</p><ul><li><strong>Clear Rubrics:</strong> Provide human raters with unambiguous criteria (e.g., a 1–5 scale for “Clarity,” “Factual Accuracy,” and “Relevance”)</li><li><strong>Sampling Strategy:</strong> Focus human review on the most critical outputs: edge cases identified by synthetic data, or failure modes flagged by computation-based or autorater methods.</li></ul><h4>3. The Rise of the Autorater (The Scalable Nuance)</h4><p>The Autorater is a breakthrough in scaling qualitative evaluation. By providing a powerful LLM (the “judge”) with the prompt, the generated output, and a detailed scoring rubric, it can effectively mimic the judgment of a human evaluator.This allows for fast, cost-effective evaluation that moves beyond simple keyword matching to assess semantic meaning and adherence to complex instructions. This method is particularly useful for continuous integration/continuous deployment (CI/CD) pipelines, enabling <strong>rapid, iterative improvements</strong> to the entire LLM system.</p><h3>Conclusion</h3><p>Evaluating LLMs is not a one-time activity but an <strong>iterative process</strong> embedded within the development lifecycle. By adopting the three pillars — prioritizing <strong>high-quality, continuously updated data</strong>, focusing on the <strong>entire system architecture</strong>, and establishing a <strong>precise definition of success</strong> — and leveraging a multi-faceted approach combining computation, human judgment, and scalable autoraters, you can build a robust framework. This ensures your LLM-powered applications are not just innovative, but also reliable, trustworthy, and fit for purpose.</p><p>This robust framework adopts the core authoritative principles from the Google Cloud whitepaper. A sincere thank you for this vital guidance on LLM reliability.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf9572c4a185" width="1" height="1" alt=""><hr><p><a href="https://medium.com/redbus-in/the-triadic-axiom-deconstructing-llm-performance-beyond-stochastic-benchmarks-bf9572c4a185">The Triadic Axiom: Deconstructing LLM Performance Beyond Stochastic Benchmarks</a> was originally published in <a href="https://medium.com/redbus-in">redbus India Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Overcoming AI Amnesia: The Power of Context Engineering]]></title>
            <link>https://medium.com/redbus-in/overcoming-ai-amnesia-the-power-of-context-engineering-572e6f71ffb8?source=rss-73701b352c31------2</link>
            <guid isPermaLink="false">https://medium.com/p/572e6f71ffb8</guid>
            <category><![CDATA[memory-management]]></category>
            <category><![CDATA[google-adk]]></category>
            <category><![CDATA[long-term-memory]]></category>
            <category><![CDATA[short-term-memory]]></category>
            <category><![CDATA[context-engineering]]></category>
            <dc:creator><![CDATA[Sandeep Belgavi]]></dc:creator>
            <pubDate>Fri, 14 Nov 2025 12:40:43 GMT</pubDate>
            <atom:updated>2025-12-02T03:49:32.096Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Context Engineering :: ADK Memory" src="https://cdn-images-1.medium.com/max/1024/1*sXDHN0xgvM3K9bIL44wLww.jpeg" /></figure><p>The core challenge in creating sophisticated AI is “AI amnesia,” where an LLM forgets previous interactions because it is <strong>inherently stateless</strong> (each query is a new beginning). <strong>Context Engineering</strong> is the strategic solution. It is the practice of dynamically ensuring the LLM’s <strong>context window</strong> (its working memory) is consistently filled with the <em>most relevant information</em> for the current task.</p><p>Context Engineering divides the AI’s memory challenge into two distinct, essential components:</p><h3>1. Sessions (Short-Term Memory) 💬</h3><ul><li><strong>Definition:</strong> The active, ongoing, and linear conversation history.</li><li><strong>Purpose:</strong> To provide <strong>continuity</strong> for a single interaction. This allows the AI to correctly interpret the current query by resolving ambiguities and understanding pronouns based on the immediate dialogue.</li><li><strong>Analogy:</strong> A conversation with a barista about your current order. It’s relevant now, but will be gone tomorrow.</li></ul><h3>2. Memory (Long-Term Knowledge) 📚</h3><ul><li><strong>Definition:</strong> Persistent, curated, and structured knowledge the AI builds over time about a user, a project, or a domain.</li><li><strong>Purpose:</strong> To enable true <strong>personalization</strong> and persistent understanding. This knowledge is retrieved strategically to anticipate needs and tailor responses.</li><li><strong>Implementation:</strong> Typically stored not as a raw transcript, but as <strong>distilled insights</strong> in a searchable database, such as a vector store.</li><li><strong>Analogy:</strong> A barista’s “regulars” notebook containing persistent facts like your preferred drink and visit schedule.</li></ul><h3>🏗️ Architectural Blueprints: Context Engineering with the ADK</h3><p>The <strong>Agent Development Kit (ADK)</strong> provides the necessary architectural patterns to practically implement Context Engineering, moving from theory to a robust, stateful system.</p><h3>Pattern 1: The Coordinator Agent (Managing the Session)</h3><p>This pattern addresses the short-term continuity of the <strong>Session</strong>.</p><ul><li><strong>Mechanism:</strong> An <strong>Intent-Based Router</strong>, or <strong>Coordinator Agent</strong>, acts as a smart traffic controller. It doesn’t answer the user’s query itself.</li><li><strong>Role:</strong> It uses the <strong>Session history</strong> (the immediate chat dialogue) to quickly understand the user’s intent. Based on this, it accurately <strong>delegates</strong> the task to the appropriate specialized sub-agent (e.g., a BusSearchAgent or a BookingAgent).</li><li><strong>ADK Advantage:</strong> The routing logic is often defined directly within the Coordinator’s prompt (LlmAgent), making the system <strong>agile</strong> and easy to update without code changes.</li></ul><h3>Pattern 2: The Data Aggregator (Enriching Context with Memory)</h3><p>This pattern is the heart of assembling rich context using <strong>Memory</strong> for complex inquiries.</p><ul><li><strong>Mechanism:</strong> The <strong>Parallel Fan-Out/Fan-In</strong> pattern.</li></ul><ol><li><strong>Fan-Out:</strong> An orchestrator agent breaks down a complex request and simultaneously sends it out to multiple, concurrent sub-agents.</li><li><strong>Memory Retrieval:</strong> Each sub-agent is responsible for fetching a specific piece of <strong>Long-Term Memory</strong> (e.g., one agent fetches pricing, another fetches customer reviews, a third fetches cancellation policies).</li><li><strong>Fan-In/Synthesis:</strong> Once all data is gathered, a final <strong>Synthesizer Agent</strong> collects (fans in) the results.</li></ol><ul><li><strong>Result:</strong> The Synthesizer agent dynamically constructs a <strong>rich, comprehensive prompt</strong> containing all the necessary long-term knowledge <em>in addition to</em> the user’s immediate question. The final LLM receives a perfectly engineered context to generate a truly informed answer.</li></ul><h3>🚀 The Future: From Chatbot to Collaborator</h3><p>By mastering Context Engineering and employing sophisticated frameworks like the ADK, AI agents make the leap from simple, stateless Q&amp;A tools to true, intelligent collaborators that can:</p><ul><li><strong>Maintain Persistence:</strong> Stop forgetting key information and repeating themselves.</li><li><strong>Handle Complexity:</strong> Tackle multi-step, multi-domain problems by leveraging specialized agents.</li><li><strong>Scale Efficiently:</strong> Remain maintainable and agile by decoupling logic into specialized, prompt-configured components.</li></ul><p>This shift proves that the future of advanced AI is not just about the size of the model, but the <strong>intelligence of the system’s architecture</strong>.</p><p>This post was directly inspired by the groundbreaking ideas in the original Google Agent Development Kit (ADK) paper.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=572e6f71ffb8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/redbus-in/overcoming-ai-amnesia-the-power-of-context-engineering-572e6f71ffb8">🧠 Overcoming AI Amnesia: The Power of Context Engineering</a> was originally published in <a href="https://medium.com/redbus-in">redbus India Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Stop Prompting, Start Coding: Building Actionable AI Agents with the Redbus-Labs Java ADK]]></title>
            <link>https://medium.com/redbus-in/stop-prompting-start-coding-building-actionable-ai-agents-with-the-redbus-labs-java-adk-00176e13cb03?source=rss-73701b352c31------2</link>
            <guid isPermaLink="false">https://medium.com/p/00176e13cb03</guid>
            <category><![CDATA[google-adk]]></category>
            <category><![CDATA[redbus]]></category>
            <category><![CDATA[redbustech]]></category>
            <category><![CDATA[redbuslabs-adk]]></category>
            <dc:creator><![CDATA[Sandeep Belgavi]]></dc:creator>
            <pubDate>Mon, 10 Nov 2025 19:08:05 GMT</pubDate>
            <atom:updated>2025-12-02T06:25:59.399Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>AI Agents</strong> are replacing static applications as the future of software. This monumental shift isn’t just for Python anymore. Thanks to powerful new toolkits, Java developers now have a <strong>direct, seamless path</strong> to building, deploying, and leading this intelligent, agent-centric revolution.</p><p>Enter the <strong>Agent Development Kit (ADK) for Java</strong>, an open-source, code-first toolkit from <a href="https://github.com/redbus-labs/adk-java">redbus-labs</a> designed to build, evaluate, and deploy sophisticated AI agents with enterprise-level flexibility and control.</p><blockquote><strong><em>State-of-the-Art:</em></strong><em> This project is a direct fork of Google’s ADK, with the redbus-labs version currently </em><strong><em>225 commits ahead</em></strong><em>, showcasing its independent and highly active development.</em></blockquote><p>This post will take you on a deep dive into the core concepts of the ADK for Java, exploring its architecture, rich tool ecosystem, and how it delivers production-ready capabilities.</p><h3>💻 The Code-First Philosophy: Control Meets Flexibility</h3><p>While the ADK supports configuration-driven agents (like YAML-based <strong>Agent Config</strong>), its power lies in the <strong>“code-first” philosophy</strong>. Define your agent’s behavior, orchestration, and tools entirely in <strong>idiomatic Java</strong> for total control and robust debugging.</p><p>This approach offers several production-grade advantages:</p><ul><li><strong>Flexibility and Control:</strong> You have fine-grained control over every aspect of your agent’s logic.</li><li><strong>Testability:</strong> Agents are plain Java code, making them easy to test using familiar tools like <strong>JUnit</strong>.</li><li><strong>Versioning:</strong> Version your agents just like any other codebase, ensuring <strong>reproducibility</strong> and traceability.</li><li><strong>Debugging:</strong> Debugging your agents is as simple as debugging any other Java application.</li></ul><h3>🏗️ Core Architecture: Inside the ADK</h3><p>The ADK is a multi-module Maven project, but its core logic resides in the core module. Understanding its components is key to building complex agents.</p><h3>1. BaseAgent: The Foundational Blueprint</h3><p>The <strong>BaseAgent</strong> class is the abstract foundation for all agents. It defines essential properties like a unique <strong>name</strong>, a descriptive <strong>description</strong>, and a list of <strong>subAgents</strong> for hierarchical agent structures.</p><p>Crucial execution methods are defined here: <strong>runAsync()</strong> (returns a stream of events asynchronously) and <strong>runLive()</strong> (executes synchronously).</p><h3>2. LlmAgent: The Intelligence Core</h3><p>The <strong>LlmAgent</strong> is the primary implementation of BaseAgent. It&#39;s the &quot;brains&quot; of the operation, responsible for interacting with the LLM. The ADK is explicitly <strong>optimized for Gemini</strong> models, though it is <strong>model-agnostic</strong> for maximum flexibility. You configure an LlmAgent with:</p><ul><li><strong>model:</strong> The LLM to use (e.g., Gemini, RedbusADG, Ollama, Claude, etc.).</li><li><strong>instruction:</strong> The system prompt guiding the LLM&#39;s behavior.</li><li><strong>tools &amp; </strong><strong>subAgents:</strong> External capabilities and delegation targets.</li></ul><h3>3. BaseSessionService: Context and Memory</h3><p>The <strong>BaseSessionService</strong> manages the session—a conversation between a user and an agent. It allows the agent to maintain context and memory across interactions via methods for:</p><ul><li>Creating, retrieving, and managing sessions.</li><li>Listing and appending events to a session.</li></ul><p>The ADK provides various implementations, including scalable options like MongoDbSessionService and PostgresSessionService.</p><h3>4. Runner: The Master Orchestrator</h3><p>The <strong>Runner</strong> class is the main entry point, responsible for orchestrating the entire execution flow: managing the session, handling event flow, and ensuring the agent and its services work together seamlessly.</p><h3>🛠️ The Game-Changer: A Rich Tool Ecosystem</h3><p>One of the most powerful features of the ADK is its support for <strong>Tools</strong>. Tools are simply annotated Java methods that the LLM can decide to call to perform real-world actions. The ADK’s <strong>Tool Ecosystem</strong> is vast and production-ready:</p><ul><li><strong>Custom Function Tools:</strong> Any standard Java method you annotate with @Tool and @ToolMethod.</li><li><strong>Built-in Tools:</strong> Including <strong>Google Search</strong> and secure <strong>Code Execution</strong>.</li><li><strong>Third-Party Integrations:</strong> Ready-made tools for services like <strong>Browserbase</strong> (web browsing), <strong>Exa</strong> (search), <strong>GitHub</strong> (code analysis), <strong>Notion</strong>, and more.</li><li><strong>Agent-as-a-Tool:</strong> The ability to use one BaseAgent as a specialized tool for another, facilitating complex, modular architectures.</li></ul><p>This allows you to build agents that not only reason and communicate but also take action and get things done.</p><h3>🚀 Orchestration and Production Readiness</h3><p>The ADK is engineered for complex, scalable deployments, offering features that go far beyond simple chatbots:</p><ul><li><strong>Flexible Orchestration:</strong> Beyond single LLM Agents, the ADK provides <strong>Workflow Agents</strong> (<strong>Sequential</strong>, <strong>Parallel</strong>, <strong>Loop</strong>) for defining predictable, step-by-step pipelines, and <strong>LlmAgent transfer</strong> for dynamic, LLM-driven routing between specialized agents.</li><li><strong>Deployment Options:</strong> Your agents are deployable anywhere. Options include the fully-managed <strong>Vertex AI Agent Engine</strong>, highly scalable <strong>Cloud Run</strong>, or standard <strong>GKE</strong> containers.</li><li><strong>Observability &amp; Evaluation:</strong> Production monitoring is built-in, with support for <strong>Logging</strong>, <strong>Cloud Trace</strong>, and a dedicated <strong>Evaluation</strong> module to systematically assess agent performance against test cases.</li></ul><h3>🎉 Conclusion</h3><p>The Agent Development Kit for Java is a true game-changer. By embracing a <strong>code-first philosophy</strong>, providing a robust, modular architecture, and seamlessly integrating powerful <strong>actionable tools</strong>, the ADK is the definitive choice for Java developers aiming to build <strong>production-ready, state-of-the-art AI agents</strong>.</p><p>Stop waiting for the AI revolution — start building it. Dive into the ADK for Java and craft the next generation of intelligent, actionable applications.</p><p>The link for the redbus-labs Agent Development Kit (ADK) for Java is:</p><p><a href="https://github.com/redbus-labs/adk-java"><strong>https://github.com/redbus-labs/adk-java</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=00176e13cb03" width="1" height="1" alt=""><hr><p><a href="https://medium.com/redbus-in/stop-prompting-start-coding-building-actionable-ai-agents-with-the-redbus-labs-java-adk-00176e13cb03">🎯 Stop Prompting, Start Coding: Building Actionable AI Agents with the Redbus-Labs Java ADK</a> was originally published in <a href="https://medium.com/redbus-in">redbus India Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bridging the Language Divide: True Interoperability with Google ADK in Hybrid AI Systems]]></title>
            <link>https://medium.com/redbus-in/bridging-the-language-divide-true-interoperability-with-google-adk-in-hybrid-ai-systems-f0d4865525d6?source=rss-73701b352c31------2</link>
            <guid isPermaLink="false">https://medium.com/p/f0d4865525d6</guid>
            <category><![CDATA[cross-language]]></category>
            <category><![CDATA[hybrid-agent-architecture]]></category>
            <category><![CDATA[google-adk]]></category>
            <category><![CDATA[enterprise-ai]]></category>
            <category><![CDATA[a2a-protocol]]></category>
            <dc:creator><![CDATA[Sandeep Belgavi]]></dc:creator>
            <pubDate>Mon, 07 Jul 2025 07:25:17 GMT</pubDate>
            <atom:updated>2025-12-02T03:53:49.243Z</atom:updated>
            <content:encoded><![CDATA[<p>In the evolving landscape of enterprise AI, organizations face a fundamental challenge: how to seamlessly integrate Python’s cutting-edge AI capabilities with Java’s battle-tested enterprise infrastructure. The solution lies in <strong>hybrid agentic architectures</strong> that leverage the strengths of both worlds while maintaining clean separation of concerns.</p><p>This is where Google’s Agent Development Kit (ADK) becomes transformative, offering a pragmatic framework for building truly interoperable multi-language AI systems. Let’s explore how ADK enables autonomous agents in different languages to collaborate intelligently and deliver sophisticated AI-powered experiences.</p><h3>The Hybrid Agentic Landscape: Why It Matters</h3><p>Consider a modern product information assistant that needs to:</p><ul><li>Process complex natural language queries (“What’s the current stock and pricing for our premium USB-C products?”)</li><li>Execute real-time database operations across distributed systems</li><li>Provide contextually aware, intelligent responses</li><li>Scale to handle enterprise-level traffic and reliability requirements</li></ul><p>Building such a system entirely in one language creates inevitable compromises:</p><p><strong>Python’s AI Supremacy</strong>: Python dominates the AI/ML landscape with frameworks like TensorFlow, PyTorch, and sophisticated NLP libraries. Its rapid prototyping capabilities and rich ecosystem make it ideal for building intelligent agents with advanced reasoning capabilities.</p><p><strong>Java’s Enterprise DNA</strong>: Java provides unmatched stability, performance, and mature tooling for large-scale distributed applications. Its robust dependency management, proven scalability patterns, and enterprise integration capabilities make it the backbone of mission-critical systems.</p><p>The optimal solution harnesses both strengths through intelligent agent orchestration. But how do you achieve this without creating a tightly coupled, maintenance nightmare?</p><h3>Enter Google’s Agent Development Kit (ADK)</h3><p>Google ADK revolutionizes how we build intelligent systems by providing a <strong>language-agnostic protocol</strong> for agent communication. Rather than forcing everything into a single language, ADK enables you to build specialized agents in their optimal languages while maintaining seamless interoperability.</p><p>ADK agents are autonomous entities that can:</p><ul><li>Understand and process complex intents</li><li>Dynamically select and execute tools</li><li>Maintain stateful conversations across distributed systems</li><li>Communicate through standardized protocols regardless of implementation language</li></ul><p>Let’s examine a real-world implementation: the <strong>Hybrid Multi-Language ADK Agent: Product Information Assistant</strong>.</p><h3>Architecture Deep Dive: The Product Information Assistant</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jzx6M9U52eS7fyd8knTgug.png" /><figcaption>Hybrid AI Architecture</figcaption></figure><p>This architecture showcases a sophisticated system where a Python-based intelligent agent service collaborates with a Java-based orchestration layer through Google ADK protocol.</p><h3>1. The Python AI Intelligence Engine: product_agent_service.py</h3><p>The Python component serves as the cognitive core of our agentic system:</p><p><strong>Advanced Natural Language Processing</strong>: Integrates with a locally hosted Llama 3.2 model via Ollama, providing sophisticated intent recognition and entity extraction capabilities. The LLM processes complex queries and determines appropriate actions through advanced reasoning.</p><p><strong>Dynamic Tool Function Calling</strong>: The Python agent features intelligent tool selection through its ProductDetailsTool. When the LLM recognizes product-related queries, it autonomously decides to invoke this tool with extracted parameters.</p><p><strong>High-Performance Database Integration</strong>: Direct integration with ClickHouse analytics database enables real-time product catalog queries, inventory management, and complex analytical operations across distributed datasets.</p><p><strong>Structured Response Generation</strong>: Utilizes ADK’s protocol to generate structured AgentResponse objects with proper status indicators (success, not_found, error) and formatted content.</p><p><strong>Microservice Architecture</strong>: Deployed as an independent FastAPI service on http://127.0.0.1:8000/, enabling horizontal scaling, independent deployment cycles, and high availability patterns.</p><h3>2. The Java Enterprise Orchestrator: PythonProxyAgent.java</h3><p>The Java component provides enterprise-grade orchestration and resilience:</p><p><strong>Intelligent Request Proxying</strong>: Acts as a sophisticated intermediary, forwarding user requests to the Python agent while handling complex routing and load balancing scenarios.</p><p><strong>Advanced Session Management</strong>: Implements automatic session recovery — when the Python agent reports session errors, the Java orchestrator automatically creates new sessions via the /apps/{app_name}/users/{user_id}/sessions/{session_id} endpoint.</p><p><strong>Enterprise-Grade Error Handling</strong>: Comprehensive error handling for connection failures, timeouts, circuit breaker patterns, and various HTTP error scenarios. Includes retry logic and fallback mechanisms.</p><p><strong>ADK Protocol Mastery</strong>: Sophisticated JSON event parsing that extracts relevant information from complex ADK response arrays, ensuring clean user-facing responses.</p><p><strong>Maven Integration</strong>: The Java ADK is easily integrated into enterprise projects using Maven:</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;com.google.adk&lt;/groupId&gt;<br>    &lt;artifactId&gt;google-adk&lt;/artifactId&gt;<br>    &lt;version&gt;0.1.0&lt;/version&gt;<br>&lt;/dependency&gt;</pre><p><strong>Enterprise-Grade Agent Creation</strong>: The Java component leverages Google’s official ADK framework to create sophisticated agents:</p><pre>import com.google.adk.agents.LlmAgent;<br>import com.google.adk.tools.GoogleSearchTool;<br>LlmAgent rootAgent = LlmAgent.builder()<br>    .name(&quot;search_assistant&quot;)<br>    .description(&quot;An assistant that can search the web.&quot;)<br>    .model(&quot;gemini-2.0-flash&quot;) // Or your preferred models<br>    .instruction(&quot;You are a helpful assistant. Answer user questions using Google Search when needed.&quot;)<br>    .tools(new GoogleSearchTool())<br>    .build();</pre><h3>Real-World Implementation: Code-First Approach</h3><p>The implementation demonstrates Google ADK’s code-first philosophy, where agent behavior is defined directly in Java code rather than through configuration files. This approach provides:</p><ul><li><strong>Ultimate Flexibility</strong>: Direct code control over agent orchestration and behavior</li><li><strong>Robust Debugging</strong>: Full IDE support for debugging agent interactions</li><li><strong>Version Control</strong>: Complete versioning of agent logic alongside application code</li><li><strong>Testability</strong>: Unit and integration testing of agent components</li></ul><p><strong>Multi-Agent System Architecture</strong>: The system supports both parallel and sequential agent execution patterns, enabling complex workflows like hierarchical task decomposition and agent coordination.</p><p>The ADK protocol serves as the universal translator between our agentic components:</p><h3>3. The Google ADK Protocol Bridge</h3><p>The ADK protocol serves as the universal translator between our agentic components:</p><p><strong>Language-Agnostic Communication</strong>: Standardized JSON-based event system that enables seamless communication regardless of implementation language.</p><p><strong>A2A Protocol Integration</strong>: For remote agent-to-agent communication, ADK integrates with the A2A protocol, enabling distributed agent architectures.</p><p><strong>Standardized Event System</strong>: Structured event types for different interaction patterns (user input, tool calls, responses, errors).</p><p><strong>Session State Management</strong>: Distributed session handling that maintains conversation context across multiple service boundaries.</p><h3>The Agentic Workflow: Intelligence in Action</h3><p>Here’s how our hybrid agentic system processes a complex query:</p><ol><li><strong>User Query Initiation</strong>: “What’s the current stock and description for product 103?”</li><li><strong>Java Orchestrator Processing</strong>: The Java PythonProxyAgent receives the query, constructs an ADK-compliant payload, and routes it to the Python intelligence engine.</li><li><strong>AI-Powered Intent Recognition</strong>: The Python agent’s LLM analyzes the query, recognizes the product information intent, and extracts the product ID (103).</li><li><strong>Autonomous Tool Selection</strong>: The LLM determines that the ProductDetailsTool is required and prepares the appropriate function call.</li><li><strong>Real-Time Data Retrieval</strong>: The ProductDetailsTool executes optimized SQL queries against the ClickHouse database to fetch product details and inventory levels.</li><li><strong>Intelligent Response Generation</strong>: The Python agent synthesizes the database results into a natural language response: “Product ID 103: ‘USB-C Hub Elite’. Description: ‘7-in-1 USB-C hub with 4K HDMI, 100W PD, and Gigabit Ethernet’. Current Stock: 200 units.”</li><li><strong>Protocol-Compliant Response</strong>: The response is wrapped in ADK’s structured event format and transmitted back to the Java orchestrator.</li><li><strong>Enterprise Response Delivery</strong>: The Java agent parses the ADK events, extracts the user-facing content, and delivers the final response.</li><li><strong>Automatic Error Recovery</strong>: If session issues occur, the Java orchestrator automatically handles session creation and request retry without user intervention.</li></ol><h3>Strategic Benefits of Hybrid Agentic Architecture</h3><p><strong>Technology Optimization</strong>: Each component operates in its optimal language environment — Python for AI reasoning, Java for enterprise orchestration.</p><p><strong>Autonomous Operation</strong>: Agents make intelligent decisions independently, reducing the need for complex coordination logic.</p><p><strong>Elastic Scalability</strong>: Independent scaling of AI processing and enterprise orchestration layers based on specific load patterns.</p><p><strong>Enterprise Resilience</strong>: Built-in error handling, session management, and recovery mechanisms ensure production-grade reliability.</p><p><strong>Evolutionary Architecture</strong>: New AI models or tools can be integrated into the Python agent without affecting the Java orchestrator, and vice versa.</p><p><strong>Protocol Standardization</strong>: Google ADK’s structured communication eliminates the complexity of custom integration protocols.</p><p><strong>Future-Proof Design</strong>: Language-agnostic architecture adapts to new technologies and frameworks without major architectural changes.</p><h3>Conclusion: The Future of Enterprise AI</h3><p>The evolution toward hybrid agentic architectures represents a fundamental shift in how we build intelligent systems. By combining Python’s advanced AI capabilities with Java’s enterprise-proven infrastructure through Google ADK’s intelligent orchestration, organizations can create truly autonomous, scalable, and maintainable AI solutions.</p><p>This approach transcends traditional monolithic constraints, enabling organizations to build systems that are not just intelligent, but intelligently architected. The result is a new generation of enterprise AI that leverages the best of both worlds while maintaining the flexibility to evolve with rapidly advancing AI technologies.</p><p>The hybrid agentic architecture isn’t just about technical integration — it’s about creating intelligent systems that can autonomously reason, adapt, and scale in the complex enterprise environment of tomorrow.</p><p><strong>Repository</strong>: <a href="https://github.com/redbus-labs/adk-java">redbus-labs/adk-java</a> <strong>Official ADK Documentation</strong>: <a href="https://google.github.io/adk-docs/">google.github.io/adk-docs</a> <strong>Sample Agents</strong>: <a href="https://github.com/google/adk-samples">google/adk-samples</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f0d4865525d6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/redbus-in/bridging-the-language-divide-true-interoperability-with-google-adk-in-hybrid-ai-systems-f0d4865525d6">Bridging the Language Divide: True Interoperability with Google ADK in Hybrid AI Systems</a> was originally published in <a href="https://medium.com/redbus-in">redbus India Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Beyond Monoliths: Crafting Interoperable AI Systems with Google’s A2A Agent Architecture]]></title>
            <link>https://medium.com/redbus-in/beyond-monoliths-crafting-interoperable-ai-systems-with-googles-a2a-agent-architecture-e0f20b5fbcb6?source=rss-73701b352c31------2</link>
            <guid isPermaLink="false">https://medium.com/p/e0f20b5fbcb6</guid>
            <category><![CDATA[agents]]></category>
            <category><![CDATA[a2a]]></category>
            <category><![CDATA[google-a2a]]></category>
            <dc:creator><![CDATA[Sandeep Belgavi]]></dc:creator>
            <pubDate>Mon, 23 Jun 2025 17:24:43 GMT</pubDate>
            <atom:updated>2025-12-02T03:53:26.220Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3q_4nAEiGq_4J7eDhRGuPA.png" /></figure><p>In today’s interconnected digital landscape, building intelligent systems often means orchestrating multiple specialized services. Google’s Agent-to-Agent (A2A) protocol provides an elegant and standardized way for these services — or “agents” — to discover, interact, and collaborate. This document provides a technical deep dive into a generic A2A architecture and it’s components.</p><h3>1. High-Level Architecture Diagram</h3><p>At its essence, an A2A system orchestrates specialized agents (servers) to expose their capabilities and clients (orchestrators or other agents) to intelligently consume those capabilities.</p><pre>+-----------------------------------+                    +-------------------------------------+<br>|      A2A Client (Orchestrator)    |                    |      A2A Agent (Server)             |<br>|                                   |                    | +---------------------------------+ |<br>| 1. Discover Agent Manifest        |     HTTP GET       | | /.well-known/agent.json         | |<br>|    (Identifies Skills, Schemas)   |&lt;-------------------| | (The Agent&#39;s Public Resume)     | |<br>|                                   |                    | +---------------------------------+ |<br>|                                   |                    |                                     |<br>| 2. Invoke Skill (Send Task)       |     HTTP POST      | +---------------------------------+ |<br>|    (A2A Request, JSON-RPC 2.0)    |-------------------&gt;| | /tasks/send                     | |<br>|                                   |                    | | (The Agent&#39;s Action Center)     | |<br>|                                   |                    | +---------+-----------------------+ |<br>|                                   |                    |           |                         |<br>|                                   |                    |           | Internal Processing     |<br>|                                   |                    |           | (NLP, Vector Embedding, |<br>|                                   |                    |           | Database Queries, AI Logic)|<br>|                                   |                    |           |                         |<br>|                                   |                    | +---------v-----------------------+ |<br>| 3. Receive Response               |&lt;-------------------| | Structured A2A Response         | |<br>|    (A2A Response, JSON-RPC 2.0)   |                    | | (Results, Status, Artifacts)    | |<br>+-----------------------------------+                    +-------------------------------------+</pre><h4>The Core Pillars of A2A</h4><p>At its heart, an A2A system comprises two main actors:</p><ol><li><strong>The A2A Agent (Server):</strong> A specialized service that exposes its capabilities.</li><li><strong>The A2A Client (Orchestrator/Consumer):</strong> A service that discovers and utilizes the agent’s capabilities.</li></ol><p>Let’s break down how they interact.</p><h4>The A2A Agent: Your Intelligent Service’s Public Face</h4><p>Every A2A agent acts as a server, making its functionalities known to the world through two crucial endpoints: the Manifest and the Task Endpoint.</p><p>a. The Agent Manifest: Your Service’s Resume (/.well-known/agent.json)</p><p>Imagine a central registry where every intelligent service publishes its capabilities. The A2A manifest fulfills this role. It’s a JSON document served at a standard, predictable URL (e.g., <a href="http://your-agent.com/.well-known/agent.json).">http://your-agent.com/.well-known/agent.json).</a></p><p>This manifest isn’t just metadata; it’s a contract. It details:</p><ul><li><strong>Identity:</strong> name, description, provider, and version of the agent.</li><li><strong>Capabilities:</strong> Whether it supports streaming, push notifications, etc.</li><li><strong>Skills:</strong> This is the most vital part. Each skill object describes a specific function the agent can perform (e.g., translate-text, generate-image, find-bus-route).</li><li><strong>id &amp; </strong><strong>name:</strong> Unique identifiers for the skill.</li><li><strong>description &amp; </strong><strong>tags:</strong> Human-readable explanations and keywords for discoverability.</li><li><strong>examples:</strong> Crucial for demonstrating how to use the skill.</li><li><strong>input_schema:</strong> A JSON Schema that strictly defines the structure of the request payload for this skill. This ensures that any client interacting with the agent sends data in the correct format.</li><li><strong>output_schema:</strong> Another JSON Schema specifying the expected structure of the response. This allows clients to reliably parse the results.</li></ul><p><strong>Code Snippet: A2A Agent Manifest (from </strong><strong>a2a_server.py)</strong></p><pre># a2a_server.py<br>@app.get(&quot;/.well-known/agent.json&quot;)<br>async def agent_manifest():<br>    return {<br>        &quot;name&quot;: &quot;Simple Greeting Agent&quot;,<br>        &quot;description&quot;: &quot;An agent that can generate personalized greetings.&quot;,<br>        &quot;url&quot;: &quot;http://localhost:8000/&quot;,<br>        &quot;version&quot;: &quot;1.0.0&quot;,<br>        &quot;provider&quot;: {<br>            &quot;organization&quot;: &quot;Sample Co.&quot;,<br>            &quot;url&quot;: &quot;https://example.com&quot;<br>        },<br>        &quot;skills&quot;: [<br>            {<br>                &quot;id&quot;: &quot;greet-user&quot;,<br>                &quot;name&quot;: &quot;Greet User&quot;,<br>                &quot;description&quot;: &quot;Generates a personalized greeting message for a given name.&quot;,<br>                &quot;input_schema&quot;: {<br>                    &quot;type&quot;: &quot;object&quot;,<br>                    &quot;properties&quot;: {<br>                        &quot;message&quot;: {<br>                            &quot;type&quot;: &quot;object&quot;,<br>                            &quot;properties&quot;: {<br>                                &quot;parts&quot;: {<br>                                    &quot;type&quot;: &quot;array&quot;,<br>                                    &quot;items&quot;: {<br>                                        &quot;type&quot;: &quot;object&quot;,<br>                                        &quot;properties&quot;: {<br>                                            &quot;type&quot;: {&quot;type&quot;: &quot;string&quot;, &quot;enum&quot;: [&quot;text&quot;]},<br>                                            &quot;text&quot;: {&quot;type&quot;: &quot;string&quot;, &quot;description&quot;: &quot;The name to greet.&quot;}<br>                                        },<br>                                        &quot;required&quot;: [&quot;type&quot;, &quot;text&quot;]<br>                                    }<br>                                }<br>                            },<br>                            &quot;required&quot;: [&quot;parts&quot;]<br>                        }<br>                    },<br>                    &quot;required&quot;: [&quot;message&quot;]<br>                },<br>                &quot;output_schema&quot;: {<br>                    &quot;type&quot;: &quot;object&quot;,<br>                    &quot;properties&quot;: {<br>                        &quot;greeting_message&quot;: {<br>                            &quot;type&quot;: &quot;string&quot;,<br>                            &quot;description&quot;: &quot;The personalized greeting generated by the agent.&quot;<br>                        }<br>                    },<br>                    &quot;required&quot;: [&quot;greeting_message&quot;]<br>                }<br>            }<br>        ]<br>    }</pre><p>b. The Task Endpoint: The Operational Core (/tasks/send)</p><p>Once a client has intelligently parsed an agent’s manifest and identified the desired skill, it sends an HTTP POST request to the agent’s /tasks/send endpoint. This endpoint serves as the operational heart, triggering the execution of the requested skill.</p><p>Upon receiving the payload, the agent’s robust internal logic springs into action, performing a sequence of sophisticated steps such as:</p><ol><li><strong>Request Parsing:</strong> Carefully extract the message and relevant parameters from the incoming A2A request.</li><li><strong>Intelligent Processing:</strong> Engage specialized modules (e.g., Natural Language Processing for intent recognition, image processing for feature extraction, business rule engines for decision making).</li><li><strong>Data Transformation:</strong> Transform data (e.g., generate high-dimensional vector embeddings for semantic understanding, convert data formats).</li><li><strong>Data Retrieval &amp; AI Inference:</strong> Interact with data stores (e.g., execute database queries, perform vector searches on specialized databases, retrieve information from external APIs).</li><li><strong>Result Refinement:</strong> Apply filtering, sorting, and aggregation to the raw outputs.</li><li><strong>Response Orchestration:</strong> Finally, the agent constructs a standardized A2A response, typically adhering to the JSON-RPC 2.0 specification. This response includes a status (e.g., completed, failed), history (if stateful), and crucial artifacts containing the precise output, tailored to the output_schema defined in the manifest.</li></ol><p><strong>Code Snippet: Illustrative A2A Task Endpoint (from </strong><strong>a2a_server.py)</strong></p><pre># a2a_server.py<br>from datetime import datetime # Import datetime for timestamp</pre><pre>@app.post(&quot;/tasks/send&quot;)<br>async def send_task(request: Request):<br>    payload = await request.json()<br>    # Extract task_id, request_id from payload (simplified for brevity)<br>    task_id = payload.get(&quot;params&quot;, {}).get(&quot;id&quot;) or payload.get(&quot;id&quot;, &quot;default_task_id&quot;)<br>    request_id = payload.get(&quot;id&quot;, &quot;default_request_id&quot;)<br>    <br>    # Extract user text from the message parts<br>    message_parts = payload.get(&quot;params&quot;, {}).get(&quot;message&quot;, {}).get(&quot;parts&quot;, [])<br>    user_text = &quot;&quot;<br>    if message_parts and isinstance(message_parts[0], dict) and &quot;text&quot; in message_parts[0]:<br>        user_text = message_parts[0][&quot;text&quot;]<br>    elif message_parts and isinstance(message_parts[0], str): # Fallback for plain string message<br>        user_text = message_parts[0]</pre><pre>    # Core logic based on user_text (e.g., generate a simple greeting)<br>    greeting = f&quot;Hello, {user_text}! A pleasure to interact with you!&quot; if user_text else &quot;Greetings, esteemed user!&quot;<br>    <br>    # Construct A2A compliant response adhering to JSON-RPC 2.0 and output_schema<br>    response_payload = {<br>        &quot;jsonrpc&quot;: &quot;2.0&quot;,<br>        &quot;id&quot;: request_id,<br>        &quot;result&quot;: {<br>            &quot;id&quot;: task_id,<br>            &quot;status&quot;: {<br>                &quot;state&quot;: &quot;completed&quot;, # Can also be &quot;failed&quot;<br>                &quot;timestamp&quot;: datetime.utcnow().isoformat()<br>            },<br>            &quot;history&quot;: [], # For stateful agents, this would contain history of state transitions<br>            &quot;artifacts&quot;: [<br>                {<br>                    &quot;parts&quot;: [<br>                        {<br>                            &quot;type&quot;: &quot;text&quot;,<br>                            &quot;text&quot;: greeting # Primary textual output<br>                        }<br>                    ],<br>                    &quot;index&quot;: 0<br>                }<br>            ]<br>        },<br>        &quot;greeting_message&quot;: greeting # Custom field as per output_schema<br>    }<br>    return JSONResponse(response_payload)</pre><h4>The A2A Client: The Intelligent Orchestrator</h4><p>An A2A client is any application or service that wants to leverage the capabilities of an A2A agent. This could be a user interface, a chatbot, or even another A2A agent acting as an orchestrator for a multi-step workflow.</p><p>The client’s workflow is straightforward:</p><ol><li><strong>Dynamic Discovery:</strong> The client initiates interaction by performing an HTTP GET request to the agent’s manifest URL (/.well-known/agent.json). This crucial step allows it to dynamically learn about the agent&#39;s skills and their precise input_schema and output_schema, without any prior hardcoding.</li><li><strong>Intelligent Request Construction:</strong> Guided by its understanding of the user’s intent or its internal logic, the client selects the most appropriate skill and constructs a request payload that rigidly conforms to that skill’s input_schema. This ensures valid and predictable data transmission.</li><li><strong>Skill Invocation:</strong> The client then dispatches an HTTP POST request, encapsulating the A2A payload, to the agent’s /tasks/send endpoint.</li><li><strong>Robust Response Processing:</strong> Upon receiving the A2A response, the client performs several critical steps: it meticulously checks the status (e.g., completed, failed) to ascertain task success, and then intelligently parses the artifacts and other custom fields according to the output_schema to extract the desired results.</li><li><strong>Actionable Outcomes:</strong> Based on the processed response, the client can then take subsequent actions: rendering results to a user, storing data, triggering another A2A agent’s skill (enabling powerful chaining), or initiating error handling routines.</li></ol><p><strong>Code Snippet: Illustrative A2A Client Interaction (from </strong><strong>a2a_client.py)</strong></p><pre># a2a_client.py<br>import requests<br>import json<br>from datetime import datetime # Import datetime for dynamic IDs<br><br>AGENT_BASE_URL = &quot;http://localhost:8000&quot; # Ensure this matches your server&#39;s address<br><br>def discover_agent_manifest(agent_url: str) -&gt; dict:<br>    &quot;&quot;&quot;<br>    Fetches and returns the agent&#39;s manifest, raising an exception on HTTP errors.<br>    &quot;&quot;&quot;<br>    manifest_url = f&quot;{agent_url}/.well-known/agent.json&quot;<br>    print(f&quot;Client: Attempting to discover manifest at: {manifest_url}&quot;)<br>    response = requests.get(manifest_url)<br>    response.raise_for_status() # Raises HTTPError for bad responses (4xx or 5xx)<br>    manifest = response.json()<br>    print(&quot;\nClient: --- Agent Manifest Discovered ---&quot;)<br>    print(json.dumps(manifest, indent=2))<br>    return manifest<br><br>def invoke_agent_skill(agent_url: str, skill_id: str, message_text: str) -&gt; dict:<br>    &quot;&quot;&quot;<br>    Invokes a specific skill on the agent with a given message text.<br>    &quot;&quot;&quot;<br>    task_send_url = f&quot;{agent_url}/tasks/send&quot;<br>    <br>    # Construct the A2A compliant request payload<br>    request_payload = {<br>        &quot;jsonrpc&quot;: &quot;2.0&quot;,<br>        &quot;id&quot;: &quot;req-client-&quot; + datetime.now().strftime(&quot;%Y%m%d%H%M%S%f&quot;), # Dynamic unique request ID<br>        &quot;params&quot;: {<br>            &quot;id&quot;: &quot;task-client-&quot; + datetime.now().strftime(&quot;%Y%m%d%H%M%S%f&quot;), # Dynamic unique task ID<br>            &quot;message&quot;: {<br>                &quot;parts&quot;: [<br>                    {&quot;type&quot;: &quot;text&quot;, &quot;text&quot;: message_text}<br>                ]<br>            }<br>        }<br>    }<br><br>    print(f&quot;\nClient: --- Sending Task to Agent for skill &#39;{skill_id}&#39; ---&quot;)<br>    print(f&quot;Client: Request Payload: {json.dumps(request_payload, indent=2)}&quot;)<br><br>    response = requests.post(task_send_url, json=request_payload)<br>    response.raise_for_status()<br>    result = response.json()<br>    print(&quot;\nClient: --- Agent Response Received ---&quot;)<br>    print(json.dumps(result, indent=2))<br>    return result<br><br>if __name__ == &quot;__main__&quot;:<br>    # Ensure the A2A server (a2a_server.py) is running before executing the client<br>    try:<br>        # Step 1: Client dynamically discovers the agent&#39;s capabilities<br>        manifest = discover_agent_manifest(AGENT_BASE_URL)<br><br>        # In a production client, you&#39;d parse the manifest to find the desired skill<br>        # by ID or a more sophisticated matching logic based on user intent.<br>        # Here, we assume &#39;greet-user&#39; is the first skill.<br>        skill_to_invoke = None<br>        for skill in manifest.get(&quot;skills&quot;, []):<br>            if skill.get(&quot;id&quot;) == &quot;greet-user&quot;:<br>                skill_to_invoke = skill.get(&quot;id&quot;)<br>                break<br>        <br>        if skill_to_invoke:<br>            # Step 2 &amp; 3: Client constructs and sends a request to invoke the skill<br>            print(f&quot;\nClient: Invoking &#39;{skill_to_invoke}&#39; Skill with input &#39;Alice&#39;...&quot;)<br>            response = invoke_agent_skill(AGENT_BASE_URL, skill_to_invoke, &quot;Alice&quot;)<br><br>            # Step 4: Client parses the response and takes action<br>            status = response.get(&quot;result&quot;, {}).get(&quot;status&quot;, {}).get(&quot;state&quot;)<br>            # Safely extract text from artifacts, checking nested dictionaries<br>            output_artifact_text = &quot;N/A&quot;<br>            if response.get(&quot;result&quot;, {}).get(&quot;artifacts&quot;):<br>                first_artifact = response[&quot;result&quot;][&quot;artifacts&quot;][0]<br>                if first_artifact.get(&quot;parts&quot;):<br>                    first_part = first_artifact[&quot;parts&quot;][0]<br>                    output_artifact_text = first_part.get(&quot;text&quot;, &quot;N/A&quot;)<br><br>            # Accessing custom fields from the output_schema<br>            custom_greeting = response.get(&quot;greeting_message&quot;, &quot;N/A&quot;)<br><br>            print(f&quot;\nClient: --- Processed Results ---&quot;)<br>            print(f&quot;Client: Task Status: {status}&quot;)<br>            print(f&quot;Client: Agent&#39;s Primary Text Artifact: {output_artifact_text}&quot;)<br>            print(f&quot;Client: Agent&#39;s Custom Greeting Field: {custom_greeting}&quot;)<br><br>            if status == &quot;completed&quot; and &quot;Alice&quot; in output_artifact_text:<br>                print(&quot;\nClient: Successfully received a personalized greeting for Alice!&quot;)<br>            else:<br>                print(&quot;\nClient: Task did not complete successfully or response was unexpected.&quot;)<br>        else:<br>            print(&quot;\nClient: No &#39;greet-user&#39; skill found in the agent manifest.&quot;)<br>    except requests.exceptions.ConnectionError:<br>        print(f&quot;\nClient: Error: Could not connect to the agent at {AGENT_BASE_URL}.&quot;)<br>        print(&quot;Please ensure the &#39;a2a_server.py&#39; is running and accessible.&quot;)<br>    except requests.exceptions.RequestException as e:<br>        print(f&quot;\nClient: An unexpected error occurred during interaction: {e}&quot;)<br>    except Exception as e:<br>        print(f&quot;\nClient: An unhandled error occurred: {e}&quot;)</pre><h4>The Strategic Benefits of A2A: Why it Matters for Your Architecture</h4><p>Adopting an A2A-inspired architecture offers profound advantages, making it an increasingly attractive paradigm for modern system design:</p><ul><li><strong>Unparalleled Interoperability:</strong> The cornerstone of A2A. Standardized manifests and meticulously defined communication schemas ensure that disparate agents — developed by different teams, using different technologies, or even managed by different organizations — can seamlessly understand and communicate with each other. This breaks down technological silos.</li><li><strong>Enhanced Modularity &amp; Specialization:</strong> Complex problems can be decomposed into smaller, highly specialized agents, each focusing on a distinct capability. This dramatically simplifies development, facilitates independent testing, and streamlines maintenance, allowing teams to become experts in specific domains.</li><li><strong>Dynamic Extensibility:</strong> The system can evolve organically. New agents or skills can be introduced into the ecosystem without necessitating modifications to existing clients or orchestrators, so long as they adhere to the A2A standard. This fosters agility and future-proofs your architecture.</li><li><strong>Optimized Scalability:</strong> Each agent, being an independent service, can be scaled autonomously based on its specific load requirements. This allows for fine-grained resource allocation and cost optimization, preventing bottlenecks in the overall system.</li><li><strong>Intelligent Adaptation:</strong> Clients gain the ability to dynamically discover and adapt to new functionalities as agents are updated or novel agents are deployed across the network. This leads to inherently more resilient, flexible, and adaptive systems that can respond to changing requirements without manual intervention.</li></ul><h3>Conclusion</h3><p>Google’s A2A protocol provides a robust and visionary blueprint for constructing intelligent, scalable, and inherently interoperable systems. By meticulously adhering to its standardized discovery and interaction mechanisms, developers can unlock the true potential of distributed intelligence. This empowers the creation of highly sophisticated and adaptive applications that were once deemed prohibitively complex. Whether your goal is to integrate existing legacy services, build groundbreaking new AI capabilities, or orchestrate complex workflows, an A2A-inspired architecture stands as a powerful and forward-thinking paradigm for your next engineering endeavor.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e0f20b5fbcb6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/redbus-in/beyond-monoliths-crafting-interoperable-ai-systems-with-googles-a2a-agent-architecture-e0f20b5fbcb6">Beyond Monoliths: Crafting Interoperable AI Systems with Google’s A2A Agent Architecture</a> was originally published in <a href="https://medium.com/redbus-in">redbus India Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cassandra’s Vector Horizon: Semantic Search at Enterprise Scale]]></title>
            <link>https://medium.com/redbus-in/cassandras-vector-horizon-semantic-search-at-enterprise-scale-5d4b8e7f9a84?source=rss-73701b352c31------2</link>
            <guid isPermaLink="false">https://medium.com/p/5d4b8e7f9a84</guid>
            <category><![CDATA[vector-search]]></category>
            <category><![CDATA[apache-cassandra]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[semantic-search]]></category>
            <category><![CDATA[vector-database]]></category>
            <dc:creator><![CDATA[Sandeep Belgavi]]></dc:creator>
            <pubDate>Sun, 06 Apr 2025 17:38:35 GMT</pubDate>
            <atom:updated>2025-12-02T06:26:04.034Z</atom:updated>
            <content:encoded><![CDATA[<p>In today’s data-driven world, the ability to search beyond keywords is becoming increasingly crucial. We need to understand the <em>meaning</em> behind the data, finding connections and similarities that traditional keyword searches often miss. Enter <strong>vector search</strong>, a powerful technique that represents data points as high-dimensional vectors, allowing us to measure their semantic similarity.</p><p>While dedicated vector databases are gaining traction, what if you could leverage the scalability, resilience, and proven reliability of Apache Cassandra for your vector search needs? Recent advancements in Cassandra have made this a reality, offering native support for vector data types and indexing.</p><p>This article will guide you through the exciting world of Cassandra’s vector search capabilities, exploring how it enables semantic search and diving into the nuances of different distance metrics.</p><p><strong>The Essence of Vector Embeddings</strong></p><p>Before we delve into Cassandra, let’s briefly touch upon the foundation: <strong>vector embeddings</strong>. These are numerical representations of data (text, images, audio, etc.) in a multi-dimensional space. The key idea is that data points with similar meanings or characteristics will have vector embeddings that are closer to each other in this space.</p><p>Creating these embeddings typically involves using machine learning models (like Transformer models for text or convolutional neural networks for images). Once you have these embeddings, you need a way to efficiently find the nearest neighbors — the data points with the most similar embeddings. This is where Cassandra’s vector search comes in.</p><h3>Cassandra’s Native Vector Search: A Game Changer</h3><p>Cassandra now supports a native vector data type, allowing you to directly store your vector embeddings within your tables. This eliminates the need for separate vector databases in many use cases, simplifying your architecture and leveraging Cassandra&#39;s inherent strengths in scalability, high availability, and fault tolerance.</p><p><strong>Defining a Table with a Vector Column:</strong></p><p>Code snippet</p><pre>CREATE TABLE IF NOT EXISTS products (<br>    id UUID PRIMARY KEY,<br>    name TEXT,<br>    description TEXT,<br>    features_embedding vector&lt;FLOAT, 3072&gt;<br>);</pre><h3>The Power of Distance Metrics: Measuring Similarity</h3><p>Once you have your vector embeddings in Cassandra, you need a way to quantify their similarity. This is where <strong>distance metrics</strong> come into play. Cassandra supports several distance metrics for vector search, including:</p><p><strong>Cosine Similarity:</strong></p><ul><li><strong>Concept:</strong> Measures the cosine of the angle between two vectors. Focuses on vector orientation.</li><li><strong>Suitable for:</strong> Comparing documents of different lengths, scenarios where vector direction is more important than magnitude.</li><li><strong>Range:</strong> -1 (opposite) to 1 (identical), 0 (orthogonal/no similarity). Higher score = greater similarity.</li><li><strong>Use Cases:</strong> Text similarity, document retrieval, recommendation systems (semantic direction).</li><li><strong>Cassandra Index:</strong></li></ul><pre>CREATE INDEX product_cosine_idx ON products (features_embedding) USING &#39;sai&#39; WITH OPTIONS = { &#39;similarity_function&#39;: &#39;COSINE&#39; };</pre><p><strong>Dot Product:</strong></p><ul><li><strong>Concept:</strong> Sum of the products of corresponding vector components.</li><li><strong>Similarity Indicator:</strong> Higher value generally means greater similarity, especially for normalized vectors.</li><li><strong>Range:</strong> Depends on vector magnitudes. For normalized vectors, equivalent to cosine similarity.</li><li><strong>Use Cases:</strong> Computationally cheaper alternative to cosine (with normalization), recommendation systems (magnitude can matter).</li><li><strong>Cassandra Index:</strong></li></ul><pre>CREATE INDEX product_dot_product_idx ON products (features_embedding) USING &#39;sai&#39; WITH OPTIONS = { &#39;similarity_function&#39;: &#39;DOT_PRODUCT&#39; };</pre><p><strong>Euclidean Distance:</strong></p><ul><li><strong>Concept:</strong> Straight-line distance between vector endpoints.</li><li><strong>Similarity Indicator:</strong> Lower value means greater similarity.</li><li><strong>Range:</strong> 0 (identical) to positive infinity.</li><li><strong>Suitable for:</strong> When vector magnitude is important, absolute feature differences matter.</li><li><strong>Use Cases:</strong> Image similarity (raw features), anomaly detection (proximity in feature space).</li><li><strong>Cassandra Index:</strong></li></ul><pre>CREATE INDEX product_euclidean_idx ON products (features_embedding) USING &#39;sai&#39; WITH OPTIONS = { &#39;similarity_function&#39;: &#39;EUCLIDEAN&#39; };</pre><p><strong>Choosing the Right Metric:</strong> The best distance metric depends on the nature of your data, how your embeddings were generated, and what constitutes “similarity” in your specific use case. Understanding the characteristics of your embeddings and experimenting with different metrics can help you find the most effective one.</p><h3>Indexing for Speed: Making Vector Search Efficient</h3><p>Performing a similarity search by comparing a query vector with every vector in your table would be computationally expensive, especially for large datasets. To address this, Cassandra offers indexing capabilities specifically designed for vector search.</p><p>You can create an index on your vector column to accelerate similarity queries. The specific type of index and its configuration can influence the performance and accuracy of your vector searches.</p><h3>Performing Vector Similarity Searches</h3><p>Once your table is set up with vector data and an appropriate index, you can perform similarity searches using CQL:</p><pre>SELECT id, name, description, features_embedding<br>FROM products<br>ORDER BY features_embedding ANN OF [0.1, 0.5, ..., -0.2] -- Your query vector here<br>LIMIT 5; -- Retrieve the top 5 most similar products</pre><p>The ANN OF keyword is used to perform Approximate Nearest Neighbor search. The query vector is provided as a list of floating-point numbers. The ORDER BY clause combined with ANN OF leverages the underlying vector index to find the most similar vectors. The LIMIT clause restricts the number of results returned.</p><p><strong>Important Note:</strong> The performance and accuracy of the ANN OF query depend on the chosen indexing strategy and the size and distribution of your data.</p><h3>Use Cases and Benefits</h3><p>Cassandra’s vector search capabilities open up a wide range of exciting possibilities:</p><ul><li><strong>Semantic Search:</strong> Understanding the meaning behind user queries to provide more relevant search results.</li><li><strong>Recommendation Engines:</strong> Finding similar items or users based on their vector representations for personalized recommendations.</li><li><strong>Content Similarity:</strong> Identifying documents, images, or other media with similar content.</li><li><strong>Anomaly Detection:</strong> Identifying unusual data points by comparing their vector embeddings to those of normal data.</li><li><strong>Question Answering Systems:</strong> Matching user questions with relevant passages in a knowledge base.</li></ul><p><strong>Benefits of using Cassandra for Vector Search:</strong></p><ul><li><strong>Scalability and High Availability:</strong> Leverage Cassandra’s proven architecture for handling massive datasets and ensuring continuous availability.</li><li><strong>Simplified Architecture:</strong> Consolidate your data storage and vector search capabilities within a single database.</li><li><strong>Real-time Performance:</strong> Cassandra’s low-latency reads and writes make it suitable for real-time applications.</li><li><strong>Data Locality:</strong> Storing vector embeddings alongside other relevant data can improve query performance.</li></ul><h3>Conclusion: Embracing Semantic Understanding with Cassandra</h3><p>Cassandra’s foray into vector search marks a significant step forward, empowering developers to build intelligent applications that go beyond keyword matching. By understanding the principles of vector embeddings and distance metrics, you can harness the power of Cassandra to unlock the semantic potential of your data. As this feature continues to evolve, we can expect even more sophisticated and performant vector search capabilities within this robust and widely adopted NoSQL database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*vmy-3LEpMN557KzbqxEPyw.png" /><figcaption><strong>Exploring the Relationships Within Your Data with Cassandra’s Vector Capabilities</strong></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5d4b8e7f9a84" width="1" height="1" alt=""><hr><p><a href="https://medium.com/redbus-in/cassandras-vector-horizon-semantic-search-at-enterprise-scale-5d4b8e7f9a84">Cassandra’s Vector Horizon: Semantic Search at Enterprise Scale</a> was originally published in <a href="https://medium.com/redbus-in">redbus India Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NLP-Powered Word Game: Building Semantic Similarity with GloVe and Flask]]></title>
            <link>https://medium.com/@sandeep.b_41968/nlp-powered-word-game-building-semantic-similarity-with-glove-and-flask-8b74121656c3?source=rss-73701b352c31------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b74121656c3</guid>
            <dc:creator><![CDATA[Sandeep Belgavi]]></dc:creator>
            <pubDate>Fri, 28 Mar 2025 05:10:49 GMT</pubDate>
            <atom:updated>2025-03-28T05:10:49.034Z</atom:updated>
            <content:encoded><![CDATA[<p>Introduction:</p><p>In the realm of Natural Language Processing (NLP), understanding the meaning and relationships between words is fundamental. Word embeddings, like GloVe, provide a powerful way to represent words as numerical vectors, capturing their semantic nuances. By measuring the similarity between these vectors, we can determine how closely related words are in meaning. This concept of semantic similarity can be harnessed to create engaging and educational word games.</p><p>The code we’re about to explore implements a “Word Context Game” that leverages this principle. The game challenges users to guess a target word by providing words with varying degrees of semantic similarity. The game uses cosine similarity to quantify the relationship between the guessed word and the target word. This game is a great example of how word embeddings can be used to create interactive and insightful NLP applications..</p><p>Core Concepts:</p><p>Word Embeddings: The heart of the game lies in word embeddings, specifically GloVe (Global Vectors for Word Representation) in this case. These embeddings represent words as dense vectors in a high-dimensional space, capturing semantic relationships between words. The load_word_embeddings function reads a GloVe file, mapping words to their corresponding vectors. This allows the game to quantify the similarity between words.</p><p>Cosine Similarity: The calculate_similarity function utilizes cosine similarity to measure the semantic relatedness between the user’s guess and the target word.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/534/0*AgM_79gV5wgZGgvj" /></figure><p>Where A and B are the vectors of the two words. A higher cosine similarity indicates a closer semantic relationship.</p><p>Game Logic: The WordContextGame class encapsulates the game’s logic. It manages the target word, difficulty level, and similarity calculations. The set_difficulty method allows users to adjust the game’s challenge. The set_target_word method selects a random word from the GloVe vocabulary, or permits the developer to set a specific word. The get_feedback function provides textual feedback based on the similarity score and the selected difficulty level.</p><p>Flask Web Application: The code utilizes Flask to create a web-based interface. The / route renders the index.html template, providing the game’s interface. The /guess route handles user input, calculates similarity, and returns feedback as JSON.</p><p>Text Preprocessing: The preprocess_text function cleans the input text by lowercasing, removing punctuation, tokenizing, and removing stop words. This ensures that the similarity calculations are based on meaningful words.</p><p>Conclusion:</p><p>“Context Connect” showcases the practical use of word embeddings and cosine similarity for interactive language games. It utilizes a Flask web interface to engage users in guessing target words based on semantic similarity. The game’s adjustable difficulty and clear feedback enhance the user experience. This project effectively translates NLP concepts into an entertaining and educational application. Further development could incorporate visual elements and user-generated content for a more immersive experience.</p><p>I’ve made the project’s code publicly available. You can explore it on GitHub</p><p><a href="https://github.com/Sandeep-BA/AI-ML/tree/main/nlp_word_game">https://github.com/Sandeep-BA/AI-ML/tree/main/nlp_word_game</a></p><p>Acknowledgements: I would like to thank the Stanford NLP Group for their publicly available GloVe word embeddings. These embeddings played a crucial role in enabling the semantic similarity calculations used in this project.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b74121656c3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unleashing Sentence Similarity with BERT and Flask: A Practical Guide]]></title>
            <link>https://medium.com/redbus-in/unleashing-sentence-similarity-with-bert-and-flask-a-practical-guide-df0b061c10d8?source=rss-73701b352c31------2</link>
            <guid isPermaLink="false">https://medium.com/p/df0b061c10d8</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[sentence-similarity]]></category>
            <category><![CDATA[bert]]></category>
            <dc:creator><![CDATA[Sandeep Belgavi]]></dc:creator>
            <pubDate>Sun, 02 Mar 2025 15:36:23 GMT</pubDate>
            <atom:updated>2025-12-02T03:50:53.833Z</atom:updated>
            <content:encoded><![CDATA[<p>In the realm of Natural Language Processing (NLP), understanding the semantic relationship between sentences is crucial for various applications, from search engines and chatbots to sentiment analysis and text summarization. This article delves into a practical implementation of sentence similarity using the powerful BERT model and a Flask web application, allowing you to easily generate sentence embeddings and calculate cosine similarity score</p><p><strong>Why BERT?</strong></p><p>BERT (Bidirectional Encoder Representations from Transformers) has revolutionized NLP by capturing contextual relationships within text. Unlike traditional word embeddings that assign a single vector to each word, BERT generates dynamic embeddings that adapt to the surrounding words, leading to a deeper understanding of sentence meaning.</p><p><strong>Building the Flask Application</strong></p><p>We’ll create a simple Flask application that allows users to input two sentences and receive their similarity score and embeddings.</p><p><strong>1. Setting up the Environment:</strong></p><p>First, ensure you have Python installed. Then, install the necessary libraries:</p><p>Bash</p><pre>pip install flask transformers torch scikit-learn</pre><p><strong>2. The Python Code (app.py):</strong></p><pre>from flask import Flask, request, jsonify, render_template_string<br>from transformers import BertTokenizer, BertModel<br>import torch<br>from sklearn.metrics.pairwise import cosine_similarity</pre><pre>app = Flask(__name__)</pre><pre>tokenizer = BertTokenizer.from_pretrained(&#39;bert-base-uncased&#39;)<br>model = BertModel.from_pretrained(&#39;bert-base-uncased&#39;)</pre><pre>def get_embedding(sentence):<br>    inputs = tokenizer(sentence, return_tensors=&#39;pt&#39;, truncation=True, padding=True, max_length=128)<br>    outputs = model(**inputs)<br>    return outputs.last_hidden_state.mean(dim=1).detach().numpy()<br>@app.route(&#39;/&#39;)<br>def index():<br>    return render_template_string(&#39;&#39;&#39;<br>        ... (HTML code from the previous response) ...<br>    &#39;&#39;&#39;)<br>@app.route(&#39;/embed&#39;, methods=[&#39;POST&#39;])<br>def embed():<br>    data = request.json<br>    sentence = data.get(&#39;sentence&#39;, &#39;&#39;)<br>    embedding = get_embedding(sentence)<br>    return jsonify({&#39;embedding&#39;: embedding.tolist()})<br>@app.route(&#39;/similarity&#39;, methods=[&#39;POST&#39;])<br>def similarity():<br>    data = request.json<br>    sentence1 = data.get(&#39;sentence1&#39;, &#39;&#39;)<br>    sentence2 = data.get(&#39;sentence2&#39;, &#39;&#39;)<br>    embedding1 = get_embedding(sentence1)<br>    embedding2 = get_embedding(sentence2)<br>    similarity_score = cosine_similarity(embedding1, embedding2)[0][0]<br>    return jsonify({&#39;similarity&#39;: float(similarity_score), &#39;embedding1&#39;: embedding1.tolist(), &#39;embedding2&#39;: embedding2.tolist()})<br>if __name__ == &#39;__main__&#39;:<br>    app.run(host=&#39;0.0.0.0&#39;, port=5000)</pre><p><strong>3. Understanding the Code:</strong></p><ul><li><strong>BERT Model and Tokenizer:</strong> We load the pre-trained BERT model and tokenizer.</li><li><strong>get_embedding(sentence):</strong> This function tokenizes the input sentence, passes it through the BERT model, and returns the mean of the last hidden state as the sentence embedding.</li><li><strong>Flask Routes:</strong></li><li>/: Renders the HTML form for inputting sentences.</li><li>/embed: receives a sentence via POST request and returns it&#39;s embedding.</li><li>/similarity: receives two sentences, calculates their embeddings, computes the cosine similarity, and returns the results.</li><li><strong>Cosine Similarity:</strong> We use sklearn.metrics.pairwise.cosine_similarity to calculate the similarity score between the two sentence embeddings.</li></ul><p><strong>4. Running the Application:</strong></p><p>Save the code as app.py and run it from your terminal:</p><pre>python app.py</pre><p>Open your browser and navigate to http://0.0.0.0:5000. You&#39;ll see the form where you can input two sentences and get their similarity score and embeddings.</p><p><strong>5. HTML Structure and Functionality</strong></p><p>The HTML portion of the code provides a user-friendly interface. It includes:</p><ul><li>Two input fields for the sentences.</li><li>A “Submit” button to trigger the similarity calculation.</li><li>A “Clear” button to reset the form.</li><li>Tables to display the similarity score and embeddings.</li><li>A collapsable section that explains how the application works.</li><li>Javascript to handle the form submission, clear the form, and toggle the collapsable section.</li></ul><p><strong>6. Practical Applications:</strong></p><p>This application can be extended for various NLP tasks:</p><ul><li><strong>Semantic Search:</strong> Improve search results by ranking documents based on semantic similarity to the query.</li><li><strong>Question Answering:</strong> Find answers to questions by comparing the question’s embedding with the embeddings of candidate answers.</li><li><strong>Text Clustering:</strong> Group similar documents or sentences together.</li><li><strong>Paraphrase Detection:</strong> Identify sentences with similar meanings.</li><li><strong>Chatbots:</strong> Enhance chatbot responses by understanding the semantic intent of user input.</li></ul><p><strong>7. Further Improvements:</strong></p><ul><li><strong>Error Handling:</strong> Add error handling for invalid input or model loading issues.</li><li><strong>Larger Datasets:</strong> Integrate with larger datasets for more complex similarity calculations.</li><li><strong>Fine-tuning:</strong> Fine-tune the BERT model on specific tasks for improved accuracy.</li><li><strong>Deployment:</strong> Deploy the Flask application to a cloud platform for wider accessibility.</li></ul><p>By combining the power of BERT with the simplicity of Flask, you can easily build practical NLP applications that leverage sentence similarity. This project serves as a foundation for exploring more advanced NLP techniques and building innovative solutions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=df0b061c10d8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/redbus-in/unleashing-sentence-similarity-with-bert-and-flask-a-practical-guide-df0b061c10d8">Unleashing Sentence Similarity with BERT and Flask: A Practical Guide</a> was originally published in <a href="https://medium.com/redbus-in">redbus India Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>