惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Project Zero
Project Zero
量子位
博客园 - 聂微东
月光博客
月光博客
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
有赞技术团队
有赞技术团队
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
雷峰网
雷峰网
人人都是产品经理
人人都是产品经理
V
Visual Studio Blog
IT之家
IT之家
酷 壳 – CoolShell
酷 壳 – CoolShell
Hugging Face - Blog
Hugging Face - Blog
J
Java Code Geeks
V
V2EX
P
Proofpoint News Feed
T
Troy Hunt's Blog
The Hacker News
The Hacker News
H
Hacker News: Front Page
小众软件
小众软件
L
Lohrmann on Cybersecurity
博客园 - 三生石上(FineUI控件)
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
L
LINUX DO - 最新话题
The Last Watchdog
The Last Watchdog
W
WeLiveSecurity
Apple Machine Learning Research
Apple Machine Learning Research
Jina AI
Jina AI
WordPress大学
WordPress大学
G
GRAHAM CLULEY
宝玉的分享
宝玉的分享
博客园 - 【当耐特】
C
CERT Recently Published Vulnerability Notes
S
Secure Thoughts
I
Intezer
Application and Cybersecurity Blog
Application and Cybersecurity Blog
Last Week in AI
Last Week in AI
腾讯CDC
C
Cybersecurity and Infrastructure Security Agency CISA
S
Securelist
博客园_首页
阮一峰的网络日志
阮一峰的网络日志
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
爱范儿
爱范儿
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
博客园 - 叶小钗
博客园 - Franky
Cloudbric
Cloudbric

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Building Production-Ready Open Source AI Infrastructure: A Technical Guide
Anil Prasad · 2026-05-19 · via DEV Community

Building Production-Ready Open Source AI Infrastructure: A Technical Guide

Over the past year, we've built and open sourced six production-grade AI infrastructure projects. This isn't toy code or proof of concepts. These are systems handling millions of requests daily in production environments.

Here's what we learned building open source AI infrastructure that actually works.

The Six Projects

  1. llm-cost-optimization: 3-layer caching plus intelligent routing
  2. ai-safety-framework: 5-layer defense with 250 red team test cases
  3. production-rag: 6-stage pipeline with re-ranking and evaluation
  4. distributed-training: PyTorch DDP with NCCL tuning
  5. roi-first-ai: Business metric selection and deployment templates
  6. agentic-ai: Multi-agent orchestration framework

All repositories are at github.com/anilatambharii

Why Open Source Our Production Code

Three reasons.

First, the AI infrastructure landscape is fragmented. Every team rebuilds the same patterns from scratch. LLM caching. RAG pipelines. Cost optimization. Agent orchestration. We've already solved these problems. Sharing the solutions helps the community.

Second, open source code is battle tested. When thousands of developers review, use, and contribute to your code, it gets better fast. Private code stays brittle. Public code gets hardened.

Third, hiring advantage. The best engineers want to work on code that matters. Open source contributions demonstrate technical credibility better than any interview.

Architecture Principle: Composition Over Configuration

Each project is a focused library, not a framework. You compose them together rather than configuring one monolithic system.

Bad approach: One repo with 47 configuration options trying to do everything.

Good approach: Six repos, each solving one problem well. Use what you need. Ignore what you don't.

Example using llm-cost-optimization and production-rag together:

from llm_cost_optimization import CachingLayer, ModelRouter
from production_rag import RAGPipeline, HybridRetriever

# Set up caching for LLM calls
cache = CachingLayer(
    semantic_cache_threshold=0.95,
    redis_url="redis://localhost:6379"
)

# Set up model routing based on query complexity
router = ModelRouter(
    models={
        "simple": "claude-haiku-4-5",
        "complex": "claude-sonnet-4-6"
    },
    complexity_threshold=0.7
)

# Set up RAG pipeline with hybrid retrieval
retriever = HybridRetriever(
    vector_weight=0.7,
    keyword_weight=0.3
)

rag = RAGPipeline(
    retriever=retriever,
    llm_cache=cache,
    llm_router=router
)

# Use them together
result = rag.query("What were Q2 financial results?")

Enter fullscreen mode Exit fullscreen mode

Each component is independent. Each can be used standalone. Together they form a complete system.

Project Deep Dive: LLM Cost Optimization

This project reduced our LLM costs from $47K monthly to $2.8K monthly. 94% cost reduction. Same quality.

Three Layer Caching

Exact match cache catches identical queries. Redis key is SHA256 hash of prompt. Cache hit returns response instantly. No LLM call. Zero cost.

