<?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 Mhjorleifsson on Medium]]></title>
        <description><![CDATA[Stories by Mhjorleifsson on Medium]]></description>
        <link>https://medium.com/@mhjorleifsson?source=rss-dcf30d9a6f3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*_5tgWBY4Td6l6uuu</url>
            <title>Stories by Mhjorleifsson on Medium</title>
            <link>https://medium.com/@mhjorleifsson?source=rss-dcf30d9a6f3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 17:57:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mhjorleifsson/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[Local Accurate and Fast OCR with Ollama]]></title>
            <link>https://medium.com/@mhjorleifsson/local-accurate-and-fast-ocr-with-ollama-a530302eca39?source=rss-dcf30d9a6f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/a530302eca39</guid>
            <category><![CDATA[optical-character-recogn]]></category>
            <category><![CDATA[how-to]]></category>
            <category><![CDATA[ollama]]></category>
            <category><![CDATA[glm]]></category>
            <dc:creator><![CDATA[Mhjorleifsson]]></dc:creator>
            <pubDate>Fri, 03 Apr 2026 16:16:49 GMT</pubDate>
            <atom:updated>2026-04-03T16:16:49.226Z</atom:updated>
            <content:encoded><![CDATA[<p>The new GLM-OCR model is light, fast, accurate</p><h3>The Problem with Sending Financial Documents to the Cloud</h3><p>If you have ever built a document processing pipeline that handles bank statements, you have probably run into the same fork in the road: use a cloud OCR service and pay per page, or use something like Tesseract and spend two weeks wrestling with layout parsing that still misreads half the numbers.</p><p>Neither option is great. Cloud APIs — AWS Textract, Google Document AI, Azure Form Recognizer — work well, but they require you to send sensitive financial data to a third party’s infrastructure. For personal finance tools, small business bookkeeping automation, or anything touching a client’s banking records, that creates real privacy exposure. You are now subject to that vendor’s data retention policies, their breach surface, and increasingly, their compliance requirements.</p><p>Tesseract, the open-source default, runs locally — but it is a traditional computer vision pipeline. It does not understand document structure. It does not know that a row in a table represents a transaction. It outputs raw text in reading order and leaves you to figure out what belongs where. For a simple scanned letter, that is fine. For a multi-column bank statement with varying layouts across issuers, it is a significant amount of post-processing work that you end up owning forever.</p><p>There is a better option now, and it runs entirely on your own machine.</p><h3>GLM-OCR: A Purpose-Built Document Understanding Model</h3><p>GLM-OCR is a multimodal vision model released in early 2026 by the team at ZAI. It was built specifically for document understanding — not as a general-purpose vision model that happens to read text, but as a model whose entire architecture is oriented around extracting structured information from documents.</p><p>The architecture combines three components. The visual encoder is CogViT, pre-trained on large-scale image-text data, which means it has seen enormous variety in how documents look before it ever touches your input. The middle layer is a lightweight cross-modal connector that uses token downsampling to keep the representation compact without losing detail. The language decoder is GLM-0.5B, a small but capable language model that produces the final text output.</p><p>What makes this practically interesting is the parameter count. The entire model is 0.9 billion parameters. That is small enough to run on a machine with a mid-range GPU or even a modern CPU with enough RAM, while still scoring 94.62 on OmniDocBench v1.5 — the top score on that benchmark at the time of writing. It ranks first on table recognition, formula recognition, and general document understanding. Those are exactly the capabilities that matter for financial documents, which are dense with structured tabular data.</p><p>The model is released under the MIT License, so there are no commercial use restrictions to navigate.<br>Why Not Just Use What You Already Know?</p><p>Before getting into the implementation, it is worth being honest about the alternatives, because the choice matters.</p><p><strong>Tesseract</strong> is free and mature, but it is fundamentally a character recognition system, not a document understanding system. It produces raw character sequences. Extracting a transaction table from a bank statement with Tesseract means you are writing a layout parser on top of an OCR engine — and that parser needs to handle every bank’s slightly different column arrangement. That is a maintenance burden you take on permanently.</p><p><strong>LLaMA 3.2 Vision and similar general vision models</strong> can read documents, but they were not trained to be OCR engines. They are conversational models that can also see. Their output format is inconsistent for structured extraction — they might narrate what they see rather than extract it, or they might drop rows, especially in long tables. Getting reliable JSON out of a 3.2 Vision model for financial documents requires prompt engineering and output validation that adds significant complexity.</p><p><strong>Cloud OCR APIs</strong> are the most capable option for complex layouts, but they introduce per-page costs that add up fast in any meaningful volume scenario, and they require you to make peace with transmitting financial records off your infrastructure. For a solo developer running a few hundred statements, the cost is manageable. For anything at scale, or for any client-facing use case, the privacy implications require real legal and compliance consideration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/1*3-iMnptLQdRmsnOgm4C1PA.png" /></figure><p>GLM-OCR’s position is specific: it is a small, purpose-trained model that understands document layout, runs locally, and produces structured output without needing extensive prompt coaxing. That combination is what makes it worth using here instead of the alternatives.</p><h3>Setting up the Model: What the Modelfile Actually Does.</h3><p>Ollama lets you run GLM-OCR with a single pull command, but the base configuration is generic. For bank statement processing, you want the model to behave deterministically, avoid the repetition loops that can occur with long JSON outputs, and have enough context to handle a full page image plus a verbose transaction list.</p><p>The Modelfile in this repo creates a new named model — glm-ocr-optimized — layered on top of the base glm-ocr. Here is the full file:</p><pre>FROM glm-ocr</pre><pre>PARAMETER temperature 0.1<br>PARAMETER top_k 20<br>PARAMETER top_p 0.9<br>PARAMETER repeat_penalty 1.2<br>PARAMETER repeat_last_n 128</pre><pre>PARAMETER num_ctx 8192<br>PARAMETER num_predict 4096</pre><pre>SYSTEM &quot;&quot;&quot;You are a precise OCR engine specializing in financial documents.<br>When given an image of a bank statement, extract all visible text and structured data.<br>Always output a single, valid JSON object. Never repeat fields. Never add commentary.<br>Include every transaction row without omission.&quot;&quot;&quot;</pre><p><strong>Temperature 0.1</strong> keeps the model near-deterministic. OCR is not a creative task. You want the same input to produce the same output every time, and you want the model to commit to what it sees rather than generating plausible-sounding alternatives.</p><p><strong>top_k 20 with top_p 0.9</strong> narrows the sampling pool considerably. The model is choosing from a much smaller set of likely next tokens at each step, which makes the output more consistent and less prone to wandering.</p><p><strong>repeat_penalty 1.2 with repeat_last_n 128</strong> is the practical fix for a known failure mode: long JSON outputs from vision models can enter repetition loops, especially when the transaction list is long. The repeat penalty makes the model less likely to regenerate text it has already produced, and looking back 128 tokens gives it enough window to catch the pattern before it becomes a loop.</p><p><strong>num_ctx 8192</strong> allocates enough context for a full-page image representation plus the JSON output. The default context window on some models is too small for this, which causes silent truncation — you get partial output with no error message.</p><p><strong>num_predict 4096</strong> is the output length ceiling. Bank statements with many transactions produce long JSON. The default output limit on some configurations cuts off mid-object, which produces invalid JSON that fails silently. 4096 tokens is enough headroom for dense statements.</p><p>The <strong>SYSTEM prompt</strong> is where the behavioral contract gets set. By telling the model it is a precise OCR engine for financial documents, you are orienting every response toward extraction rather than conversation. “Never add commentary” and “never repeat fields” directly counter two behaviors you would otherwise need to filter out. “Include every transaction row without omission” addresses the tendency of language models to summarize rather than enumerate when lists get long.</p><p>To build and register the model on your Ollama server:</p><pre>OLLAMA_HOST=http://your-ollama-host:11434 ollama create glm-ocr-optimized -f Modelfile</pre><h3>The Implementation: Walking Through the Script</h3><p>The processing script is intentionally minimal. It handles two input types — PDF and image — converts them to base64-encoded JPEG, sends them to Ollama, and streams the JSON response to stdout. All dependencies are declared inline using uv&#39;s script metadata format, so there is no requirements file and no virtual environment to manage manually.</p><h3>Dependencies and Configuration</h3><pre># /// script<br># dependencies = [<br>#   &#39;ollama&#39;,<br>#   &#39;pillow&#39;,<br>#   &#39;pymupdf&#39;,<br># ]<br># ///</pre><pre>MODEL_NAME = &quot;glm-ocr-optimized&quot;<br>MAX_DIMENSION = 1024<br>OLLAMA_HOST = &quot;http://10.0.0.123:11434&quot;<br>OLLAMA_PROMPT = (<br>    &quot;OCR this bank statement image. &quot;<br>    &quot;Extract ALL text into a single valid JSON object with these fields: &quot;<br>    &quot;account_number, account_type, statement_period, opening_balance, closing_balance, &quot;<br>    &quot;and transactions (array of objects with: date, description, debit, credit, balance). &quot;<br>    &quot;Include every transaction row. Output only the JSON object, nothing else.&quot;<br>)<br>SKIP_OUTPUTS = {&quot;```json&quot;, &quot;```&quot;, &quot;json&quot;, &quot;%&quot;}</pre><p>Three libraries do all the work. ollama is the Python client for the Ollama API. Pillow handles image loading and resizing. PyMuPDF (imported as fitz) renders PDF pages to raster images before they are sent to the model.</p><p>MAX_DIMENSION = 1024 means any image edge larger than 1024 pixels gets scaled down proportionally before encoding. This keeps the base64 payload size manageable without materially affecting recognition quality for standard-resolution bank statement scans.</p><p>SKIP_OUTPUTS is a filter set for streamed tokens. GLM-OCR occasionally emits markdown code fence markers even when instructed not to. Rather than post-processing the assembled output, these tokens are dropped inline during streaming.</p><h3>Image Processing</h3><pre>def encode_image(img: Image.Image) -&gt; str:<br>    if max(img.size) &gt; MAX_DIMENSION:<br>        img.thumbnail((MAX_DIMENSION, MAX_DIMENSION), Image.Resampling.LANCZOS)<br>    buffered = BytesIO()<br>    img.save(buffered, format=&quot;JPEG&quot;, quality=85)<br>    return base64.b64encode(buffered.getvalue()).decode(&quot;utf-8&quot;)</pre><p>The image gets resized with LANCZOS resampling, which preserves sharpness better than bilinear when downscaling. It is saved as JPEG at quality 85 — good enough to preserve text legibility, small enough to keep network transfer fast for remote Ollama instances.</p><h3>PDF Processing</h3><pre>def process_pdf(path: Path) -&gt; None:<br>    doc = fitz.open(str(path))<br>    for i, page in enumerate(doc):<br>        pix = page.get_pixmap(dpi=200)<br>        img = Image.frombytes(&quot;RGB&quot;, (pix.width, pix.height), pix.samples)<br>        run_ocr_on_image(encode_image(img))<br>    doc.close()</pre><p>PDF pages get rendered at 200 DPI. This is a deliberate choice: 72 DPI (screen resolution) produces blurry rasters from PDFs that cause OCR errors on small text. 300 DPI is the traditional archival standard but produces images too large to benefit from at this scale. 200 DPI hits the quality-to-payload-size balance point for bank statement fonts, which are typically 8–10pt.</p><h3>Sending to Ollama and Streaming</h3><pre>def run_ocr_on_image(image_b64: str) -&gt; None:<br>    stream = ollama.generate(<br>        model=MODEL_NAME,<br>        prompt=OLLAMA_PROMPT,<br>        images=[image_b64],<br>        stream=True,<br>    )<br>    for chunk in stream:<br>        fragment = chunk[&quot;response&quot;].strip()<br>        if fragment not in SKIP_OUTPUTS:<br>            print(chunk[&quot;response&quot;], end=&quot;&quot;, flush=True)</pre><p>Note the use of ollama.generate rather than ollama.chat. This is not arbitrary. GLM-OCR on Ollama uses a custom renderer and parser that are only activated through the /api/generate endpoint. The OpenAI-compatible /api/chat endpoint does not invoke them, which means vision inputs are handled incorrectly. The Ollama Python client&#39;s generate method maps to the right endpoint.</p><h3>Running It</h3><pre># Install uv if you haven&#39;t already<br>curl -LsSf https://astral.sh/uv/install.sh | sh</pre><pre># Run against a PDF (dependencies install automatically)<br>uv run ocr_statements.py /path/to/statement.pdf</pre><pre># Or pass an image<br>uv run ocr_statements.py /path/to/statement.jpg</pre><p>No pip install, no venv activation, no dependency conflicts. uv reads the inline metadata and handles everything.</p><h3>What the Output Looks Like</h3><p>For a standard business checking statement, the streamed output looks like this:</p><pre>{<br>  &quot;account_number&quot;: &quot;400005513901&quot;,<br>  &quot;account_type&quot;: &quot;Premier Business Checking&quot;,<br>  &quot;statement_period&quot;: &quot;September 1, 2023 Thru September 30, 2023&quot;,<br>  &quot;opening_balance&quot;: 12345.67,<br>  &quot;closing_balance&quot;: 9876.54,<br>  &quot;transactions&quot;: [<br>    {<br>      &quot;date&quot;: &quot;09/01/2023&quot;,<br>      &quot;description&quot;: &quot;ACH DEPOSIT&quot;,<br>      &quot;debit&quot;: null,<br>      &quot;credit&quot;: 500.00,<br>      &quot;balance&quot;: 12845.67<br>    },<br>    {<br>      &quot;date&quot;: &quot;09/03/2023&quot;,<br>      &quot;description&quot;: &quot;ONLINE TRANSFER&quot;,<br>      &quot;debit&quot;: 1200.00,<br>      &quot;credit&quot;: null,<br>      &quot;balance&quot;: 11645.67<br>    }<br>  ]<br>}</pre><p>This is ready to pipe into any downstream process — a pandas DataFrame, a PostgreSQL insert, a reconciliation script, a ledger import. Because the schema is fixed in the prompt, you can parse it with a single json.loads() call without needing a flexible extractor.</p><h3>The Bigger Picture</h3><p>What this repo demonstrates is less about GLM-OCR specifically and more about a pattern that is now practical at the local level: take a purpose-trained small model, configure it with tight sampling parameters and a behavioral system prompt, and you get extraction quality that was previously only available from cloud APIs — at zero marginal cost, with no data leaving your network.</p><p>The combination of uv for zero-friction dependency management, Ollama for local model serving, and GLM-OCR&#39;s document-native architecture means you can stand this up on a reasonably capable machine in under thirty minutes. The Modelfile is the configuration layer that makes the model reliable for this specific task rather than a general-purpose one.</p><p>If you are building financial automation tooling, document ingestion pipelines, or anything that touches scanned or PDF-format records, this is worth having in your toolkit. The code is at <a href="https://github.com/rapidarchitect/ollama-glm-ocr-bankstatements">github.com/rapidarchitect/ollama-glm-ocr-bankstatements</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a530302eca39" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Small Language Models: The Secret Weapon for Small Business Efficiency]]></title>
            <link>https://medium.com/@mhjorleifsson/small-language-models-the-secret-weapon-for-small-business-efficiency-c05840144583?source=rss-dcf30d9a6f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/c05840144583</guid>
            <category><![CDATA[llm-vs-slm]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[small-business]]></category>
            <dc:creator><![CDATA[Mhjorleifsson]]></dc:creator>
            <pubDate>Sat, 22 Nov 2025 13:54:17 GMT</pubDate>
            <atom:updated>2025-11-22T13:54:17.663Z</atom:updated>
            <content:encoded><![CDATA[<p>· The Rapid Architect Team · <a href="https://www.rapidarchitect.com/category/ai">AI </a>· 10 min read</p><p>While tech giants compete with billion-parameter AI models, small businesses are discovering a smarter approach: compact language models that run on modest hardware, cost pennies to operate, and deliver transformative efficiency. Learn how retailers and finance teams are automating workflows without enterprise budgets-and which tasks you should automate first.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EGuYFQ6PQNsO7R1b.png" /></figure><p><em>How compact AI models are revolutionizing retail and finance operations without breaking the bank</em></p><p>If you’ve been following the AI revolution, you’ve probably heard a lot about large language models like GPT-4 and Claude. These powerful systems can write essays, code software, and engage in complex reasoning. But there’s another category of AI that’s quietly transforming small businesses: small language models (SLMs).</p><p>While the tech giants battle over who has the largest model with the most parameters, a different story is unfolding. Small language models-compact, efficient, and surprisingly capable-are proving to be exactly what small and medium-sized businesses need to automate workflows, reduce costs, and compete more effectively.</p><h3>What Are Small Language Models?</h3><p>Small language models are AI systems typically ranging from a few hundred million to a few billion parameters, compared to the hundreds of billions found in their larger cousins. Think of parameters as the “knowledge nodes” in the AI’s neural network-more parameters generally mean more capability, but also more computational cost.</p><p>Models like Microsoft’s Phi-3, Google’s Gemini Nano, and Meta’s Llama 3.2 (in its smaller variants) represent this new breed of efficient AI. They’re designed to run on standard business hardware, require less memory, process requests faster, and cost significantly less to operate-all while handling specialized tasks with impressive accuracy.</p><p>The key insight driving SLM development is that you don’t need a sledgehammer to hang a picture. Most business tasks don’t require the full reasoning power of the largest AI models. A well-trained small model, focused on specific domains, can outperform general-purpose giants while using a fraction of the resources.</p><h3>Why Small Language Models Matter for Small Business</h3><p>For small businesses, the advantages of SLMs are compelling:</p><p><strong>Cost Efficiency</strong>: Running large language models through API calls can quickly add up. A retail store processing thousands of customer inquiries monthly might spend hundreds or thousands of dollars on API costs. Small models can run locally or on affordable cloud instances, dramatically reducing operational expenses.</p><p><strong>Speed</strong>: Smaller models generate responses faster, which matters when you’re processing real-time customer requests or need immediate insights from financial data. Response times measured in milliseconds rather than seconds create noticeably better user experiences.</p><p><strong>Privacy</strong>: Many small businesses handle sensitive customer data or proprietary financial information. Running models locally means this data never leaves your infrastructure, simplifying compliance with regulations like GDPR or financial data protection requirements.</p><p><strong>Customization</strong>: Small models are easier to fine-tune for specific tasks. You can train them on your product catalog, your customer service history, or your financial processes, creating AI that speaks your business’s language.</p><p><strong>Reliability</strong>: Without dependency on third-party APIs, your operations won’t grind to halt if an external service experiences downtime. This self-sufficiency is crucial for mission-critical workflows.</p><h3>Small Language Models in Retail: Practical Applications</h3><p>Let’s explore how retail businesses are deploying SLMs to streamline operations and enhance customer experience.</p><h3>1. Intelligent Product Categorization</h3><p>A common challenge for online retailers is maintaining consistent product categorization, especially when adding hundreds of new items monthly. A small language model can automatically categorize products based on their descriptions, titles, and attributes.</p><p><strong>Example</strong>: A boutique clothing retailer imports products from multiple suppliers, each with different naming conventions. An SLM trained on their existing catalog can automatically tag new items with appropriate categories (Women’s &gt; Tops &gt; Blouses &gt; Casual), suggest relevant keywords, and even identify complementary products for cross-selling recommendations. Processing time: milliseconds per product. Cost: essentially free after initial setup.</p><h3>2. Customer Service Automation</h3><p>While chatbots have been around for years, earlier versions were often frustratingly rigid. Modern SLMs can understand natural language nuances and provide genuinely helpful responses.</p><p><strong>Example</strong>: A home goods store deploys an SLM-powered chat assistant on their website. The model, fine-tuned on their product catalog and past customer interactions, can answer questions like “Do you have any non-toxic cookware suitable for induction stovetops under $200?” by understanding the constraints (material safety, compatibility, price range) and returning relevant results. When the query exceeds the model’s confidence threshold or requires human judgment, it smoothly escalates to a human representative.</p><p>The business runs this model on a modest server for about $50/month, handling 80% of routine inquiries that previously required staff time.</p><h3>3. Inventory Management Assistance</h3><p>SLMs can analyze inventory data and generate human-readable insights, making it easier for non-technical staff to make informed decisions.</p><p><strong>Example</strong>: A garden supply center uses an SLM to generate daily inventory reports that don’t just show numbers but provide context: “Potting soil inventory is running lower than typical for this time of year. Based on last year’s patterns, consider reordering before the spring rush begins in three weeks. Current stock will likely deplete in 12 days at current sales velocity.”</p><p>This transforms raw data into actionable intelligence without requiring expensive business intelligence software or data analysis expertise.</p><h3>4. Personalized Email Marketing</h3><p>Generic email blasts have poor engagement rates. SLMs can help create personalized content at scale.</p><p><strong>Example</strong>: A specialty coffee roaster uses an SLM to personalize their weekly newsletter. The model analyzes each customer’s purchase history and generates customized product recommendations and descriptions. A customer who regularly buys light Ethiopian roasts might receive: “Based on your love for bright, floral coffees, you’ll appreciate our new Kenyan Kirinyaga-notes of blackcurrant and bergamot with a wine-like acidity.”</p><p>The model generates hundreds of these personalized snippets in minutes, creating genuine individual relevance without the impossibility of hand-crafting each message.</p><h3>5. Review Response Generation</h3><p>Responding to customer reviews is time-consuming but important for reputation management. SLMs can draft thoughtful, contextually appropriate responses.</p><p><strong>Example</strong>: A small electronics retailer receives dozens of reviews weekly across Google, Yelp, and their own site. An SLM analyzes each review’s sentiment and content, then drafts appropriate responses-thanking customers for positive feedback with specific acknowledgment of what they appreciated, or addressing concerns in negative reviews with empathy and concrete solutions. A human manager quickly reviews and approves these drafts, reducing response time from hours to minutes.</p><h3>Small Language Models in Finance: Transforming Operations</h3><p>Financial services, even at the small business level, involve complex documents, regulatory requirements, and data-heavy decision-making. SLMs are proving valuable here too.</p><h3>1. Invoice Processing and Data Extraction</h3><p>Small accounting firms and bookkeeping services process mountains of invoices in various formats. SLMs can extract key information regardless of document layout.</p><p><strong>Example</strong>: A bookkeeping service handling 30 small business clients receives invoices in dozens of different formats-PDFs, scanned images, emails, digital receipts. An SLM processes these documents, extracting vendor names, amounts, dates, line items, and tax information with 95%+ accuracy. The model flags unusual items (like an invoice amount 3x higher than historical averages from that vendor) for human review. What used to take 2–3 hours of manual data entry daily now takes 20 minutes of verification.</p><h3>2. Financial Report Summarization</h3><p>Small business owners often lack time to dig through detailed financial statements. SLMs can generate executive summaries in plain English.</p><p><strong>Example</strong>: A fractional CFO service uses an SLM to transform client financial data into narrative reports: “Revenue increased 12% this quarter compared to Q3, driven primarily by growth in your consulting services division. However, your client acquisition cost has risen from $450 to $680 per client, suggesting your recent marketing campaign isn’t delivering expected ROI. Cash position remains healthy at 4.2 months of operating expenses.”</p><p>These summaries help business owners quickly grasp their financial position without needing to be accounting experts.</p><h3>3. Expense Categorization and Policy Compliance</h3><p>Expense report processing is tedious and error-prone. SLMs can automatically categorize expenses and flag policy violations.</p><p><strong>Example</strong>: A small consulting firm’s employees submit expense reports weekly. An SLM automatically categorizes each expense (meals, travel, office supplies, etc.) based on merchant name and description, even handling ambiguous cases using context. The model also checks compliance: “This $150 dinner expense exceeds the $75 per-person meal policy. Please provide justification or split among multiple attendees.” This automation saves the office manager 5–6 hours weekly.</p><h3>4. Contract Review and Risk Flagging</h3><p>Small businesses sign numerous contracts but often can’t afford legal review for routine agreements. SLMs can perform initial risk assessment.</p><p><strong>Example</strong>: A small marketing agency uses an SLM to review client contracts before signing. The model, trained on contract language and the company’s standard terms, flags unusual clauses: “This contract includes an unlimited liability clause in section 7.3, which differs from your standard limitation of liability terms. This also contains a non-compete clause preventing work with any company in the ‘media industry’ for 24 months-broader than your typical 90-day client-specific non-compete.”</p><p>While not replacing legal counsel for complex agreements, this provides valuable early-warning on problematic terms.</p><h3>5. Customer Credit Assessment</h3><p>Small businesses extending credit or payment plans need to assess customer reliability without enterprise-grade credit systems.</p><p><strong>Example</strong>: A B2B supplier uses an SLM to analyze customer payment histories and generate credit recommendations. The model considers payment timeliness, order patterns, communication history, and industry factors: “Customer XYZ has maintained perfect payment history over 14 months with gradually increasing order sizes. Industry conditions are stable. Recommend extending net-60 terms with a $25,000 credit limit.”</p><p>This systematic approach reduces bad debt while enabling the business to confidently extend favorable terms to reliable customers.</p><h3>Implementing Small Language Models: What You Need to Know</h3><p>If these applications sound appealing, here’s what small business owners should consider when exploring SLMs:</p><p><strong>Start with Clear Use Cases</strong>: Don’t deploy AI for AI’s sake. Identify specific, repetitive tasks where automation would save meaningful time or reduce errors. Calculate the value: if a task takes an employee 10 hours weekly at $30/hour, that’s $15,600 annually that automation could save.</p><p><strong>Choose the Right Model</strong>: Open-source options like Llama 3.2, Phi-3, or Mistral offer excellent performance without licensing costs. Cloud platforms like AWS, Google Cloud, and Azure provide managed services that handle infrastructure complexity. For non-technical implementations, platforms like Hugging Face or specialized business AI tools offer user-friendly interfaces.</p><p><strong>Plan for Fine-Tuning</strong>: Out-of-the-box models provide general capability, but fine-tuning on your data creates transformative results. Gather relevant examples-past customer service conversations, correctly categorized products, or well-written report summaries. Even a few hundred quality examples can significantly improve performance for your specific needs.</p><p><strong>Keep Humans in the Loop</strong>: SLMs should augment human decision-making, not replace it entirely. Design workflows where the AI handles the bulk of routine work but humans review outputs, especially for customer-facing content or financial decisions. This hybrid approach maintains quality while capturing efficiency gains.</p><p><strong>Measure and Iterate</strong>: Track metrics like time saved, error rates, and customer satisfaction. SLMs improve with feedback, so establish processes for identifying mistakes and retraining the model. A model that’s 90% accurate today can become 97% accurate with three months of corrections.</p><h3>The Bottom Line</h3><p>Small language models represent a democratization of AI capability. While tech giants deploy massive models requiring millions in infrastructure, small businesses can achieve practical results with models that run on modest hardware and cost little to operate.</p><p>The key is recognizing that business efficiency doesn’t require the most powerful AI available-it requires the right AI for specific tasks. A small model that’s been fine-tuned for your product catalog, your customer base, and your workflows will outperform a general-purpose giant for your specific needs.</p><p><em>Ready to explore small language models for your business? Start by identifying one repetitive, time-consuming task in your daily operations. That’s your entry point into practical AI that delivers real results without enterprise-level investment.</em></p><p>As these models continue improving and tooling becomes more accessible, small businesses that adopt SLMs thoughtfully will find themselves operating with an efficiency previously available only to large enterprises. The playing field is leveling, and smart small business owners are already taking advantage.</p><p>The question isn’t whether your business can benefit from small language models-it’s which workflow you’ll automate first.</p><p><em>Originally published at </em><a href="https://www.rapidarchitect.com/ai-rise-of-small-lms/"><em>https://www.rapidarchitect.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c05840144583" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Beyond Vector Search: Building Intelligent Context Layers for Agentic AI]]></title>
            <link>https://medium.com/@mhjorleifsson/beyond-vector-search-building-intelligent-context-layers-for-agentic-ai-ee1d3921d9e1?source=rss-dcf30d9a6f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee1d3921d9e1</guid>
            <category><![CDATA[agentic-rag]]></category>
            <category><![CDATA[langgraph]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[context-engineering]]></category>
            <dc:creator><![CDATA[Mhjorleifsson]]></dc:creator>
            <pubDate>Fri, 24 Oct 2025 05:53:13 GMT</pubDate>
            <atom:updated>2025-10-24T05:53:13.605Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LGrFxofvOJked1wb" /></figure><p>The promise of Retrieval-Augmented Generation (RAG) was simple: augment your LLM prompts with relevant data, and suddenly you’d have answers grounded in your organization’s knowledge. Build a demo in a weekend, they said. Ship to production in a sprint, they said.</p><p>Two years later, countless organizations learned a hard lesson: traditional RAG breaks down at scale. Vector search alone isn’t intelligent enough. You end up with “context poisoning,” where irrelevant information contaminates your model’s reasoning. Or “context confusion,” where the model drowns in data. Or worse — you realize that retrieving flat text chunks can’t explain <em>why</em> it found something, or whether an agent has permission to access it.</p><p>The industry has moved on. And if you’re building enterprise AI systems that actually need to reason responsibly, you should too.</p><h3>From RAG to Context Engineering</h3><p><em>This article is inspired by Steve Hedden’s “Beyond RAG: Is RAG Dead? The Rise of Context Engineering and Semantic Layers for Agentic AI” on Towards Data Science, which articulates a crucial evolution in how organizations are approaching retrieval and context management.</em></p><p>Last year, the conversation shifted. The term “RAG” didn’t disappear, but its naive implementation did. In its place, thought leaders from Contextual AI, LlamaIndex, and LangChain began popularizing the term “context engineering” — the art and science of filling the context window with <em>just the right information</em> at each step of an agent’s trajectory.</p><p>This shift reflects a fundamental rethinking of what retrieval means in the age of agentic AI. No longer is retrieval a single, one-shot operation. Instead, it’s one part of a four-step loop that Lance Martin of LangChain describes elegantly:</p><ol><li><strong>Write</strong>: Agents need to persist or remember information from task to task</li><li><strong>Compress</strong>: Too much context accumulates; it must be summarized or pruned</li><li><strong>Isolate</strong>: Rather than giving all context to one model, distribute it across specialized agents</li><li><strong>Select</strong>: Actively choose which context to retrieve — tools, memories, and data — rather than blindly pulling everything</li></ol><p>This is where semantic layers and knowledge graphs enter the picture. These aren’t just metadata management tools anymore; they’re the connective tissue that makes context engineering possible.</p><h3>The Layered Context Framework: Putting Theory Into Practice</h3><p>The open-source <a href="https://github.com/rapidarchitect/langgraph-layered-context">LangGraph Layered Context Framework</a> (which draws explicit inspiration from Hedden’s article) demonstrates what context engineering looks like in production code.</p><p>Rather than relying on a single vector search, this framework organizes information into <em>four hierarchical semantic layers</em>, each designed for different agent needs:</p><p><strong>Layer 1: Raw</strong> The baseline — traditional RAG chunks. Fast retrieval, minimal processing. Good for answering simple factual questions.</p><p><strong>Layer 2: Entity</strong> Chunks enriched with Named Entity Recognition (NER), entity linking, and relationships. An agent knows which people, places, and concepts are involved without running its own analysis.</p><p><strong>Layer 3: Graph</strong> Structured as a knowledge graph with entities and relationships made explicit. Perfect for questions requiring multi-hop reasoning: “What projects did the people involved in Project X also work on?”</p><p><strong>Layer 4: Abstract</strong> High-level summaries and abstracts tailored to agent purpose. A researcher might get a different summary than an analyst — same underlying data, context optimized for their role.</p><p>Each layer sits on top of the others. Your orchestrator — built with LangGraph — asks: “What does this agent need?” and assembles only the layers relevant to answering the question.</p><h3>How This Solves Real Problems</h3><p><strong>Context Poisoning &amp; Confusion</strong>: By organizing information hierarchically, you drastically reduce noise. A researcher looking for high-level trends gets the abstract layer, not 50 megabytes of raw text.</p><p><strong>Explainability</strong>: Each layer includes provenance tracking. You can trace why a given piece of context was retrieved, who extracted it, and which processing steps created it. This is critical for regulated industries.</p><p><strong>Governance &amp; Access Control</strong>: The framework includes role-based access control (RBAC) at the layer level. A junior analyst might only see Layer 1 (raw), while a senior researcher can access all layers including the abstract summaries. Every access is logged.</p><p><strong>Scalability</strong>: With parallel document ingestion, multi-format support (PDFs, markdown, SQL, MongoDB), and optional caching, the framework handles enterprise-scale ingestion while keeping queries fast.</p><p><strong>Multi-Agent Orchestration</strong>: Different agents have different capabilities and layer preferences. The orchestrator routes queries intelligently, ensuring each agent gets the context it needs to reason effectively.</p><h3>Under The Hood: The Architecture</h3><p>The framework is built on battle-tested components:</p><ul><li><strong>spaCy</strong> for NER and relationship extraction</li><li><strong>NetworkX</strong> for lightweight graph operations (extensible to Neo4j for larger deployments)</li><li><strong>Chroma</strong> for vector search with metadata filtering</li><li><strong>Sentence-Transformers</strong> for embeddings</li><li><strong>LangGraph</strong> for multi-agent orchestration and state management</li></ul><p>The ingestion pipeline runs in parallel, using asyncio to load documents from directories, databases, or URLs without blocking. For enrichment, spaCy performs entity recognition and dependency parsing to extract relationships automatically. Those entities and relationships get stored in the graph, while embeddings go into Chroma. The orchestrator then assembles context from all three sources based on the agent’s role and the query’s purpose.</p><p>Here’s what the basic workflow looks like in code:</p><p>python</p><pre>from src.ingestion import DocumentIngestionPipeline<br>from src.extraction import ChunkEnricher<br>from src.graph import NetworkXGraphStore<br>from src.context import ContextAssembler<br>from src.retrieval import ChromaVectorStore<br>from src.agents import AgentOrchestrator<br>from src.governance import AccessController, AuditLogger</pre><pre># 1. Ingest documents<br>pipeline = DocumentIngestionPipeline(max_workers=4)<br>chunks = []<br>async for chunk in pipeline.ingest_from_directory(<br>    &quot;documents/&quot;,<br>    file_types=[&quot;md&quot;, &quot;txt&quot;, &quot;pdf&quot;],<br>    chunk_size=512,<br>):<br>    chunks.append(chunk)</pre><pre># 2. Extract entities and relationships<br>enricher = ChunkEnricher(nlp_model=&quot;en_core_web_md&quot;)<br>enriched = await enricher.enrich_chunks(chunks)</pre><pre># 3. Build knowledge graph<br>graph = NetworkXGraphStore()<br>for chunk in enriched:<br>    graph.add_entities_and_relationships(<br>        chunk.entities,<br>        chunk.relationships,<br>    )</pre><pre># 4. Index for vector search<br>vector_store = ChromaVectorStore()<br>vector_store.add_chunks(chunks)</pre><pre># 5. Set up governance<br>access_controller = AccessController()<br>audit_logger = AuditLogger()</pre><pre># 6. Create orchestrator<br>orchestrator = AgentOrchestrator(<br>    access_controller=access_controller,<br>    audit_logger=audit_logger,<br>)</pre><pre># 7. Register agents and execute<br>from src.agents import Agent, AgentRole, AgentCapability</pre><pre>researcher = Agent(<br>    name=&quot;Research Agent&quot;,<br>    role=AgentRole.RESEARCHER,<br>    capabilities=[AgentCapability.RETRIEVE_CONTEXT],<br>)<br>orchestrator.register_agent(researcher)</pre><pre>state = await orchestrator.execute_agent(<br>    agent_id=researcher.agent_id,<br>    query=&quot;What are the key entities in the documents?&quot;,<br>)</pre><h3>Real-World Use Cases</h3><h3>1. Building Enterprise Knowledge Bases</h3><p>Traditional RAG works fine on 100 documents. Scale to 100,000 and you’re drowning in false positives. The layered approach lets you build intelligent search systems where:</p><ul><li>Users get instant answers from the raw layer (fast, good for FAQ-style queries)</li><li>The system can explain <em>which entities</em> answered your question (entity layer)</li><li>Complex research gets supplemented with relationship context (graph layer)</li><li>Topic summaries are automatically tailored to user role and access level (abstract layer)</li></ul><p>Add governance on top and you’ve got a system where compliance teams can audit who accessed what, and policy teams can prevent sensitive data from leaking to unauthorized users.</p><h3>2. Code Review &amp; Documentation Generation</h3><p>Imagine a code review agent that doesn’t just search for similar functions — it understands the relationships between modules, the data flow between components, and can generate focused documentation that highlights what changed and why.</p><p>With the layered framework:</p><ul><li><strong>Raw layer</strong>: Function definitions and docstrings</li><li><strong>Entity layer</strong>: Classes, functions, and variables with type information</li><li><strong>Graph layer</strong>: Dependency relationships (which functions call which, which modules import which)</li><li><strong>Abstract layer</strong>: Purpose-driven summaries (“Here’s what changed in the auth module and what depends on it”)</li></ul><p>A refactoring agent can then use the graph layer to understand impact, while the abstract layer helps communicate changes to stakeholders.</p><h3>3. Internal Search &amp; Discovery</h3><p>Most enterprises have internal knowledge scattered across wikis, Slack, documents, and databases. Traditional search is keyword-based. A semantic layer changes this.</p><p>Instead of “find documents containing the word ‘budget,’” an agent can now ask:</p><ul><li>“What projects did team X work on last quarter?” (raw + graph layers for teams)</li><li>“Which projects are budget-constrained?” (entity layer with extracted budget entities)</li><li>“Summarize the biggest risks to our roadmap” (abstract layer, summarized for exec level)</li></ul><p>And every query is auditable. You know who asked what, when, and what they got back.</p><h3>4. Agentic Decision Support</h3><p>When you’re building autonomous agents that make decisions affecting your business, explainability isn’t nice-to-have — it’s essential. Why did the supply chain optimization agent choose this vendor? What data drove that decision?</p><p>The layered context framework tracks provenance through every step. When an agent makes a decision, you can inspect:</p><ul><li>The raw chunks that informed it</li><li>The extracted entities that mattered</li><li>The relationship paths that connected the dots</li><li>The summarized abstract that drove the conclusion</li></ul><p>This is what governance looks like in the age of agentic AI.</p><h3>The Bigger Picture: Semantic Layers as Infrastructure</h3><p>The framework is a concrete implementation of a much larger trend. Organizations are finally waking up to the fact that you can’t build intelligent AI systems on top of unstructured data. You need metadata. You need semantics. You need <em>governance</em>.</p><p>This is why we’ve seen an explosion of acquisitions in the semantic technology space:</p><ul><li>Samsung acquired Oxford Semantic Technologies (RDFox) for on-device reasoning</li><li>ServiceNow acquired data.world for semantic layer and knowledge graph integration</li><li>Salesforce acquired Informatica (metadata leader) for $8 billion</li><li>Ontotext and Semantic Web Company merged to form Graphwise, explicitly positioning around GraphRAG</li></ul><p>These aren’t random moves. They signal market consolidation around a single insight: <em>knowledge graphs and semantic layers are the infrastructure for intelligent AI.</em></p><p>The framework open-sources what enterprise teams are building behind closed doors. It shows that you don’t need a massive budget or a PhD in graph theory to start building systems that reason over semantic layers. You need:</p><ol><li>A way to organize data hierarchically (the four layers)</li><li>Tools to extract meaning (NER, relationships, entity linking)</li><li>Multiple retrieval paths (vector search + graph traversal)</li><li>Governance built in from the start (RBAC, audit logging, provenance)</li><li>Agent orchestration that can route queries intelligently (LangGraph)</li></ol><h3>Getting Started</h3><p>The framework is production-ready and MIT-licensed. You can start with the basic workflow on a single machine, then scale:</p><p>bash</p><pre>git clone https://github.com/rapidarchitect/langgraph-layered-context<br>cd langgraph-layered-context<br>source .venv/bin/activate<br>uv pip install -e .<br>python -m spacy download en_core_web_md<br>python examples/01_basic_workflow.py</pre><p>The examples demonstrate knowledge base Q&amp;A, code review automation, refactoring assistance, and more. The documentation includes use case guides and a detailed architecture overview. The test suite shows how to extend the framework for your specific needs.</p><h3>The Future Is Semantic</h3><p>RAG didn’t die. It evolved. What you’re seeing now is the maturation of a discipline: context engineering. And the foundation for context engineering is semantic layers — metadata, knowledge graphs, and governance built into the architecture from the start.</p><p>If you’re still building traditional RAG systems in 2025, you’re not failing — you’re just leaving capability on the table. You’re missing explainability. You’re missing governance. You’re missing the ability to reason over relationships. You’re missing the precision that comes from organizing information semantically.</p><p>The LangGraph Layered Context Framework shows what’s possible when you move beyond vector search and build on semantic foundations. It’s a reminder that the future of AI isn’t about bigger models or fancier algorithms — it’s about smarter context.</p><p><strong>Acknowledgment</strong>: This article draws heavily on Steve Hedden’s excellent Towards Data Science piece, “<a href="https://towardsdatascience.com/beyond-rag/">Beyond RAG: Is RAG Dead? The Rise of Context Engineering and Semantic Layers for Agentic AI</a>.” If you haven’t read it yet, you should. It’s the most comprehensive treatment of where the industry is headed and why semantic layers matter. The LangGraph Layered Context Framework demonstrates these concepts in executable code.</p><p><strong>References</strong>:</p><ul><li><a href="https://towardsdatascience.com/beyond-rag/">Beyond RAG — Towards Data Science</a></li><li><a href="https://github.com/rapidarchitect/langgraph-layered-context">LangGraph Layered Context — GitHub</a></li><li><a href="https://langchain-ai.github.io/langgraph/">LangGraph Documentation</a></li><li><a href="https://arxiv.org/pdf/2311.07509">Knowledge Graphs &amp; LLMs — data.world Research</a></li><li><a href="https://www.microsoft.com/en-us/research/blog/graphrag-new-tool-for-complex-data-discovery-now-on-github/">Microsoft GraphRAG</a></li></ul><p><em>Have you built systems that move beyond traditional RAG? What semantic techniques have worked for you? Drop a comment or reach out — I’m curious to hear how teams are approaching context engineering in practice.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee1d3921d9e1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Securing AI’s Communication Layer: How MCP-SEC Can Bring Mutual Authentication to the Model Context…]]></title>
            <link>https://medium.com/@mhjorleifsson/securing-ais-communication-layer-how-mcp-sec-can-bring-mutual-authentication-to-the-model-context-aa09bfcfc5c4?source=rss-dcf30d9a6f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa09bfcfc5c4</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[information-security]]></category>
            <category><![CDATA[ai-security]]></category>
            <dc:creator><![CDATA[Mhjorleifsson]]></dc:creator>
            <pubDate>Thu, 16 Oct 2025 05:02:56 GMT</pubDate>
            <atom:updated>2025-10-16T05:02:56.166Z</atom:updated>
            <content:encoded><![CDATA[<h3>Securing AI’s Communication Layer: How MCP-SEC Can Bring Mutual Authentication to the Model Context Protocol</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cWRtiihgjKx1XYa5" /></figure><h3>Securing AI’s Communication Layer: How MCP-SEC Brings Mutual Authentication to the Model Context Protocol</h3><p>As AI systems become increasingly integrated into our workflows, a critical question emerges: how do we ensure these systems communicate securely? While we’ve been focused on making AI models smarter, we’ve sometimes overlooked the pipes connecting them to our data and services.</p><p>Enter the Model Context Protocol (MCP) and a new open-source project that’s tackling its security head-on: mcp-sec.</p><h3>The Context Problem in AI Systems</h3><p>If you’ve worked with AI assistants like Claude, ChatGPT, or custom LLM applications, you’ve likely encountered a fundamental challenge: these models need context to be useful. They need access to your documents, databases, APIs, and services. The Model Context Protocol was created to standardize how AI systems connect to these resources, much like how HTTP standardized web communication.</p><p>But here’s the catch: when you’re connecting powerful AI systems to sensitive resources, authentication becomes critical. You wouldn’t let just any application access your company’s database, so why would you let any MCP client or server connect without proper verification?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IfTHO81YYMsuERGvd6ypIg.png" /></figure><h3>The Trust Problem</h3><p>Traditional authentication often flows one way. Your browser authenticates to a server, or your app authenticates to an API. But when you’re building AI agent systems, both sides need assurance:</p><ul><li><strong>Servers need to know:</strong> Is this really a trusted AI client, or is someone trying to abuse my data sources?</li><li><strong>Clients need to know:</strong> Is this really the MCP server I’m trying to connect to, or have I been redirected to a malicious endpoint?</li></ul><p>This is where mutual authentication comes in, and where mcp-sec offers an elegant solution.</p><h3>Introducing MCP-SEC: Mutual Authentication for AI Context</h3><p>The mcp-sec project implements a robust mutual authentication system for MCP using ed25519 public key cryptography. Think of it as SSH-style authentication for your AI infrastructure, where both parties prove their identity before any data exchange begins.</p><h3>The Four-Message Handshake</h3><p>At its core, mcp-sec implements a clean four-step authentication dance:</p><p><strong>Step 1:</strong> The client sends an authentication request with its public key<br> <strong>Step 2:</strong> The server validates the client’s key against its allowlist, then responds with a cryptographic challenge<br> <strong>Step 3:</strong> The client proves it possesses the private key by signing the challenge and sends back the response<br> <strong>Step 4:</strong> The server verifies the signature and confirms successful authentication</p><p>This entire exchange typically completes in under 10 milliseconds, adding negligible overhead to your AI operations.</p><h3>Why Ed25519?</h3><p>You might wonder why ed25519 specifically. This modern elliptic curve signature scheme offers several advantages for AI infrastructure:</p><p><strong>Speed:</strong> Ed25519 is blazingly fast, crucial when you’re authenticating potentially thousands of MCP connections per minute.</p><p><strong>Security:</strong> With 128-bit security level, ed25519 provides strong protection without the bloat of older algorithms like RSA-2048.</p><p><strong>Simplicity:</strong> The public keys are just 32 bytes, making them easy to manage and distribute.</p><p><strong>Modern:</strong> It’s designed to resist timing attacks and other cryptographic vulnerabilities that plague older algorithms.</p><h3>Key Features That Matter</h3><h3>Replay Attack Prevention</h3><p>Every authentication challenge includes a timestamp and unique nonce. Even if an attacker captures the entire authentication exchange, they can’t replay it. The server maintains a cache of recently used nonces and rejects duplicates, while timestamp validation ensures challenges don’t remain valid indefinitely.</p><h3>Allowlist-Based Access Control</h3><p>Rather than relying on implicit trust, mcp-sec uses explicit allowlists. Each server maintains a list of trusted client public key fingerprints, and vice versa. This provides fine-grained control over who can connect to what.</p><p>You can attach rich metadata to each allowed key:</p><pre>{<br>  &quot;role&quot;: &quot;analytics_client&quot;,<br>  &quot;organization&quot;: &quot;data_team&quot;,<br>  &quot;expires&quot;: &quot;2024-12-31&quot;,<br>  &quot;permissions&quot;: [&quot;read_only&quot;]<br>}</pre><h3>Comprehensive Audit Logging</h3><p>Every authentication attempt gets logged in structured JSON format, including:</p><ul><li>Success or failure status</li><li>Public key fingerprints of both parties</li><li>Timestamp and duration</li><li>Performance metrics</li><li>Custom metadata</li></ul><p>This creates an audit trail that security teams love and compliance officers require.</p><h3>Transport Flexibility</h3><p>The system works seamlessly over HTTP, HTTPS, WebSocket, and secure WebSocket connections. You can start simple and upgrade to encrypted transports as your security requirements evolve.</p><h3>Getting Started in Five Minutes</h3><p>For those eager to try it out, here’s how quickly you can secure an MCP connection:</p><p><strong>Generate key pairs:</strong></p><pre>mcp-keygen --output-dir ./keys --key-name server<br>mcp-keygen --output-dir ./keys --key-name client</pre><p><strong>Set up mutual trust:</strong></p><pre># Client trusts server<br>mcp-allowlist add --config client_config.yml \<br>  --key-file ./keys/server_public.pem</pre><pre># Server trusts client<br>mcp-allowlist add --config server_config.yml \<br>  --key-file ./keys/client_public.pem</pre><p><strong>Start secured communication:</strong></p><pre># Terminal 1<br>python -m mcp_pki_auth.examples.server --config server_config.yml</pre><pre># Terminal 2<br>python -m mcp_pki_auth.examples.client \<br>  --server-url <a href="https://localhost:8443/auth">https://localhost:8443/auth</a></pre><p>That’s it. You now have mutually authenticated MCP connections.</p><h3>Real-World Applications</h3><p>Consider these scenarios where mcp-sec adds critical security:</p><p><strong>Enterprise AI Deployments:</strong> Multiple AI agents need to access internal databases and APIs. With mcp-sec, you can ensure only authorized agents with valid credentials can connect, preventing unauthorized data access.</p><p><strong>Multi-Tenant AI Platforms:</strong> SaaS providers running AI services for different customers can use mcp-sec to isolate tenant contexts and prevent cross-tenant data leakage.</p><p><strong>Federated AI Systems:</strong> When AI systems need to collaborate across organizational boundaries, mcp-sec provides the authentication framework that lets them establish trust without sharing sensitive credentials.</p><p><strong>AI Agent Marketplaces:</strong> As we move toward ecosystems of specialized AI agents, mcp-sec enables servers to verify agent authenticity before granting access to premium data sources or compute resources.</p><h3>The Developer Experience</h3><p>One of mcp-sec’s strengths is its approachability. The project includes:</p><ul><li><strong>CLI tools</strong> for key management, allowlist administration, and testing</li><li><strong>Python SDK</strong> with clean, async-ready APIs</li><li><strong>Docker support</strong> for containerized deployments</li><li><strong>Comprehensive examples</strong> covering common use cases</li><li><strong>Performance benchmarks</strong> to validate your configuration</li></ul><p>Whether you’re a security engineer hardening production systems or a hobbyist building your first AI agent, the tooling meets you where you are.</p><h3>Security Best Practices Built-In</h3><p>The project embodies security best practices:</p><ul><li>No implicit trust relationships</li><li>Minimal attack surface through stateless server design</li><li>Defense in depth with transport-layer encryption plus authentication</li><li>Regular key rotation support</li><li>Rate limiting and connection pooling to prevent resource exhaustion</li><li>Comprehensive logging for security monitoring</li></ul><h3>Looking Forward</h3><p>The mcp-sec project represents just the beginning. The roadmap includes:</p><ul><li><strong>Multi-language implementations</strong> (Go, Rust, Node.js)</li><li><strong>Automated key rotation protocols</strong></li><li><strong>Federation support</strong> for cross-domain authentication</li><li><strong>Hardware security module (HSM) integration</strong></li><li><strong>Prometheus metrics</strong> for operational monitoring</li></ul><p>But even in its current form, it provides production-ready security for MCP deployments.</p><h3>Why This Matters for AI’s Future</h3><p>As we build increasingly autonomous AI systems, security can’t be an afterthought. The Model Context Protocol is becoming a standard for AI-to-resource communication, and projects like mcp-sec ensure that standard includes robust authentication from day one.</p><p>Whether you’re building AI agents, deploying MCP servers, or architecting AI infrastructure, mutual authentication needs to be part of your security strategy. The good news? With mcp-sec, it’s now straightforward to implement.</p><p>The code is open source, the documentation is comprehensive, and the community is just getting started. If you’re working with MCP or thinking about AI system security, this is a project worth exploring.</p><p><strong>Resources:</strong></p><ul><li>GitHub Repository: <a href="https://github.com/rapidarchitect/mcp-sec">https://github.com/rapidarchitect/mcp-sec</a></li><li>Documentation: Available in the repo’s docs/ directory</li><li>License: MIT</li></ul><p><strong>About the Project:</strong> mcp-sec is maintained by M. Hjorleifsson and welcomes contributions from the community. Whether you’re reporting issues, submitting PRs, or implementing the protocol in other languages, there’s room for everyone to contribute to making AI communication more secure.</p><p><em>Have you implemented authentication for your AI systems? What challenges have you faced? Share your experiences in the comments below.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa09bfcfc5c4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Your Python API Should Ditch JSON for Protocol Buffers (And How to Do It Right)]]></title>
            <link>https://medium.com/@mhjorleifsson/why-your-python-api-should-ditch-json-for-protocol-buffers-and-how-to-do-it-right-61229868748a?source=rss-dcf30d9a6f3------2</link>
            <guid isPermaLink="false">https://medium.com/p/61229868748a</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[json]]></category>
            <dc:creator><![CDATA[Mhjorleifsson]]></dc:creator>
            <pubDate>Sat, 11 Oct 2025 15:14:02 GMT</pubDate>
            <atom:updated>2025-10-11T15:14:02.612Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A practical guide to reducing API payload sizes by 64%, cutting response times by 3x, and saving thousands in bandwidth costs — all with Python.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pgjmtmWXS6DqFie3" /></figure><h3>The $22,000 Question</h3><p>Last year, I watched our fintech platform’s AWS bill climb every month as we scaled to 50,000 API calls per minute. Our JSON payloads had bloated to 523 bytes for a simple transaction response. The math was brutal:</p><ul><li><strong>50,000 requests/minute</strong> × <strong>523 bytes</strong> × <strong>43,200 minutes/month</strong> = <strong>1.13 TB of data transfer</strong></li><li>At AWS pricing: <strong>~$100/month just in bandwidth</strong></li><li>Multiply by microservices, mobile apps, webhooks… you get the picture.</li></ul><p>Then we discovered Protocol Buffers. Six months later:</p><ul><li>Payloads: <strong>523 bytes → 187 bytes (64% reduction)</strong></li><li>Response times: <strong>280ms → 95ms average (66% faster)</strong></li><li>Bandwidth costs: <strong>Down 70%</strong></li><li>Annual savings: <strong>$22,000+</strong></li></ul><p>Here’s how we did it in Python, and why you should consider the same.</p><h3>JSON: The Universal Language We Love to Hate</h3><p>Don’t get me wrong — JSON is fantastic for many use cases:</p><p>✅ Human-readable<br>✅ Built into every language<br>✅ No compilation step<br>✅ Browser-native<br>✅ Great for debugging</p><p>But JSON has serious problems at scale:</p><p>❌ <strong>Verbose</strong> — Field names repeated in every record<br>❌ <strong>Slow</strong> — Text parsing is CPU-intensive<br>❌ <strong>Loose typing</strong> — Runtime validation required<br>❌ <strong>Large payloads</strong> — Significant bandwidth waste<br>❌ <strong>No schema enforcement</strong> — Breaking changes are invisible</p><p>Let me show you what I mean:</p><pre>{<br>  &quot;transaction&quot;: {<br>    &quot;id&quot;: &quot;txn_1234567890&quot;,<br>    &quot;user_id&quot;: &quot;usr_abcdef123456&quot;,<br>    &quot;amount&quot;: 1250.50,<br>    &quot;currency&quot;: &quot;USD&quot;,<br>    &quot;status&quot;: &quot;completed&quot;,<br>    &quot;created_at&quot;: &quot;2024-03-15T10:30:00Z&quot;,<br>    &quot;metadata&quot;: {<br>      &quot;payment_method&quot;: &quot;credit_card&quot;,<br>      &quot;merchant_name&quot;: &quot;Coffee Shop Downtown&quot;,<br>      &quot;location&quot;: {<br>        &quot;latitude&quot;: 40.7128,<br>        &quot;longitude&quot;: -74.0060<br>      }<br>    }<br>  }<br>}</pre><p><strong>Size: 523 bytes</strong></p><p>Every field name is transmitted. Every time. For every request.</p><h3>Protocol Buffers: The Binary Alternative</h3><p>Protocol Buffers (protobuf) is Google’s language-neutral serialization format. Instead of transmitting field names, it uses <strong>numbered field tags</strong>. Instead of text, it uses <strong>compact binary encoding</strong>.</p><p>Here’s the same data in protobuf format:</p><pre>syntax = &quot;proto3&quot;;</pre><pre>message Transaction {<br>  string id = 1;<br>  string user_id = 2;<br>  double amount = 3;<br>  string currency = 4;<br>  string status = 5;<br>  int64 created_at = 6;<br>  Metadata metadata = 7;<br>}</pre><pre>message Metadata {<br>  string payment_method = 1;<br>  string merchant_name = 2;<br>  Location location = 3;<br>}</pre><pre>message Location {<br>  double latitude = 1;<br>  double longitude = 2;<br>}</pre><p><strong>Size: 187 bytes</strong> (64% smaller!)</p><p>The schema is defined once, compiled, and then the binary format uses field numbers instead of names. It’s like switching from verbose English to efficient shorthand.</p><h3>The Five Key Benefits for Python Developers</h3><h3>1. Massive Payload Reduction</h3><p>Our real-world data:</p><ul><li>Simple transaction: <strong>523 → 187 bytes (64% smaller)</strong></li><li>Complex user profile: <strong>2.1 KB → 780 bytes (63% smaller)</strong></li><li>Bulk data export: <strong>45 MB → 16 MB (64% smaller)</strong></li></ul><p>The pattern is consistent: <strong>60–70% size reduction</strong> across the board.</p><h3>2. Significantly Faster Serialization</h3><p>From our benchmarks (10,000 operations):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/488/1*iOR6vjUo5ynOvOssMzlSHg.png" /></figure><h3>3. Type Safety Across Your Stack</h3><pre># JSON - Runtime errors waiting to happen<br>data = json.loads(payload)<br>amount = data[&#39;transaction&#39;][&#39;amount&#39;]  # KeyError? TypeError? Who knows!</pre><pre># Protobuf - Compile-time guarantees<br>transaction = Transaction()<br>transaction.ParseFromString(payload)<br>amount = transaction.amount  # Type-safe, autocomplete works, errors at compile time</pre><h3>4. Schema Evolution Without Breaking Changes</h3><pre>message Transaction {<br>  string id = 1;<br>  double amount = 2;<br>  <br>  // Add new fields without breaking old clients<br>  string new_feature = 10;  // Old clients ignore this<br>  <br>  // Reserve deprecated fields<br>  reserved 5, 8, 9;  // Can&#39;t accidentally reuse<br>}</pre><h3>5. Real Cost Savings</h3><p>At different scales (AWS data transfer pricing):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/533/1*3E1SCTWwGtbwDeG3w11LcQ.png" /></figure><h3>Python Implementation: Which Library Should You Use?</h3><p>Based on our comprehensive testing, here are the Python options:</p><h3>Performance Analysis Results</h3><p>We tested four Protocol Buffers implementations in Python (1,000 operations):</p><pre>======================================================================<br>Backend Comparison<br>======================================================================</pre><pre>Official Google Protobuf:<br>  - upb (C extension):      0.07ms  ← FASTEST, default since 2022<br>  - cpp (C++ extension):    0.07ms  ← Legacy, deprecated<br>  - python (pure Python):   0.07ms  ← Portable, no C needed</pre><pre>pure-protobuf (Alternative):<br>  - Serialization:          1.25ms<br>  - Deserialization:        5.08ms<br>  - Total:                  6.33ms  ← ~90x slower, but clean API</pre><p><strong>Key Finding:</strong> The official Google protobuf library (any backend) significantly outperforms alternatives, even the pure Python backend is highly optimized.</p><h3>Our Recommendations: Choose Your Implementation</h3><h3>🥇 Best for Production: Official Protobuf with UPB Backend</h3><p><strong>When to use:</strong> High-traffic APIs, production systems, when performance matters</p><pre>pip install protobuf</pre><p><strong>Pros:</strong></p><ul><li>✅ Fastest performance (default since protobuf 4.21.0)</li><li>✅ Battle-tested by Google at massive scale</li><li>✅ Excellent documentation</li><li>✅ All three backends included (upb, cpp, python)</li></ul><p><strong>Cons:</strong></p><ul><li>❌ Requires .proto file compilation</li><li>❌ Learning curve for schema syntax</li></ul><p><strong>Example:</strong></p><pre># transaction.proto<br>syntax = &quot;proto3&quot;;</pre><pre>message Transaction {<br>  string id = 1;<br>  double amount = 2;<br>  string currency = 3;<br>}</pre><pre># Compile: protoc --python_out=. transaction.proto</pre><pre># Use in Python<br>import transaction_pb2</pre><pre>transaction = transaction_pb2.Transaction()<br>transaction.id = &quot;txn_123&quot;<br>transaction.amount = 1250.50<br>transaction.currency = &quot;USD&quot;</pre><pre># Serialize (0.07ms for 1000 ops!)<br>binary_data = transaction.SerializeToString()</pre><pre># Deserialize<br>loaded = transaction_pb2.Transaction()<br>loaded.ParseFromString(binary_data)</pre><h3>🥈 Best for Portability: Official Protobuf (Pure Python Backend)</h3><p><strong>When to use:</strong> Embedded systems, no C compiler, PyPy, maximum portability</p><pre>export PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION=python<br>pip install protobuf</pre><p><strong>Pros:</strong></p><ul><li>✅ No C dependencies</li><li>✅ Same API as C backend</li><li>✅ Works everywhere Python works</li><li>✅ Still very fast (0.07ms in our tests)</li></ul><p><strong>Cons:</strong></p><ul><li>❌ Still requires .proto compilation</li><li>❌ Slightly slower than C backends (though still excellent)</li></ul><h3>🥉 Best for Rapid Development: pure-protobuf</h3><p><strong>When to use:</strong> Prototyping, small-scale projects, when you want clean Python-native API</p><pre>pip install pure-protobuf</pre><p><strong>Pros:</strong></p><ul><li>✅ No .proto compilation needed</li><li>✅ Beautiful dataclass-based API</li><li>✅ Pydantic integration</li><li>✅ Great for Python-only projects</li></ul><p><strong>Cons:</strong></p><ul><li>❌ ~90x slower than official implementation</li><li>❌ Smaller community</li><li>❌ Not suitable for high-throughput APIs</li></ul><p><strong>Example:</strong></p><pre>from dataclasses import dataclass<br>from pure_protobuf.annotations import Field<br>from pure_protobuf.message import BaseMessage<br>from typing_extensions import Annotated</pre><pre>@dataclass<br>class Transaction(BaseMessage):<br>    id: Annotated[str, Field(1)] = &quot;&quot;<br>    amount: Annotated[float, Field(2)] = 0.0<br>    currency: Annotated[str, Field(3)] = &quot;&quot;</pre><pre># Use it!<br>transaction = Transaction(id=&quot;txn_123&quot;, amount=1250.50, currency=&quot;USD&quot;)<br>binary_data = bytes(transaction)  # That&#39;s it!</pre><pre># Deserialize<br>from io import BytesIO<br>loaded = Transaction.read_from(BytesIO(binary_data))</pre><h3>Practical Migration: FastAPI Example</h3><p>Here’s how to add Protocol Buffers to an existing FastAPI application:</p><h3>Step 1: Install Dependencies</h3><pre>pip install fastapi uvicorn protobuf</pre><h3>Step 2: Define Your Schema</h3><pre>// transaction.proto<br>syntax = &quot;proto3&quot;;</pre><pre>message Transaction {<br>  string id = 1;<br>  string user_id = 2;<br>  double amount = 3;<br>  string currency = 4;<br>  string status = 5;<br>}</pre><pre># Compile<br>protoc --python_out=. transaction.proto</pre><h3>Step 3: Create Dual-Format Endpoint</h3><pre>from fastapi import FastAPI, Response, Header<br>from fastapi.responses import JSONResponse<br>import transaction_pb2<br>import json</pre><pre>app = FastAPI()</pre><pre>@app.get(&quot;/api/transaction/{transaction_id}&quot;)<br>async def get_transaction(<br>    transaction_id: str,<br>    accept: str = Header(default=&quot;application/json&quot;)<br>):<br>    # Fetch from database<br>    data = {<br>        &quot;id&quot;: transaction_id,<br>        &quot;user_id&quot;: &quot;usr_123&quot;,<br>        &quot;amount&quot;: 1250.50,<br>        &quot;currency&quot;: &quot;USD&quot;,<br>        &quot;status&quot;: &quot;completed&quot;<br>    }<br>    <br>    # Serve protobuf if requested<br>    if &quot;protobuf&quot; in accept.lower():<br>        transaction = transaction_pb2.Transaction(<br>            id=data[&quot;id&quot;],<br>            user_id=data[&quot;user_id&quot;],<br>            amount=data[&quot;amount&quot;],<br>            currency=data[&quot;currency&quot;],<br>            status=data[&quot;status&quot;]<br>        )<br>        <br>        binary = transaction.SerializeToString()<br>        <br>        return Response(<br>            content=binary,<br>            media_type=&quot;application/x-protobuf&quot;,<br>            headers={&quot;X-Payload-Size&quot;: str(len(binary))}<br>        )<br>    <br>    # Default to JSON<br>    json_str = json.dumps(data)<br>    return JSONResponse(<br>        content=data,<br>        headers={&quot;X-Payload-Size&quot;: str(len(json_str.encode()))}<br>    )</pre><h3>Step 4: Test Both Formats</h3><pre># JSON (523 bytes)<br>curl http://localhost:8000/api/transaction/txn_123</pre><pre># Protobuf (187 bytes)<br>curl -H &quot;Accept: application/x-protobuf&quot; \<br>     <a href="http://localhost:8000/api/transaction/txn_123">http://localhost:8000/api/transaction/txn_123</a> \<br>     --output transaction.bin</pre><h3>When NOT to Use Protocol Buffers</h3><p>Let’s be honest: Protocol Buffers aren’t always the right choice.</p><h3>❌ Stick with JSON if:</h3><ol><li><strong>You have a public API</strong> — Third-party developers expect JSON</li><li><strong>Browser-only app</strong> — JavaScript handles JSON natively</li><li><strong>Low traffic</strong> — &lt;1,000 requests/minute, savings are negligible</li><li><strong>Rapid prototyping</strong> — JSON’s flexibility speeds development</li><li><strong>Small team</strong> — Learning curve might not be worth it</li><li><strong>Complex queries</strong> — Use GraphQL instead</li><li><strong>Human readability critical</strong> — Debugging needs to be simple</li></ol><h3>✅ Use Protocol Buffers when:</h3><ol><li><strong>High throughput</strong> →10,000 requests/minute</li><li><strong>Mobile apps</strong> — Bandwidth and battery life matter</li><li><strong>Microservices</strong> — Internal service communication</li><li><strong>IoT devices</strong> — Bandwidth constrained</li><li><strong>Real-time systems</strong> — Every millisecond counts</li><li><strong>Binary data</strong> — Already dealing with non-text data</li><li><strong>Type safety required</strong> — Strict contracts between services</li></ol><h3>Real-World Migration Results</h3><p>Here’s what happened when we migrated our transaction API:</p><h3>Before (JSON)</h3><pre>Average response time:     280ms<br>P95 response time:         450ms<br>Payload size:              523 bytes<br>Monthly bandwidth:         1.13 TB<br>Monthly AWS cost:          $102<br>Mobile battery impact:     High (frequent polling)<br>Serialization errors:      12 per day</pre><h3>After (Protocol Buffers)</h3><pre>Average response time:     95ms   (66% faster!)<br>P95 response time:         145ms  (68% faster!)<br>Payload size:              187 bytes (64% smaller!)<br>Monthly bandwidth:         0.40 TB (64% reduction!)<br>Monthly AWS cost:          $36 (65% cheaper!)<br>Mobile battery impact:     Medium (15% improvement)<br>Serialization errors:      0 per day (type safety!)</pre><p><strong>Total annual savings: $792 in bandwidth + immeasurable gains in user experience</strong></p><p>And this is just one API endpoint. Across our entire platform with 50+ endpoints, the savings multiply.</p><h3>Getting Started: Your First Protobuf API</h3><p>Here’s a complete, copy-paste-ready example:</p><h3>1. Install</h3><pre>pip install fastapi uvicorn protobuf</pre><h3>2. Create Schema (user.proto)</h3><pre>syntax = &quot;proto3&quot;;</pre><pre>message User {<br>  string id = 1;<br>  string email = 2;<br>  string name = 3;<br>  int32 age = 4;<br>}</pre><h3>3. Compile</h3><pre>protoc --python_out=. user.proto</pre><h3>4. Create API (app.py)</h3><pre>from fastapi import FastAPI, Response<br>import user_pb2</pre><pre>app = FastAPI()</pre><pre>@app.get(&quot;/user/{user_id}&quot;)<br>async def get_user(user_id: str):<br>    # Create user<br>    user = user_pb2.User()<br>    user.id = user_id<br>    user.email = &quot;john@example.com&quot;<br>    user.name = &quot;John Doe&quot;<br>    user.age = 30<br>    <br>    # Serialize to binary<br>    binary_data = user.SerializeToString()<br>    <br>    return Response(<br>        content=binary_data,<br>        media_type=&quot;application/x-protobuf&quot;<br>    )</pre><pre>if __name__ == &quot;__main__&quot;:<br>    import uvicorn<br>    uvicorn.run(app, host=&quot;0.0.0.0&quot;, port=8000)</pre><h3>5. Test</h3><pre># client.py<br>import requests<br>import user_pb2</pre><pre>response = requests.get(&quot;http://localhost:8000/user/123&quot;)<br>user = user_pb2.User()<br>user.ParseFromString(response.content)</pre><pre>print(f&quot;Name: {user.name}&quot;)<br>print(f&quot;Email: {user.email}&quot;)<br>print(f&quot;Age: {user.age}&quot;)</pre><h3>Common Pitfalls and How to Avoid Them</h3><h3>Pitfall 1: Forgetting to Reserve Deleted Fields</h3><pre>// ❌ WRONG - Field 3 could be reused!<br>message User {<br>  string id = 1;<br>  string email = 2;<br>  // Deleted: string phone = 3;<br>  string name = 4;<br>}</pre><pre>// ✅ CORRECT - Reserve deleted field numbers<br>message User {<br>  string id = 1;<br>  string email = 2;<br>  reserved 3;  // Never reuse this!<br>  string name = 4;<br>}</pre><h3>Pitfall 2: Not Handling Backward Compatibility</h3><pre>// ✅ Safe evolution<br>message User {<br>  string id = 1;<br>  string email = 2;<br>  <br>  // New optional fields at the end<br>  string phone = 10;  // Old clients ignore this<br>  int32 age = 11;     // Old clients ignore this<br>}</pre><h3>Pitfall 3: Ignoring Default Values</h3><pre># ❌ WRONG - Assumes field is always present<br>if user.email:  # Empty string is falsy!<br>    send_email(user.email)</pre><pre># ✅ CORRECT - Check if field was set<br>if user.HasField(&#39;email&#39;):<br>    send_email(user.email)</pre><h3>The Bottom Line</h3><p>After six months of using Protocol Buffers in production, here’s what I learned:</p><h3>✅ Do it if:</h3><ul><li>You’re processing &gt;10k requests/minute</li><li>Bandwidth costs are noticeable (&gt;$100/month)</li><li>You have mobile clients</li><li>Type safety would prevent bugs</li><li>You’re building microservices</li></ul><h3>🤔 Consider it if:</h3><ul><li>You want to future-proof your API</li><li>You value performance optimization</li><li>You’re starting a new project (no legacy JSON)</li><li>Your team is comfortable with the learning curve</li></ul><h3>❌ Skip it if:</h3><ul><li>You have a simple CRUD app with low traffic</li><li>You need a public API (stick with REST + JSON)</li><li>Your team is small and learning curve matters more</li><li>Debugging simplicity trumps performance</li></ul><h3>Our Recommendation: Start Here</h3><p>Based on our testing and the performance data above, here’s the ideal path:</p><p><strong>Week 1–2: Learn and Prototype</strong></p><pre># Use pure-protobuf for experimentation<br>pip install pure-protobuf<br># Play with the clean API, get comfortable</pre><p><strong>Week 3–4: Production Migration</strong></p><pre># Switch to official implementation<br>pip install protobuf<br># Use default upb backend (fastest)<br># Migrate one endpoint at a time</pre><p><strong>Month 2+: Scale Up</strong></p><pre># Add protobuf to all high-traffic endpoints<br># Keep JSON for public APIs<br># Monitor bandwidth savings</pre><h3>Final Thoughts</h3><p>Switching from JSON to Protocol Buffers isn’t a silver bullet. It’s a tool for a specific job: <strong>high-performance, type-safe serialization at scale</strong>.</p><p>For us, it was transformative:</p><ul><li><strong>64% smaller payloads</strong></li><li><strong>66% faster response times</strong></li><li><strong>$22,000+ annual savings</strong></li><li><strong>Zero serialization bugs</strong></li></ul><p>But more importantly, it made our API more reliable, our mobile app more responsive, and our infrastructure costs more predictable.</p><p>If you’re building a high-traffic Python API, Protocol Buffers deserve a serious look. The performance improvements are real, measurable, and significant.</p><h3>Resources</h3><h3>Official Documentation</h3><ul><li><a href="https://protobuf.dev/getting-started/pythontutorial/">Protocol Buffers Python Tutorial</a></li><li><a href="https://protobuf.dev/reference/python/">Python API Reference</a></li></ul><h3>Libraries Tested</h3><ul><li><a href="https://pypi.org/project/protobuf/">protobuf</a> — Official Google implementation ⭐ <strong>Recommended</strong></li><li><a href="https://pypi.org/project/pure-protobuf/">pure-protobuf</a> — Pure Python alternative</li></ul><h3>Tools</h3><ul><li><a href="https://buf.build/">Buf</a> — Modern protobuf tooling</li><li><a href="https://www.postman.com/">Postman</a> — Protobuf testing support</li></ul><h3><strong>Have you tried Protocol Buffers in Python? What were your results?</strong> Share your experiences in the comments below!</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=61229868748a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>