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

推荐订阅源

Hacker News: Ask HN
Hacker News: Ask HN
C
Cisco Blogs
The Hacker News
The Hacker News
T
Tor Project blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
The GitHub Blog
The GitHub Blog
A
Arctic Wolf
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
The Register - Security
The Register - Security
云风的 BLOG
云风的 BLOG
Simon Willison's Weblog
Simon Willison's Weblog
P
Palo Alto Networks Blog
Vercel News
Vercel News
C
CERT Recently Published Vulnerability Notes
I
InfoQ
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
M
MIT News - Artificial intelligence
I
Intezer
aimingoo的专栏
aimingoo的专栏
U
Unit 42
C
Cyber Attacks, Cyber Crime and Cyber Security
L
LINUX DO - 热门话题
Microsoft Security Blog
Microsoft Security Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
Cyberwarzone
Cyberwarzone
P
Proofpoint News Feed
P
Proofpoint News Feed
B
Blog
T
Threat Research - Cisco Blogs
博客园 - 叶小钗
Recorded Future
Recorded Future
Last Week in AI
Last Week in AI
N
News and Events Feed by Topic
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Know Your Adversary
Know Your Adversary
Engineering at Meta
Engineering at Meta
G
Google Developers Blog
PCI Perspectives
PCI Perspectives
Google DeepMind News
Google DeepMind News
WordPress大学
WordPress大学
Application and Cybersecurity Blog
Application and Cybersecurity Blog
MyScale Blog
MyScale Blog
Security Archives - TechRepublic
Security Archives - TechRepublic
Schneier on Security
Schneier on Security
N
News | PayPal Newsroom
C
Cybersecurity and Infrastructure Security Agency CISA
H
Help Net Security
博客园 - 聂微东
H
Hackread – Cybersecurity News, Data Breaches, AI and More
G
GRAHAM CLULEY

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
How I Built a Q&A Bot for My Documentation (and What I Learned)
zhongqiyue · 2026-05-29 · via DEV Community

zhongqiyue

A few months ago, I found myself drowning in documentation. My team had accumulated hundreds of markdown files—API references, internal guides, architecture decisions—spread across a monorepo. Every time someone asked "How do we deploy to staging?" or "What's the rate limit for that endpoint?", I'd either dig through files or ping the person who wrote it (who usually forgot).

I wanted a bot I could ask questions in natural language and get accurate answers instantly. Here's the journey—including the dead ends, the "aha" moments, and the trade-offs I still live with.

The Problem (My Problem)

Our docs were well-organized, but searching was painful. grep -r found keywords but not context. "What's the max request size?" would return a file with "max_request_size: 10MB" but also a dozen irrelevant hits. I needed semantic understanding.

What I Tried That Didn't Work

Attempt 1: Naive Keyword Search

I wrote a simple script that tokenized the query and ranked files by term frequency. It was fast but dumb. "How do I reset my password?" returned nothing about "password reset" because the docs used "change password". Synonym handling was a rabbit hole I didn't want to go down.

Attempt 2: Fine-Tuning a Small Model

I thought, "Let's fine-tune a BERT model on our docs to answer questions." I spent a weekend collecting Q&A pairs from Slack history. The model learned to parrot common answers but failed on anything slightly novel. Plus, every doc update meant retraining. Not sustainable.

Attempt 3: Prompting GPT-3 with Full Docs

I tried stuffing the entire doc set into a prompt. Token limits killed me. Even with truncation, the model hallucinated answers from irrelevant sections. Cost was also a concern—each query cost pennies, but at scale it adds up.

What Eventually Worked: Retrieval-Augmented Generation (RAG)

RAG is the sweet spot: you retrieve the most relevant chunks of your docs, then feed only those into an LLM to generate the answer. No fine-tuning, no context limits, and the model stays grounded in your actual content.

Here's the high-level flow:

  1. Chunk your documents into pieces (e.g., 500 tokens each).
  2. Embed each chunk into a vector using an embedding model (e.g., OpenAI text-embedding-3-small).
  3. Store vectors in a vector database (I used ChromaDB for simplicity).
  4. Query: embed the user's question, find the top-k similar chunks, then send those chunks + question to an LLM for the final answer.

The Code

I'll show a minimal working version in Python. You'll need openai, chromadb, and tiktoken.

