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

推荐订阅源

Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
WordPress大学
WordPress大学
云风的 BLOG
云风的 BLOG
Stack Overflow Blog
Stack Overflow Blog
MongoDB | Blog
MongoDB | Blog
腾讯CDC
V
V2EX
Martin Fowler
Martin Fowler
A
About on SuperTechFans
大猫的无限游戏
大猫的无限游戏
Blog — PlanetScale
Blog — PlanetScale
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
酷 壳 – CoolShell
酷 壳 – CoolShell
C
Check Point Blog
博客园 - 【当耐特】
Cisco Talos Blog
Cisco Talos Blog
The Hacker News
The Hacker News
K
Kaspersky official blog
Security Latest
Security Latest
H
Help Net Security
博客园_首页
美团技术团队
Spread Privacy
Spread Privacy
博客园 - 司徒正美
Hugging Face - Blog
Hugging Face - Blog
S
SegmentFault 最新的问题
G
Google Developers Blog
NISL@THU
NISL@THU
爱范儿
爱范儿
I
Intezer
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
阮一峰的网络日志
阮一峰的网络日志
N
News and Events Feed by Topic
P
Privacy International News Feed
Application and Cybersecurity Blog
Application and Cybersecurity Blog
S
Security @ Cisco Blogs
Schneier on Security
Schneier on Security
雷峰网
雷峰网
人人都是产品经理
人人都是产品经理
V
Vulnerabilities – Threatpost
W
WeLiveSecurity
P
Palo Alto Networks Blog
G
GRAHAM CLULEY
Hacker News: Ask HN
Hacker News: Ask HN
I
InfoQ
The Cloudflare Blog
F
Full Disclosure
SecWiki News
SecWiki News
宝玉的分享
宝玉的分享
N
Netflix TechBlog - Medium

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 a Context-Aware AI Chat Without a Vector Database
Ryan Carter · 2026-04-29 · via DEV Community

Ryan Carter

You can ground an AI chat in your own data without a vector database by assembling the relevant documents directly into the system prompt before each request. No embedding pipeline, no similarity search, no separate infrastructure — just your structured data, formatted cleanly, injected as system context. It works well when your dataset is modest (hundreds of documents, not millions) and naturally segmented into logical groups.

This is the pattern I used building Wiskr, a multi-model chat app that grounds conversations in documents from a connected document store. The rest of this post walks through how to implement it, where it breaks down, and how to upgrade to full RAG when you outgrow it.

TL;DR

  • The pattern: Group documents into named contexts, load active contexts on each request, format them into a system prompt, prepend it to every API call.
  • No vector DB needed: For modest datasets, the model reads structured JSON directly — embeddings and similarity search are unnecessary overhead.
  • Token-limit guardrails: Cap documents per context, summarize long ones, let users pin important ones, then add vector search only when those run out of room.
  • Upgrade path: When you need real RAG later, the context-assembly layer stays put — you just add smarter document selection in front of it.
  • Best fit: Personal assistants, support tools, document Q&A, and any AI feature that needs to reason about a bounded, structured user-specific dataset.

The core idea

A standard LLM chat call looks like this:

const response = await client.chat.completions.create({
  model: "anthropic/claude-sonnet-4",
  messages: [
    { role: "user", content: "What's my copay for metformin?" }
  ]
});

Enter fullscreen mode Exit fullscreen mode

The model has no idea who you are or what documents you have. It can only work with what's in the messages array.

The context assembly pattern adds a system message that packages your relevant data before the conversation begins:

const response = await client.chat.completions.create({
  model: "anthropic/claude-sonnet-4",
  messages: [
    { role: "system", content: assembledContext },
    { role: "user", content: "What's my copay for metformin?" }
  ]
});

Enter fullscreen mode Exit fullscreen mode

Now the model has your data and can reason against it. The question is how to build assembledContext well.

Step 1: Organize data into contexts

The first thing you need is a way to group related documents. In Wiskr these are called contexts — named buckets like "Medical," "Vehicle," "Insurance," or "House." Each conversation has a set of active contexts the user selects before chatting.

In the database this is a simple structure:

CREATE TABLE contexts (
  id uuid PRIMARY KEY,
  user_id uuid,
  name text,
  created_at timestamptz
);

CREATE TABLE documents (
  id uuid PRIMARY KEY,
  context_id uuid REFERENCES contexts(id),
  title text,
  content jsonb,
  created_at timestamptz
);

Enter fullscreen mode Exit fullscreen mode

Documents belong to contexts. Contexts belong to users. When a chat starts, the user picks which contexts are active — and only those get assembled into the prompt.

Step 2: Load active context documents

When a conversation starts, load the documents for each active context:

async function loadContextDocuments(db, contextIds) {
  const result = await db.query(
    `SELECT c.name as context_name, d.title, d.content
     FROM documents d
     JOIN contexts c ON c.id = d.context_id
     WHERE d.context_id = ANY($1)
     ORDER BY c.name, d.created_at DESC`,
    [contextIds]
  );
  return result.rows;
}

Enter fullscreen mode Exit fullscreen mode

Step 3: Assemble the system prompt

With the documents loaded, format them into a readable system prompt:

