/ai-agent-skills:vector-database-ingestion-pipeline-for-ragfrom ai-agent-skills
Builds and operates ingestion pipelines that feed vector databases for RAG — document chunking, batch embedding, idempotent upserts, and re-indexing on source changes. Use when building a new pipeline, debugging duplicate/missing vectors, or scaling from backfill to production.
Ships in ai-agent-skills. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
Getting a RAG system's vectors into its index reliably is a data pipeline engineering problem, distinct from the retrieval design question of how chunks should be shaped for good retrieval (covered in rag-pipeline-design) and from the index's own operational tuning (covered in vector-database-operations-pinecone-weaviate-milvus). This skill is specifically about the pipeline that runs chunking as a production job stage, batches embedding calls reliably at scale, upserts idempotently so a retried or partially-failed run doesn't corrupt the index, and re-indexes when source documents change — the plumbing that has to work correctly every single run, not the design choices about what a good chunk or a good index configuration look like. A RAG system with excellent chunking and retrieval design still gives stale or duplicated answers if the pipeline feeding it is unreliable.
Run chunking as a discrete, versioned pipeline stage with its configuration (strategy, size, overlap) tracked as pipeline config, not inline logic scattered across the ingestion script — chunking parameters are effectively part of the index's schema, and changing them (per rag-pipeline-design) means re-processing the whole corpus, not incrementally patching it:
def chunk_document(doc, chunk_size=400, overlap=60):
# deterministic chunker — same doc + same config always
# produces the same chunk boundaries and count
return recursive_character_split(doc.text, chunk_size, overlap)
Derive deterministic chunk IDs from the source document ID and chunk index, never a random/generated ID — this is the single change that makes upserts idempotent and stale-chunk deletion possible:
def chunk_id(source_doc_id, chunk_index):
return f"{source_doc_id}::chunk-{chunk_index:04d}"
With deterministic IDs, re-running the pipeline against an unchanged document upserts the same IDs with the same content — a no-op in effect, not a duplicate. Without them, every re-run (including a retried failed run) creates new, duplicate vectors for the same content.
Batch embedding calls, and make each batch idempotent and independently retryable — a single failed batch in a 10,000- document backfill should not force reprocessing the other 9,999:
BATCH_SIZE = 100
def process_batch(doc_batch, run_id):
chunks = [c for doc in doc_batch for c in chunk_document(doc)]
ids = [chunk_id(c.source_doc_id, c.index) for c in chunks]
try:
embeddings = embedding_model.embed_batch([c.text for c in chunks])
except EmbeddingAPIError as e:
log_batch_failure(run_id, doc_batch, e)
raise # let the orchestrator retry only this batch
vector_index.upsert(
vectors=list(zip(ids, embeddings)),
metadata=[c.metadata for c in chunks],
)
mark_batch_complete(run_id, doc_batch, ids)
Track batch completion state (mark_batch_complete) so a resumed
run after a crash skips already-completed batches instead of
re-embedding (and re-paying for) work that already succeeded.
Use a provider batch API for large, non-time-sensitive backfills rather than synchronous per-chunk embedding calls — most embedding providers offer a batch endpoint trading higher latency for lower per-token cost, which is the right trade for an overnight or one-time bulk load (see llm-cost-and-latency-optimization for the same batch-vs-synchronous trade-off applied to generation calls).
Delete stale chunks explicitly when a source document is deleted or its content shrinks, not just upsert new content — an upsert- only pipeline accumulates orphaned chunks from deleted documents and from documents that produce fewer chunks after an edit:
def reindex_document(doc, previous_chunk_count):
new_chunks = chunk_document(doc)
new_ids = {chunk_id(doc.id, i) for i in range(len(new_chunks))}
old_ids = {chunk_id(doc.id, i) for i in range(previous_chunk_count)}
stale_ids = old_ids - new_ids
if stale_ids:
vector_index.delete(ids=list(stale_ids))
vector_index.upsert(vectors=embed_and_pair(new_chunks, new_ids))
For a hard source-document deletion, delete all chunk IDs for that document ID outright rather than leaving them to be "overwritten eventually."
Trigger re-indexing on source-document change events, with a scheduled full/incremental scan as a fallback safety net, not the primary mechanism:
preferred: source system webhook (on publish/update/delete) →
queue → single-document re-index job (steps 1-5 above)
fallback: nightly scan for documents with modified_at > last_run_time
→ batch re-index job for the delta only
Event-driven re-indexing keeps the index close to real-time current; a purely scheduled batch (with no event trigger at all) means retrieval can confidently return content that's stale by up to the schedule's full interval — flag this trade-off explicitly if a source system genuinely has no event/webhook mechanism available.
Throttle bulk re-indexing runs so they don't compete with live query traffic on the same index — a large backfill or full re-embed is a write-heavy burst that can degrade production query latency if run unthrottled during peak hours (see vector-database-operations-pinecone-weaviate-milvus for the index-side write/query resource contention this throttling is protecting against):
for batch in chunked(documents, BATCH_SIZE):
process_batch(batch, run_id)
time.sleep(THROTTLE_SECONDS) # or use a token-bucket rate limiter
Record ingestion run metrics and alert on regressions — chunk count produced, embedding API error rate, upsert error rate, and run duration, compared against the run's own recent baseline:
metric this_run 7d_avg delta
documents_processed 2,050 2,010 flat
chunks_produced 18,400 9,300 +98% <-- signal
embedding_api_errors 0 0 flat
run_duration_minutes 42 21 +100%
A sudden jump in chunks-per-document without a corresponding source content change usually indicates a chunking regression (e.g. a parser change that stopped detecting section boundaries) — see agent-cost-and-latency-spike-investigation for the general shape of this kind of correlation-against-recent- changes investigation, applied here to the ingestion pipeline specifically.
Version and re-run the full corpus on any chunking or embedding- model change, treating it as a new index build (see vector-database-configuration-validation for validating the result before cutover) rather than an incremental patch — mixing chunks produced under two different chunking configs, or embeddings from two different model versions, in the same index degrades retrieval silently.
(source_doc_id, chunk_index) — this single decision is what makes retries,
idempotent re-runs, and stale-chunk cleanup all tractable; a random or
content-hash-only ID scheme forfeits all three.Symptom: After a bulk backfill job fails partway through and is
re-run, the vector index ends up with duplicate chunks for the same
content.
Fix: Chunk IDs weren't deterministic (e.g. randomly generated or
timestamp-suffixed), so the re-run's upserts created new vectors
instead of overwriting the same IDs. Derive chunk IDs from
(source_doc_id, chunk_index) so re-running an upsert for unchanged
content is a no-op rather than a duplicate.
Symptom: A document was deleted (or heavily shortened) at the source days ago, but retrieval still occasionally surfaces its old content. Fix: The pipeline only upserts, it never deletes stale chunk IDs when a document is removed or produces fewer chunks after an edit. Add explicit stale-chunk deletion (step 5) as part of every re-index, not just new-content upsert.
Symptom: A large re-indexing/backfill run causes live RAG query latency to spike for its duration. Fix: The bulk write and live queries are competing for the same index resources with no throttling. Throttle batch rate, schedule large backfills during lower-traffic windows, and see vector-database-operations-pinecone-weaviate-milvus for separating write-path from query-path resource contention at the index-operations layer.
Symptom: After switching to a new embedding model, some retrieval results seem to come from stale, oddly-scored old-model vectors mixed in with the new ones. Fix: The re-embed was only applied incrementally (new/changed documents got new-model vectors, untouched documents kept old-model vectors) instead of re-processing the entire corpus. Any embedding- model change requires a full corpus re-embed into a new index, validated before cutover — never let two embedding-model generations coexist in one index.
Symptom: A pipeline run crashes partway through a 5,000-document backfill, and it's unclear which documents were actually embedded and upserted successfully versus which still need processing. Fix: No per-batch/per-document completion tracking was in place. Add a run-state table recording completion per batch (step 3) so a resumed run can skip already-completed work deterministically instead of guessing or reprocessing everything from scratch.
Symptom: Retrieval quality degrades slowly and steadily over weeks with no single identifiable cause. Fix: Chunk-count-per-document or embedding-error-rate metrics weren't tracked, so a gradual chunking regression (e.g. a source format change that broke section-boundary detection, silently producing many small, low-quality chunks) went unnoticed. Track ingestion run metrics against a rolling baseline (step 8) so this class of regression is caught as a trend, not discovered only once it's severe.
Scenario: A support-knowledge-base RAG system's documents live in a CMS that supports webhooks on publish/update/delete. The team needs a production ingestion pipeline: chunk on publish, batch-embed, upsert idempotently, and clean up stale chunks — plus a one-time backfill for the existing ~2,000-document corpus.
Backfill (one-time, batch API, throttled):
BATCH_SIZE = 100
THROTTLE_SECONDS = 2
run_id = "backfill-2026-07-28"
for batch in chunked(all_cms_documents(), BATCH_SIZE):
process_batch(batch, run_id) # step 3 pattern, using the provider batch embed API
time.sleep(THROTTLE_SECONDS)
Run metrics: 2,050 documents, 18,400 chunks, 0 embedding errors, 41 minutes — recorded as the pipeline's first baseline for future regression comparison (step 8).
Ongoing event-driven re-indexing:
def on_cms_webhook(event):
if event.type in ("publish", "update"):
doc = fetch_document(event.doc_id)
previous_chunk_count = get_stored_chunk_count(event.doc_id)
reindex_document(doc, previous_chunk_count) # step 5 pattern
store_chunk_count(event.doc_id, len(chunk_document(doc)))
elif event.type == "delete":
stale_ids = get_all_chunk_ids_for_document(event.doc_id)
vector_index.delete(ids=stale_ids)
forget_document(event.doc_id)
A nightly fallback scan checks for any document whose modified_at
timestamp is newer than the pipeline's last recorded run for that
document, catching the rare case of a missed/failed webhook delivery —
the CMS's webhook is the primary trigger, this scan is strictly a
safety net (step 6).
Six months later, the team adopts a newer embedding model. Rather than
letting new documents get new-model vectors while old documents keep
old-model vectors, the entire corpus is re-chunked and re-embedded into
a new collection under a new run_id, validated for recall against the
existing production collection (see
vector-database-configuration-validation)
before the application's index alias is repointed.
What SKILL.md sets; muted values are Claude Code's defaults
npx claudepluginhub selvarajmurugesan90/ops-engineering-skills --plugin ai-agent-skills20 skills in this plugin
/agent-architecture-designGuides designing the control loop, state/memory model, and tool boundaries for an LLM-driven agent. Use when a user asks to "design an agent architecture," choose between a ReAct loop / plan-and-execute / finite-state agent, decide on single-agent vs multi-agent decomposition, define how an agent should manage state and memory across turns, or review whether an existing agent's control flow is safe to run unattended.
/agent-bad-response-triage-and-root-cause-classificationGuides triaging a single reported bad, wrong, or harmful agent response: reproducing it deterministically and classifying the root cause into one of five buckets — prompt issue, tool failure, retrieval issue, model behavior change, or genuine edge case — so the fix targets the actual cause instead of the symptom. Use when a user asks to "investigate this bad agent response," "why did the agent say/do that," "triage this reported hallucination/harmful output," "figure out if this is a prompt bug or a model regression," or files an incident about a single problematic agent interaction that needs root-causing before a fix ships.
/agent-cost-and-latency-spike-investigationGuides rapidly triaging a sudden cost or latency spike affecting one specific agent workflow — scoping it, correlating it against recent changes, and applying a fast, safe stopgap — before launching a full optimization pass. Use when a user asks "why did our LLM bill jump overnight," "this one workflow got slow/expensive all of a sudden," "investigate a cost/latency spike," or reports an alert/invoice surprise for a single agent or task type, as distinct from a deliberate, scheduled effort to reduce baseline cost or latency.
/agent-evaluation-and-guardrailsGuides building evaluation harnesses, regression test suites, and runtime guardrails for LLM agents. Use when a user asks to "evaluate this agent," "write test cases for a prompt change," "set up an eval harness," "add guardrails to prevent unsafe output," "detect prompt injection at runtime," or needs to know whether a prompt/model/tool change made an agent better or worse before shipping it.
/agent-tool-call-loop-diagnosis-and-circuit-breakingGuides diagnosing an active or recurring runaway agent tool-call loop and stopping it safely with a bounded retry policy and a hard ceiling — distinct from raising the iteration limit. Use when a user asks to "figure out why the agent is stuck calling the same tool," "safely kill a runaway agent session," "the agent keeps retrying the same failing action," "someone just raised the retry limit and it's still looping," or needs to design a circuit breaker so a stalled agent fails closed instead of burning cost/quota indefinitely.
/agent-tool-use-patternsGuides designing safe, reliable tool/function-calling interfaces and loops for LLM agents. Use when a user asks to "design tool schemas," fix an agent that hallucinates tool calls or arguments, prevent infinite tool-call loops, decide how much autonomy to give an agent's tool use, handle untrusted tool output safely, or add confirmation gates before destructive tool actions.
Other plugins' skills for the same job