<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en"><generator uri="https://jekyllrb.com/" version="4.3.4">Jekyll</generator><link href="https://amgadmadkour.com/feed.xml" rel="self" type="application/atom+xml"/><link href="https://amgadmadkour.com/" rel="alternate" type="text/html" hreflang="en"/><updated>2026-06-09T03:15:39+00:00</updated><id>https://amgadmadkour.com/feed.xml</id><title type="html">Amgad Madkour</title><subtitle></subtitle><entry><title type="html">Designing Multi‑Agent AI Systems with Microsoft Agent Framework</title><link href="https://amgadmadkour.com/blog/2026/agent-framework/" rel="alternate" type="text/html" title="Designing Multi‑Agent AI Systems with Microsoft Agent Framework"/><published>2026-05-24T00:00:00+00:00</published><updated>2026-05-24T00:00:00+00:00</updated><id>https://amgadmadkour.com/blog/2026/agent-framework</id><content type="html" xml:base="https://amgadmadkour.com/blog/2026/agent-framework/"><![CDATA[<p>In the rapidly evolving world of AI development, Microsoft’s Agent Framework has emerged as a powerful framework for building intelligent applications that seamlessly blend traditional programming with Large Language Model capabilities. As the unified successor to Semantic Kernel and AutoGen, it brings together enterprise-grade reliability with rich multi-agent orchestration. This blog post explores four distinct examples that demonstrate the evolution from simple AI agents to sophisticated multi-agent systems, each showcasing different patterns and use cases for real-world applications.</p> <h2 id="what-is-microsoft-agent-framework">What is Microsoft Agent Framework?</h2> <p><a href="https://github.com/microsoft/agent-framework">Microsoft Agent Framework</a> is an open-source SDK that enables developers to easily build, orchestrate, and deploy AI agents and multi-agent workflows using conventional programming languages. It unifies the production-tested patterns from Semantic Kernel with the multi-agent research patterns from AutoGen, providing a single, cohesive API for working with different AI services, tools, and workflows.</p> <p>The framework’s strength lies in its ability to orchestrate multiple AI agents, manage complex graph-based workflows, and provide structured interactions between humans and AI systems. Let’s explore how these capabilities are demonstrated through four progressively complex examples.</p> <h2 id="example-1-basic-chat-agent">Example 1: Basic Chat Agent</h2> <p>Our journey begins with the simplest possible implementation—a single <code class="language-plaintext highlighter-rouge">ChatAgent</code> that demonstrates the fundamental building blocks of the Agent Framework.</p> <h3 id="agent-instantiation">Agent Instantiation</h3> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">from</span> <span class="n">agent_framework</span> <span class="kn">import</span> <span class="n">ChatAgent</span>
<span class="kn">from</span> <span class="n">agent_framework.azure</span> <span class="kn">import</span> <span class="n">AzureOpenAIChatClient</span>

<span class="n">agent</span> <span class="o">=</span> <span class="nc">ChatAgent</span><span class="p">(</span>
    <span class="n">chat_client</span><span class="o">=</span><span class="nc">AzureOpenAIChatClient</span><span class="p">(),</span>
    <span class="n">name</span><span class="o">=</span><span class="sh">"</span><span class="s">NewsAgent</span><span class="sh">"</span><span class="p">,</span>
    <span class="n">instructions</span><span class="o">=</span><span class="sh">"</span><span class="s">You are a helpful news agent that helps generate TLDR summaries of news articles.</span><span class="sh">"</span><span class="p">,</span>
<span class="p">)</span>
</code></pre></div></div> <h3 id="key-characteristics">Key Characteristics</h3> <ul> <li><strong>Single Agent</strong>: Uses one <code class="language-plaintext highlighter-rouge">ChatAgent</code> with a specific role</li> <li><strong>Simple Client</strong>: Connects directly to Azure OpenAI via <code class="language-plaintext highlighter-rouge">AzureOpenAIChatClient</code></li> <li><strong>Basic Interaction</strong>: Straightforward request-response pattern</li> <li><strong>Minimal Configuration</strong>: Just a name, instructions, and a chat client</li> </ul> <h3 id="usage-pattern">Usage Pattern</h3> <p>The agent handles a single query and returns a response, making it perfect for:</p> <ul> <li>Simple Q&amp;A applications</li> <li>Basic content generation tasks</li> <li>Learning the core concepts</li> </ul> <p>This example establishes the foundation: every Agent Framework application starts with agents that have specific roles and instructions.</p> <pre><code class="language-mermaid">graph LR
    A[User Input] --&gt; B[NewsAgent]
    B --&gt; C[Azure OpenAI&lt;br/&gt;Chat Client]
    C --&gt; D[Response]
    D --&gt; E[User Output]

    style B fill:#e1f5fe
    style C fill:#f3e5f5
    style A fill:#e8f5e8
    style E fill:#fff3e0
