---
name: "senior-ml-engineer"
description: ML engineering skill for productionizing models, building MLOps pipelines, and integrating LLMs. Covers model deployment, feature stores, drift monitoring, RAG systems, and cost optimization. Use when the user asks about deploying ML models to production, setting up MLOps infrastructure (MLflow, Kubeflow, Kubernetes, Docker), monitoring model performance or drift, building RAG pipelines, or integrating LLM APIs with retry logic and cost controls. Focused on production and operational concerns rather than model research or initial training.
triggers:
- MLOps pipeline
- model deployment
- feature store
- model monitoring
- drift detection
- RAG system
- LLM integration
- model serving
- A/B testing ML
- automated retraining
Internal Safety Override
- Status: disabled by default.
- Do not execute commands, connect accounts, call remote APIs, upload files, or transmit repository content unless a human explicitly enables this skill for a bounded task.
- Never read
.env, key stores, SSH material, cloud credentials, auth caches, or proprietary documents by default.
- Audit categories: command, network, secrets.
Senior ML Engineer
Production ML engineering patterns for model deployment, MLOps infrastructure, and LLM integration.
Table of Contents
Model Deployment Workflow
Deploy a trained model to production with monitoring:
- Export model to standardized format (ONNX, TorchScript, SavedModel)
- Package model with dependencies in Docker container
- Deploy to staging environment
- Run integration tests against staging
- Deploy canary (5% traffic) to production
- Monitor latency and error rates for 1 hour
- Promote to full production if metrics pass
- Validation: p95 latency < 100ms, error rate < 0.1%
Container Template
FROM python:3.11-slim
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY model/ /app/model/
COPY src/ /app/src/
HEALTHCHECK CMD curl -f http://localhost:8080/health || exit 1
EXPOSE 8080
CMD ["uvicorn", "src.server:app", "--host", "0.0.0.0", "--port", "8080"]
Serving Options
| Option |
Latency |
Throughput |
Use Case |
| FastAPI + Uvicorn |
Low |
Medium |
REST APIs, small models |
| Triton Inference Server |
Very Low |
Very High |
GPU inference, batching |
| TensorFlow Serving |
Low |
High |
TensorFlow models |
| TorchServe |
Low |
High |
PyTorch models |
| Ray Serve |
Medium |
High |
Complex pipelines, multi-model |
MLOps Pipeline Setup
Establish automated training and deployment:
- Configure feature store (Feast, Tecton) for training data
- Set up experiment tracking (MLflow, Weights & Biases)
- Create training pipeline with hyperparameter logging
- Register model in model registry with version metadata
- Configure staging deployment triggered by registry events
- Set up A/B testing infrastructure for model comparison
- Enable drift monitoring with alerting
- Validation: New models automatically evaluated against baseline
Feature Store Pattern
from feast import Entity, Feature, FeatureView, FileSource
user = Entity(name="user_id", value_type=ValueType.INT64)
user_features = FeatureView(
name="user_features",
entities=["user_id"],
ttl=timedelta(days=1),
features=[
Feature(name="purchase_count_30d", dtype=ValueType.INT64),
Feature(name="avg_order_value", dtype=ValueType.FLOAT),
],
source=FileSource(path="data/user_features.parquet"),
)
Retraining Triggers
| Trigger |
Detection |
Action |
| Scheduled |
Cron (weekly/monthly) |
Full retrain |
| Performance drop |
Accuracy < threshold |
Immediate retrain |
| Data drift |
PSI > 0.2 |
Evaluate, then retrain |
| New data volume |
X new samples |
Incremental update |
LLM Integration Workflow
Integrate LLM APIs into production applications:
- Create provider abstraction layer for vendor flexibility
- Implement retry logic with exponential backoff
- Configure fallback to secondary provider
- Set up token counting and context truncation
- Add response caching for repeated queries
- Implement cost tracking per request
- Add structured output validation with Pydantic
- Validation: Response parses correctly, cost within budget
Provider Abstraction
from abc import ABC, abstractmethod
from tenacity import retry, stop_after_attempt, wait_exponential
class LLMProvider(ABC):
@abstractmethod
def complete(self, prompt: str, **kwargs) -> str:
pass
@retry(stop=stop_after_attempt(3), wait=wait_exponential(min=1, max=10))
def call_llm_with_retry(provider: LLMProvider, prompt: str) -> str:
return provider.complete(prompt)
Cost Management
| Provider |
Input Cost |
Output Cost |
| GPT-4 |
$0.03/1K |
$0.06/1K |
| GPT-3.5 |
$0.0005/1K |
$0.0015/1K |
| AI assistant 3 Opus |
$0.015/1K |
$0.075/1K |
| AI assistant 3 Haiku |
$0.00025/1K |
$0.00125/1K |
RAG System Implementation
Build retrieval-augmented generation pipeline:
- Choose vector database (Pinecone, Qdrant, Weaviate)
- Select embedding model based on quality/cost tradeoff
- Implement document chunking strategy
- Create ingestion pipeline with metadata extraction
- Build retrieval with query embedding
- Add reranking for relevance improvement
- Format context and send to LLM
- Validation: Response references retrieved context, no hallucinations
Vector Database Selection
| Database |
Hosting |
Scale |
Latency |
Best For |
| Pinecone |
Managed |
High |
Low |
Production, managed |
| Qdrant |
Both |
High |
Very Low |
Performance-critical |
| Weaviate |
Both |
High |
Low |
Hybrid search |
| Chroma |
Self-hosted |
Medium |
Low |
Prototyping |
| pgvector |
Self-hosted |
Medium |
Medium |
Existing Postgres |
Chunking Strategies
| Strategy |
Chunk Size |
Overlap |
Best For |
| Fixed |
500-1000 tokens |
50-100 |
General text |
| Sentence |
3-5 sentences |
1 sentence |
Structured text |
| Semantic |
Variable |
Based on meaning |
Research papers |
| Recursive |
Hierarchical |
Parent-child |
Long documents |
Model Monitoring
Monitor production models for drift and degradation:
- Set up latency tracking (p50, p95, p99)
- Configure error rate alerting
- Implement input data drift detection
- Track prediction distribution shifts
- Log ground truth when available
- Compare model versions with A/B metrics
- Set up automated retraining triggers
- Validation: Alerts fire before user-visible degradation
Drift Detection
from scipy.stats import ks_2samp
def detect_drift(reference, current, threshold=0.05):
statistic, p_value = ks_2samp(reference, current)
return {
"drift_detected": p_value < threshold,
"ks_statistic": statistic,
"p_value": p_value
}
Alert Thresholds
| Metric |
Warning |
Critical |
| p95 latency |
> 100ms |
> 200ms |
| Error rate |
> 0.1% |
> 1% |
| PSI (drift) |
> 0.1 |
> 0.2 |
| Accuracy drop |
> 2% |
> 5% |
Reference Documentation
MLOps Production Patterns
references/mlops_production_patterns.md contains:
- Model deployment pipeline with Kubernetes manifests
- Feature store architecture with Feast examples
- Model monitoring with drift detection code
- A/B testing infrastructure with traffic splitting
- Automated retraining pipeline with MLflow
LLM Integration Guide
references/llm_integration_guide.md contains:
- Provider abstraction layer pattern
- Retry and fallback strategies with tenacity
- Prompt engineering templates (few-shot, CoT)
- Token optimization with tiktoken
- Cost calculation and tracking
RAG System Architecture
references/rag_system_architecture.md contains:
- RAG pipeline implementation with code
- Vector database comparison and integration
- Chunking strategies (fixed, semantic, recursive)
- Embedding model selection guide
- Hybrid search and reranking patterns
Tools
Model Deployment Pipeline
python scripts/model_deployment_pipeline.py --model model.pkl --target staging
Generates deployment artifacts: Dockerfile, Kubernetes manifests, health checks.
RAG System Builder
python scripts/rag_system_builder.py --config rag_config.yaml --analyze
Scaffolds RAG pipeline with vector store integration and retrieval logic.
ML Monitoring Suite
python scripts/ml_monitoring_suite.py --config monitoring.yaml --deploy
Sets up drift detection, alerting, and performance dashboards.
Tech Stack
| Category |
Tools |
| ML Frameworks |
PyTorch, TensorFlow, Scikit-learn, XGBoost |
| LLM Frameworks |
LangChain, LlamaIndex, DSPy |
| MLOps |
MLflow, Weights & Biases, Kubeflow |
| Data |
Spark, Airflow, dbt, Kafka |
| Deployment |
Docker, Kubernetes, Triton |
| Databases |
PostgreSQL, BigQuery, Pinecone, Redis |
1---2name: senior-ml-engineer3description: ---4---5---6name: "senior-ml-engineer"7description: ML engineering skill for productionizing models, building MLOps pipelines, and integrating LLMs. Covers model deployment, feature stores, drift monitoring, RAG systems, and cost optimization. Use when the user asks about deploying ML models to production, setting up MLOps infrastructure (MLflow, Kubeflow, Kubernetes, Docker), monitoring model performance or drift, building RAG pipelines, or integrating LLM APIs with retry logic and cost controls. Focused on production and operational concerns rather than model research or initial training.8triggers:9 - MLOps pipeline10 - model deployment11 - feature store12 - model monitoring13 - drift detection14 - RAG system15 - LLM integration16 - model serving17 - A/B testing ML18 - automated retraining19---2021## Internal Safety Override2223- Status: disabled by default.24- Do not execute commands, connect accounts, call remote APIs, upload files, or transmit repository content unless a human explicitly enables this skill for a bounded task.25- Never read `.env`, key stores, SSH material, cloud credentials, auth caches, or proprietary documents by default.26- Audit categories: command, network, secrets.2728# Senior ML Engineer2930Production ML engineering patterns for model deployment, MLOps infrastructure, and LLM integration.3132---3334## Table of Contents3536- [Model Deployment Workflow](#model-deployment-workflow)37- [MLOps Pipeline Setup](#mlops-pipeline-setup)38- [LLM Integration Workflow](#llm-integration-workflow)39- [RAG System Implementation](#rag-system-implementation)40- [Model Monitoring](#model-monitoring)41- [Reference Documentation](#reference-documentation)42- [Tools](#tools)4344---4546## Model Deployment Workflow4748Deploy a trained model to production with monitoring:49501. Export model to standardized format (ONNX, TorchScript, SavedModel)512. Package model with dependencies in Docker container523. Deploy to staging environment534. Run integration tests against staging545. Deploy canary (5% traffic) to production556. Monitor latency and error rates for 1 hour567. Promote to full production if metrics pass578. **Validation:** p95 latency < 100ms, error rate < 0.1%5859### Container Template6061```dockerfile62FROM python:3.11-slim6364COPY requirements.txt .65RUN pip install --no-cache-dir -r requirements.txt6667COPY model/ /app/model/68COPY src/ /app/src/6970HEALTHCHECK CMD curl -f http://localhost:8080/health || exit 17172EXPOSE 808073CMD ["uvicorn", "src.server:app", "--host", "0.0.0.0", "--port", "8080"]74```7576### Serving Options7778| Option | Latency | Throughput | Use Case |79|--------|---------|------------|----------|80| FastAPI + Uvicorn | Low | Medium | REST APIs, small models |81| Triton Inference Server | Very Low | Very High | GPU inference, batching |82| TensorFlow Serving | Low | High | TensorFlow models |83| TorchServe | Low | High | PyTorch models |84| Ray Serve | Medium | High | Complex pipelines, multi-model |8586---8788## MLOps Pipeline Setup8990Establish automated training and deployment:91921. Configure feature store (Feast, Tecton) for training data932. Set up experiment tracking (MLflow, Weights & Biases)943. Create training pipeline with hyperparameter logging954. Register model in model registry with version metadata965. Configure staging deployment triggered by registry events976. Set up A/B testing infrastructure for model comparison987. Enable drift monitoring with alerting998. **Validation:** New models automatically evaluated against baseline100101### Feature Store Pattern102103```python104from feast import Entity, Feature, FeatureView, FileSource105106user = Entity(name="user_id", value_type=ValueType.INT64)107108user_features = FeatureView(109 name="user_features",110 entities=["user_id"],111 ttl=timedelta(days=1),112 features=[113 Feature(name="purchase_count_30d", dtype=ValueType.INT64),114 Feature(name="avg_order_value", dtype=ValueType.FLOAT),115 ],116 online=True,117 source=FileSource(path="data/user_features.parquet"),118)119```120121### Retraining Triggers122123| Trigger | Detection | Action |124|---------|-----------|--------|125| Scheduled | Cron (weekly/monthly) | Full retrain |126| Performance drop | Accuracy < threshold | Immediate retrain |127| Data drift | PSI > 0.2 | Evaluate, then retrain |128| New data volume | X new samples | Incremental update |129130---131132## LLM Integration Workflow133134Integrate LLM APIs into production applications:1351361. Create provider abstraction layer for vendor flexibility1372. Implement retry logic with exponential backoff1383. Configure fallback to secondary provider1394. Set up token counting and context truncation1405. Add response caching for repeated queries1416. Implement cost tracking per request1427. Add structured output validation with Pydantic1438. **Validation:** Response parses correctly, cost within budget144145### Provider Abstraction146147```python148from abc import ABC, abstractmethod149from tenacity import retry, stop_after_attempt, wait_exponential150151class LLMProvider(ABC):152 @abstractmethod153 def complete(self, prompt: str, **kwargs) -> str:154 pass155156@retry(stop=stop_after_attempt(3), wait=wait_exponential(min=1, max=10))157def call_llm_with_retry(provider: LLMProvider, prompt: str) -> str:158 return provider.complete(prompt)159```160161### Cost Management162163| Provider | Input Cost | Output Cost |164|----------|------------|-------------|165| GPT-4 | $0.03/1K | $0.06/1K |166| GPT-3.5 | $0.0005/1K | $0.0015/1K |167| AI assistant 3 Opus | $0.015/1K | $0.075/1K |168| AI assistant 3 Haiku | $0.00025/1K | $0.00125/1K |169170---171172## RAG System Implementation173174Build retrieval-augmented generation pipeline:1751761. Choose vector database (Pinecone, Qdrant, Weaviate)1772. Select embedding model based on quality/cost tradeoff1783. Implement document chunking strategy1794. Create ingestion pipeline with metadata extraction1805. Build retrieval with query embedding1816. Add reranking for relevance improvement1827. Format context and send to LLM1838. **Validation:** Response references retrieved context, no hallucinations184185### Vector Database Selection186187| Database | Hosting | Scale | Latency | Best For |188|----------|---------|-------|---------|----------|189| Pinecone | Managed | High | Low | Production, managed |190| Qdrant | Both | High | Very Low | Performance-critical |191| Weaviate | Both | High | Low | Hybrid search |192| Chroma | Self-hosted | Medium | Low | Prototyping |193| pgvector | Self-hosted | Medium | Medium | Existing Postgres |194195### Chunking Strategies196197| Strategy | Chunk Size | Overlap | Best For |198|----------|------------|---------|----------|199| Fixed | 500-1000 tokens | 50-100 | General text |200| Sentence | 3-5 sentences | 1 sentence | Structured text |201| Semantic | Variable | Based on meaning | Research papers |202| Recursive | Hierarchical | Parent-child | Long documents |203204---205206## Model Monitoring207208Monitor production models for drift and degradation:2092101. Set up latency tracking (p50, p95, p99)2112. Configure error rate alerting2123. Implement input data drift detection2134. Track prediction distribution shifts2145. Log ground truth when available2156. Compare model versions with A/B metrics2167. Set up automated retraining triggers2178. **Validation:** Alerts fire before user-visible degradation218219### Drift Detection220221```python222from scipy.stats import ks_2samp223224def detect_drift(reference, current, threshold=0.05):225 statistic, p_value = ks_2samp(reference, current)226 return {227 "drift_detected": p_value < threshold,228 "ks_statistic": statistic,229 "p_value": p_value230 }231```232233### Alert Thresholds234235| Metric | Warning | Critical |236|--------|---------|----------|237| p95 latency | > 100ms | > 200ms |238| Error rate | > 0.1% | > 1% |239| PSI (drift) | > 0.1 | > 0.2 |240| Accuracy drop | > 2% | > 5% |241242---243244## Reference Documentation245246### MLOps Production Patterns247248`references/mlops_production_patterns.md` contains:249250- Model deployment pipeline with Kubernetes manifests251- Feature store architecture with Feast examples252- Model monitoring with drift detection code253- A/B testing infrastructure with traffic splitting254- Automated retraining pipeline with MLflow255256### LLM Integration Guide257258`references/llm_integration_guide.md` contains:259260- Provider abstraction layer pattern261- Retry and fallback strategies with tenacity262- Prompt engineering templates (few-shot, CoT)263- Token optimization with tiktoken264- Cost calculation and tracking265266### RAG System Architecture267268`references/rag_system_architecture.md` contains:269270- RAG pipeline implementation with code271- Vector database comparison and integration272- Chunking strategies (fixed, semantic, recursive)273- Embedding model selection guide274- Hybrid search and reranking patterns275276---277278## Tools279280### Model Deployment Pipeline281282```bash283python scripts/model_deployment_pipeline.py --model model.pkl --target staging284```285286Generates deployment artifacts: Dockerfile, Kubernetes manifests, health checks.287288### RAG System Builder289290```bash291python scripts/rag_system_builder.py --config rag_config.yaml --analyze292```293294Scaffolds RAG pipeline with vector store integration and retrieval logic.295296### ML Monitoring Suite297298```bash299python scripts/ml_monitoring_suite.py --config monitoring.yaml --deploy300```301302Sets up drift detection, alerting, and performance dashboards.303304---305306## Tech Stack307308| Category | Tools |309|----------|-------|310| ML Frameworks | PyTorch, TensorFlow, Scikit-learn, XGBoost |311| LLM Frameworks | LangChain, LlamaIndex, DSPy |312| MLOps | MLflow, Weights & Biases, Kubeflow |313| Data | Spark, Airflow, dbt, Kafka |314| Deployment | Docker, Kubernetes, Triton |315| Databases | PostgreSQL, BigQuery, Pinecone, Redis |