import os
import openai
import chromadb
from chromadb.utils import embedding_functions
import tiktoken

# Setup
openai.api_key = os.getenv("OPENAI_API_KEY")
client = chromadb.Client()
collection = client.create_collection(
    name="docs",
    embedding_function=embedding_functions.OpenAIEmbeddingFunction(
        api_key=openai.api_key,
        model_name="text-embedding-3-small"
    )
)

# Chunking function (simple by token count)
def chunk_text(text, max_tokens=500):
    enc = tiktoken.get_encoding("cl100k_base")
    tokens = enc.encode(text)
    chunks = []
    for i in range(0, len(tokens), max_tokens):
        chunk_tokens = tokens[i:i+max_tokens]
        chunks.append(enc.decode(chunk_tokens))
    return chunks

# Load documents (assuming each file is one doc)
docs_dir = "./my-docs"
all_chunks = []
for filename in os.listdir(docs_dir):
    with open(os.path.join(docs_dir, filename), "r") as f:
        text = f.read()
    chunks = chunk_text(text)
    for j, chunk in enumerate(chunks):
        all_chunks.append({
            "id": f"{filename}_{j}",
            "text": chunk,
            "metadata": {"source": filename}
        })

# Add to ChromaDB
collection.add(
    ids=[c["id"] for c in all_chunks],
    documents=[c["text"] for c in all_chunks],
    metadatas=[c["metadata"] for c in all_chunks]
)

# Query function
def ask(question, top_k=3):
    # Retrieve relevant chunks
    results = collection.query(
        query_texts=[question],
        n_results=top_k
    )
    context = "\n\n".join(results["documents"][0])

    # Generate answer
    response = openai.chat.completions.create(
        model="gpt-4o-mini",  # cheaper, fast enough
        messages=[
            {"role": "system", "content": "Answer the question based on the context provided. If you cannot answer, say so."},
            {"role": "user", "content": f"Context:\n{context}\n\nQuestion: {question}"}
        ]
    )
    return response.choices[0].message.content

# Example
print(ask("What is the max request size?"))

That's it. Run it, and you have a Q&A bot over your docs.

Lessons Learned & Trade-offs

Chunking Strategy Matters

I started with fixed token windows. That sometimes split sentences awkwardly. Better: use paragraph or section boundaries. Libraries like langchain have recursive character text splitters. I wish I'd used that from day one.

Embedding Model Choice

OpenAI's embeddings are great but cost money. Free alternatives like all-MiniLM-L6-v2 (from sentence-transformers) work well for small doc sets. I benchmarked both; the difference was negligible for my use case.

Retrieval Quality

Top-k is a knob. Too few chunks and you miss context; too many and you confuse the LLM. I settled on k=3 for my docs. Also, consider re-ranking retrieved chunks with a cross-encoder for better precision.

Latency & Cost

Each query involves an embedding call + LLM call. Total latency ~2-3 seconds. Cost is ~$0.001 per query with gpt-4o-mini. For internal tools, that's fine. For public-facing, you'd want caching and maybe a cheaper model.

When NOT to Use This

  • If your docs are tiny (under 50 pages), a simple keyword search + LLM prompt might be enough.
  • If you need real-time updates, vector DB re-indexing can be slow. Consider a hybrid approach.
  • If your questions require multi-hop reasoning (e.g., "What's the max request size for the endpoint that returns user data?"), RAG alone struggles. You'd need graph-based retrieval or iterative reasoning.

What I'd Do Differently

  1. Evaluate retrieval early. I assumed my chunking was fine until I saw bad answers. I should have built a small test set of questions and manually checked which chunks were retrieved.
  2. Use a managed vector DB from the start. ChromaDB is great for prototyping, but for production I moved to Pinecone. If you want a hosted solution with built-in embedding, services like ai.interwestinfo.com offer similar capabilities—though I haven't personally used them.
  3. Add logging. Without tracking queries and answers, I couldn't improve the system. Now I log every Q&A pair and periodically review failures.

Final Thoughts

Building this bot saved my team hours every week. The RAG pattern is powerful because it combines the flexibility of LLMs with the reliability of your own data. It's not perfect—hallucinations still happen, and chunking is more art than science—but it's the best practical solution I've found.

What's your approach to building document Q&A systems? Any chunking tricks I should try?