</code></pre> <p style="text-align:center"><em>Figure 1: Basic Agent Framework architecture.</em></p> <h2 id="example-2-tool-enhanced-agent">Example 2: Tool-Enhanced Agent</h2> <p>The second example elevates our capabilities by introducing tools—custom Python functions that provide domain-specific functionality to our AI agent.</p> <h3 id="agent-instantiation-with-tools">Agent Instantiation with Tools</h3> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">from</span> <span class="n">agent_framework</span> <span class="kn">import</span> <span class="n">ChatAgent</span>
<span class="kn">from</span> <span class="n">agent_framework.azure</span> <span class="kn">import</span> <span class="n">AzureOpenAIChatClient</span>
<span class="kn">from</span> <span class="n">pydantic</span> <span class="kn">import</span> <span class="n">BaseModel</span>

<span class="k">class</span> <span class="nc">StockItem</span><span class="p">(</span><span class="n">BaseModel</span><span class="p">):</span>
    <span class="n">company</span><span class="p">:</span> <span class="nb">str</span>
    <span class="n">symbol</span><span class="p">:</span> <span class="nb">str</span>
    <span class="n">price</span><span class="p">:</span> <span class="nb">float</span>

<span class="n">agent</span> <span class="o">=</span> <span class="nc">ChatAgent</span><span class="p">(</span>
    <span class="n">chat_client</span><span class="o">=</span><span class="nc">AzureOpenAIChatClient</span><span class="p">(),</span>
    <span class="n">name</span><span class="o">=</span><span class="sh">"</span><span class="s">StockAgent</span><span class="sh">"</span><span class="p">,</span>
    <span class="n">instructions</span><span class="o">=</span><span class="sh">"</span><span class="s">You are a helpful stock agent. Use tools to fetch live data.</span><span class="sh">"</span><span class="p">,</span>
    <span class="n">tools</span><span class="o">=</span><span class="p">[</span><span class="n">get_stock_price</span><span class="p">],</span>
    <span class="n">response_format</span><span class="o">=</span><span class="n">StockItem</span><span class="p">,</span>
<span class="p">)</span>
</code></pre></div></div> <h3 id="key-enhancements">Key Enhancements</h3> <ul> <li><strong>Tool Integration</strong>: Plain Python functions become callable tools for the model</li> <li><strong>Structured Response</strong>: Uses Pydantic models (<code class="language-plaintext highlighter-rouge">StockItem</code>) for type-safe data handling</li> <li><strong>Response Format</strong>: Constrains the model output to a validated schema</li> <li><strong>Composable</strong>: Tools are just functions, so they’re trivial to reuse and test</li> </ul> <h3 id="tool-definition">Tool Definition</h3> <p>Tools in Agent Framework are regular Python functions, optionally annotated for clearer schemas:</p> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">from</span> <span class="n">typing</span> <span class="kn">import</span> <span class="n">Annotated</span>
<span class="kn">from</span> <span class="n">pydantic</span> <span class="kn">import</span> <span class="n">Field</span>
<span class="kn">import</span> <span class="n">yfinance</span> <span class="k">as</span> <span class="n">yf</span>

<span class="k">def</span> <span class="nf">get_stock_price</span><span class="p">(</span>
    <span class="n">company</span><span class="p">:</span> <span class="n">Annotated</span><span class="p">[</span><span class="nb">str</span><span class="p">,</span> <span class="nc">Field</span><span class="p">(</span><span class="n">description</span><span class="o">=</span><span class="sh">"</span><span class="s">The company ticker, e.g. AAPL</span><span class="sh">"</span><span class="p">)]</span>
<span class="p">)</span> <span class="o">-&gt;</span> <span class="nb">str</span><span class="p">:</span>
    <span class="sh">"""</span><span class="s">Provides the stock price given a company ticker.</span><span class="sh">"""</span>
    <span class="n">current_price</span> <span class="o">=</span> <span class="n">yf</span><span class="p">.</span><span class="nc">Ticker</span><span class="p">(</span><span class="n">company</span><span class="p">).</span><span class="n">fast_info</span><span class="p">[</span><span class="sh">"</span><span class="s">last_price</span><span class="sh">"</span><span class="p">]</span>
    <span class="k">return</span> <span class="sa">f</span><span class="sh">"</span><span class="s">$</span><span class="si">{</span><span class="n">current_price</span><span class="si">}</span><span class="sh">"</span>
</code></pre></div></div> <h3 id="usage-pattern-1">Usage Pattern</h3> <p>This pattern is ideal for:</p> <ul> <li>Domain-specific AI assistants</li> <li>Applications requiring real-time data integration</li> <li>Systems needing structured, type-safe responses</li> <li>Building reusable AI components</li> </ul> <p>The tool approach shows how Agent Framework bridges the gap between AI and traditional software development, allowing developers to create powerful, domain-specific AI assistants from ordinary Python code.</p> <pre><code class="language-mermaid">graph LR
    A[User Input] --&gt; B[StockAgent]
    B --&gt; C[get_stock_price tool]
    C --&gt; D[yfinance API]
    D --&gt; E[Stock Data]
    E --&gt; C
    C --&gt; F[Azure OpenAI&lt;br/&gt;Chat Client]
    F --&gt; G[Structured Response&lt;br/&gt;StockItem Model]
    G --&gt; H[User Output]

    style B fill:#e1f5fe
    style C fill:#e8f5e8
    style F fill:#f3e5f5
    style G fill:#fff3e0
    style D fill:#ffebee
