AI Integration Expert Skill
Quick Start
# 1. Navigation rapide vers un agent
ai-integration/agents/llm/openai # Intégration OpenAI API
ai-integration/agents/llm/claude # Intégration Claude API
ai-integration/agents/rag/architecture # Architecture RAG
ai-integration/agents/vectors/pgvector # PostgreSQL + pgvector
ai-integration/agents/prompting/patterns # Prompt engineering
# 2. Questions fréquentes
"Comment intégrer l'API OpenAI ?" → llm/openai
"Mettre en place un RAG ?" → rag/architecture
"Quelle vector DB choisir ?" → vectors/orchestrator
"Optimiser mes prompts ?" → prompting/patterns
"Déployer un modèle ML ?" → mlops/deployment
Position dans l'Architecture
Ce skill est au NIVEAU 3 : IMPLÉMENTATION. Il implémente les capacités IA dans les applications.
flowchart TB
subgraph N1["NIVEAU 1 : STRATÉGIE"]
DT[direction-technique]
end
subgraph N2["NIVEAU 2 : OPÉRATIONS"]
WDP[web-dev-process]
LD[lead-dev]
end
subgraph N3["NIVEAU 3 : IMPLÉMENTATION"]
AI[ai-integration]
subgraph DOMAINS["Domaines"]
LLM[llm/]
RAG[rag/]
VEC[vectors/]
PROMPT[prompting/]
AGENTS[agents/]
MLOPS[mlops/]
end
end
DT -->|stratégie IA| WDP
DT -->|budget, providers| AI
WDP -->|process| AI
LD -->|coordination| AI
AI --> DOMAINS
style N1 fill:#ffebee
style N2 fill:#fff3e0
style N3 fill:#e8f5e9
style AI fill:#c8e6c9,stroke:#2e7d32,stroke-width:2px
Philosophie
Intégrer l'IA de manière pragmatique, sécurisée et maintenable.
Ce skill :
- ✅ Intègre les APIs LLM (OpenAI, Claude, Mistral, etc.)
- ✅ Implémente les patterns RAG
- ✅ Configure les vector databases
- ✅ Optimise les prompts et outputs
- ✅ Déploie et monitore les modèles
Il ne fait PAS :
- ❌ Les décisions stratégiques IA →
direction-technique
- ❌ L'entraînement de modèles from scratch → ML spécialisé
- ❌ La recherche fondamentale → hors scope agence web
Domaines et Agents (40 agents)
1. llm/ - Intégration LLMs (8 agents)
APIs et SDKs des principaux LLMs.
| Agent |
Responsabilité |
Technologies |
orchestrator |
Coordination LLM |
- |
openai |
OpenAI API |
GPT-4, GPT-4o, Whisper, DALL-E |
claude |
Anthropic API |
Claude 3.5, Claude 3 |
mistral |
Mistral AI |
Mistral Large, Codestral |
ollama |
LLMs locaux |
Llama 3, Mistral local |
langchain |
Framework LLM |
LangChain.js, LCEL |
vercel-ai |
Vercel AI SDK |
Streaming, Edge |
cost-optimization |
Optimisation coûts |
Caching, batching, model selection |
2. rag/ - Retrieval Augmented Generation (7 agents)
Patterns RAG pour enrichir les LLMs avec vos données.
| Agent |
Responsabilité |
Technologies |
orchestrator |
Coordination RAG |
- |
architecture |
Architecture RAG |
Patterns, chunking strategies |
ingestion |
Pipeline d'ingestion |
Document loaders, parsers |
chunking |
Stratégies de découpage |
Semantic, recursive, sentence |
retrieval |
Stratégies de retrieval |
Hybrid search, reranking |
evaluation |
Évaluation RAG |
RAGAS, faithfulness, relevance |
advanced |
RAG avancé |
HyDE, CRAG, Agentic RAG |
3. vectors/ - Vector Databases (6 agents)
Stockage et recherche de vecteurs.
| Agent |
Responsabilité |
Technologies |
orchestrator |
Coordination vectors |
- |
pgvector |
PostgreSQL vectors |
pgvector, indexing |
pinecone |
Pinecone |
Serverless, namespaces |
weaviate |
Weaviate |
Hybrid search, modules |
qdrant |
Qdrant |
Filtering, payloads |
embeddings |
Génération embeddings |
OpenAI, Cohere, local |
4. prompting/ - Prompt Engineering (6 agents)
Techniques d'optimisation des prompts.
| Agent |
Responsabilité |
Technologies |
orchestrator |
Coordination prompting |
- |
patterns |
Patterns de prompts |
Few-shot, CoT, ReAct |
templates |
Gestion templates |
Langchain, Jinja |
output-parsing |
Parsing des outputs |
Structured output, JSON mode |
guardrails |
Sécurité des outputs |
Validation, filtering |
testing |
Test des prompts |
Promptfoo, eval frameworks |
5. agents/ - AI Agents (6 agents)
Construction d'agents IA autonomes.
| Agent |
Responsabilité |
Technologies |
orchestrator |
Coordination agents |
- |
architecture |
Architecture agents |
ReAct, Plan-and-Execute |
tools |
Définition d'outils |
Function calling, MCP |
memory |
Gestion mémoire |
Short/long-term, summarization |
multi-agent |
Multi-agents |
Orchestration, communication |
claude-computer-use |
Computer Use |
Anthropic Computer Use API |
6. mlops/ - ML Operations (7 agents)
Déploiement et monitoring des modèles.
| Agent |
Responsabilité |
Technologies |
orchestrator |
Coordination MLOps |
- |
deployment |
Déploiement modèles |
HuggingFace, Replicate |
fine-tuning |
Fine-tuning |
OpenAI, LoRA, QLoRA |
monitoring |
Monitoring IA |
LangSmith, Helicone |
evaluation |
Évaluation modèles |
Benchmarks, A/B testing |
versioning |
Versioning modèles |
MLflow, DVC |
edge |
IA en edge |
ONNX, TensorFlow Lite |
Total : 40 agents spécialisés
Règles de Routage
Par Type de Question
| Question |
Domaine |
| Intégrer OpenAI, Claude, Mistral |
llm/ |
| RAG, enrichir avec mes données |
rag/ |
| Vector database, embeddings |
vectors/ |
| Prompt engineering, templates |
prompting/ |
| Agents IA, tools, autonomie |
agents/ |
| Déployer, monitorer, fine-tuner |
mlops/ |
Par Mots-Clés
| Mots-clés |
Agent |
| GPT-4, OpenAI, chat completion |
llm/openai |
| Claude, Anthropic, Messages API |
llm/claude |
| Mistral, Le Chat, Codestral |
llm/mistral |
| Ollama, local, Llama |
llm/ollama |
| LangChain, LCEL, chains |
llm/langchain |
| RAG, retrieval, knowledge base |
rag/architecture |
| chunking, splitting, documents |
rag/chunking |
| pgvector, PostgreSQL, embedding |
vectors/pgvector |
| Pinecone, serverless, index |
vectors/pinecone |
| prompt, few-shot, chain-of-thought |
prompting/patterns |
| function calling, tools |
agents/tools |
| fine-tuning, LoRA, training |
mlops/fine-tuning |
| LangSmith, traces, monitoring |
mlops/monitoring |
Arbre de Décision
Requête AI Integration
│
├─ Intégrer une API LLM ?
│ ├─ OpenAI (GPT-4, DALL-E) → llm/openai
│ ├─ Anthropic (Claude) → llm/claude
│ ├─ Mistral → llm/mistral
│ ├─ Local (Ollama) → llm/ollama
│ └─ Framework (LangChain) → llm/langchain
│
├─ Enrichir le LLM avec mes données ?
│ ├─ Architecture globale → rag/architecture
│ ├─ Ingestion documents → rag/ingestion
│ ├─ Découpage → rag/chunking
│ ├─ Recherche → rag/retrieval
│ └─ Évaluation → rag/evaluation
│
├─ Stocker des embeddings ?
│ ├─ PostgreSQL existant → vectors/pgvector
│ ├─ Serverless → vectors/pinecone
│ ├─ Self-hosted → vectors/weaviate ou qdrant
│ └─ Générer embeddings → vectors/embeddings
│
├─ Optimiser les prompts ?
│ ├─ Techniques de prompting → prompting/patterns
│ ├─ Templates réutilisables → prompting/templates
│ ├─ Valider les outputs → prompting/guardrails
│ └─ Tester les prompts → prompting/testing
│
├─ Construire un agent autonome ?
│ ├─ Architecture → agents/architecture
│ ├─ Définir des tools → agents/tools
│ ├─ Gérer la mémoire → agents/memory
│ └─ Multi-agents → agents/multi-agent
│
└─ Déployer/monitorer ?
├─ Déployer un modèle → mlops/deployment
├─ Fine-tuner → mlops/fine-tuning
├─ Monitorer → mlops/monitoring
└─ Versionner → mlops/versioning
Interaction avec les Autres Skills
Flux Entrants
direction-technique ──► ai-integration (stratégie IA → implémentation)
web-dev-process ──► ai-integration (process → intégration)
Flux Sortants
ai-integration ──► backend-developer (APIs, services)
ai-integration ──► frontend-developer (UI chat, streaming)
ai-integration ──► devops (déploiement, infra)
Points d'Escalade
Vers direction-technique
| Situation |
Raison |
| Choix du provider LLM |
Coûts, compliance |
| Données sensibles dans le RAG |
Sécurité, RGPD |
| Budget API |
Validation financière |
Vers l'humain
| Situation |
Raison |
| Fine-tuning sur données métier |
Validation contenu |
| Prompts pour cas sensibles |
Éthique, légal |
| Évaluation qualité outputs |
Jugement métier |
Sécurité et Bonnes Pratiques
API Keys - Gestion des Secrets (CRITIQUE)
JAMAIS en code source. Toujours via secrets manager.
# .gitignore (OBLIGATOIRE)
.env
.env.*
!.env.example
*.pem
*credentials*.json
# .env.example (template sans valeurs)
OPENAI_API_KEY=sk-your-key-here
ANTHROPIC_API_KEY=sk-ant-your-key-here
# Ne JAMAIS committer de vraies clés
# pre-commit hook (.husky/pre-commit)
#!/bin/sh
# Detecter les secrets accidentels
if git diff --cached --name-only | xargs grep -l "sk-[a-zA-Z0-9]\{20,\}" 2>/dev/null; then
echo "ERROR: Potential API key detected in commit!"
echo "Remove secrets and use environment variables."
exit 1
fi
Production: Secrets Managers
// AWS Secrets Manager
import { SecretsManagerClient, GetSecretValueCommand } from '@aws-sdk/client-secrets-manager';
async function getApiKey(secretName: string): Promise<string> {
const client = new SecretsManagerClient({ region: 'eu-west-1' });
const response = await client.send(
new GetSecretValueCommand({ SecretId: secretName })
);
return JSON.parse(response.SecretString!).apiKey;
}
// Initialisation au demarrage
const OPENAI_API_KEY = await getApiKey('prod/openai-api-key');
// HashiCorp Vault
import Vault from 'node-vault';
const vault = Vault({
endpoint: process.env.VAULT_ADDR,
token: process.env.VAULT_TOKEN,
});
async function getSecret(path: string): Promise<string> {
const { data } = await vault.read(path);
return data.data.value;
}
const ANTHROPIC_API_KEY = await getSecret('secret/data/anthropic');
// Vercel/Next.js (Edge-safe)
// Les secrets sont injectes via le dashboard, pas en code
// Settings > Environment Variables > Add
// Validation au runtime
import { z } from 'zod';
const EnvSchema = z.object({
OPENAI_API_KEY: z.string().startsWith('sk-'),
ANTHROPIC_API_KEY: z.string().startsWith('sk-ant-'),
});
// Fail fast si secrets manquants
const env = EnvSchema.parse(process.env);
Rate Limiting
// Implémenter rate limiting côté client
import Bottleneck from 'bottleneck';
const limiter = new Bottleneck({
minTime: 100, // 10 req/sec
maxConcurrent: 5,
});
const rateLimitedCall = limiter.wrap(openai.chat.completions.create);
Prompt Injection Prevention
// Sanitize user input pour eviter les injections
function sanitizeUserInput(input: string): string {
if (!input || typeof input !== 'string') {
return '';
}
return input
// Limite la longueur
.slice(0, 10000)
// Supprime les caracteres de controle
.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g, '')
// Normalise les whitespaces
.replace(/\s+/g, ' ')
.trim();
}
// Detecter les tentatives d'injection
function detectInjectionAttempt(input: string): boolean {
const patterns = [
/ignore\s+(all\s+)?(previous|above|prior)/i,
/disregard\s+(all\s+)?(instructions|rules)/i,
/you\s+are\s+now/i,
/new\s+instructions?:/i,
/system\s*:/i,
/\[INST\]/i,
/<\|im_start\|>/i,
];
return patterns.some(p => p.test(input));
}
// Usage
const systemPrompt = `Tu es un assistant. Réponds uniquement aux questions sur les produits.`;
const rawInput = req.body.message;
const userInput = sanitizeUserInput(rawInput);
// Verifier les injections
if (detectInjectionAttempt(userInput)) {
logger.warn('Potential injection attempt', { input: userInput.slice(0, 100) });
return res.status(400).json({ error: 'Invalid input' });
}
const response = await openai.chat.completions.create({
model: 'gpt-4',
messages: [
{ role: 'system', content: systemPrompt },
{ role: 'user', content: userInput },
],
});
Coûts
// Estimer les coûts avant appel
function estimateCost(tokens: number, model: string): number {
const rates = {
'gpt-4': { input: 0.03, output: 0.06 },
'gpt-4o': { input: 0.005, output: 0.015 },
'gpt-4o-mini': { input: 0.00015, output: 0.0006 },
'claude-3-5-sonnet': { input: 0.003, output: 0.015 },
};
// ...
}
// Logger les coûts
logger.info('API call', { model, tokens, estimatedCost });
Skills Associés
| Skill |
Niveau |
Relation |
direction-technique |
STRATÉGIE |
Reçoit les directives IA |
backend-developer |
IMPLÉMENTATION |
APIs, services backend |
frontend-developer |
IMPLÉMENTATION |
UI, streaming |
devops |
IMPLÉMENTATION |
Déploiement, monitoring |
security-expert |
IMPLÉMENTATION |
Sécurité des données |
Changelog
v1.0.0
- Création initiale avec 6 domaines et 40 agents
- Couverture : LLMs, RAG, vectors, prompting, agents, MLOps
- Position : NIVEAU 3 IMPLÉMENTATION
1---2name: ai-integration3description: |-4 Expert intégration IA/ML dans applications web - LLMs, RAG, vector databases, embeddings. Utilise ce skill quand: (1) intégration API OpenAI/Claude/Mistral, (2) mise en place RAG, (3) vector databases, (4) prompt engineering, (5) fine-tuning, (6) ML ops et déploiement modèles.5metadata:6 version: 1.0.07 status: active8---910# AI Integration Expert Skill1112## Quick Start1314```bash15# 1. Navigation rapide vers un agent16ai-integration/agents/llm/openai # Intégration OpenAI API17ai-integration/agents/llm/claude # Intégration Claude API18ai-integration/agents/rag/architecture # Architecture RAG19ai-integration/agents/vectors/pgvector # PostgreSQL + pgvector20ai-integration/agents/prompting/patterns # Prompt engineering2122# 2. Questions fréquentes23"Comment intégrer l'API OpenAI ?" → llm/openai24"Mettre en place un RAG ?" → rag/architecture25"Quelle vector DB choisir ?" → vectors/orchestrator26"Optimiser mes prompts ?" → prompting/patterns27"Déployer un modèle ML ?" → mlops/deployment28```2930## Position dans l'Architecture3132Ce skill est au **NIVEAU 3 : IMPLÉMENTATION**. Il implémente les capacités IA dans les applications.3334```mermaid35flowchart TB36 subgraph N1["NIVEAU 1 : STRATÉGIE"]37 DT[direction-technique]38 end3940 subgraph N2["NIVEAU 2 : OPÉRATIONS"]41 WDP[web-dev-process]42 LD[lead-dev]43 end4445 subgraph N3["NIVEAU 3 : IMPLÉMENTATION"]46 AI[ai-integration]4748 subgraph DOMAINS["Domaines"]49 LLM[llm/]50 RAG[rag/]51 VEC[vectors/]52 PROMPT[prompting/]53 AGENTS[agents/]54 MLOPS[mlops/]55 end56 end5758 DT -->|stratégie IA| WDP59 DT -->|budget, providers| AI60 WDP -->|process| AI61 LD -->|coordination| AI62 AI --> DOMAINS6364 style N1 fill:#ffebee65 style N2 fill:#fff3e066 style N3 fill:#e8f5e967 style AI fill:#c8e6c9,stroke:#2e7d32,stroke-width:2px68```6970## Philosophie7172> Intégrer l'IA de manière pragmatique, sécurisée et maintenable.7374Ce skill :75- ✅ Intègre les APIs LLM (OpenAI, Claude, Mistral, etc.)76- ✅ Implémente les patterns RAG77- ✅ Configure les vector databases78- ✅ Optimise les prompts et outputs79- ✅ Déploie et monitore les modèles8081Il ne fait PAS :82- ❌ Les décisions stratégiques IA → `direction-technique`83- ❌ L'entraînement de modèles from scratch → ML spécialisé84- ❌ La recherche fondamentale → hors scope agence web8586## Domaines et Agents (40 agents)8788### 1. llm/ - Intégration LLMs (8 agents)8990APIs et SDKs des principaux LLMs.9192| Agent | Responsabilité | Technologies |93|-------|----------------|--------------|94| `orchestrator` | Coordination LLM | - |95| `openai` | OpenAI API | GPT-4, GPT-4o, Whisper, DALL-E |96| `claude` | Anthropic API | Claude 3.5, Claude 3 |97| `mistral` | Mistral AI | Mistral Large, Codestral |98| `ollama` | LLMs locaux | Llama 3, Mistral local |99| `langchain` | Framework LLM | LangChain.js, LCEL |100| `vercel-ai` | Vercel AI SDK | Streaming, Edge |101| `cost-optimization` | Optimisation coûts | Caching, batching, model selection |102103### 2. rag/ - Retrieval Augmented Generation (7 agents)104105Patterns RAG pour enrichir les LLMs avec vos données.106107| Agent | Responsabilité | Technologies |108|-------|----------------|--------------|109| `orchestrator` | Coordination RAG | - |110| `architecture` | Architecture RAG | Patterns, chunking strategies |111| `ingestion` | Pipeline d'ingestion | Document loaders, parsers |112| `chunking` | Stratégies de découpage | Semantic, recursive, sentence |113| `retrieval` | Stratégies de retrieval | Hybrid search, reranking |114| `evaluation` | Évaluation RAG | RAGAS, faithfulness, relevance |115| `advanced` | RAG avancé | HyDE, CRAG, Agentic RAG |116117### 3. vectors/ - Vector Databases (6 agents)118119Stockage et recherche de vecteurs.120121| Agent | Responsabilité | Technologies |122|-------|----------------|--------------|123| `orchestrator` | Coordination vectors | - |124| `pgvector` | PostgreSQL vectors | pgvector, indexing |125| `pinecone` | Pinecone | Serverless, namespaces |126| `weaviate` | Weaviate | Hybrid search, modules |127| `qdrant` | Qdrant | Filtering, payloads |128| `embeddings` | Génération embeddings | OpenAI, Cohere, local |129130### 4. prompting/ - Prompt Engineering (6 agents)131132Techniques d'optimisation des prompts.133134| Agent | Responsabilité | Technologies |135|-------|----------------|--------------|136| `orchestrator` | Coordination prompting | - |137| `patterns` | Patterns de prompts | Few-shot, CoT, ReAct |138| `templates` | Gestion templates | Langchain, Jinja |139| `output-parsing` | Parsing des outputs | Structured output, JSON mode |140| `guardrails` | Sécurité des outputs | Validation, filtering |141| `testing` | Test des prompts | Promptfoo, eval frameworks |142143### 5. agents/ - AI Agents (6 agents)144145Construction d'agents IA autonomes.146147| Agent | Responsabilité | Technologies |148|-------|----------------|--------------|149| `orchestrator` | Coordination agents | - |150| `architecture` | Architecture agents | ReAct, Plan-and-Execute |151| `tools` | Définition d'outils | Function calling, MCP |152| `memory` | Gestion mémoire | Short/long-term, summarization |153| `multi-agent` | Multi-agents | Orchestration, communication |154| `claude-computer-use` | Computer Use | Anthropic Computer Use API |155156### 6. mlops/ - ML Operations (7 agents)157158Déploiement et monitoring des modèles.159160| Agent | Responsabilité | Technologies |161|-------|----------------|--------------|162| `orchestrator` | Coordination MLOps | - |163| `deployment` | Déploiement modèles | HuggingFace, Replicate |164| `fine-tuning` | Fine-tuning | OpenAI, LoRA, QLoRA |165| `monitoring` | Monitoring IA | LangSmith, Helicone |166| `evaluation` | Évaluation modèles | Benchmarks, A/B testing |167| `versioning` | Versioning modèles | MLflow, DVC |168| `edge` | IA en edge | ONNX, TensorFlow Lite |169170**Total : 40 agents spécialisés**171172## Règles de Routage173174### Par Type de Question175176| Question | Domaine |177|----------|---------|178| Intégrer OpenAI, Claude, Mistral | `llm/` |179| RAG, enrichir avec mes données | `rag/` |180| Vector database, embeddings | `vectors/` |181| Prompt engineering, templates | `prompting/` |182| Agents IA, tools, autonomie | `agents/` |183| Déployer, monitorer, fine-tuner | `mlops/` |184185### Par Mots-Clés186187| Mots-clés | Agent |188|-----------|-------|189| GPT-4, OpenAI, chat completion | `llm/openai` |190| Claude, Anthropic, Messages API | `llm/claude` |191| Mistral, Le Chat, Codestral | `llm/mistral` |192| Ollama, local, Llama | `llm/ollama` |193| LangChain, LCEL, chains | `llm/langchain` |194| RAG, retrieval, knowledge base | `rag/architecture` |195| chunking, splitting, documents | `rag/chunking` |196| pgvector, PostgreSQL, embedding | `vectors/pgvector` |197| Pinecone, serverless, index | `vectors/pinecone` |198| prompt, few-shot, chain-of-thought | `prompting/patterns` |199| function calling, tools | `agents/tools` |200| fine-tuning, LoRA, training | `mlops/fine-tuning` |201| LangSmith, traces, monitoring | `mlops/monitoring` |202203## Arbre de Décision204205```206Requête AI Integration207│208├─ Intégrer une API LLM ?209│ ├─ OpenAI (GPT-4, DALL-E) → llm/openai210│ ├─ Anthropic (Claude) → llm/claude211│ ├─ Mistral → llm/mistral212│ ├─ Local (Ollama) → llm/ollama213│ └─ Framework (LangChain) → llm/langchain214│215├─ Enrichir le LLM avec mes données ?216│ ├─ Architecture globale → rag/architecture217│ ├─ Ingestion documents → rag/ingestion218│ ├─ Découpage → rag/chunking219│ ├─ Recherche → rag/retrieval220│ └─ Évaluation → rag/evaluation221│222├─ Stocker des embeddings ?223│ ├─ PostgreSQL existant → vectors/pgvector224│ ├─ Serverless → vectors/pinecone225│ ├─ Self-hosted → vectors/weaviate ou qdrant226│ └─ Générer embeddings → vectors/embeddings227│228├─ Optimiser les prompts ?229│ ├─ Techniques de prompting → prompting/patterns230│ ├─ Templates réutilisables → prompting/templates231│ ├─ Valider les outputs → prompting/guardrails232│ └─ Tester les prompts → prompting/testing233│234├─ Construire un agent autonome ?235│ ├─ Architecture → agents/architecture236│ ├─ Définir des tools → agents/tools237│ ├─ Gérer la mémoire → agents/memory238│ └─ Multi-agents → agents/multi-agent239│240└─ Déployer/monitorer ?241 ├─ Déployer un modèle → mlops/deployment242 ├─ Fine-tuner → mlops/fine-tuning243 ├─ Monitorer → mlops/monitoring244 └─ Versionner → mlops/versioning245```246247## Interaction avec les Autres Skills248249### Flux Entrants250251```252direction-technique ──► ai-integration (stratégie IA → implémentation)253web-dev-process ──► ai-integration (process → intégration)254```255256### Flux Sortants257258```259ai-integration ──► backend-developer (APIs, services)260ai-integration ──► frontend-developer (UI chat, streaming)261ai-integration ──► devops (déploiement, infra)262```263264## Points d'Escalade265266### Vers direction-technique267268| Situation | Raison |269|-----------|--------|270| Choix du provider LLM | Coûts, compliance |271| Données sensibles dans le RAG | Sécurité, RGPD |272| Budget API | Validation financière |273274### Vers l'humain275276| Situation | Raison |277|-----------|--------|278| Fine-tuning sur données métier | Validation contenu |279| Prompts pour cas sensibles | Éthique, légal |280| Évaluation qualité outputs | Jugement métier |281282## Sécurité et Bonnes Pratiques283284### API Keys - Gestion des Secrets (CRITIQUE)285286**JAMAIS en code source. Toujours via secrets manager.**287288```bash289# .gitignore (OBLIGATOIRE)290.env291.env.*292!.env.example293*.pem294*credentials*.json295```296297```bash298# .env.example (template sans valeurs)299OPENAI_API_KEY=sk-your-key-here300ANTHROPIC_API_KEY=sk-ant-your-key-here301# Ne JAMAIS committer de vraies clés302```303304```bash305# pre-commit hook (.husky/pre-commit)306#!/bin/sh307# Detecter les secrets accidentels308if git diff --cached --name-only | xargs grep -l "sk-[a-zA-Z0-9]\{20,\}" 2>/dev/null; then309 echo "ERROR: Potential API key detected in commit!"310 echo "Remove secrets and use environment variables."311 exit 1312fi313```314315#### Production: Secrets Managers316317```typescript318// AWS Secrets Manager319import { SecretsManagerClient, GetSecretValueCommand } from '@aws-sdk/client-secrets-manager';320321async function getApiKey(secretName: string): Promise<string> {322 const client = new SecretsManagerClient({ region: 'eu-west-1' });323 const response = await client.send(324 new GetSecretValueCommand({ SecretId: secretName })325 );326 return JSON.parse(response.SecretString!).apiKey;327}328329// Initialisation au demarrage330const OPENAI_API_KEY = await getApiKey('prod/openai-api-key');331```332333```typescript334// HashiCorp Vault335import Vault from 'node-vault';336337const vault = Vault({338 endpoint: process.env.VAULT_ADDR,339 token: process.env.VAULT_TOKEN,340});341342async function getSecret(path: string): Promise<string> {343 const { data } = await vault.read(path);344 return data.data.value;345}346347const ANTHROPIC_API_KEY = await getSecret('secret/data/anthropic');348```349350```typescript351// Vercel/Next.js (Edge-safe)352// Les secrets sont injectes via le dashboard, pas en code353// Settings > Environment Variables > Add354355// Validation au runtime356import { z } from 'zod';357358const EnvSchema = z.object({359 OPENAI_API_KEY: z.string().startsWith('sk-'),360 ANTHROPIC_API_KEY: z.string().startsWith('sk-ant-'),361});362363// Fail fast si secrets manquants364const env = EnvSchema.parse(process.env);365```366367### Rate Limiting368369```typescript370// Implémenter rate limiting côté client371import Bottleneck from 'bottleneck';372373const limiter = new Bottleneck({374 minTime: 100, // 10 req/sec375 maxConcurrent: 5,376});377378const rateLimitedCall = limiter.wrap(openai.chat.completions.create);379```380381### Prompt Injection Prevention382383```typescript384// Sanitize user input pour eviter les injections385function sanitizeUserInput(input: string): string {386 if (!input || typeof input !== 'string') {387 return '';388 }389390 return input391 // Limite la longueur392 .slice(0, 10000)393 // Supprime les caracteres de controle394 .replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g, '')395 // Normalise les whitespaces396 .replace(/\s+/g, ' ')397 .trim();398}399400// Detecter les tentatives d'injection401function detectInjectionAttempt(input: string): boolean {402 const patterns = [403 /ignore\s+(all\s+)?(previous|above|prior)/i,404 /disregard\s+(all\s+)?(instructions|rules)/i,405 /you\s+are\s+now/i,406 /new\s+instructions?:/i,407 /system\s*:/i,408 /\[INST\]/i,409 /<\|im_start\|>/i,410 ];411 return patterns.some(p => p.test(input));412}413414// Usage415const systemPrompt = `Tu es un assistant. Réponds uniquement aux questions sur les produits.`;416const rawInput = req.body.message;417const userInput = sanitizeUserInput(rawInput);418419// Verifier les injections420if (detectInjectionAttempt(userInput)) {421 logger.warn('Potential injection attempt', { input: userInput.slice(0, 100) });422 return res.status(400).json({ error: 'Invalid input' });423}424425const response = await openai.chat.completions.create({426 model: 'gpt-4',427 messages: [428 { role: 'system', content: systemPrompt },429 { role: 'user', content: userInput },430 ],431});432```433434### Coûts435436```typescript437// Estimer les coûts avant appel438function estimateCost(tokens: number, model: string): number {439 const rates = {440 'gpt-4': { input: 0.03, output: 0.06 },441 'gpt-4o': { input: 0.005, output: 0.015 },442 'gpt-4o-mini': { input: 0.00015, output: 0.0006 },443 'claude-3-5-sonnet': { input: 0.003, output: 0.015 },444 };445 // ...446}447448// Logger les coûts449logger.info('API call', { model, tokens, estimatedCost });450```451452## Skills Associés453454| Skill | Niveau | Relation |455|-------|--------|----------|456| `direction-technique` | STRATÉGIE | Reçoit les directives IA |457| `backend-developer` | IMPLÉMENTATION | APIs, services backend |458| `frontend-developer` | IMPLÉMENTATION | UI, streaming |459| `devops` | IMPLÉMENTATION | Déploiement, monitoring |460| `security-expert` | IMPLÉMENTATION | Sécurité des données |461462## Changelog463464### v1.0.0465- Création initiale avec 6 domaines et 40 agents466- Couverture : LLMs, RAG, vectors, prompting, agents, MLOps467- Position : NIVEAU 3 IMPLÉMENTATION