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: 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.4---56# AI Integration Expert Skill78## Quick Start910```bash11# 1. Navigation rapide vers un agent12ai-integration/agents/llm/openai # Intégration OpenAI API13ai-integration/agents/llm/claude # Intégration Claude API14ai-integration/agents/rag/architecture # Architecture RAG15ai-integration/agents/vectors/pgvector # PostgreSQL + pgvector16ai-integration/agents/prompting/patterns # Prompt engineering1718# 2. Questions fréquentes19"Comment intégrer l'API OpenAI ?" → llm/openai20"Mettre en place un RAG ?" → rag/architecture21"Quelle vector DB choisir ?" → vectors/orchestrator22"Optimiser mes prompts ?" → prompting/patterns23"Déployer un modèle ML ?" → mlops/deployment24```2526## Position dans l'Architecture2728Ce skill est au **NIVEAU 3 : IMPLÉMENTATION**. Il implémente les capacités IA dans les applications.2930```mermaid31flowchart TB32 subgraph N1["NIVEAU 1 : STRATÉGIE"]33 DT[direction-technique]34 end3536 subgraph N2["NIVEAU 2 : OPÉRATIONS"]37 WDP[web-dev-process]38 LD[lead-dev]39 end4041 subgraph N3["NIVEAU 3 : IMPLÉMENTATION"]42 AI[ai-integration]4344 subgraph DOMAINS["Domaines"]45 LLM[llm/]46 RAG[rag/]47 VEC[vectors/]48 PROMPT[prompting/]49 AGENTS[agents/]50 MLOPS[mlops/]51 end52 end5354 DT -->|stratégie IA| WDP55 DT -->|budget, providers| AI56 WDP -->|process| AI57 LD -->|coordination| AI58 AI --> DOMAINS5960 style N1 fill:#ffebee61 style N2 fill:#fff3e062 style N3 fill:#e8f5e963 style AI fill:#c8e6c9,stroke:#2e7d32,stroke-width:2px64```6566## Philosophie6768> Intégrer l'IA de manière pragmatique, sécurisée et maintenable.6970Ce skill :71- ✅ Intègre les APIs LLM (OpenAI, Claude, Mistral, etc.)72- ✅ Implémente les patterns RAG73- ✅ Configure les vector databases74- ✅ Optimise les prompts et outputs75- ✅ Déploie et monitore les modèles7677Il ne fait PAS :78- ❌ Les décisions stratégiques IA → `direction-technique`79- ❌ L'entraînement de modèles from scratch → ML spécialisé80- ❌ La recherche fondamentale → hors scope agence web8182## Domaines et Agents (40 agents)8384### 1. llm/ - Intégration LLMs (8 agents)8586APIs et SDKs des principaux LLMs.8788| Agent | Responsabilité | Technologies |89|-------|----------------|--------------|90| `orchestrator` | Coordination LLM | - |91| `openai` | OpenAI API | GPT-4, GPT-4o, Whisper, DALL-E |92| `claude` | Anthropic API | Claude 3.5, Claude 3 |93| `mistral` | Mistral AI | Mistral Large, Codestral |94| `ollama` | LLMs locaux | Llama 3, Mistral local |95| `langchain` | Framework LLM | LangChain.js, LCEL |96| `vercel-ai` | Vercel AI SDK | Streaming, Edge |97| `cost-optimization` | Optimisation coûts | Caching, batching, model selection |9899### 2. rag/ - Retrieval Augmented Generation (7 agents)100101Patterns RAG pour enrichir les LLMs avec vos données.102103| Agent | Responsabilité | Technologies |104|-------|----------------|--------------|105| `orchestrator` | Coordination RAG | - |106| `architecture` | Architecture RAG | Patterns, chunking strategies |107| `ingestion` | Pipeline d'ingestion | Document loaders, parsers |108| `chunking` | Stratégies de découpage | Semantic, recursive, sentence |109| `retrieval` | Stratégies de retrieval | Hybrid search, reranking |110| `evaluation` | Évaluation RAG | RAGAS, faithfulness, relevance |111| `advanced` | RAG avancé | HyDE, CRAG, Agentic RAG |112113### 3. vectors/ - Vector Databases (6 agents)114115Stockage et recherche de vecteurs.116117| Agent | Responsabilité | Technologies |118|-------|----------------|--------------|119| `orchestrator` | Coordination vectors | - |120| `pgvector` | PostgreSQL vectors | pgvector, indexing |121| `pinecone` | Pinecone | Serverless, namespaces |122| `weaviate` | Weaviate | Hybrid search, modules |123| `qdrant` | Qdrant | Filtering, payloads |124| `embeddings` | Génération embeddings | OpenAI, Cohere, local |125126### 4. prompting/ - Prompt Engineering (6 agents)127128Techniques d'optimisation des prompts.129130| Agent | Responsabilité | Technologies |131|-------|----------------|--------------|132| `orchestrator` | Coordination prompting | - |133| `patterns` | Patterns de prompts | Few-shot, CoT, ReAct |134| `templates` | Gestion templates | Langchain, Jinja |135| `output-parsing` | Parsing des outputs | Structured output, JSON mode |136| `guardrails` | Sécurité des outputs | Validation, filtering |137| `testing` | Test des prompts | Promptfoo, eval frameworks |138139### 5. agents/ - AI Agents (6 agents)140141Construction d'agents IA autonomes.142143| Agent | Responsabilité | Technologies |144|-------|----------------|--------------|145| `orchestrator` | Coordination agents | - |146| `architecture` | Architecture agents | ReAct, Plan-and-Execute |147| `tools` | Définition d'outils | Function calling, MCP |148| `memory` | Gestion mémoire | Short/long-term, summarization |149| `multi-agent` | Multi-agents | Orchestration, communication |150| `claude-computer-use` | Computer Use | Anthropic Computer Use API |151152### 6. mlops/ - ML Operations (7 agents)153154Déploiement et monitoring des modèles.155156| Agent | Responsabilité | Technologies |157|-------|----------------|--------------|158| `orchestrator` | Coordination MLOps | - |159| `deployment` | Déploiement modèles | HuggingFace, Replicate |160| `fine-tuning` | Fine-tuning | OpenAI, LoRA, QLoRA |161| `monitoring` | Monitoring IA | LangSmith, Helicone |162| `evaluation` | Évaluation modèles | Benchmarks, A/B testing |163| `versioning` | Versioning modèles | MLflow, DVC |164| `edge` | IA en edge | ONNX, TensorFlow Lite |165166**Total : 40 agents spécialisés**167168## Règles de Routage169170### Par Type de Question171172| Question | Domaine |173|----------|---------|174| Intégrer OpenAI, Claude, Mistral | `llm/` |175| RAG, enrichir avec mes données | `rag/` |176| Vector database, embeddings | `vectors/` |177| Prompt engineering, templates | `prompting/` |178| Agents IA, tools, autonomie | `agents/` |179| Déployer, monitorer, fine-tuner | `mlops/` |180181### Par Mots-Clés182183| Mots-clés | Agent |184|-----------|-------|185| GPT-4, OpenAI, chat completion | `llm/openai` |186| Claude, Anthropic, Messages API | `llm/claude` |187| Mistral, Le Chat, Codestral | `llm/mistral` |188| Ollama, local, Llama | `llm/ollama` |189| LangChain, LCEL, chains | `llm/langchain` |190| RAG, retrieval, knowledge base | `rag/architecture` |191| chunking, splitting, documents | `rag/chunking` |192| pgvector, PostgreSQL, embedding | `vectors/pgvector` |193| Pinecone, serverless, index | `vectors/pinecone` |194| prompt, few-shot, chain-of-thought | `prompting/patterns` |195| function calling, tools | `agents/tools` |196| fine-tuning, LoRA, training | `mlops/fine-tuning` |197| LangSmith, traces, monitoring | `mlops/monitoring` |198199## Arbre de Décision200201```202Requête AI Integration203│204├─ Intégrer une API LLM ?205│ ├─ OpenAI (GPT-4, DALL-E) → llm/openai206│ ├─ Anthropic (Claude) → llm/claude207│ ├─ Mistral → llm/mistral208│ ├─ Local (Ollama) → llm/ollama209│ └─ Framework (LangChain) → llm/langchain210│211├─ Enrichir le LLM avec mes données ?212│ ├─ Architecture globale → rag/architecture213│ ├─ Ingestion documents → rag/ingestion214│ ├─ Découpage → rag/chunking215│ ├─ Recherche → rag/retrieval216│ └─ Évaluation → rag/evaluation217│218├─ Stocker des embeddings ?219│ ├─ PostgreSQL existant → vectors/pgvector220│ ├─ Serverless → vectors/pinecone221│ ├─ Self-hosted → vectors/weaviate ou qdrant222│ └─ Générer embeddings → vectors/embeddings223│224├─ Optimiser les prompts ?225│ ├─ Techniques de prompting → prompting/patterns226│ ├─ Templates réutilisables → prompting/templates227│ ├─ Valider les outputs → prompting/guardrails228│ └─ Tester les prompts → prompting/testing229│230├─ Construire un agent autonome ?231│ ├─ Architecture → agents/architecture232│ ├─ Définir des tools → agents/tools233│ ├─ Gérer la mémoire → agents/memory234│ └─ Multi-agents → agents/multi-agent235│236└─ Déployer/monitorer ?237 ├─ Déployer un modèle → mlops/deployment238 ├─ Fine-tuner → mlops/fine-tuning239 ├─ Monitorer → mlops/monitoring240 └─ Versionner → mlops/versioning241```242243## Interaction avec les Autres Skills244245### Flux Entrants246247```248direction-technique ──► ai-integration (stratégie IA → implémentation)249web-dev-process ──► ai-integration (process → intégration)250```251252### Flux Sortants253254```255ai-integration ──► backend-developer (APIs, services)256ai-integration ──► frontend-developer (UI chat, streaming)257ai-integration ──► devops (déploiement, infra)258```259260## Points d'Escalade261262### Vers direction-technique263264| Situation | Raison |265|-----------|--------|266| Choix du provider LLM | Coûts, compliance |267| Données sensibles dans le RAG | Sécurité, RGPD |268| Budget API | Validation financière |269270### Vers l'humain271272| Situation | Raison |273|-----------|--------|274| Fine-tuning sur données métier | Validation contenu |275| Prompts pour cas sensibles | Éthique, légal |276| Évaluation qualité outputs | Jugement métier |277278## Sécurité et Bonnes Pratiques279280### API Keys - Gestion des Secrets (CRITIQUE)281282**JAMAIS en code source. Toujours via secrets manager.**283284```bash285# .gitignore (OBLIGATOIRE)286.env287.env.*288!.env.example289*.pem290*credentials*.json291```292293```bash294# .env.example (template sans valeurs)295OPENAI_API_KEY=sk-your-key-here296ANTHROPIC_API_KEY=sk-ant-your-key-here297# Ne JAMAIS committer de vraies clés298```299300```bash301# pre-commit hook (.husky/pre-commit)302#!/bin/sh303# Detecter les secrets accidentels304if git diff --cached --name-only | xargs grep -l "sk-[a-zA-Z0-9]\{20,\}" 2>/dev/null; then305 echo "ERROR: Potential API key detected in commit!"306 echo "Remove secrets and use environment variables."307 exit 1308fi309```310311#### Production: Secrets Managers312313```typescript314// AWS Secrets Manager315import { SecretsManagerClient, GetSecretValueCommand } from '@aws-sdk/client-secrets-manager';316317async function getApiKey(secretName: string): Promise<string> {318 const client = new SecretsManagerClient({ region: 'eu-west-1' });319 const response = await client.send(320 new GetSecretValueCommand({ SecretId: secretName })321 );322 return JSON.parse(response.SecretString!).apiKey;323}324325// Initialisation au demarrage326const OPENAI_API_KEY = await getApiKey('prod/openai-api-key');327```328329```typescript330// HashiCorp Vault331import Vault from 'node-vault';332333const vault = Vault({334 endpoint: process.env.VAULT_ADDR,335 token: process.env.VAULT_TOKEN,336});337338async function getSecret(path: string): Promise<string> {339 const { data } = await vault.read(path);340 return data.data.value;341}342343const ANTHROPIC_API_KEY = await getSecret('secret/data/anthropic');344```345346```typescript347// Vercel/Next.js (Edge-safe)348// Les secrets sont injectes via le dashboard, pas en code349// Settings > Environment Variables > Add350351// Validation au runtime352import { z } from 'zod';353354const EnvSchema = z.object({355 OPENAI_API_KEY: z.string().startsWith('sk-'),356 ANTHROPIC_API_KEY: z.string().startsWith('sk-ant-'),357});358359// Fail fast si secrets manquants360const env = EnvSchema.parse(process.env);361```362363### Rate Limiting364365```typescript366// Implémenter rate limiting côté client367import Bottleneck from 'bottleneck';368369const limiter = new Bottleneck({370 minTime: 100, // 10 req/sec371 maxConcurrent: 5,372});373374const rateLimitedCall = limiter.wrap(openai.chat.completions.create);375```376377### Prompt Injection Prevention378379```typescript380// Sanitize user input pour eviter les injections381function sanitizeUserInput(input: string): string {382 if (!input || typeof input !== 'string') {383 return '';384 }385386 return input387 // Limite la longueur388 .slice(0, 10000)389 // Supprime les caracteres de controle390 .replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g, '')391 // Normalise les whitespaces392 .replace(/\s+/g, ' ')393 .trim();394}395396// Detecter les tentatives d'injection397function detectInjectionAttempt(input: string): boolean {398 const patterns = [399 /ignore\s+(all\s+)?(previous|above|prior)/i,400 /disregard\s+(all\s+)?(instructions|rules)/i,401 /you\s+are\s+now/i,402 /new\s+instructions?:/i,403 /system\s*:/i,404 /\[INST\]/i,405 /<\|im_start\|>/i,406 ];407 return patterns.some(p => p.test(input));408}409410// Usage411const systemPrompt = `Tu es un assistant. Réponds uniquement aux questions sur les produits.`;412const rawInput = req.body.message;413const userInput = sanitizeUserInput(rawInput);414415// Verifier les injections416if (detectInjectionAttempt(userInput)) {417 logger.warn('Potential injection attempt', { input: userInput.slice(0, 100) });418 return res.status(400).json({ error: 'Invalid input' });419}420421const response = await openai.chat.completions.create({422 model: 'gpt-4',423 messages: [424 { role: 'system', content: systemPrompt },425 { role: 'user', content: userInput },426 ],427});428```429430### Coûts431432```typescript433// Estimer les coûts avant appel434function estimateCost(tokens: number, model: string): number {435 const rates = {436 'gpt-4': { input: 0.03, output: 0.06 },437 'gpt-4o': { input: 0.005, output: 0.015 },438 'gpt-4o-mini': { input: 0.00015, output: 0.0006 },439 'claude-3-5-sonnet': { input: 0.003, output: 0.015 },440 };441 // ...442}443444// Logger les coûts445logger.info('API call', { model, tokens, estimatedCost });446```447448## Skills Associés449450| Skill | Niveau | Relation |451|-------|--------|----------|452| `direction-technique` | STRATÉGIE | Reçoit les directives IA |453| `backend-developer` | IMPLÉMENTATION | APIs, services backend |454| `frontend-developer` | IMPLÉMENTATION | UI, streaming |455| `devops` | IMPLÉMENTATION | Déploiement, monitoring |456| `security-expert` | IMPLÉMENTATION | Sécurité des données |457458## Changelog459460### v1.0.0461- Création initiale avec 6 domaines et 40 agents462- Couverture : LLMs, RAG, vectors, prompting, agents, MLOps463- Position : NIVEAU 3 IMPLÉMENTATION