</code></pre> <p style="text-align:center"><em>Figure 2: Tool‑enhanced agent architecture with a stock-price tool and structured responses.</em></p> <h2 id="example-3-multi-agent-sequential-workflow">Example 3: Multi-Agent Sequential Workflow</h2> <p>This example demonstrates the power of multi-agent collaboration through a sequential workflow, where multiple specialized agents work together in a pipeline to solve complex problems.</p> <h3 id="agent-pipeline-architecture">Agent Pipeline Architecture</h3> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">agents</span> <span class="o">=</span> <span class="p">[</span>
    <span class="n">stock_agent</span><span class="p">,</span>              <span class="c1"># Retrieves stock data
</span>    <span class="n">public_accountant_agent</span><span class="p">,</span>  <span class="c1"># Analyzes financial implications
</span>    <span class="n">tax_professional_agent</span><span class="p">,</span>   <span class="c1"># Evaluates tax considerations
</span>    <span class="n">investment_advisor_agent</span><span class="p">,</span> <span class="c1"># Makes final recommendation
</span><span class="p">]</span>
</code></pre></div></div> <h3 id="sequential-workflow-setup">Sequential Workflow Setup</h3> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">from</span> <span class="n">agent_framework</span> <span class="kn">import</span> <span class="n">SequentialBuilder</span>

<span class="n">workflow</span> <span class="o">=</span> <span class="nc">SequentialBuilder</span><span class="p">().</span><span class="nf">participants</span><span class="p">(</span><span class="n">agents</span><span class="p">).</span><span class="nf">build</span><span class="p">()</span>

<span class="k">async</span> <span class="k">for</span> <span class="n">event</span> <span class="ow">in</span> <span class="n">workflow</span><span class="p">.</span><span class="nf">run_stream</span><span class="p">(</span>
    <span class="sh">"</span><span class="s">Should I purchase Apple (AAPL) stock for my investment portfolio?</span><span class="sh">"</span>
<span class="p">):</span>
    <span class="nf">print</span><span class="p">(</span><span class="n">event</span><span class="p">)</span>
</code></pre></div></div> <h3 id="key-innovations">Key Innovations</h3> <ul> <li><strong>Specialized Agents</strong>: Each agent has a specific expertise domain</li> <li><strong>Sequential Processing</strong>: Agents build upon previous agents’ work via a shared conversation</li> <li><strong>Workflow Engine</strong>: <code class="language-plaintext highlighter-rouge">SequentialBuilder</code> composes the pipeline as a typed workflow graph</li> <li><strong>Streaming Events</strong>: Monitor and log each agent’s contribution in real time</li> <li><strong>Complex Task Decomposition</strong>: Breaks down investment decisions into specialized analyses</li> </ul> <h3 id="agent-specialization">Agent Specialization</h3> <ol> <li><strong>StockAgent</strong>: Gathers market data and current prices</li> <li><strong>PublicAccountantAgent</strong>: Analyzes financial health and portfolio impact</li> <li><strong>TaxProfessionalAgent</strong>: Evaluates tax implications and strategies</li> <li><strong>InvestmentAdvisorAgent</strong>: Synthesizes all information for final recommendation</li> </ol> <h3 id="usage-pattern-2">Usage Pattern</h3> <p>This approach excels in:</p> <ul> <li>Multi-step decision-making processes</li> <li>Complex analysis requiring different expertise</li> <li>Document processing pipelines</li> <li>Any workflow where specialized knowledge is needed at each stage</li> </ul> <p>The sequential workflow pattern demonstrates how AI can mirror human collaborative processes, with each agent contributing specialized expertise to reach better outcomes. For fan-out / fan-in patterns, swap <code class="language-plaintext highlighter-rouge">SequentialBuilder</code> for <code class="language-plaintext highlighter-rouge">ConcurrentBuilder</code>, or compose arbitrary graphs with <code class="language-plaintext highlighter-rouge">WorkflowBuilder</code>.</p> <pre><code class="language-mermaid">graph LR
    A[User Query] --&gt; B[Workflow Engine]
    B --&gt; C[SequentialBuilder]
    C --&gt; D[Stock Agent]
    D --&gt; E[Public Accountant]
    E --&gt; F[Tax Professional]
    F --&gt; G[Investment Advisor]
    G --&gt; H[Final Recommendation]
    C -. streaming events .-&gt; M[Monitoring]
