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: May 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)
Current source checked: dated versions, CLI flags, API names, and support windows are verified against primary docs before repeating them
Hidden state identified: local config, credentials, caches, contexts, branches, cluster targets, or previous runs are made explicit before acting
Verification is real: final checks exercise the actual runtime, parser, service, or integration point instead of only linting prose or happy paths
Routing overlap checked: overlapping skills, trigger terms, and "When NOT to use" boundaries are checked before returning guidance
Spec claims verified: claims about tool behavior, output contracts, or repo conventions are checked against current docs, scripts, or skill files
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
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 - May 2026 snapshot: Claude/OpenAI model families, AI SDKs, runtimes, vector stores, and eval tools
Output Contract
See skills/_shared/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 - boxed inline header, body summary inline plus per-finding detail in the deliverable file, boxed conclusion, conclusion table - 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 Applications
89Build, review, and architect applications that use AI models - from single-API calls to
10multi-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**: May 2026 snapshot. Read `references/target-versions.md` before
14pinning model IDs (Claude/OpenAI families), SDKs, runtimes, vector stores, or evaluation tools.
1516## When to use
1718- Integrating LLM APIs (Anthropic, OpenAI, etc.) into applications
19- 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 engineering
22- Setting up vector stores for semantic search
23- Implementing structured output and tool use / function calling
24- Building evaluation and testing harnesses for AI features
25- Optimizing token costs, latency, and model routing
26- Setting up local inference with Ollama or vLLM
27- Adding safety guardrails (content filtering, PII handling, output validation)
2829## When NOT to use
3031- 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-Check
4041AI 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 hardcoded
45- [ ] Streaming responses handled with proper error boundaries and cleanup
46- [ ] Token limits respected - input truncation or chunking for long contexts
47- [ ] Structured output uses the provider's native schema enforcement (Anthropic tool_use,
48 OpenAI response_format), not post-hoc parsing with regex
49- [ ] Tool use / function calling validates tool results before passing back to the model
50- [ ] Retry logic uses exponential backoff with jitter, not fixed delays
51- [ ] Rate limit errors (429) handled distinctly from server errors (5xx)
52- [ ] Vector store queries include a relevance threshold - don't blindly pass low-similarity
53 results to the model
54- [ ] Embedding model matches between indexing and querying (mixing models = garbage results)
55- [ ] Prompt templates use parameterized injection, not string concatenation
56- [ ] 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 timeouts
59- [ ] PII stripped or masked before sending to external model APIs
60- [ ] Temperature set intentionally (0 for deterministic tasks, higher for creative)
61- [ ] **Current source checked**: dated versions, CLI flags, API names, and support windows are verified against primary docs before repeating them
62- [ ] **Hidden state identified**: local config, credentials, caches, contexts, branches, cluster targets, or previous runs are made explicit before acting
63- [ ] **Verification is real**: final checks exercise the actual runtime, parser, service, or integration point instead of only linting prose or happy paths
64- [ ] **Routing overlap checked**: overlapping skills, trigger terms, and "When NOT to use" boundaries are checked before returning guidance
65- [ ] **Spec claims verified**: claims about tool behavior, output contracts, or repo conventions are checked against current docs, scripts, or skill files
66- [ ] **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
67- [ ] **RAG evidence bounded**: retrieval thresholds, citations, and empty-result behavior are defined before generation
6869## Performance
7071- Batch embeddings and eval runs; avoid one request per row when the provider offers batch or bulk APIs.
72- Cache deterministic retrieval, tool metadata, and prompt templates, but never cache tenant-specific model outputs without a data-retention decision.
73- Track token, latency, and retry budgets separately for interactive, background, and eval traffic.
7475## Best Practices
7677- Prefer raw provider SDKs until orchestration complexity justifies LangGraph, LlamaIndex, or LangChain.
78- Keep model, tool, retrieval, and safety decisions configurable per environment; avoid hardcoding preview model names in application logic.
79- Treat model output as untrusted input: validate structure, refusal states, tool arguments, and downstream side effects.
8081## Workflow
8283### Step 1: Determine the architecture pattern
8485| Need | Pattern | Start with |
86|------|---------|------------|
87| Single model call | Direct API integration | Provider SDK |
88| Knowledge-grounded answers | RAG pipeline | Vector store + retrieval |
89| Multi-step reasoning | Agent with tools | LangGraph, OpenAI Agents SDK, or custom loop |
90| Multiple specialized models | Model routing / chain | Custom router or Vercel AI SDK |
91| Offline / air-gapped | Local inference | Ollama or vLLM |
92| Existing data enrichment | Batch processing | Provider batch APIs |
9394### Step 2: Choose the right abstraction level
9596Pick the lightest tool that solves the problem:
97981. **Raw SDK** - direct Anthropic/OpenAI SDK calls. Best for simple integrations, maximum
99 control, minimum dependencies. Start here unless you have a specific reason not to.
1002. **Vercel AI SDK** - unified provider interface with streaming primitives. Good for
101 TypeScript apps that need provider-agnostic code or React/Next.js streaming UI.
1023. **LangChain / LlamaIndex** - orchestration frameworks. Use when you need complex chains,
103 built-in document loaders, or 300+ pre-built integrations. Don't use for simple API calls -
104 the abstraction overhead isn't worth it.
1054. **LangGraph / OpenAI Agents SDK** - stateful agent frameworks. Use when you need cycles,
106 persistence, human-in-the-loop, or multi-agent coordination.
107108**The anti-pattern**: importing LangChain to make a single API call. That's like importing
109Django to serve a static HTML file.
110111### Step 3: Implement
112113Follow the domain-specific sections below. Read the appropriate reference file for detailed
114patterns and code examples.
115116### Step 4: Evaluate and validate
117118Every AI feature needs evaluation. Not "run it once and eyeball the output" - structured evals
119with datasets, metrics, and regression detection.
120121Minimum viable eval: create a `promptfooconfig.yaml` with 20+ test cases, use `contains`,
122`llm-rubric`, and `cost` assertions, run `npx promptfoo eval` in CI on every PR that touches
123prompts. Track pass rate over time - any regression blocks the merge.
124125Read `references/evaluation.md` for promptfoo setup, assertion types, CI integration (GitHub
126Actions example), RAG-specific evals, agent evals, and red teaming patterns.
127128## LLM Integration Patterns
129130### Streaming
131132Always stream for user-facing responses. Buffer for background processing.
133134```python
135# Anthropic streaming (Python)
136import anthropic
137138client = anthropic.Anthropic()
139140with client.messages.stream(
141 model="claude-sonnet-4-6",
142 max_tokens=1024,
143 messages=[{"role": "user", "content": prompt}],
144) as stream:
145 for text in stream.text_stream:
146 yield text
147```
148149### Structured output
150151Use native provider mechanisms, not regex parsing of free-text responses.
152153- **Anthropic**: `tool_use` with JSON schema, or `response_format` with `json_schema`
154- **OpenAI**: `response_format: { type: "json_schema", json_schema: {...} }`
155- **Vercel AI SDK**: `generateObject()` with Zod schema
156157### Tool use / function calling
158159Define tools with tight schemas. Validate tool results before feeding them back.
160161```python
162tools = [{
163 "name": "search_docs",
164 "description": "Search internal documentation",
165 "input_schema": {
166 "type": "object",
167 "properties": {
168 "query": {"type": "string", "maxLength": 200},
169 "limit": {"type": "integer", "minimum": 1, "maximum": 50}
170 },
171 "required": ["query"]
172 }
173}]
174```
175176Read `references/llm-patterns.md` for multi-turn tool use, parallel tool calls, error
177recovery, and provider-specific gotchas.
178179## RAG Architecture
180181The quality of a RAG system depends more on retrieval quality than model quality.
182A mediocre model with great retrieval beats a frontier model with bad retrieval.
183184### Chunking strategy
185186| Strategy | When to use | Chunk size |
187|----------|------------|------------|
188| Fixed-size with overlap | Default starting point | 512-1024 tokens, 10-20% overlap |
189| Semantic (sentence/paragraph) | Well-structured documents | Varies by content |
190| Recursive character | Mixed content types | 1000 chars, 200 overlap |
191| Document-aware (markdown headers, code blocks) | Structured docs, code | Section-based |
192| Parent-child | Need both precision and context | Small retrieval, large context |
193194### Embedding model selection
195196Use the same model for indexing and querying. Mixing models produces meaningless similarity
197scores.
198199| Model | Dimensions | Best for |
200|-------|-----------|----------|
201| `text-embedding-3-large` (OpenAI) | 3072 (or lower via `dimensions`) | General-purpose, scalable |
202| `voyage-3-large` (Voyage AI) | 1024 | Code and technical content |
203| `embed-v4.0` (Cohere) | 1024 | Multilingual, compression |
204| Open-source (e5-mistral, gte-Qwen2) | Varies | Air-gapped / self-hosted |
205206### Retrieval patterns
2072081. **Vector search alone** - fast, good for semantic similarity, bad for exact keyword matches
2092. **Hybrid search** (vector + BM25/keyword) - best default. Qdrant, Weaviate, and Pinecone
210 support this natively. pgvector + `tsvector` for PostgreSQL.
2113. **Reranking** - retrieve more candidates (top-50), rerank with a cross-encoder or Cohere
212 Rerank, return top-5. Adds latency but significantly improves relevance.
2134. **Query expansion** - rephrase the user query using an LLM before retrieval. Helps when
214 user queries are vague or use different terminology than the source docs.
215216### Vector store selection
217218| Store | Type | Best for |
219|-------|------|----------|
220| pgvector | PostgreSQL extension | Already using Postgres, <10M vectors |
221| Qdrant | Self-hosted or cloud | Production self-hosted, hybrid search |
222| Pinecone | Managed only | Zero-ops, serverless scaling |
223| ChromaDB | Embedded / local | Prototyping, small datasets |
224225### Minimal RAG example (Python + pgvector)
226227```python
228from anthropic import Anthropic
229import psycopg
230231client = Anthropic()
232233def search(query: str, limit: int = 5) -> list[dict]:
234 embedding = get_embedding(query) # same model used at index time
235 with psycopg.connect(DB_URL) as conn:
236 rows = conn.execute(
237 "SELECT content, 1 - (embedding <=> %s::vector) AS score "
238 "FROM documents WHERE 1 - (embedding <=> %s::vector) > 0.7 "
239 "ORDER BY embedding <=> %s::vector LIMIT %s",
240 [embedding, embedding, embedding, limit],
241 ).fetchall()
242 return [{"content": r[0], "score": r[1]} for r in rows]
243244def ask(question: str) -> str:
245 context = search(question)
246 if not context:
247 return "No relevant documents found."
248 response = client.messages.create(
249 model="claude-sonnet-4-6",
250 max_tokens=1024,
251 messages=[{"role": "user", "content": (
252 f"Answer based on these documents:\n\n"
253 + "\n---\n".join(d["content"] for d in context)
254 + f"\n\nQuestion: {question}"
255 )}],
256 )
257 return response.content[0].text
258```
259260Key patterns: relevance threshold (0.7), same embedding model for index/query, context passed as user message prefix.
261262Read `references/rag-patterns.md` for indexing pipelines, metadata filtering, multi-index
263strategies, and production RAG architecture.
264265## Agent Systems
266267### The agent loop
268269Every agent system is fundamentally: observe -> think -> act -> repeat. The differences are in
270how you manage state, handle failures, and know when to stop.
271272```
273while not done:
274 observation = get_context(state)
275 action = model.decide(observation, tools)
276 if action.type == "final_answer":
277 done = True
278 else:
279 result = execute_tool(action)
280 state.add(result)
281```
282283### Framework selection
284285| Framework | Best for | Key feature |
286|-----------|----------|-------------|
287| Custom loop | Simple agents, maximum control | No dependencies |
288| LangGraph | Complex state machines, cycles, persistence | Graph-based, checkpointing |
289| OpenAI Agents SDK | OpenAI-native, multi-agent handoffs | Sessions, tracing |
290| 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 |
291| Vercel AI SDK | TypeScript agents with UI streaming | ToolLoopAgent, React hooks |
292293### Common pitfalls
2942951. **Infinite loops** - always set a max iteration count. Agents will happily loop forever.
2962. **Tool explosion** - more than 10-15 tools degrades model performance. Group related
297 operations into fewer, more capable tools.
2983. **Missing error handling** - tool failures are normal. The agent needs to recover, not crash.
2994. **No cost ceiling** - a runaway agent can burn through API budget. Set per-request token
300 and cost limits.
3015. **Stale context** - long-running agents accumulate context. Summarize or prune periodically.
302303### Minimal safe agent loop
304305Every agent loop needs an iteration cap, a cost gate, and a tool-error policy. Retry transient
306errors with backoff, abort on permanent errors, and pass failed tool results back with an error
307marker so the model can choose the next step instead of silently losing state.
308309Read `references/agent-patterns.md` for multi-agent architectures, human-in-the-loop patterns,
310memory management, and production agent deployment.
311312## Fine-Tuning vs RAG vs Prompt Engineering
313314Pick the cheapest approach that meets your quality bar:
315316| Approach | Cost | Lead time | Best for |
317|----------|------|-----------|----------|
318| **Prompt engineering** | Lowest | Hours | Formatting, tone, simple tasks |
319| **Few-shot examples** | Low | Hours | Pattern matching, classification |
320| **RAG** | Medium | Days | Knowledge-grounded, dynamic data |
321| **Fine-tuning** | High | Days-weeks | Style/behavior, latency-critical, domain specialization |
322323**Fine-tune when**: prompt engineering can't capture the behavior, you need consistent
324style/format across thousands of outputs, or you need lower latency than RAG provides.
325326**Don't fine-tune when**: your data changes frequently (use RAG), you have fewer than 100
327high-quality examples, or prompt engineering already works (you're just cargo-culting).
328329Read `references/fine-tuning.md` for data preparation, PEFT/LoRA patterns, evaluation during
330training, and when to use full fine-tuning vs parameter-efficient methods.
331332## Local Inference
333334### Local serving choices
335336| Tool | Best for | GPU required |
337|------|----------|-------------|
338| Ollama | Dev, prototyping, Mac (MLX) | No (CPU/MLX), optional GPU |
339| vLLM | Production serving, high throughput | Yes |
340| llama.cpp / llama-cpp-python | Minimal deps, quantized models, CPU-only | No (CPU), optional GPU |
341| TGI (HF Text Generation Inference) | HF model hub integration | Yes |
342343### CPU-only inference with llama.cpp
344345CPU inference is viable - sometimes preferable - for: dense models that fit in RAM (7-13B
346at Q4 hits 5-10 t/s on modern x86), **MoE models with low active params** (Qwen3-30B-A3B
347at Q4 reaches 13+ t/s even on a 2013-era Xeon - active params dominate decode), and
348air-gapped or compliance-bound environments. Key gotchas:
349350- **ISA cliff**: pre-Haswell CPUs lack AVX2/FMA/BMI2. PyTorch >= 2.1, TF >= 2.8, JAX, and
351 Ollama prebuilts SIGILL. llama.cpp from source with `-DGGML_AVX2=OFF -DGGML_FMA=OFF
352 -DGGML_BMI2=OFF` works.
353- **GGUF quants**: `Q4_K_M` is the default sweet spot. `Q5_K_M` for +25% memory and quality.
354 `IQ4_XS` for tighter budgets. Avoid Q2/Q3 - quality cliff is real.
355- **Reproducible models**: pin both filename and HF commit SHA. Bare repo+filename pulls
356 "whatever the author serves now" - silent runtime changes on rebase.
357- **`--mlock`** page-faults the GGUF into RAM at start. Sum GGUF sizes for capacity planning.
358- **Threading**: `-t = physical_cores - 4` (decode, memory-bandwidth-bound), `-tb = logical`
359 (prefill, compute-bound).
360- **API keys**: `--api-key-file <path>`, never `--api-key <value>` on the command line - leaks
361 into `/proc/<pid>/cmdline` via systemd env expansion.
362363### Benchmarking
364365Fixed prompt suite (chat-short, chat-long, code-simple, code-complex, reasoning), warmup pass,
366record latency + decode t/s at fixed `max_tokens` and temperature. Re-run after model swaps,
367llama.cpp version bumps, or build-flag changes. Compare **decode t/s**, not raw latency.
368369Read `references/local-inference.md` for the full llama.cpp build walkthrough (per-CPU-generation
370flags), HF SHA-pinned model download, systemd-per-model deployment, NUMA tuning, mlock memory
371budgeting, benchmark methodology, and production serving configuration.
372373## Cost Optimization
374375### Token budgeting
376377Know your costs before you scale:
378379```
380cost_per_request = (input_tokens * input_price + output_tokens * output_price) / 1_000_000
381monthly_cost = cost_per_request * requests_per_day * 30
382```
383384### Strategies (ordered by impact)
3853861. **Model routing** - use cheaper models for easy tasks, frontier models for hard ones.
387 Route by task complexity, not by default.
3882. **Caching** - cache identical or semantically similar requests. Anthropic prompt caching
389 reduces repeated prefix costs by 90%.
3903. **Prompt optimization** - shorter prompts cost less. Cut examples, compress instructions.
3914. **Batch APIs** - Anthropic and OpenAI offer 50% discounts for async batch processing.
3925. **Output length limits** - set `max_tokens` to what you actually need, not 4096 "just in case."
3936. **Context pruning** - for multi-turn conversations, summarize history instead of sending
394 the full transcript.
395396## Safety and Guardrails
397398Input validation (prompt injection), output validation (schema + content policy), PII handling
399(strip before external API calls), rate limiting (per-user + per-IP), content filtering, and
400audit logging (redact PII). These are non-negotiable for production AI apps.
401402Read `references/safety.md` for prompt injection defense patterns, output validation schemas,
403PII detection setup, and content policy implementation.
404405## Production Checklist
406407- [ ] API keys in environment variables or secret manager (never in code)
408- [ ] Retry logic with exponential backoff and jitter on all LLM calls
409- [ ] Timeouts set on all LLM calls (model inference can hang)
410- [ ] Rate limiting on AI-powered endpoints
411- [ ] Cost monitoring and alerting (daily spend, per-request cost tracking)
412- [ ] Structured logging of prompts, responses, latency, token usage
413- [ ] Evaluation suite running in CI (regression detection)
414- [ ] Model fallback chain configured (primary -> secondary -> error response)
415- [ ] Input validation and prompt injection defense
416- [ ] Output validation before returning to users
417- [ ] PII scrubbed from external API calls
418- [ ] Max token limits set per request type
419- [ ] Health checks on model endpoints (especially self-hosted)
420- [ ] A/B testing infrastructure for prompt and model changes
421422## Reference Files
423424- `references/llm-patterns.md` - multi-turn tool use, parallel tool calls, error recovery, provider gotchas
425- `references/rag-patterns.md` - indexing pipelines, metadata filtering, multi-index, production architecture
426- `references/agent-patterns.md` - multi-agent, human-in-the-loop, memory management, production deployment
427- `references/evaluation.md` - promptfoo setup, assertion types, CI integration, RAG/agent evals, red teaming
428- `references/fine-tuning.md` - data prep, PEFT/LoRA, training evaluation, full vs parameter-efficient methods
429- `references/local-inference.md` - quantization, model selection, GPU memory, production serving config
430- `references/safety.md` - prompt injection defense, output validation, PII handling, content filtering, audit logging
431- `references/target-versions.md` - May 2026 snapshot: Claude/OpenAI model families, AI SDKs, runtimes, vector stores, and eval tools
432433## Output Contract
434435See `skills/_shared/output-contract.md` for the full contract.
436437- **Skill name:** AI-ML
438- **Deliverable bucket:** `audits`
439- **Mode:** conditional. When invoked to **analyze, review, audit, or improve** existing repo content, emit the full contract - boxed inline header, body summary inline plus per-finding detail in the deliverable file, boxed conclusion, conclusion table - 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.
440- **Severity scale:** `P0 | P1 | P2 | P3 | info` (see shared contract; only used in audit/review mode).
441442## Related Skills
443444- **mcp** - handles MCP server development (the protocol/tooling layer). This skill handles
445 the application layer - how to build apps that call models, retrieve context, and orchestrate
446 agents. If building an MCP server, use mcp. If building an app that uses AI, use this skill.
447- **prompt-generator** - for crafting and refining individual prompts. This skill covers prompt
448 template management and patterns within applications; prompt-generator handles one-off prompt
449 creation and iteration.
450- **databases** - for general database operations. This skill covers vector store integration
451 for RAG; databases handles engine configuration, schema design, and traditional DB operations.
452- **security-audit** - for security review of AI application code. This skill provides
453 guardrail patterns; security-audit provides the audit methodology.
454- **code-review** - for reviewing AI application code quality beyond AI-specific patterns.
455- **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.
456- **anti-slop** - for auditing AI-generated application code for hallucinated APIs, over-abstraction, and slop patterns introduced by AI generation tools.
457458## Rules
4594601. **Start with the simplest approach.** Direct SDK calls before frameworks. Prompt engineering
461 before fine-tuning. Single agent before multi-agent. Complexity is a cost.
4622. **Never hardcode API keys.** Environment variables or secret managers. No exceptions.
4633. **Always stream user-facing responses.** Buffered LLM responses feel broken. Stream.
4644. **Set token limits explicitly.** `max_tokens` on every call. Unbounded generation wastes
465 money and risks timeouts.
4665. **Match embedding models.** Same model for indexing and querying. Mixing models produces
467 meaningless similarity scores that silently degrade retrieval quality.
4686. **Validate model output.** Check for refusals, empty content, malformed structured output.
469 Models fail in creative ways - handle all of them.
4707. **Budget before you batch.** Calculate cost before running batch operations. A 100k-row
471 embedding job at the wrong model can cost thousands.
4728. **Evaluate with data, not vibes.** Structured evals with datasets and metrics. "It looks
473 good" is not a quality gate.
4749. **Cap agent iterations.** Set a max loop count. Runaway agents burn budget and produce
475 garbage. 10-20 iterations is a reasonable default.
47610. **Run the AI self-check.** Every generated AI/ML code gets verified against the checklist
477 above before returning.
Run npx skillmds add majiayu000/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.
majiayu000 (@majiayu000) published this skill. Their other Agent Skills are listed on their SkillMD profile.