function assembleSystemPrompt(documents) {
  // Group documents by context name
  const byContext = documents.reduce((acc, doc) => {
    if (!acc[doc.context_name]) acc[doc.context_name] = [];
    acc[doc.context_name].push(doc);
    return acc;
  }, {});

  const contextBlocks = Object.entries(byContext).map(([contextName, docs]) => {
    const docBlocks = docs.map(doc => `
### ${doc.title}
${JSON.stringify(doc.content, null, 2)}
    `).join('\n');

    return `## ${contextName}\n${docBlocks}`;
  }).join('\n\n');

  return `You are a helpful assistant with access to the user's personal documents.
Use the information below to give accurate, personalized responses.
If the answer isn't in the documents, say so — don't guess.

${contextBlocks}`;
}

Enter fullscreen mode Exit fullscreen mode

Raw JSON is fine for the document content. Current models read it well, and it preserves the structure of your data without you having to write custom serializers for every document type.

Step 4: Inject into every request

Pass the assembled context as the system message on every API call, alongside the full conversation history:

async function chat(db, conversationId, userMessage) {
  // Load conversation state
  const conversation = await getConversation(db, conversationId);
  const documents = await loadContextDocuments(db, conversation.activeContextIds);
  const history = await getMessageHistory(db, conversationId);

  // Assemble context
  const systemPrompt = assembleSystemPrompt(documents);

  // Build messages array
  const messages = [
    { role: "system", content: systemPrompt },
    ...history,
    { role: "user", content: userMessage }
  ];

  // Call the model
  const response = await client.chat.completions.create({
    model: conversation.model,
    messages,
  });

  const assistantMessage = response.choices[0].message.content;

  // Save to history
  await saveMessage(db, conversationId, "user", userMessage);
  await saveMessage(db, conversationId, "assistant", assistantMessage);

  return assistantMessage;
}

Enter fullscreen mode Exit fullscreen mode

Handling token limits

The obvious risk with this approach is bloated prompts. If a user has 50 documents in their active contexts you'll hit token limits fast.

A few practical strategies:

Cap documents per context. The simplest option — include only the N most recent documents per context. For most use cases, the newest 10-15 documents per context are the most relevant anyway.

const result = await db.query(
  `SELECT c.name as context_name, d.title, d.content
   FROM documents d
   JOIN contexts c ON c.id = d.context_id
   WHERE d.context_id = ANY($1)
   ORDER BY c.name, d.created_at DESC
   LIMIT 15`,  // cap per context
  [contextIds]
);

Enter fullscreen mode Exit fullscreen mode

Summarize large documents. If individual documents are long, run them through a cheap fast model first to produce a condensed version before assembling the prompt.

Let users pin documents. Give users control — a pinned document always gets included, everything else is capped or summarized. This is often more useful than trying to guess relevance automatically.

Add vector search later. When your data grows large enough that capping and pinning don't cut it, vector search is the right next step. You add an embedding column, generate embeddings on save, and query by cosine similarity to find the most relevant documents for each conversation. The context assembly step stays the same — you just get smarter document selection feeding into it.

When this is the right approach

This pattern works well when:

  • Your data is structured (JSON, not unstructured text blobs)
  • Your dataset is modest (hundreds of documents, not millions)
  • Users naturally segment their data into logical groups
  • You want something working fast without infrastructure overhead

It's a good starting point for any AI feature that needs to reason about user-specific data — support tools, personal assistants, document Q&A, anything where the data set is bounded and the structure is known.

When you outgrow it, the upgrade path to full RAG is incremental rather than a rewrite. The context assembly layer stays. You just add smarter selection in front of it.

FAQ

When should I use context assembly instead of full RAG with a vector database?

Use context assembly when your dataset is bounded (a few hundred documents per user, max), the documents are already structured (JSON, key-value, or short prose), and users have a natural way to scope which subset is relevant for a conversation. Switch to vector-database RAG when you can't fit the relevant slice in a system prompt, when relevance ranking actually matters, or when content is long-form unstructured text.

How big can the system prompt get before this falls apart?

Modern frontier models accept 200K+ token context windows, but cost and latency both scale with prompt size. As a practical rule, keep the assembled context under ~20K tokens for most consumer use cases — beyond that you'll feel the latency in chat, and the per-request cost adds up fast.

Does this work with any LLM provider?

Yes. The pattern is just a system message — every chat-completions API supports it. I've used the same code unchanged across OpenAI, Anthropic, and OpenRouter.

How do I migrate to full RAG later without rewriting everything?

Keep the context-assembly function as-is. Add an embedding column to the documents table, generate embeddings on save, and replace the "load all documents in active contexts" query with "load top N documents in active contexts ranked by cosine similarity to the user's question." Everything downstream of that — the prompt formatting, the chat call — stays identical.

What about prompt caching?

This pattern composes well with prompt caching. The system prompt changes only when documents are added/edited, so providers that support prompt caching (Anthropic, OpenAI) can cache the assembled context across turns and dramatically cut input-token cost on follow-up messages.

Is it safe to dump raw user data into the system prompt?

For a single-tenant app where the user owns the data, yes — that's the whole point. For multi-tenant apps, be strict about which user's contexts get loaded, and never assemble across users. A bug in context selection becomes a data-leak bug.