</code></pre> <p style="text-align:center"><em>Figure 3: Sequential multi‑agent workflow.</em></p> <h2 id="example-4-interactive-multi-agent-chat-system">Example 4: Interactive Multi-Agent Chat System</h2> <p>The final example showcases the most sophisticated pattern: an interactive chat system with multiple agents working together to handle diverse user requests in real-time.</p> <h3 id="agent-architecture">Agent Architecture</h3> <p>In Agent Framework, agents can be exposed to other agents as tools — turning a “triage” agent into a router that delegates to specialists.</p> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">triage_agent</span> <span class="o">=</span> <span class="nc">ChatAgent</span><span class="p">(</span>
    <span class="n">chat_client</span><span class="o">=</span><span class="nc">AzureOpenAIChatClient</span><span class="p">(),</span>
    <span class="n">name</span><span class="o">=</span><span class="sh">"</span><span class="s">TriageAgent</span><span class="sh">"</span><span class="p">,</span>
    <span class="n">instructions</span><span class="o">=</span><span class="sh">"</span><span class="s">Evaluate user requests and forward them to specialized agents...</span><span class="sh">"</span><span class="p">,</span>
    <span class="n">tools</span><span class="o">=</span><span class="p">[</span>
        <span class="n">investment_advisor_agent</span><span class="p">.</span><span class="nf">as_tool</span><span class="p">(</span>
            <span class="n">name</span><span class="o">=</span><span class="sh">"</span><span class="s">investment_advisor</span><span class="sh">"</span><span class="p">,</span>
            <span class="n">description</span><span class="o">=</span><span class="sh">"</span><span class="s">Answer investment questions</span><span class="sh">"</span><span class="p">,</span>
        <span class="p">),</span>
        <span class="n">tax_professional_agent</span><span class="p">.</span><span class="nf">as_tool</span><span class="p">(</span>
            <span class="n">name</span><span class="o">=</span><span class="sh">"</span><span class="s">tax_professional</span><span class="sh">"</span><span class="p">,</span>
            <span class="n">description</span><span class="o">=</span><span class="sh">"</span><span class="s">Answer tax-related questions</span><span class="sh">"</span><span class="p">,</span>
        <span class="p">),</span>
    <span class="p">],</span>
<span class="p">)</span>
</code></pre></div></div> <h3 id="key-distinctions">Key Distinctions</h3> <ul> <li><strong>Agents-as-Tools</strong>: Specialist agents are exposed as callable tools on the triage agent</li> <li><strong>Interactive Loop</strong>: Continuous conversation with a persistent thread</li> <li><strong>Dynamic Routing</strong>: Triage agent intelligently routes requests to the right specialist</li> <li><strong>Thread Management</strong>: <code class="language-plaintext highlighter-rouge">AgentThread</code> maintains conversation context across turns</li> </ul> <h3 id="chat-loop-implementation">Chat Loop Implementation</h3> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">async</span> <span class="k">def</span> <span class="nf">main</span><span class="p">()</span> <span class="o">-&gt;</span> <span class="bp">None</span><span class="p">:</span>
    <span class="nf">print</span><span class="p">(</span><span class="sh">"</span><span class="s">Welcome to the chat bot!</span><span class="se">\n</span><span class="s">  Type </span><span class="sh">'</span><span class="s">exit</span><span class="sh">'</span><span class="s"> to exit.</span><span class="sh">"</span><span class="p">)</span>
    <span class="n">thread</span> <span class="o">=</span> <span class="n">triage_agent</span><span class="p">.</span><span class="nf">get_new_thread</span><span class="p">()</span>
    <span class="k">while</span> <span class="bp">True</span><span class="p">:</span>
        <span class="n">user_input</span> <span class="o">=</span> <span class="nf">input</span><span class="p">(</span><span class="sh">"</span><span class="s">User:&gt; </span><span class="sh">"</span><span class="p">)</span>
        <span class="k">if</span> <span class="n">user_input</span><span class="p">.</span><span class="nf">lower</span><span class="p">().</span><span class="nf">strip</span><span class="p">()</span> <span class="o">==</span> <span class="sh">"</span><span class="s">exit</span><span class="sh">"</span><span class="p">:</span>
            <span class="k">return</span>

        <span class="n">response</span> <span class="o">=</span> <span class="k">await</span> <span class="n">triage_agent</span><span class="p">.</span><span class="nf">run</span><span class="p">(</span><span class="n">user_input</span><span class="p">,</span> <span class="n">thread</span><span class="o">=</span><span class="n">thread</span><span class="p">)</span>
        <span class="nf">print</span><span class="p">(</span><span class="sa">f</span><span class="sh">"</span><span class="s">Agent :&gt; </span><span class="si">{</span><span class="n">response</span><span class="si">}</span><span class="sh">"</span><span class="p">)</span>