class ExactMatchCache:
    def __init__(self, redis_client):
        self.redis = redis_client

    def get(self, prompt: str) -> Optional[str]:
        key = hashlib.sha256(prompt.encode()).hexdigest()
        return self.redis.get(f"exact:{key}")

    def set(self, prompt: str, response: str, ttl: int = 3600):
        key = hashlib.sha256(prompt.encode()).hexdigest()
        self.redis.setex(f"exact:{key}", ttl, response)

Enter fullscreen mode Exit fullscreen mode

Hit rate: 23% of queries.

Semantic cache catches similar queries. Embed the prompt. Find nearest neighbors in vector DB. If similarity > threshold (0.95), return cached response.

class SemanticCache:
    def __init__(self, embedding_model, vector_db, threshold=0.95):
        self.embed = embedding_model
        self.db = vector_db
        self.threshold = threshold

    def get(self, prompt: str) -> Optional[str]:
        embedding = self.embed(prompt)
        results = self.db.search(embedding, k=1)

        if results and results[0].score > self.threshold:
            return results[0].cached_response
        return None

    def set(self, prompt: str, response: str):
        embedding = self.embed(prompt)
        self.db.insert(embedding, cached_response=response)

Enter fullscreen mode Exit fullscreen mode

Hit rate: 31% of queries not caught by exact match.

Prefix cache reuses computation for prompts with common prefixes. System prompt is usually identical. Few-shot examples are usually identical. Only the user query changes.

Anthropic's prompt caching API handles this automatically. Mark static parts as cacheable.

response = client.messages.create(
    model="claude-sonnet-4-6",
    max_tokens=1024,
    system=[
        {
            "type": "text",
            "text": LONG_SYSTEM_PROMPT,
            "cache_control": {"type": "ephemeral"}
        }
    ],
    messages=[
        {"role": "user", "content": user_query}
    ]
)

Enter fullscreen mode Exit fullscreen mode

Combined hit rate: 73% of queries serve from cache. 27% hit the LLM. Cost reduced 73% from caching alone.

Intelligent Model Routing

Not every query needs GPT-4 or Claude Opus. Simple queries work fine on Haiku. Complex queries need Sonnet.

Routing strategy:

class ModelRouter:
    def route(self, query: str) -> str:
        complexity = self.calculate_complexity(query)

        if complexity < 0.3:
            return "claude-haiku-4-5"  # $0.25 per 1M tokens
        elif complexity < 0.7:
            return "claude-sonnet-4-6"  # $3 per 1M tokens
        else:
            return "claude-opus-4-6"    # $15 per 1M tokens

    def calculate_complexity(self, query: str) -> float:
        # Features: length, question marks, technical terms, etc.
        features = self.extract_features(query)
        return self.classifier.predict_proba(features)[1]

Enter fullscreen mode Exit fullscreen mode

Trained a simple classifier on 10K labeled examples. "What's the capital of France?" → Haiku. "Analyze this 50 page contract for liability clauses" → Opus.

Result: 89% of queries route to Haiku. 9% to Sonnet. 2% to Opus. Average cost per query drops 88%.

Implementation Notes

Cache invalidation is the hard part. We invalidate based on TTL (1 hour default) and explicit updates. When source data changes, we flush related cache entries.

Monitoring tracks hit rates, latency, cost per query. Dashboard shows cache performance in real time. Alerts fire when hit rate drops below threshold.

Gradual rollout started with 1% of traffic. Measured cache hit rate and accuracy. Ramped to 10%, 50%, 100% over 3 weeks.

Project Deep Dive: Production RAG

We increased RAG accuracy from 52% to 89% by fixing retrieval, not the LLM.

The 6-Stage Pipeline

Stage 1: Query Processing

Don't send raw user queries to vector DB. Expand with synonyms. Extract metadata. Generate context-aware embedding.

class QueryProcessor:
    def process(self, query: str) -> ProcessedQuery:
        # Extract metadata
        metadata = {
            "date_range": self.extract_date_range(query),
            "department": self.extract_department(query),
            "doc_type": self.extract_doc_type(query)
        }

        # Expand with synonyms
        expanded = self.expand_synonyms(query)

        # Generate embedding
        embedding = self.embed_model(expanded)

        return ProcessedQuery(
            original=query,
            expanded=expanded,
            embedding=embedding,
            metadata=metadata
        )

Enter fullscreen mode Exit fullscreen mode

Stage 2: Vector Database Search

Cosine similarity threshold 0.85. Top-k 50 candidates (not 5, not 10). Use Pinecone with metadata filtering.

