Build, review, and architect applications that use AI models - from single-API calls to
multi-agent systems with RAG pipelines. The goal is production-grade AI apps that are reliable,
cost-effective, and don't hallucinate their way into an incident.
Target versions: September 2026 snapshot. Read references/target-versions.md before
pinning model IDs (Claude/OpenAI families), SDKs, runtimes, vector stores, or evaluation tools.
When to use
Integrating LLM APIs (Anthropic, OpenAI, etc.) into applications
Building RAG pipelines (chunking, embedding, retrieval, generation)
Designing agent systems (tool use, loops, state, multi-agent)
Choosing between fine-tuning, RAG, and prompt engineering
Setting up vector stores for semantic search
Implementing structured output and tool use / function calling
Building evaluation and testing harnesses for AI features
Optimizing token costs, latency, and model routing
Building MCP servers or tools (use mcp - it handles the protocol layer)
Writing or refining individual prompts (use prompt-generator)
General database configuration, schema design, or migrations (use databases)
Security auditing AI application code (use security-audit)
Reviewing code quality unrelated to AI/ML patterns (use code-review)
Building AI-powered HTTP APIs (use backend-api for the API layer; return here for the LLM integration within it)
Reviewing AI-generated application code for slop, hallucinated APIs, or over-abstraction (use anti-slop)
AI Self-Check
AI tools consistently produce the same mistakes when generating AI application code.
Before returning any generated AI/ML code, verify against this list:
API keys loaded from environment variables, never hardcoded
Streaming responses handled with proper error boundaries and cleanup
Token limits respected - input truncation or chunking for long contexts
Structured output uses the provider's native schema enforcement (Anthropic tool_use,
OpenAI response_format), not post-hoc parsing with regex
Tool use / function calling validates tool results before passing back to the model
Retry logic uses exponential backoff with jitter, not fixed delays
Rate limit errors (429) handled distinctly from server errors (5xx)
Vector store queries include a relevance threshold - don't blindly pass low-similarity
results to the model
Embedding model matches between indexing and querying (mixing models = garbage results)
Prompt templates use parameterized injection, not string concatenation
Model responses validated before use (check for refusals, empty content, malformed JSON)
No synchronous LLM calls in request handlers - always async with timeouts
PII stripped or masked before sending to external model APIs
Temperature set intentionally (0 for deterministic tasks, higher for creative)
Provider drift checked: Responses/Agents/SDK examples use current provider surfaces, not deprecated patterns - specifically verify no use of openai.beta.assistants.create (Assistants API, superseded by Responses/Agents API) or other Assistants-era surfaces
RAG evidence bounded: retrieval thresholds, citations, and empty-result behavior are defined before generation
Cross-cutting agent hygiene applied - see references/agent-hygiene.md
Performance
Batch embeddings and eval runs; avoid one request per row when the provider offers batch or bulk APIs.
Cache deterministic retrieval, tool metadata, and prompt templates, but never cache tenant-specific model outputs without a data-retention decision.
Track token, latency, and retry budgets separately for interactive, background, and eval traffic.
Best Practices
Prefer raw provider SDKs until orchestration complexity justifies LangGraph, LlamaIndex, or LangChain.
Keep model, tool, retrieval, and safety decisions configurable per environment; avoid hardcoding preview model names in application logic.
Treat model output as untrusted input: validate structure, refusal states, tool arguments, and downstream side effects.
Workflow
Step 1: Determine the architecture pattern
Need
Pattern
Start with
Single model call
Direct API integration
Provider SDK
Knowledge-grounded answers
RAG pipeline
Vector store + retrieval
Multi-step reasoning
Agent with tools
LangGraph, OpenAI Agents SDK, or custom loop
Multiple specialized models
Model routing / chain
Custom router or Vercel AI SDK
Offline / air-gapped
Local inference
Ollama or vLLM
Existing data enrichment
Batch processing
Provider batch APIs
Step 2: Choose the right abstraction level
Pick the lightest tool that solves the problem:
Raw SDK - direct Anthropic/OpenAI SDK calls. Best for simple integrations, maximum
control, minimum dependencies. Start here unless you have a specific reason not to.
Vercel AI SDK - unified provider interface with streaming primitives. Good for
TypeScript apps that need provider-agnostic code or React/Next.js streaming UI.
LangChain / LlamaIndex - orchestration frameworks. Use when you need complex chains,
built-in document loaders, or 300+ pre-built integrations. Don't use for simple API calls -
the abstraction overhead isn't worth it.
LangGraph / OpenAI Agents SDK - stateful agent frameworks. Use when you need cycles,
persistence, human-in-the-loop, or multi-agent coordination.
The anti-pattern: importing LangChain to make a single API call. That's like importing
Django to serve a static HTML file.
Step 3: Implement
Follow the domain-specific sections below. Read the appropriate reference file for detailed
patterns and code examples.
Step 4: Evaluate and validate
Every AI feature needs evaluation. Not "run it once and eyeball the output" - structured evals
with datasets, metrics, and regression detection.
Minimum viable eval: create a promptfooconfig.yaml with 20+ test cases, use contains,
llm-rubric, and cost assertions, run npx promptfoo eval in CI on every PR that touches
prompts. Track pass rate over time - any regression blocks the merge.
Read references/evaluation.md for promptfoo setup, assertion types, CI integration (GitHub
Actions example), RAG-specific evals, agent evals, and red teaming patterns.
LLM Integration Patterns
Streaming
Always stream for user-facing responses. Buffer for background processing.
# Anthropic streaming (Python)
import anthropic
client = anthropic.Anthropic()
with client.messages.stream(
model="claude-sonnet-4-6",
max_tokens=1024,
messages=[{"role": "user", "content": prompt}],
) as stream:
for text in stream.text_stream:
yield text
Structured output
Use native provider mechanisms, not regex parsing of free-text responses.
Anthropic: tool_use with JSON schema, or response_format with json_schema
Read references/llm-patterns.md for multi-turn tool use, parallel tool calls, error
recovery, and provider-specific gotchas.
RAG Architecture
The quality of a RAG system depends more on retrieval quality than model quality.
A mediocre model with great retrieval beats a frontier model with bad retrieval.
Chunking strategy
Strategy
When to use
Chunk size
Fixed-size with overlap
Default starting point
512-1024 tokens, 10-20% overlap
Semantic (sentence/paragraph)
Well-structured documents
Varies by content
Recursive character
Mixed content types
1000 chars, 200 overlap
Document-aware (markdown headers, code blocks)
Structured docs, code
Section-based
Parent-child
Need both precision and context
Small retrieval, large context
Embedding model selection
Use the same model for indexing and querying. Mixing models produces meaningless similarity
scores.
Model
Dimensions
Best for
text-embedding-3-large (OpenAI)
3072 (or lower via dimensions)
General-purpose, scalable
voyage-3-large (Voyage AI)
1024
Code and technical content
embed-v4.0 (Cohere)
1024
Multilingual, compression
Open-source (e5-mistral, gte-Qwen2)
Varies
Air-gapped / self-hosted
Retrieval patterns
Vector search alone - fast, good for semantic similarity, bad for exact keyword matches
Hybrid search (vector + BM25/keyword) - best default. Qdrant, Weaviate, and Pinecone
support this natively. pgvector + tsvector for PostgreSQL.
Reranking - retrieve more candidates (top-50), rerank with a cross-encoder or Cohere
Rerank, return top-5. Adds latency but significantly improves relevance.
Query expansion - rephrase the user query using an LLM before retrieval. Helps when
user queries are vague or use different terminology than the source docs.
Vector store selection
Store
Type
Best for
pgvector
PostgreSQL extension
Already using Postgres, <10M vectors
Qdrant
Self-hosted or cloud
Production self-hosted, hybrid search
Pinecone
Managed only
Zero-ops, serverless scaling
ChromaDB
Embedded / local
Prototyping, small datasets
Minimal RAG example (Python + pgvector)
from anthropic import Anthropic
import psycopg
client = Anthropic()
def search(query: str, limit: int = 5) -> list[dict]:
embedding = get_embedding(query) # same model used at index time
with psycopg.connect(DB_URL) as conn:
rows = conn.execute(
"SELECT content, 1 - (embedding <=> %s::vector) AS score "
"FROM documents WHERE 1 - (embedding <=> %s::vector) > 0.7 "
"ORDER BY embedding <=> %s::vector LIMIT %s",
[embedding, embedding, embedding, limit],
).fetchall()
return [{"content": r[0], "score": r[1]} for r in rows]
def ask(question: str) -> str:
context = search(question)
if not context:
return "No relevant documents found."
response = client.messages.create(
model="claude-sonnet-4-6",
max_tokens=1024,
messages=[{"role": "user", "content": (
f"Answer based on these documents:\n\n"
+ "\n---\n".join(d["content"] for d in context)
+ f"\n\nQuestion: {question}"
)}],
)
return response.content[0].text
Key patterns: relevance threshold (0.7), same embedding model for index/query, context passed as user message prefix.
Read references/rag-patterns.md for indexing pipelines, metadata filtering, multi-index
strategies, and production RAG architecture.
Agent Systems
The agent loop
Every agent system is fundamentally: observe -> think -> act -> repeat. The differences are in
how you manage state, handle failures, and know when to stop.
while not done:
observation = get_context(state)
action = model.decide(observation, tools)
if action.type == "final_answer":
done = True
else:
result = execute_tool(action)
state.add(result)
Framework selection
Framework
Best for
Key feature
Custom loop
Simple agents, maximum control
No dependencies
LangGraph
Complex state machines, cycles, persistence
Graph-based, checkpointing
OpenAI Agents SDK
OpenAI-native, multi-agent handoffs
Sessions, tracing
Claude Agent SDK
Claude-native agentic loops in code
Programmatic SDK for building custom agents with Claude; use when you need fine-grained control over Claude agent behavior in your own application
Vercel AI SDK
TypeScript agents with UI streaming
ToolLoopAgent, React hooks
Common pitfalls
Infinite loops - always set a max iteration count. Agents will happily loop forever.
Tool explosion - more than 10-15 tools degrades model performance. Group related
operations into fewer, more capable tools.
Missing error handling - tool failures are normal. The agent needs to recover, not crash.
No cost ceiling - a runaway agent can burn through API budget. Set per-request token
and cost limits.
Stale context - long-running agents accumulate context. Summarize or prune periodically.
Minimal safe agent loop
Every agent loop needs an iteration cap, a cost gate, and a tool-error policy. Retry transient
errors with backoff, abort on permanent errors, and pass failed tool results back with an error
marker so the model can choose the next step instead of silently losing state.
Read references/agent-patterns.md for multi-agent architectures, human-in-the-loop patterns,
memory management, and production agent deployment.
Fine-Tuning vs RAG vs Prompt Engineering
Pick the cheapest approach that meets your quality bar:
Fine-tune when: prompt engineering can't capture the behavior, you need consistent
style/format across thousands of outputs, or you need lower latency than RAG provides.
Don't fine-tune when: your data changes frequently (use RAG), you have fewer than 100
high-quality examples, or prompt engineering already works (you're just cargo-culting).
Read references/fine-tuning.md for data preparation, PEFT/LoRA patterns, evaluation during
training, and when to use full fine-tuning vs parameter-efficient methods.
Local Inference
Local serving choices
Tool
Best for
GPU required
Ollama
Dev, prototyping, Mac (MLX)
No (CPU/MLX), optional GPU
vLLM
Production serving, high throughput
Yes
llama.cpp / llama-cpp-python
Minimal deps, quantized models, CPU-only
No (CPU), optional GPU
TGI (HF Text Generation Inference)
HF model hub integration
Yes
CPU-only inference with llama.cpp
CPU inference is viable - sometimes preferable - for: dense models that fit in RAM (7-13B
at Q4 hits 5-10 t/s on modern x86), MoE models with low active params (Qwen3-30B-A3B
at Q4 reaches 13+ t/s even on a 2013-era Xeon - active params dominate decode), and
air-gapped or compliance-bound environments. Key gotchas:
ISA cliff: pre-Haswell CPUs lack AVX2/FMA/BMI2. PyTorch >= 2.1, TF >= 2.8, JAX, and
Ollama prebuilts SIGILL. llama.cpp from source with -DGGML_AVX2=OFF -DGGML_FMA=OFF -DGGML_BMI2=OFF works.
GGUF quants: Q4_K_M is the default sweet spot. Q5_K_M for +25% memory and quality.
IQ4_XS for tighter budgets. Avoid Q2/Q3 - quality cliff is real.
Reproducible models: pin both filename and HF commit SHA. Bare repo+filename pulls
"whatever the author serves now" - silent runtime changes on rebase.
--mlock page-faults the GGUF into RAM at start. Sum GGUF sizes for capacity planning.
API keys: --api-key-file <path>, never --api-key <value> on the command line - leaks
into /proc/<pid>/cmdline via systemd env expansion.
Benchmarking
Fixed prompt suite (chat-short, chat-long, code-simple, code-complex, reasoning), warmup pass,
record latency + decode t/s at fixed max_tokens and temperature. Re-run after model swaps,
llama.cpp version bumps, or build-flag changes. Compare decode t/s, not raw latency.
Read references/local-inference.md for the full llama.cpp build walkthrough (per-CPU-generation
flags), HF SHA-pinned model download, systemd-per-model deployment, NUMA tuning, mlock memory
budgeting, benchmark methodology, and production serving configuration.
Batch APIs - Anthropic and OpenAI offer 50% discounts for async batch processing.
Output length limits - set max_tokens to what you actually need, not 4096 "just in case."
Context pruning - for multi-turn conversations, summarize history instead of sending
the full transcript.
Safety and Guardrails
Input validation (prompt injection), output validation (schema + content policy), PII handling
(strip before external API calls), rate limiting (per-user + per-IP), content filtering, and
audit logging (redact PII). These are non-negotiable for production AI apps.
Read references/safety.md for prompt injection defense patterns, output validation schemas,
PII detection setup, and content policy implementation.
Production Checklist
API keys in environment variables or secret manager (never in code)
Retry logic with exponential backoff and jitter on all LLM calls
Timeouts set on all LLM calls (model inference can hang)
Rate limiting on AI-powered endpoints
Cost monitoring and alerting (daily spend, per-request cost tracking)
Structured logging of prompts, responses, latency, token usage
Evaluation suite running in CI (regression detection)
Model fallback chain configured (primary -> secondary -> error response)
Input validation and prompt injection defense
Output validation before returning to users
PII scrubbed from external API calls
Max token limits set per request type
Health checks on model endpoints (especially self-hosted)
A/B testing infrastructure for prompt and model changes
references/target-versions.md - September 2026 snapshot: Claude/OpenAI model families, AI SDKs, runtimes, vector stores, and eval tools
Output Contract
See references/output-contract.md for the full contract.
Skill name: AI-ML
Deliverable bucket:audits
Mode: conditional. When invoked to analyze, review, audit, or improve existing repo content, emit the full contract - monospace inline header, severity-grouped inline summary, linked Markdown deliverable, and concise monospace conclusion - and write the deliverable to docs/local/audits/ai-ml/<YYYY-MM-DD>-<slug>.md. When invoked to answer a question, teach a concept, build a new artifact, or generate content, respond freely without the contract.
Severity scale:P0 | P1 | P2 | P3 | info (see shared contract; only used in audit/review mode).
Related Skills
mcp - handles MCP server development (the protocol/tooling layer). This skill handles
the application layer - how to build apps that call models, retrieve context, and orchestrate
agents. If building an MCP server, use mcp. If building an app that uses AI, use this skill.
prompt-generator - for crafting and refining individual prompts. This skill covers prompt
template management and patterns within applications; prompt-generator handles one-off prompt
creation and iteration.
databases - for general database operations. This skill covers vector store integration
for RAG; databases handles engine configuration, schema design, and traditional DB operations.
security-audit - for security review of AI application code. This skill provides
guardrail patterns; security-audit provides the audit methodology.
code-review - for reviewing AI application code quality beyond AI-specific patterns.
backend-api - for the HTTP API layer wrapping AI features. Use backend-api for contract design, auth, and route structure; use this skill for the LLM integration within those handlers.
anti-slop - for auditing AI-generated application code for hallucinated APIs, over-abstraction, and slop patterns introduced by AI generation tools.
Rules
Start with the simplest approach. Direct SDK calls before frameworks. Prompt engineering
before fine-tuning. Single agent before multi-agent. Complexity is a cost.
Never hardcode API keys. Environment variables or secret managers. No exceptions.
Set token limits explicitly.max_tokens on every call. Unbounded generation wastes
money and risks timeouts.
Match embedding models. Same model for indexing and querying. Mixing models produces
meaningless similarity scores that silently degrade retrieval quality.
Validate model output. Check for refusals, empty content, malformed structured output.
Models fail in creative ways - handle all of them.
Budget before you batch. Calculate cost before running batch operations. A 100k-row
embedding job at the wrong model can cost thousands.
Evaluate with data, not vibes. Structured evals with datasets and metrics. "It looks
good" is not a quality gate.
Cap agent iterations. Set a max loop count. Runaway agents burn budget and produce
garbage. 10-20 iterations is a reasonable default.
Run the AI self-check. Every generated AI/ML code gets verified against the checklist
above before returning.
1---2name: ai-ml3description: · Build/review AI apps: LLMs, RAG, embeddings, agents, evals, local inference. Triggers: 'llm', 'rag', 'embedding', 'openai sdk', 'agent loop', 'fine-tune', 'ollama', 'vllm'. Not for MCP (use mcp).4license: MIT5---67# AI/ML: Building Production AI Applications89Build, review, and architect applications that use AI models - from single-API calls to10multi-agent systems with RAG pipelines. The goal is production-grade AI apps that are reliable,11cost-effective, and don't hallucinate their way into an incident.1213**Target versions**: September 2026 snapshot. Read `references/target-versions.md` before14pinning model IDs (Claude/OpenAI families), SDKs, runtimes, vector stores, or evaluation tools.1516## When to use1718- Integrating LLM APIs (Anthropic, OpenAI, etc.) into applications19- Building RAG pipelines (chunking, embedding, retrieval, generation)20- Designing agent systems (tool use, loops, state, multi-agent)21- Choosing between fine-tuning, RAG, and prompt engineering22- Setting up vector stores for semantic search23- Implementing structured output and tool use / function calling24- Building evaluation and testing harnesses for AI features25- Optimizing token costs, latency, and model routing26- Setting up local inference with Ollama or vLLM27- Adding safety guardrails (content filtering, PII handling, output validation)2829## When NOT to use3031- Building MCP servers or tools (use **mcp** - it handles the protocol layer)32- Writing or refining individual prompts (use **prompt-generator**)33- General database configuration, schema design, or migrations (use **databases**)34- Security auditing AI application code (use **security-audit**)35- Reviewing code quality unrelated to AI/ML patterns (use **code-review**)36- Building AI-powered HTTP APIs (use **backend-api** for the API layer; return here for the LLM integration within it)37- Reviewing AI-generated application code for slop, hallucinated APIs, or over-abstraction (use **anti-slop**)3839## AI Self-Check4041AI tools consistently produce the same mistakes when generating AI application code.42**Before returning any generated AI/ML code, verify against this list:**4344- [ ] API keys loaded from environment variables, never hardcoded45- [ ] Streaming responses handled with proper error boundaries and cleanup46- [ ] Token limits respected - input truncation or chunking for long contexts47- [ ] Structured output uses the provider's native schema enforcement (Anthropic tool_use,48 OpenAI response_format), not post-hoc parsing with regex49- [ ] Tool use / function calling validates tool results before passing back to the model50- [ ] Retry logic uses exponential backoff with jitter, not fixed delays51- [ ] Rate limit errors (429) handled distinctly from server errors (5xx)52- [ ] Vector store queries include a relevance threshold - don't blindly pass low-similarity53 results to the model54- [ ] Embedding model matches between indexing and querying (mixing models = garbage results)55- [ ] Prompt templates use parameterized injection, not string concatenation56- [ ] Model responses validated before use (check for refusals, empty content, malformed JSON)57- [ ] Cost estimation done before batch operations (token count * price * volume)58- [ ] No synchronous LLM calls in request handlers - always async with timeouts59- [ ] PII stripped or masked before sending to external model APIs60- [ ] Temperature set intentionally (0 for deterministic tasks, higher for creative)61- [ ] **Provider drift checked**: Responses/Agents/SDK examples use current provider surfaces, not deprecated patterns - specifically verify no use of `openai.beta.assistants.create` (Assistants API, superseded by Responses/Agents API) or other Assistants-era surfaces62- [ ] **RAG evidence bounded**: retrieval thresholds, citations, and empty-result behavior are defined before generation63- [ ] Cross-cutting agent hygiene applied - see `references/agent-hygiene.md`6465## Performance6667- Batch embeddings and eval runs; avoid one request per row when the provider offers batch or bulk APIs.68- Cache deterministic retrieval, tool metadata, and prompt templates, but never cache tenant-specific model outputs without a data-retention decision.69- Track token, latency, and retry budgets separately for interactive, background, and eval traffic.7071## Best Practices7273- Prefer raw provider SDKs until orchestration complexity justifies LangGraph, LlamaIndex, or LangChain.74- Keep model, tool, retrieval, and safety decisions configurable per environment; avoid hardcoding preview model names in application logic.75- Treat model output as untrusted input: validate structure, refusal states, tool arguments, and downstream side effects.7677## Workflow7879### Step 1: Determine the architecture pattern8081| Need | Pattern | Start with |82|------|---------|------------|83| Single model call | Direct API integration | Provider SDK |84| Knowledge-grounded answers | RAG pipeline | Vector store + retrieval |85| Multi-step reasoning | Agent with tools | LangGraph, OpenAI Agents SDK, or custom loop |86| Multiple specialized models | Model routing / chain | Custom router or Vercel AI SDK |87| Offline / air-gapped | Local inference | Ollama or vLLM |88| Existing data enrichment | Batch processing | Provider batch APIs |8990### Step 2: Choose the right abstraction level9192Pick the lightest tool that solves the problem:93941. **Raw SDK** - direct Anthropic/OpenAI SDK calls. Best for simple integrations, maximum95 control, minimum dependencies. Start here unless you have a specific reason not to.962. **Vercel AI SDK** - unified provider interface with streaming primitives. Good for97 TypeScript apps that need provider-agnostic code or React/Next.js streaming UI.983. **LangChain / LlamaIndex** - orchestration frameworks. Use when you need complex chains,99 built-in document loaders, or 300+ pre-built integrations. Don't use for simple API calls -100 the abstraction overhead isn't worth it.1014. **LangGraph / OpenAI Agents SDK** - stateful agent frameworks. Use when you need cycles,102 persistence, human-in-the-loop, or multi-agent coordination.103104**The anti-pattern**: importing LangChain to make a single API call. That's like importing105Django to serve a static HTML file.106107### Step 3: Implement108109Follow the domain-specific sections below. Read the appropriate reference file for detailed110patterns and code examples.111112### Step 4: Evaluate and validate113114Every AI feature needs evaluation. Not "run it once and eyeball the output" - structured evals115with datasets, metrics, and regression detection.116117Minimum viable eval: create a `promptfooconfig.yaml` with 20+ test cases, use `contains`,118`llm-rubric`, and `cost` assertions, run `npx promptfoo eval` in CI on every PR that touches119prompts. Track pass rate over time - any regression blocks the merge.120121Read `references/evaluation.md` for promptfoo setup, assertion types, CI integration (GitHub122Actions example), RAG-specific evals, agent evals, and red teaming patterns.123124## LLM Integration Patterns125126### Streaming127128Always stream for user-facing responses. Buffer for background processing.129130```python131# Anthropic streaming (Python)132import anthropic133134client = anthropic.Anthropic()135136with client.messages.stream(137 model="claude-sonnet-4-6",138 max_tokens=1024,139 messages=[{"role": "user", "content": prompt}],140) as stream:141 for text in stream.text_stream:142 yield text143```144145### Structured output146147Use native provider mechanisms, not regex parsing of free-text responses.148149- **Anthropic**: `tool_use` with JSON schema, or `response_format` with `json_schema`150- **OpenAI**: `response_format: { type: "json_schema", json_schema: {...} }`151- **Vercel AI SDK**: `generateObject()` with Zod schema152153### Tool use / function calling154155Define tools with tight schemas. Validate tool results before feeding them back.156157```python158tools = [{159 "name": "search_docs",160 "description": "Search internal documentation",161 "input_schema": {162 "type": "object",163 "properties": {164 "query": {"type": "string", "maxLength": 200},165 "limit": {"type": "integer", "minimum": 1, "maximum": 50}166 },167 "required": ["query"]168 }169}]170```171172Read `references/llm-patterns.md` for multi-turn tool use, parallel tool calls, error173recovery, and provider-specific gotchas.174175## RAG Architecture176177The quality of a RAG system depends more on retrieval quality than model quality.178A mediocre model with great retrieval beats a frontier model with bad retrieval.179180### Chunking strategy181182| Strategy | When to use | Chunk size |183|----------|------------|------------|184| Fixed-size with overlap | Default starting point | 512-1024 tokens, 10-20% overlap |185| Semantic (sentence/paragraph) | Well-structured documents | Varies by content |186| Recursive character | Mixed content types | 1000 chars, 200 overlap |187| Document-aware (markdown headers, code blocks) | Structured docs, code | Section-based |188| Parent-child | Need both precision and context | Small retrieval, large context |189190### Embedding model selection191192Use the same model for indexing and querying. Mixing models produces meaningless similarity193scores.194195| Model | Dimensions | Best for |196|-------|-----------|----------|197| `text-embedding-3-large` (OpenAI) | 3072 (or lower via `dimensions`) | General-purpose, scalable |198| `voyage-3-large` (Voyage AI) | 1024 | Code and technical content |199| `embed-v4.0` (Cohere) | 1024 | Multilingual, compression |200| Open-source (e5-mistral, gte-Qwen2) | Varies | Air-gapped / self-hosted |201202### Retrieval patterns2032041. **Vector search alone** - fast, good for semantic similarity, bad for exact keyword matches2052. **Hybrid search** (vector + BM25/keyword) - best default. Qdrant, Weaviate, and Pinecone206 support this natively. pgvector + `tsvector` for PostgreSQL.2073. **Reranking** - retrieve more candidates (top-50), rerank with a cross-encoder or Cohere208 Rerank, return top-5. Adds latency but significantly improves relevance.2094. **Query expansion** - rephrase the user query using an LLM before retrieval. Helps when210 user queries are vague or use different terminology than the source docs.211212### Vector store selection213214| Store | Type | Best for |215|-------|------|----------|216| pgvector | PostgreSQL extension | Already using Postgres, <10M vectors |217| Qdrant | Self-hosted or cloud | Production self-hosted, hybrid search |218| Pinecone | Managed only | Zero-ops, serverless scaling |219| ChromaDB | Embedded / local | Prototyping, small datasets |220221### Minimal RAG example (Python + pgvector)222223```python224from anthropic import Anthropic225import psycopg226227client = Anthropic()228229def search(query: str, limit: int = 5) -> list[dict]:230 embedding = get_embedding(query) # same model used at index time231 with psycopg.connect(DB_URL) as conn:232 rows = conn.execute(233 "SELECT content, 1 - (embedding <=> %s::vector) AS score "234 "FROM documents WHERE 1 - (embedding <=> %s::vector) > 0.7 "235 "ORDER BY embedding <=> %s::vector LIMIT %s",236 [embedding, embedding, embedding, limit],237 ).fetchall()238 return [{"content": r[0], "score": r[1]} for r in rows]239240def ask(question: str) -> str:241 context = search(question)242 if not context:243 return "No relevant documents found."244 response = client.messages.create(245 model="claude-sonnet-4-6",246 max_tokens=1024,247 messages=[{"role": "user", "content": (248 f"Answer based on these documents:\n\n"249 + "\n---\n".join(d["content"] for d in context)250 + f"\n\nQuestion: {question}"251 )}],252 )253 return response.content[0].text254```255256Key patterns: relevance threshold (0.7), same embedding model for index/query, context passed as user message prefix.257258Read `references/rag-patterns.md` for indexing pipelines, metadata filtering, multi-index259strategies, and production RAG architecture.260261## Agent Systems262263### The agent loop264265Every agent system is fundamentally: observe -> think -> act -> repeat. The differences are in266how you manage state, handle failures, and know when to stop.267268```269while not done:270 observation = get_context(state)271 action = model.decide(observation, tools)272 if action.type == "final_answer":273 done = True274 else:275 result = execute_tool(action)276 state.add(result)277```278279### Framework selection280281| Framework | Best for | Key feature |282|-----------|----------|-------------|283| Custom loop | Simple agents, maximum control | No dependencies |284| LangGraph | Complex state machines, cycles, persistence | Graph-based, checkpointing |285| OpenAI Agents SDK | OpenAI-native, multi-agent handoffs | Sessions, tracing |286| Claude Agent SDK | Claude-native agentic loops in code | Programmatic SDK for building custom agents with Claude; use when you need fine-grained control over Claude agent behavior in your own application |287| Vercel AI SDK | TypeScript agents with UI streaming | ToolLoopAgent, React hooks |288289### Common pitfalls2902911. **Infinite loops** - always set a max iteration count. Agents will happily loop forever.2922. **Tool explosion** - more than 10-15 tools degrades model performance. Group related293 operations into fewer, more capable tools.2943. **Missing error handling** - tool failures are normal. The agent needs to recover, not crash.2954. **No cost ceiling** - a runaway agent can burn through API budget. Set per-request token296 and cost limits.2975. **Stale context** - long-running agents accumulate context. Summarize or prune periodically.298299### Minimal safe agent loop300301Every agent loop needs an iteration cap, a cost gate, and a tool-error policy. Retry transient302errors with backoff, abort on permanent errors, and pass failed tool results back with an error303marker so the model can choose the next step instead of silently losing state.304305Read `references/agent-patterns.md` for multi-agent architectures, human-in-the-loop patterns,306memory management, and production agent deployment.307308## Fine-Tuning vs RAG vs Prompt Engineering309310Pick the cheapest approach that meets your quality bar:311312| Approach | Cost | Lead time | Best for |313|----------|------|-----------|----------|314| **Prompt engineering** | Lowest | Hours | Formatting, tone, simple tasks |315| **Few-shot examples** | Low | Hours | Pattern matching, classification |316| **RAG** | Medium | Days | Knowledge-grounded, dynamic data |317| **Fine-tuning** | High | Days-weeks | Style/behavior, latency-critical, domain specialization |318319**Fine-tune when**: prompt engineering can't capture the behavior, you need consistent320style/format across thousands of outputs, or you need lower latency than RAG provides.321322**Don't fine-tune when**: your data changes frequently (use RAG), you have fewer than 100323high-quality examples, or prompt engineering already works (you're just cargo-culting).324325Read `references/fine-tuning.md` for data preparation, PEFT/LoRA patterns, evaluation during326training, and when to use full fine-tuning vs parameter-efficient methods.327328## Local Inference329330### Local serving choices331332| Tool | Best for | GPU required |333|------|----------|-------------|334| Ollama | Dev, prototyping, Mac (MLX) | No (CPU/MLX), optional GPU |335| vLLM | Production serving, high throughput | Yes |336| llama.cpp / llama-cpp-python | Minimal deps, quantized models, CPU-only | No (CPU), optional GPU |337| TGI (HF Text Generation Inference) | HF model hub integration | Yes |338339### CPU-only inference with llama.cpp340341CPU inference is viable - sometimes preferable - for: dense models that fit in RAM (7-13B342at Q4 hits 5-10 t/s on modern x86), **MoE models with low active params** (Qwen3-30B-A3B343at Q4 reaches 13+ t/s even on a 2013-era Xeon - active params dominate decode), and344air-gapped or compliance-bound environments. Key gotchas:345346- **ISA cliff**: pre-Haswell CPUs lack AVX2/FMA/BMI2. PyTorch >= 2.1, TF >= 2.8, JAX, and347 Ollama prebuilts SIGILL. llama.cpp from source with `-DGGML_AVX2=OFF -DGGML_FMA=OFF348 -DGGML_BMI2=OFF` works.349- **GGUF quants**: `Q4_K_M` is the default sweet spot. `Q5_K_M` for +25% memory and quality.350 `IQ4_XS` for tighter budgets. Avoid Q2/Q3 - quality cliff is real.351- **Reproducible models**: pin both filename and HF commit SHA. Bare repo+filename pulls352 "whatever the author serves now" - silent runtime changes on rebase.353- **`--mlock`** page-faults the GGUF into RAM at start. Sum GGUF sizes for capacity planning.354- **Threading**: `-t = physical_cores - 4` (decode, memory-bandwidth-bound), `-tb = logical`355 (prefill, compute-bound).356- **API keys**: `--api-key-file <path>`, never `--api-key <value>` on the command line - leaks357 into `/proc/<pid>/cmdline` via systemd env expansion.358359### Benchmarking360361Fixed prompt suite (chat-short, chat-long, code-simple, code-complex, reasoning), warmup pass,362record latency + decode t/s at fixed `max_tokens` and temperature. Re-run after model swaps,363llama.cpp version bumps, or build-flag changes. Compare **decode t/s**, not raw latency.364365Read `references/local-inference.md` for the full llama.cpp build walkthrough (per-CPU-generation366flags), HF SHA-pinned model download, systemd-per-model deployment, NUMA tuning, mlock memory367budgeting, benchmark methodology, and production serving configuration.368369## Cost Optimization370371### Token budgeting372373Know your costs before you scale:374375```376cost_per_request = (input_tokens * input_price + output_tokens * output_price) / 1_000_000377monthly_cost = cost_per_request * requests_per_day * 30378```379380### Strategies (ordered by impact)3813821. **Model routing** - use cheaper models for easy tasks, frontier models for hard ones.383 Route by task complexity, not by default.3842. **Caching** - cache identical or semantically similar requests. Anthropic prompt caching385 reduces repeated prefix costs by 90%.3863. **Prompt optimization** - shorter prompts cost less. Cut examples, compress instructions.3874. **Batch APIs** - Anthropic and OpenAI offer 50% discounts for async batch processing.3885. **Output length limits** - set `max_tokens` to what you actually need, not 4096 "just in case."3896. **Context pruning** - for multi-turn conversations, summarize history instead of sending390 the full transcript.391392## Safety and Guardrails393394Input validation (prompt injection), output validation (schema + content policy), PII handling395(strip before external API calls), rate limiting (per-user + per-IP), content filtering, and396audit logging (redact PII). These are non-negotiable for production AI apps.397398Read `references/safety.md` for prompt injection defense patterns, output validation schemas,399PII detection setup, and content policy implementation.400401## Production Checklist402403- [ ] API keys in environment variables or secret manager (never in code)404- [ ] Retry logic with exponential backoff and jitter on all LLM calls405- [ ] Timeouts set on all LLM calls (model inference can hang)406- [ ] Rate limiting on AI-powered endpoints407- [ ] Cost monitoring and alerting (daily spend, per-request cost tracking)408- [ ] Structured logging of prompts, responses, latency, token usage409- [ ] Evaluation suite running in CI (regression detection)410- [ ] Model fallback chain configured (primary -> secondary -> error response)411- [ ] Input validation and prompt injection defense412- [ ] Output validation before returning to users413- [ ] PII scrubbed from external API calls414- [ ] Max token limits set per request type415- [ ] Health checks on model endpoints (especially self-hosted)416- [ ] A/B testing infrastructure for prompt and model changes417418## Reference Files419420- `references/llm-patterns.md` - multi-turn tool use, parallel tool calls, error recovery, provider gotchas421- `references/rag-patterns.md` - indexing pipelines, metadata filtering, multi-index, production architecture422- `references/agent-patterns.md` - multi-agent, human-in-the-loop, memory management, production deployment423- `references/evaluation.md` - promptfoo setup, assertion types, CI integration, RAG/agent evals, red teaming424- `references/fine-tuning.md` - data prep, PEFT/LoRA, training evaluation, full vs parameter-efficient methods425- `references/local-inference.md` - quantization, model selection, GPU memory, production serving config426- `references/safety.md` - prompt injection defense, output validation, PII handling, content filtering, audit logging427- `references/target-versions.md` - September 2026 snapshot: Claude/OpenAI model families, AI SDKs, runtimes, vector stores, and eval tools428429## Output Contract430431See `references/output-contract.md` for the full contract.432433- **Skill name:** AI-ML434- **Deliverable bucket:** `audits`435- **Mode:** conditional. When invoked to **analyze, review, audit, or improve** existing repo content, emit the full contract - monospace inline header, severity-grouped inline summary, linked Markdown deliverable, and concise monospace conclusion - and write the deliverable to `docs/local/audits/ai-ml/<YYYY-MM-DD>-<slug>.md`. When invoked to **answer a question, teach a concept, build a new artifact, or generate content**, respond freely without the contract.436- **Severity scale:** `P0 | P1 | P2 | P3 | info` (see shared contract; only used in audit/review mode).437438## Related Skills439440- **mcp** - handles MCP server development (the protocol/tooling layer). This skill handles441 the application layer - how to build apps that call models, retrieve context, and orchestrate442 agents. If building an MCP server, use mcp. If building an app that uses AI, use this skill.443- **prompt-generator** - for crafting and refining individual prompts. This skill covers prompt444 template management and patterns within applications; prompt-generator handles one-off prompt445 creation and iteration.446- **databases** - for general database operations. This skill covers vector store integration447 for RAG; databases handles engine configuration, schema design, and traditional DB operations.448- **security-audit** - for security review of AI application code. This skill provides449 guardrail patterns; security-audit provides the audit methodology.450- **code-review** - for reviewing AI application code quality beyond AI-specific patterns.451- **backend-api** - for the HTTP API layer wrapping AI features. Use backend-api for contract design, auth, and route structure; use this skill for the LLM integration within those handlers.452- **anti-slop** - for auditing AI-generated application code for hallucinated APIs, over-abstraction, and slop patterns introduced by AI generation tools.453454## Rules4554561. **Start with the simplest approach.** Direct SDK calls before frameworks. Prompt engineering457 before fine-tuning. Single agent before multi-agent. Complexity is a cost.4582. **Never hardcode API keys.** Environment variables or secret managers. No exceptions.4593. **Always stream user-facing responses.** Buffered LLM responses feel broken. Stream.4604. **Set token limits explicitly.** `max_tokens` on every call. Unbounded generation wastes461 money and risks timeouts.4625. **Match embedding models.** Same model for indexing and querying. Mixing models produces463 meaningless similarity scores that silently degrade retrieval quality.4646. **Validate model output.** Check for refusals, empty content, malformed structured output.465 Models fail in creative ways - handle all of them.4667. **Budget before you batch.** Calculate cost before running batch operations. A 100k-row467 embedding job at the wrong model can cost thousands.4688. **Evaluate with data, not vibes.** Structured evals with datasets and metrics. "It looks469 good" is not a quality gate.4709. **Cap agent iterations.** Set a max loop count. Runaway agents burn budget and produce471 garbage. 10-20 iterations is a reasonable default.47210. **Run the AI self-check.** Every generated AI/ML code gets verified against the checklist473 above before returning.
Run npx skillmds@latest add iuliandita/ai-ml in your terminal (requires Node.js), paste this page's agent-chat prompt into Claude, Cursor, or any MCP-connected agent, or download the SKILL.md file and copy it into your agent's skills directory.
· Build/review AI apps: LLMs, RAG, embeddings, agents, evals, local inference. Triggers: 'llm', 'rag', 'embedding', 'openai sdk', 'agent loop', 'fine-tune', 'ollama', 'vllm'. Not for MCP (use mcp). It is listed under AI & ML on SkillMD.
This skill has not completed SkillMD's automated safety review yet. Capability flags: reads secrets. SkillMD never runs a skill's scripts for you; review the SKILL.md before installing.
This skill is tagged as working with Claude Code, Claude.ai, OpenAI Codex. SKILL.md is an open format, so most agents that read a skills directory can load it too.
Yes. Installing skills from SkillMD is free. This skill is licensed under MIT.
iuliandita (@iuliandita) published this skill. Their other Agent Skills are listed on their SkillMD profile.