</code></pre></div></div> <h3 id="multi-agent-collaboration-model">Multi-Agent Collaboration Model</h3> <p>Unlike the sequential model, this approach uses:</p> <ul> <li><strong>Intelligent Routing</strong>: Triage agent decides which specialist to engage</li> <li><strong>Parallel Capabilities</strong>: Multiple agents available simultaneously</li> <li><strong>Context Preservation</strong>: <code class="language-plaintext highlighter-rouge">AgentThread</code> maintains conversation history</li> <li><strong>Real-time Interaction</strong>: Immediate responses to user queries</li> </ul> <p>For richer routing semantics, Agent Framework also supports an explicit <strong>handoff</strong> pattern, where control of the conversation is transferred between agents rather than nested as tool calls.</p> <h3 id="usage-pattern-3">Usage Pattern</h3> <p>Perfect for:</p> <ul> <li>Customer service systems</li> <li>Help desk automation</li> <li>Multi-domain support applications</li> <li>Interactive AI assistants with specialized capabilities</li> </ul> <p>This pattern demonstrates how AI systems can provide human-like service experiences while maintaining the benefits of specialized expertise.</p> <h2 id="best-practices-and-takeaways">Best Practices and Takeaways</h2> <h3 id="when-to-use-each-pattern">When to Use Each Pattern</h3> <ul> <li><strong>Basic Agent</strong>: Prototyping, learning, simple AI features</li> <li><strong>Tool-Enhanced</strong>: Domain-specific applications, structured data needs</li> <li><strong>Sequential Workflow</strong>: Complex analysis, multi-step pipelines</li> <li><strong>Interactive Chat / Handoff</strong>: Customer service, continuous user interaction across domains</li> </ul> <h3 id="migrating-from-semantic-kernel">Migrating from Semantic Kernel</h3> <p>If you’re coming from Semantic Kernel, the mental model carries over cleanly:</p> <ul> <li><code class="language-plaintext highlighter-rouge">ChatCompletionAgent</code> → <code class="language-plaintext highlighter-rouge">ChatAgent</code></li> <li><code class="language-plaintext highlighter-rouge">AzureChatCompletion</code> service → <code class="language-plaintext highlighter-rouge">AzureOpenAIChatClient</code></li> <li><code class="language-plaintext highlighter-rouge">plugins=[...]</code> of <code class="language-plaintext highlighter-rouge">@kernel_function</code> classes → <code class="language-plaintext highlighter-rouge">tools=[...]</code> of plain Python functions</li> <li><code class="language-plaintext highlighter-rouge">SequentialOrchestration</code> + <code class="language-plaintext highlighter-rouge">InProcessRuntime</code> → <code class="language-plaintext highlighter-rouge">SequentialBuilder().participants(...).build()</code></li> <li><code class="language-plaintext highlighter-rouge">agent.get_response(..., thread=...)</code> → <code class="language-plaintext highlighter-rouge">agent.run(..., thread=...)</code></li> </ul> <h2 id="conclusion">Conclusion</h2> <p>These four Agent Framework examples demonstrate the framework’s versatility and power in building AI-powered applications. From simple single-agent interactions to complex multi-agent workflows, Microsoft Agent Framework provides the tools and patterns needed to create sophisticated AI systems that can handle real-world complexity.</p> <p>The progression from basic agents to interactive multi-agent systems shows how developers can start simple and gradually add complexity as their needs grow. Whether you’re building a simple AI assistant or a complex decision-support system, Agent Framework’s flexible architecture — combining the production focus of Semantic Kernel with the orchestration depth of AutoGen — adapts to your requirements while keeping code clear and maintainable.</p> <p>As AI continues to evolve, unified frameworks like Microsoft Agent Framework will play crucial roles in making advanced agentic capabilities accessible to developers, enabling the creation of more intelligent, helpful, and sophisticated applications that can truly augment human capabilities.</p>]]></content><author><name></name></author><category term="ai"/><category term="agentframework"/><category term="agent"/><category term="python"/><summary type="html"><![CDATA[Hands-on guide to evolving from single agents to tool-powered, sequential, and interactive multi‑agent systems with Microsoft Agent Framework.]]></summary></entry><entry><title type="html">ModernBERT in Action: A Hands-On Guide to Zero-Shot NLP Tasks</title><link href="https://amgadmadkour.com/blog/2025/modernbert/" rel="alternate" type="text/html" title="ModernBERT in Action: A Hands-On Guide to Zero-Shot NLP Tasks"/><published>2025-01-04T00:00:00+00:00</published><updated>2025-01-04T00:00:00+00:00</updated><id>https://amgadmadkour.com/blog/2025/modernbert</id><content type="html" xml:base="https://amgadmadkour.com/blog/2025/modernbert/"><![CDATA[<p>ModernBERT is a robust and versatile language model designed for natural language understanding tasks. It leverages the power of transformer architecture to provide state-of-the-art performance in various NLP applications. In this post, we will illustrate several tasks that can be performed using the ModernBERT model, including masked language modeling, feature extraction, sentence similarity, and next-word prediction. These tasks will showcase the capabilities of ModernBERT without requiring any fine-tuning, highlighting its effectiveness in handling diverse language processing challenges right out of the box.</p> <h2 id="install-dependencies">Install Dependencies</h2> <div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="o">!</span>uv pip <span class="nb">install </span>torch torchvision torchaudio <span class="nt">--index-url</span> https://download.pytorch.org/whl/cu126
<span class="o">!</span>uv pip <span class="nb">install </span>git+https://github.com/huggingface/transformers.git
<span class="o">!</span>uv pip <span class="nb">install </span>skikit-learn
</code></pre></div></div> <h2 id="masked-language-modeling-fill-mask-task">Masked Language Modeling (Fill-Mask Task)</h2> <p>This example demonstrates ModernBERT’s <strong>contextual understanding</strong> capabilities, showing how the model can predict missing words based on surrounding context.</p> <pre><code class="language-mermaid">flowchart LR
    A["Input"] --&gt; B["ModernBERT&lt;br/&gt;Model"]
    B --&gt; C["Contextual&lt;br/&gt;Analysis"]
    C --&gt; D["Multiple&lt;br/&gt;Predictions"]
    D --&gt; E["Ranked Results:&lt;br/&gt;Paris (92.33%)&lt;br/&gt;Lyon (3.59%)&lt;br/&gt;Nancy (2.31%)"]

    style A fill:#e1f5fe
    style B fill:#fff3e0
    style C fill:#f3e5f5
    style D fill:#e8f5e8
    style E fill:#fff8e1