results = index.query(
    vector=processed_query.embedding,
    top_k=50,
    filter={
        "department": processed_query.metadata["department"],
        "date": {"$gte": processed_query.metadata["date_range"][0]}
    }
)

Enter fullscreen mode Exit fullscreen mode

Stage 3: Hybrid Search

Combine semantic search (70%) with keyword search (30%) using BM25.

class HybridRetriever:
    def retrieve(self, query: ProcessedQuery) -> List[Document]:
        # Vector search
        vector_results = self.vector_search(query, k=50)

        # Keyword search
        keyword_results = self.bm25_search(query.expanded, k=50)

        # Combine with weights
        combined = self.merge_results(
            vector_results, 
            keyword_results,
            vector_weight=0.7,
            keyword_weight=0.3
        )

        return combined[:50]

Enter fullscreen mode Exit fullscreen mode

Stage 4: Re-ranking

This single stage improved accuracy by 23%. Use cross-encoder to score each candidate against the actual query.

class Reranker:
    def __init__(self, model_name="cross-encoder/ms-marco-MiniLM-L-12-v2"):
        self.model = CrossEncoder(model_name)

    def rerank(self, query: str, documents: List[Document]) -> List[Document]:
        # Score each doc against query
        pairs = [(query, doc.text) for doc in documents]
        scores = self.model.predict(pairs)

        # Sort by score
        ranked = sorted(
            zip(documents, scores),
            key=lambda x: x[1],
            reverse=True
        )

        return [doc for doc, score in ranked[:5]]

Enter fullscreen mode Exit fullscreen mode

Top 50 candidates from hybrid search → Re-rank → Best 5 to LLM.

Stage 5: Context Assembly

Smart chunking with overlap. 512 token chunks with 50 token overlap. Include surrounding context. Add metadata.

def assemble_context(ranked_docs: List[Document]) -> str:
    context_parts = []

    for i, doc in enumerate(ranked_docs):
        context_parts.append(f"""
Source {i+1}: {doc.metadata['title']}
Date: {doc.metadata['date']}
Department: {doc.metadata['department']}

{doc.text}

---
        """)

    return "\n".join(context_parts)

Enter fullscreen mode Exit fullscreen mode

Stage 6: LLM Generation

Force grounded responses. System prompt enforces citation. User query includes assembled context.

system_prompt = """You are a helpful assistant. Use ONLY the provided context to answer questions. 

If the context doesn't contain enough information, say "I don't have enough information to answer that question."

Always cite your sources using the Source number."""

user_prompt = f"""Context:
{assembled_context}

Question: {original_query}

Answer:"""

Enter fullscreen mode Exit fullscreen mode

Results

Before: 52% answer accuracy. 3.8s latency. 31% hallucination rate.

After: 89% accuracy (+71%). 1.2s latency (faster!). 4% hallucination rate (-87%).

The insight: Don't optimize the LLM. Optimize the retrieval. GPT-4 with bad context = bad answers. Haiku with perfect context = great answers.

Making Projects Production Ready

Every project includes:

Comprehensive tests: Unit tests for every function. Integration tests for pipelines. End-to-end tests for workflows. 90%+ coverage.

Documentation: README with quick start. Detailed API docs. Architecture diagrams. Example notebooks.

Benchmarks: Performance metrics. Accuracy measurements. Cost comparisons. Real numbers, not claims.

Monitoring: Prometheus metrics. Logging. Error tracking. Observability built in.

Deployment: Docker containers. Kubernetes manifests. Terraform modules. Production ready deployment.

Contributing to Open Source AI

Our projects welcome contributions. Here's how to get started:

  1. Pick a project that interests you
  2. Read the CONTRIBUTING.md
  3. Check the issues for "good first issue" labels
  4. Submit a PR with tests and documentation
  5. Respond to review feedback

We review all PRs within 48 hours. Quality bar is high but we help contributors meet it.

Conclusion

Open source AI infrastructure should be production ready, not proof of concept. These six projects represent thousands of hours of real world testing and optimization.

Use them. Contribute to them. Build on them.

The code is at github.com/anilatambharii. Documentation is comprehensive. Examples are plentiful. Issues are welcome.

Let's build better AI infrastructure together.


About the Author

Anil Prasad is Head of Engineering at Ambharii Labs, recognized as one of "100 Most Influential AI Leaders in USA 2024." He builds production-scale AI and data systems for enterprise organizations. Connect on LinkedIn at linkedin.com/in/anilsprasad or visit ambharii.com.

Related Reading