/ai-and-data:rag-and-agentsfrom ai-and-data
Production reference for RAG and AI agent development covering document parsing, chunking strategies, embedding models, vector databases, hybrid search, GraphRAG, RAGAS evaluation, agent frameworks (LangGraph, CrewAI, Microsoft Agent Framework), MCP, multi-agent patterns, and Azure-native RAG solutions.
Ships in ai-and-data. 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.
Start naive → add complexity only when evaluation shows a quality ceiling.
Progression:
Each step adds cost. Advance only when a 50–200 QA golden set proves it.
Four problems RAG solves:
The full pipeline: ingestion → chunking → embedding → indexing → query processing → retrieval → reranking → context assembly → generation
RAG vs Fine-tuning vs Long-context:
They combine — fine-tune for domain language, RAG for facts.
"Lost in the middle" (Liu et al., TACL 2024): performance degrades significantly when relevant information is in the middle of long contexts, even for explicitly long-context models. Critical info should be first or last. A 1M-token window is not a license to fill it.
Quality framework — the "3 C's":
| Parser | F1 (benchmark) | Best for | Cost | Notes |
|---|---|---|---|---|
| LlamaParse | ~92% | Complex layouts | ~$0.10/page (top tier), API-only | Multimodal LLM-based; highest accuracy |
| Azure Document Intelligence | ~90% structured, ~75% free-form | Azure workloads; standardized forms | ~$1.50/1K pages (prebuilt) | Layout model outputs Markdown; natively callable as AI Search skill |
| Docling (IBM, MIT) | ~88%, ~45 pages/sec GPU | Self-hosted; MCP server available | Free | Best open-source; fully local for sensitive data |
| PyMuPDF4LLM | — | Digital text; speed/lightness | Free | Fully local |
| Unstructured | — | 30+ formats with built-in chunking | Free/paid | Broad format support |
For RAG: Markdown output beats JSON — chunks cleanly while preserving hierarchy.
Azure Document Intelligence Layout model: produces Markdown (MarkdownOutputFormat), extracts tables/selection-marks, cross-page tables (since Ignite 2025); the cheaper Read model handles OCR/handwriting only.
Pre-processing checklist: Unicode normalization, header/footer/boilerplate removal, language detection, PII scrubbing (Azure AI Language / Presidio / Content Safety), quality filtering, dedup (exact + near-duplicate via MinHash/SimHash).
| Strategy | How | When to use |
|---|---|---|
| Recursive character splitting | Split by newlines, spaces, chars | Standard baseline; default in LangChain |
| Markdown/HTML header splitters | Split at header boundaries | When document structure matters |
| Semantic chunking | Embedding-similarity breakpoints | When topics vary within a document |
| Method | Description | Best for |
|---|---|---|
| Sentence-window | Retrieve a sentence, expand ±k neighbors | Conversational/factoid |
| Late chunking (Jina, 2024) | Embed full doc first, pool per-chunk so chunk embeddings retain document context | Any domain with long documents |
| Contextual Retrieval (Anthropic, Sept 2024) | Prepend LLM-generated chunk-specific context summary before embedding/indexing | General — see numbers below |
Contextual Retrieval verified numbers (Anthropic, Sept 2024):
Size guidance by use case:
MTEB leaderboard is directional only — always test on your own data.
| Model | Dimensions | Price/1M tokens | Notes |
|---|---|---|---|
| text-embedding-3-large | 3,072 (Matryoshka) | ~$0.13 | Safe OpenAI default; truncatable to 256/512/1024 |
| text-embedding-3-small | 1,536 (Matryoshka) | ~$0.02 | 5× cheaper; adequate for most workloads |
| Cohere embed-v4 | 1,024 | ~$0.01 | Multilingual 100+ languages |
| Voyage voyage-3-large / voyage-4 | — | — | Domain leader for code/legal/medical; +4–6 MTEB points on domain retrieval |
| BGE-M3 | — | Self-hosted | Open; self-hostable |
Matryoshka Representation Learning: truncate dimensions (3,072→256/512/1,024) without retraining for graceful quality/storage trade-offs. Now standard.
Asymmetric search: E5-instruct task prefixes align query vs document intent — important for asymmetric query/passage retrieval.
M, efConstruction, efSearch| DB | Strength | Weakness |
|---|---|---|
| Pinecone | Zero-ops managed | Can't tune HNSW parameters |
| Qdrant (Rust) | Best-in-class filtered search, quantization | Self-host/cloud — ops burden if self-hosted |
| Weaviate | Best native hybrid search (BlockMax WAND GA 2025) | |
| Milvus/Zilliz | Billion-scale | Heavy ops (Kafka/MinIO/etcd) |
| Chroma | Prototyping | No native hybrid search |
| LanceDB | Embedded + columnar; native hybrid | |
| pgvector | Good enough under ~10M vectors if already on Postgres | Query planner can choose seqscan on filtered queries; degrades past 10M |
pgvector production note: HNSW since 0.5.0 matches dedicated DBs at 1M scale. Use SET enable_seqscan=off or pgvectorscale's StreamingDiskANN for filtered queries. At 50M vectors: Qdrant ~41 QPS vs pgvectorscale ~471 QPS at 99% recall.
| Technique | What it does |
|---|---|
| HyDE | Generate a hypothetical answer, embed it as the query |
| Step-back prompting | Rephrase to a more general question |
| Multi-query | Generate multiple phrasings; union results |
| Decomposition | Break complex question into sub-questions; synthesize |
| Routing | Classify query type → pick retrieval strategy |
Two-stage pipeline: retrieve top 50–200 (bi-encoder) → rerank to top 3–10 (cross-encoder).
Expected gains: independent benchmarks (Voyage AI) report +13.89% for Cohere rerank-2 and +11.86% for rerank-2-lite across 93 datasets on top of OpenAI text-embedding-3-large. Cohere's own materials cite 20–35%; expect 10–35% depending on baseline and domain.
| Reranker | Notes |
|---|---|
| Cohere Rerank 3.5 / 4.0 | Best-in-class managed; multilingual 100+ languages; underperforms on identifier-heavy queries (function names, statute numbers) |
| BGE-Reranker-v2-m3 | Self-hosted |
| Jina Reranker v2 | 8K context |
| FlashRank | CPU; lightweight |
| ColBERT/RAGatouille | Late interaction; good when exact term matching matters |
| Azure AI Search semantic ranker | Microsoft-trained cross-encoder (Bing corpus); rescores top 50; returns @search.rerankerScore 0–4; score below ~1.0 signals weak match |
Azure semantic ranker: passes up to 2,048 tokens per doc (raised from 256 in Nov 2024). Order fields in semantic configuration by priority — long fields are trimmed.
Fight "lost in the middle": place best material at the beginning or end of the context window.
System prompt structure for RAG:
[role/instruction]
[document format description]
[citation rules]
[anti-hallucination instruction: "Answer only from the provided context; if the answer is not in the documents, say you don't know."]
From: "From Local to Global: A Graph RAG Approach to Query-Focused Summarization" (arXiv 2404.16130)
Indexing: LLM extracts entities/relationships per chunk → builds graph → partitions with Leiden algorithm hierarchically → generates community summaries bottom-up.
Query modes:
Paper results vs vector RAG: comprehensiveness win 72–83%, diversity 62–82%. Vector RAG scored higher only on Directness (expected — passage retriever is more targeted for local questions).
Cost cliff: original GraphRAG indexing was prohibitively expensive (one estimate: $33K for a 5GB legal case). Use LazyGraphRAG (Microsoft Research, Nov 25, 2024):
When to use GraphRAG: multi-hop or thematic queries across large, relatively static corpus. Start with LazyGraphRAG, not full GraphRAG, unless you have high-utilization static corpus justifying expensive indexing. Never deploy on high-update or simple-factoid corpus.
Build a 50–200 QA golden dataset before launch (human-curated + LLM-synthesized then filtered). Run it on every change.
| Metric | Definition |
|---|---|
| Faithfulness | Claims in answer supported by context ÷ total claims in answer |
| Answer Relevancy | Mean cosine similarity between the question and questions reverse-generated from the answer |
| Context Precision | Average precision@k over retrieved chunks (are relevant chunks ranked high?) |
| Context Recall | Reference claims supported by retrieved context ÷ total reference claims — only metric needing ground truth |
Groundedness, Groundedness Pro (Content-Safety-model-based), Relevance, Retrieval, Document Retrieval, Response Completeness, Coherence, Fluency. Continuous evaluation on sampled production traffic surfaced through Azure Monitor.
Other frameworks: DeepEval (pytest-style), TruLens (RAG triad: groundedness/answer-relevance/context-relevance), Arize Phoenix.
Free (3 indexes, 50MB) → Basic → Standard S1/S2/S3 → Storage-Optimized L1/L2. New Serverless (Compute Unit-based) model rolling out.
m, efConstruction, efSearch, metric (cosine/euclidean/dotProduct)vectorSearch + text search → RRF fusion → queryType: semantic → semantic reranker
vectorFilterMode: preFilter (accurate, slower) or postFilter (fast, can under-return)queryType: semantic + semanticConfiguration + optional answers/captionsDrives auto-embedding via indexer skillsets calling Azure OpenAI. A query-time vectorizer removes app-side embedding code. Index projections create chunk + parent indexes from one document. Index aliases enable blue-green zero-downtime reindexing.
search.in(group_ids,...) security trimming/knowledgebases/<kb>/mcp?api-version=2025-11-01-preview)Microsoft stopped onboarding new models. Only supports GPT-4o (2024-05-13, 2024-08-06, 2024-11-20) and GPT-4o-mini (2024-07-18). Migration path: Foundry Agent Service with Foundry IQ (or custom Azure AI Search RAG pipeline — only managed On Your Data workloads need to migrate).
Agent = LLM + tools + memory + planning loop
Base pattern: ReAct (Yao et al., 2022) — interleaved Thought/Action/Observation. Foundation of modern tool-using agents implemented via function calling.
When to use agents vs deterministic workflows:
Top failure modes: tool-call errors, infinite loops, context loss, hallucinated tool calls, over-planning.
parallel_tool_calls for independent calls| Tier | Storage | Use |
|---|---|---|
| In-context (working) | Token window | Current task context |
| Episodic | Vector DB (Cosmos DB, Redis, AI Search) | Past conversations |
| Semantic | Long-term facts store | Knowledge base |
| Procedural | Fine-tuning / system prompt | Action patterns |
Production memory (Azure): Cosmos DB for durable history, Redis for fast recent, AI Search for semantic retrieval. Foundry Agent Service Memory (public preview) for automatic extraction/consolidation.
interrupt() for human-in-the-loopAzureAISearchVectorStore with hybrid + semantic rerankerAzureSearchUseOpenTelemetry() built in; YAML declarative agents/openai/v1/Managed (Foundry) vs self-built (LangGraph):
Standardizes LLM↔tool/data connections. Anthropic Nov 2024; donated to Linux Foundation (Agentic AI Foundation) Dec 9, 2025; adopted by OpenAI, Google, Microsoft, Amazon. Over 97M monthly SDK downloads, 10,000 active servers at donation.
Architecture: Host/client/server roles. Transports: stdio (local), HTTP+SSE/streamable HTTP (remote), WebSocket.
Primitives: Resources (readable data), Tools (callable functions), Prompts (templates), Sampling (server requests completion). OAuth 2.0 for remote servers.
Build with: FastMCP (Python decorators) or official SDKs.
Azure MCP servers: Azure DevOps, ARM, Bing, Azure SQL, Blob, Monitor. Deploy custom servers on Azure Container Apps or Azure Functions (/runtime/webhooks/mcp).
A2A (Google, 2025): complementary agent-to-agent protocol.
Security risks: prompt injection via malicious servers, confused-deputy attacks. Restrict capabilities, sandbox, validate.
Justified by: specialization, parallelism, redundancy, context-window scale. Costs: coordination overhead, non-determinism, debugging difficulty, cost multiplication.
max_iterations limitinterrupt() / Foundry approvalsThe "AI cost snowball" — runaway agents without limits is a documented incident class; hard limits are mandatory, not polish.
Azure Container Apps Dynamic Sessions (GA): Hyper-V-isolated, per-session, millisecond startup. Python/Node/shell + custom container. Never run LLM-generated code in-process.
Azure OpenAI Realtime API (GA Aug 2025): WebRTC/WebSocket/SIP, ~250–500ms end-to-end. Pattern: Realtime API → function call → AI Search retrieval → grounded spoken response.
Event Hubs → Stream Analytics → AI Search push API; Cosmos DB change feed → embedding pipeline.
Beats RAG for exact aggregations/joins/filters. Pattern: schema injection → NL→SQL→execute→synthesize. Evaluate on Spider/BIRD benchmarks.
Stage 1 — Baseline (weeks 1–2): Stand up hybrid search + semantic reranking. Azure: AI Search Standard + integrated vectorization with text-embedding-3-large + queryType: semantic. Custom: Qdrant or pgvector (<10M vectors) + Cohere Rerank 3.5 or BGE-reranker. Build the 50–200 QA golden set now.
Stage 2 — Chunking & context (weeks 3–4): Add parent-child chunking (child 100–256 tokens, parent 512–2,048). Switch parsers to LlamaParse/Docling/Azure Document Intelligence Layout (Markdown output) if table/layout fidelity is failing. Add Contextual Retrieval if retrieval misses persist.
Stage 3 — Advanced retrieval (month 2): Add query decomposition/multi-query, or adopt Azure AI Search agentic retrieval / Foundry IQ for multi-intent queries. GraphRAG only if queries are genuinely multi-hop/thematic on large static corpus — start with LazyGraphRAG.
Stage 4 — Agents (months 2–3): If dynamic tool use/planning is needed: Foundry Agent Service + Foundry IQ for fastest enterprise time-to-production; LangGraph for full control; Microsoft Agent Framework 1.0 for open-source Azure-aligned path. Enforce termination contracts, sandbox code execution, trace everything.
Migration deadlines: Migrate "On Your Data" workloads to Foundry IQ before GPT-4o 2024-11-20 retires (2026-10-01). Migrate AzureML SDK v1 before June 30, 2026 end-of-support.
What SKILL.md sets; muted values are Claude Code's defaults
Other plugins' skills for the same job
4 skills in this plugin
/ai-ml-landscapeComprehensive practitioner reference for the 2025–2026 AI/ML landscape covering frontier model selection and routing, open-weight vs hosted API trade-offs, reasoning models and test-time compute, RAG and agent production patterns, classical ML for tabular data, deep learning foundations (transformers, attention, MoE, SSMs), LLM training and post-training (DPO/GRPO/LoRA/QLoRA), inference serving (vLLM/SGLang), evaluation benchmark skepticism, safety/alignment, EU AI Act governance, and hardware selection. Use when advising on model selection, AI architecture decisions, LLM deployment, fine-tuning strategy, benchmark interpretation, or AI governance compliance./data-engineeringProduction data engineering reference covering ELT/ETL patterns, dbt project structure, orchestration (Airflow/Dagster/Prefect), Python data stack (pandas/Polars/DuckDB/Spark), cloud warehouses (Snowflake/BigQuery/Azure Fabric), lakehouse formats (Iceberg/Delta/Hudi), CDC with Debezium, SCD2, data quality, feature stores, and ML productionization with MLflow. Use when answering questions about data pipelines, SQL optimization, warehouse cost control, Python data tools, gradient boosting, A/B testing, or modern data stack architecture./llm-cost-optimizationProduction reference for LLM token economics, cost optimization, and prompt engineering on Azure. Covers tokenization and pricing asymmetry, prompt caching (Azure/Anthropic/Google), model routing and cascades, PTU vs PAYG break-even, Azure APIM AI gateway, semantic caching, context window engineering, prompt/context compression (LLMLingua, LongLLMLingua, RECOMP, Selective Context, extractive compression), caveman/telegraphic prompting, token-lean serialization formats (TOON/Markdown/YAML vs JSON/XML), output control (Concise CoT, Chain-of-Draft), fine-tuning for cost, Batch API, structured outputs, conversation history management, and Azure-specific deployment patterns. Use when optimizing LLM spend, compressing prompts or context, choosing a compression library, picking token-lean formats, reducing output verbosity, designing cost-efficient AI architectures, troubleshooting token costs, engineering prompts for performance, or sizing Azure OpenAI deployments.2 plugins ship this exact skill · first indexed Aug 12, 2026
npx claudepluginhub the-vibey-project/vibey --plugin ai-and-data