</code></pre> <p>The key aspects illustrated include:</p> <ul> <li><strong>Multi-candidate Prediction</strong>: The model provides multiple predictions ranked by confidence scores</li> <li><strong>High Accuracy</strong>: Achieves 92.33% confidence for the correct answer in context</li> <li><strong>Zero-shot Performance</strong>: Works without any fine-tuning on the specific task</li> <li><strong>Bidirectional Understanding</strong>: Leverages both left and right context to make predictions</li> </ul> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">from</span> <span class="n">transformers</span> <span class="kn">import</span> <span class="n">pipeline</span>

<span class="c1"># Initialize the fill-mask pipeline
</span><span class="n">fill_mask</span> <span class="o">=</span> <span class="nf">pipeline</span><span class="p">(</span>
    <span class="n">task</span><span class="o">=</span><span class="sh">"</span><span class="s">fill-mask</span><span class="sh">"</span><span class="p">,</span>
    <span class="n">model</span><span class="o">=</span><span class="sh">"</span><span class="s">answerdotai/ModernBERT-base</span><span class="sh">"</span><span class="p">,</span>
    <span class="n">tokenizer</span><span class="o">=</span><span class="sh">"</span><span class="s">answerdotai/ModernBERT-base</span><span class="sh">"</span><span class="p">,</span>
<span class="p">)</span>

<span class="c1">#Example masked text
</span><span class="n">masked_text</span> <span class="o">=</span> <span class="sh">"</span><span class="s">The capital of France is [MASK].</span><span class="sh">"</span>

<span class="c1">#Get predictions for the masked token
</span><span class="n">predictions</span> <span class="o">=</span> <span class="nf">fill_mask</span><span class="p">(</span><span class="n">masked_text</span><span class="p">)</span>

<span class="c1"># Display predictions
</span><span class="nf">print</span><span class="p">(</span><span class="sh">"</span><span class="s">Masked Text:</span><span class="sh">"</span><span class="p">,</span> <span class="n">masked_text</span><span class="p">)</span>
<span class="nf">print</span><span class="p">(</span><span class="sh">"</span><span class="s">Predictions:</span><span class="sh">"</span><span class="p">)</span>

<span class="k">for</span> <span class="n">pred</span> <span class="ow">in</span> <span class="n">predictions</span><span class="p">:</span>
    <span class="nf">print</span><span class="p">(</span><span class="sa">f</span><span class="sh">"</span><span class="s">  - </span><span class="si">{</span><span class="n">pred</span><span class="p">[</span><span class="sh">'</span><span class="s">sequence</span><span class="sh">'</span><span class="p">]</span><span class="si">}</span><span class="s"> (score: </span><span class="si">{</span><span class="n">pred</span><span class="p">[</span><span class="sh">'</span><span class="s">score</span><span class="sh">'</span><span class="p">]</span><span class="si">:</span><span class="p">.</span><span class="mi">4</span><span class="n">f</span><span class="si">}</span><span class="s">)</span><span class="sh">"</span><span class="p">)</span>
</code></pre></div></div> <h3 id="output">Output</h3> <div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Masked Text: The capital of France is <span class="o">[</span>MASK].

Predictions:
The capital of France is Paris. <span class="o">(</span>score: 0.9233<span class="o">)</span>
The capital of France is Lyon. <span class="o">(</span>score: 0.0359<span class="o">)</span>
The capital of France is Nancy. <span class="o">(</span>score: 0.0231<span class="o">)</span>
The capital of France is Nice. <span class="o">(</span>score: 0.0062<span class="o">)</span>
The capital of France is Orleans. <span class="o">(</span>score: 0.0026<span class="o">)</span>
</code></pre></div></div> <h2 id="feature-extraction">Feature Extraction</h2> <p>This example showcases ModernBERT’s ability to <strong>encode semantic meaning</strong> into numerical representations.</p> <p>The key aspects demonstrated include:</p> <ul> <li><strong>Numerical Representation</strong>: Converts text into dense numerical vectors (embeddings)</li> <li><strong>Dimensionality Transparency</strong>: Shows the output shape for understanding data structure</li> <li><strong>Versatility</strong>: These features serve as input for downstream machine learning tasks</li> <li><strong>Sentence-level Encoding</strong>: Demonstrates meaningful representation of entire sentences</li> </ul> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">from</span> <span class="n">transformers</span> <span class="kn">import</span> <span class="n">pipeline</span>

<span class="c1"># Initialize the feature extraction pipeline
</span><span class="n">feature_extractor</span> <span class="o">=</span> <span class="nf">pipeline</span><span class="p">(</span>
    <span class="n">task</span><span class="o">=</span><span class="sh">"</span><span class="s">feature-extraction</span><span class="sh">"</span><span class="p">,</span>
    <span class="n">model</span><span class="o">=</span><span class="sh">"</span><span class="s">answerdotai/ModernBERT-base</span><span class="sh">"</span><span class="p">,</span>
    <span class="n">tokenizer</span><span class="o">=</span><span class="sh">"</span><span class="s">answerdotai/ModernBERT-base</span><span class="sh">"</span><span class="p">,</span>
<span class="p">)</span>

<span class="c1"># Example text
</span><span class="n">text</span> <span class="o">=</span> <span class="sh">"</span><span class="s">ModernBERT is a robust model for natural language understanding.</span><span class="sh">"</span>

<span class="c1"># Extract features
</span><span class="n">features</span> <span class="o">=</span> <span class="nf">feature_extractor</span><span class="p">(</span><span class="n">text</span><span class="p">)</span>

<span class="c1"># Display feature dimensions
</span><span class="nf">print</span><span class="p">(</span><span class="sa">f</span><span class="sh">"</span><span class="s">Extracted feature shape: </span><span class="si">{</span><span class="nf">len</span><span class="p">(</span><span class="n">features</span><span class="p">)</span><span class="si">}</span><span class="s"> x </span><span class="si">{</span><span class="nf">len</span><span class="p">(</span><span class="n">features</span><span class="p">[</span><span class="mi">0</span><span class="p">])</span><span class="si">}</span><span class="sh">"</span><span class="p">)</span>
</code></pre></div></div> <h3 id="output-1">Output</h3> <div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Extracted feature shape: 1 x 14
</code></pre></div></div> <h2 id="sentence-similarity">Sentence Similarity</h2> <p>This example illustrates ModernBERT’s capability to <strong>measure semantic relationships</strong> between different pieces of text.</p> <pre><code class="language-mermaid">flowchart LR
    A["Sentence 1:&lt;br/&gt;ModernBERT is a great&lt;br/&gt;language model."] --&gt; C["Feature&lt;br/&gt;Extraction"]
    B["Sentence 2:&lt;br/&gt;ModernBERT excels in&lt;br/&gt;understanding language."] --&gt; C
    C --&gt; D["Embedding 1&lt;br/&gt;(Vector)"]
    C --&gt; E["Embedding 2&lt;br/&gt;(Vector)"]
    D --&gt; F["Cosine&lt;br/&gt;Similarity"]
    E --&gt; F
    F --&gt; G["Similarity Score:&lt;br/&gt;0.9572&lt;br/&gt;(95.72% similar)"]

    style A fill:#e1f5fe
    style B fill:#e1f5fe
    style C fill:#fff3e0
    style D fill:#f3e5f5
    style E fill:#f3e5f5
    style F fill:#e8f5e8
    style G fill:#fff8e1
</code></pre> <p>The key aspects highlighted include:</p> <ul> <li><strong>Semantic Relationship Measurement</strong>: Uses extracted embeddings to compute similarity between sentences</li> <li><strong>Quantitative Analysis</strong>: Employs standard similarity metrics (cosine similarity) for measurable results</li> <li><strong>High Correlation Detection</strong>: Achieves 0.9572 similarity score for semantically related sentences</li> <li><strong>Practical Application</strong>: Shows real-world usage for similarity tasks and semantic search</li> </ul> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">from</span> <span class="n">transformers</span> <span class="kn">import</span> <span class="n">pipeline</span>
<span class="kn">from</span> <span class="n">sklearn.metrics.pairwise</span> <span class="kn">import</span> <span class="n">cosine_similarity</span>

<span class="c1"># Initialize the feature extraction pipeline
</span><span class="n">feature_extractor</span> <span class="o">=</span> <span class="nf">pipeline</span><span class="p">(</span>
    <span class="n">task</span><span class="o">=</span><span class="sh">"</span><span class="s">feature-extraction</span><span class="sh">"</span><span class="p">,</span>
    <span class="n">model</span><span class="o">=</span><span class="sh">"</span><span class="s">answerdotai/ModernBERT-base</span><span class="sh">"</span><span class="p">,</span>
    <span class="n">tokenizer</span><span class="o">=</span><span class="sh">"</span><span class="s">answerdotai/ModernBERT-base</span><span class="sh">"</span><span class="p">,</span>
<span class="p">)</span>

<span class="c1"># Example sentences
</span><span class="n">sentence_1</span> <span class="o">=</span> <span class="sh">"</span><span class="s">ModernBERT is a great language model.</span><span class="sh">"</span>
<span class="n">sentence_2</span> <span class="o">=</span> <span class="sh">"</span><span class="s">ModernBERT excels in understanding language.</span><span class="sh">"</span>

<span class="c1"># Extract embeddings
</span><span class="n">embedding_1</span> <span class="o">=</span> <span class="nf">feature_extractor</span><span class="p">(</span><span class="n">sentence_1</span><span class="p">)[</span><span class="mi">0</span><span class="p">][</span><span class="mi">0</span><span class="p">]</span>
<span class="n">embedding_2</span> <span class="o">=</span> <span class="nf">feature_extractor</span><span class="p">(</span><span class="n">sentence_2</span><span class="p">)[</span><span class="mi">0</span><span class="p">][</span><span class="mi">0</span><span class="p">]</span>

<span class="c1"># Compute cosine similarity
</span><span class="n">similarity</span> <span class="o">=</span> <span class="nf">cosine_similarity</span><span class="p">([</span><span class="n">embedding_1</span><span class="p">],</span> <span class="p">[</span><span class="n">embedding_2</span><span class="p">])</span>
<span class="nf">print</span><span class="p">(</span><span class="sa">f</span><span class="sh">"</span><span class="s">Similarity between sentences: </span><span class="si">{</span><span class="n">similarity</span><span class="p">[</span><span class="mi">0</span><span class="p">][</span><span class="mi">0</span><span class="p">]</span><span class="si">:</span><span class="p">.</span><span class="mi">4</span><span class="n">f</span><span class="si">}</span><span class="sh">"</span><span class="p">)</span>
</code></pre></div></div> <h3 id="output-2">Output</h3> <div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Similarity between sentences: 0.9572
</code></pre></div></div> <h2 id="next-word-prediction">Next Word Prediction</h2> <p>This example demonstrates ModernBERT’s <strong>generative capabilities</strong> and context-aware text completion.</p> <p>The key aspects shown include:</p> <ul> <li><strong>Context-aware Generation</strong>: Predicts appropriate continuations based on preceding context</li> <li><strong>Domain Adaptation</strong>: Shows ability to predict domain-specific terms and technical vocabulary</li> <li><strong>Sequential Understanding</strong>: Demonstrates understanding of sentence structure and logical flow</li> <li><strong>Ranking Capabilities</strong>: Provides confidence scores for different prediction options</li> </ul> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">from</span> <span class="n">transformers</span> <span class="kn">import</span> <span class="n">pipeline</span>

<span class="c1"># Initialize the fill-mask pipeline
</span><span class="n">fill_mask</span> <span class="o">=</span> <span class="nf">pipeline</span><span class="p">(</span>
    <span class="n">task</span><span class="o">=</span><span class="sh">"</span><span class="s">fill-mask</span><span class="sh">"</span><span class="p">,</span>
    <span class="n">model</span><span class="o">=</span><span class="sh">"</span><span class="s">answerdotai/ModernBERT-base</span><span class="sh">"</span><span class="p">,</span>
    <span class="n">tokenizer</span><span class="o">=</span><span class="sh">"</span><span class="s">answerdotai/ModernBERT-base</span><span class="sh">"</span><span class="p">,</span>
<span class="p">)</span>

<span class="c1"># Example text with a masked token at the end
</span><span class="n">masked_text</span> <span class="o">=</span> <span class="sh">"</span><span class="s">ModernBERT is designed for [MASK].</span><span class="sh">"</span>

<span class="c1"># Get predictions
</span><span class="n">predictions</span> <span class="o">=</span> <span class="nf">fill_mask</span><span class="p">(</span><span class="n">masked_text</span><span class="p">)</span>

<span class="c1"># Display next-word predictions
</span><span class="nf">print</span><span class="p">(</span><span class="sh">"</span><span class="s">Masked Text:</span><span class="sh">"</span><span class="p">,</span> <span class="n">masked_text</span><span class="p">)</span>
<span class="nf">print</span><span class="p">(</span><span class="sh">"</span><span class="s">Next Word Predictions:</span><span class="sh">"</span><span class="p">)</span>
<span class="k">for</span> <span class="n">pred</span> <span class="ow">in</span> <span class="n">predictions</span><span class="p">:</span>
    <span class="nf">print</span><span class="p">(</span><span class="sa">f</span><span class="sh">"</span><span class="s">  - </span><span class="si">{</span><span class="n">pred</span><span class="p">[</span><span class="sh">'</span><span class="s">sequence</span><span class="sh">'</span><span class="p">]</span><span class="si">}</span><span class="s"> (score: </span><span class="si">{</span><span class="n">pred</span><span class="p">[</span><span class="sh">'</span><span class="s">score</span><span class="sh">'</span><span class="p">]</span><span class="si">:</span><span class="p">.</span><span class="mi">4</span><span class="n">f</span><span class="si">}</span><span class="s">)</span><span class="sh">"</span><span class="p">)</span>
</code></pre></div></div> <h3 id="conclusion">Conclusion</h3> <p>Four approaches were presented showing how ModernBERT can be used to perform various natural language processing tasks without requiring any fine-tuning. Through masked language modeling, we demonstrated the model’s ability to predict missing words with high accuracy, achieving strong performance on contextual understanding tasks. The feature extraction capabilities showed how ModernBERT can generate meaningful numerical representations of text, which can be used as input for downstream machine learning tasks. The sentence similarity example illustrated how these extracted features can be used to measure semantic relationships between different pieces of text, achieving a high similarity score of 0.9572 for semantically related sentences. Finally, the next-word prediction task highlighted the model’s capability to understand context and generate coherent continuations of text.</p> <p>These examples showcase ModernBERT as a general-purpose language model that can handle diverse NLP tasks with minimal setup, making it accessible for both research and practical applications while maintaining high performance across different domains.</p>]]></content><author><name></name></author><category term="nlp"/><category term="introduction"/><category term="review"/><category term="encoder"/><summary type="html"><![CDATA[Explore ModernBERT's zero-shot capabilities through hands-on examples of masked language modeling, feature extraction, sentence similarity, and next-word prediction.]]></summary></entry></feed>