@aigis-ai/cli 1.0.3 → 2.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/CONTRIBUTING.md +53 -0
  2. package/README.md +58 -188
  3. package/SKILL.md +20 -55
  4. package/aigis-ai-cli-2.0.1.tgz +0 -0
  5. package/bin/aigis.js +446 -59
  6. package/content/index/audit-scan.md +21 -207
  7. package/content/index/auto-verify-rules.json +439 -0
  8. package/content/index/context-rules.json +90 -0
  9. package/content/resolvers/triggers.json +229 -0
  10. package/content/{implement → skills/areas}/audit-logging.md +5 -0
  11. package/content/skills/areas/fallback-patterns.md +200 -0
  12. package/content/skills/areas/input-validation.md +380 -0
  13. package/content/skills/areas/pii-handling.md +189 -0
  14. package/content/skills/areas/rate-limiting.md +246 -0
  15. package/content/skills/core.md +62 -0
  16. package/content/skills/infrastructure/logging.md +202 -0
  17. package/content/skills/infrastructure/rate-limiting.md +169 -0
  18. package/content/skills/infrastructure/secrets.md +167 -0
  19. package/content/skills/workflows/fastapi-llm.md +86 -0
  20. package/docs/resolvers.md +114 -0
  21. package/lib/auto-verify.js +378 -0
  22. package/lib/build.js +629 -0
  23. package/lib/checksum.js +39 -0
  24. package/lib/fetch.js +164 -9
  25. package/lib/init.js +141 -93
  26. package/lib/keywords.js +92 -130
  27. package/lib/special-recognizers.js +370 -0
  28. package/package.json +1 -1
  29. package/scripts/baseline-cursorrules.snapshot.txt +30 -0
  30. package/scripts/bootstrap-step-6-bench.js +85 -0
  31. package/scripts/check-content-sync.js +91 -0
  32. package/scripts/triggers.schema.json +50 -0
  33. package/scripts/validate-triggers.js +176 -0
  34. package/content/implement/fallback-patterns.md +0 -190
  35. package/content/implement/input-validation.md +0 -212
  36. package/content/implement/pii-handling.md +0 -207
  37. package/content/implement/rate-limiting.md +0 -217
  38. /package/content/{implement → skills/areas}/bias-monitoring.md +0 -0
  39. /package/content/{implement → skills/areas}/confidence-scoring.md +0 -0
  40. /package/content/{implement → skills/areas}/data-integrity.md +0 -0
  41. /package/content/{implement → skills/areas}/explainability.md +0 -0
  42. /package/content/{implement → skills/areas}/human-oversight.md +0 -0
  43. /package/content/{implement → skills/areas}/monitoring.md +0 -0
  44. /package/content/{implement → skills/areas}/output-sanitization.md +0 -0
  45. /package/content/{implement → skills/areas}/prompt-security.md +0 -0
  46. /package/content/{implement → skills/areas}/rag-security.md +0 -0
  47. /package/content/{implement → skills/areas}/supply-chain.md +0 -0
@@ -1,212 +0,0 @@
1
- ---
2
- id: input-validation
3
- title: Input validation and sanitization
4
- controls:
5
- owasp: [LLM01]
6
- nist: [MEASURE-2.7, MANAGE-1.3]
7
- iso42001: [Clause-8.2, Annex-A.6]
8
- min_risk_tier: all
9
- system_traits: [uses-llm, accepts-user-input]
10
- ---
11
-
12
- ## What this addresses
13
-
14
- Prompt injection is the #1 security risk for LLM applications (OWASP LLM01:2025). Attackers manipulate inputs to override system instructions, extract sensitive data, or trigger unintended behavior. Two vectors: direct injection (malicious user input) and indirect injection (malicious content in documents or data the LLM processes).
15
-
16
- ## Implementation patterns
17
-
18
- ### Pattern 1: Input length enforcement
19
-
20
- ```python
21
- MAX_INPUT_LENGTH = 4000 # characters
22
- MAX_INPUT_TOKENS = 1000 # tokens
23
-
24
- def validate_input_length(user_input: str) -> str:
25
- if len(user_input) > MAX_INPUT_LENGTH:
26
- raise ValueError(f"Input exceeds {MAX_INPUT_LENGTH} characters")
27
- token_count = len(tokenizer.encode(user_input))
28
- if token_count > MAX_INPUT_TOKENS:
29
- raise ValueError(f"Input exceeds {MAX_INPUT_TOKENS} tokens")
30
- return user_input
31
- ```
32
-
33
- ```javascript
34
- const MAX_INPUT_LENGTH = 4000;
35
- const MAX_INPUT_TOKENS = 1000;
36
-
37
- function validateInputLength(userInput) {
38
- if (userInput.length > MAX_INPUT_LENGTH)
39
- throw new Error(`Input exceeds ${MAX_INPUT_LENGTH} characters`);
40
- const tokenCount = tokenizer.encode(userInput).length;
41
- if (tokenCount > MAX_INPUT_TOKENS)
42
- throw new Error(`Input exceeds ${MAX_INPUT_TOKENS} tokens`);
43
- return userInput;
44
- }
45
- ```
46
-
47
- ### Pattern 2: System/user prompt separation
48
-
49
- Never concatenate user input into the system prompt. Use the API's native role separation.
50
-
51
- ```python
52
- # CORRECT
53
- messages = [
54
- {"role": "system", "content": SYSTEM_PROMPT},
55
- {"role": "user", "content": sanitize_input(user_input)}
56
- ]
57
-
58
- # WRONG - never do this
59
- prompt = SYSTEM_PROMPT + "\nUser says: " + user_input
60
- ```
61
-
62
- ```javascript
63
- // CORRECT
64
- const messages = [
65
- { role: 'system', content: SYSTEM_PROMPT },
66
- { role: 'user', content: sanitizeInput(userInput) }
67
- ];
68
-
69
- // WRONG - never do this
70
- // const prompt = SYSTEM_PROMPT + '\nUser says: ' + userInput;
71
- ```
72
-
73
-
74
- ### Pattern 3: Character and encoding sanitization
75
-
76
- ```python
77
- import unicodedata, re
78
-
79
- DANGEROUS_CHARS = re.compile(
80
- '[\x00-\x08\x0b\x0c\x0e-\x1f'
81
- '\u200b-\u200f'
82
- '\u202a-\u202e'
83
- '\u2060-\u2064'
84
- '\ufeff]'
85
- )
86
-
87
- def sanitize_input(raw_input: str) -> str:
88
- cleaned = DANGEROUS_CHARS.sub('', raw_input)
89
- cleaned = unicodedata.normalize('NFC', cleaned)
90
- return cleaned.strip()
91
- ```
92
-
93
- ```javascript
94
- const DANGEROUS_CHARS = /[\x00-\x08\x0b\x0c\x0e-\x1f\u200b-\u200f\u202a-\u202e\u2060-\u2064\ufeff]/g;
95
-
96
- function sanitizeInput(rawInput) {
97
- let cleaned = rawInput.replace(DANGEROUS_CHARS, '');
98
- cleaned = cleaned.normalize('NFC');
99
- return cleaned.trim();
100
- }
101
- ```
102
-
103
-
104
- ### Pattern 4: Output schema enforcement
105
-
106
- ```python
107
- from pydantic import BaseModel, Field
108
- from enum import Enum
109
-
110
- class Recommendation(str, Enum):
111
- FAST_TRACK = "fast-track"
112
- STANDARD = "standard"
113
- ESCALATE = "escalate"
114
-
115
- class AssessmentOutput(BaseModel):
116
- severity_score: int = Field(ge=1, le=10)
117
- recommendation: Recommendation
118
- confidence: float = Field(ge=0.0, le=1.0)
119
-
120
- def validate_llm_output(raw_response: str) -> AssessmentOutput:
121
- try:
122
- return AssessmentOutput(**json.loads(raw_response))
123
- except (json.JSONDecodeError, ValidationError) as e:
124
- log_anomaly("output_schema_violation", raw_response, str(e))
125
- return default_safe_response() # See fallback-patterns.md Pattern 1 (default safe response) for the fallback value
126
- ```
127
-
128
- ```javascript
129
- const Ajv = require('ajv');
130
- const ajv = new Ajv();
131
-
132
- const outputSchema = {
133
- type: 'object',
134
- properties: {
135
- severity_score: { type: 'integer', minimum: 1, maximum: 10 },
136
- recommendation: { type: 'string', enum: ['fast-track', 'standard', 'escalate'] },
137
- confidence: { type: 'number', minimum: 0, maximum: 1 }
138
- },
139
- required: ['severity_score', 'recommendation', 'confidence'],
140
- additionalProperties: false
141
- };
142
- const validate = ajv.compile(outputSchema);
143
-
144
- function validateLlmOutput(rawResponse) {
145
- try {
146
- const parsed = JSON.parse(rawResponse);
147
- if (!validate(parsed)) {
148
- logAnomaly('output_schema_violation', rawResponse, validate.errors);
149
- return defaultSafeResponse(); // See fallback-patterns.md Pattern 1
150
- }
151
- return parsed;
152
- } catch (e) {
153
- logAnomaly('output_parse_failure', rawResponse, e.message);
154
- return defaultSafeResponse();
155
- }
156
- }
157
- ```
158
-
159
-
160
- ### Pattern 5: Injection pattern detection (defense in depth)
161
-
162
- ```python
163
- SUSPICIOUS_PATTERNS = [
164
- "ignore previous instructions", "ignore all prior",
165
- "you are now", "system prompt", "reveal your instructions",
166
- "act as", "pretend you are", "do not follow",
167
- "disregard", "new instructions:",
168
- ]
169
-
170
- def check_injection_patterns(user_input: str) -> dict:
171
- input_lower = user_input.lower()
172
- for pattern in SUSPICIOUS_PATTERNS:
173
- if pattern in input_lower:
174
- log_security_event("injection_pattern_detected", pattern=pattern)
175
- return {"flagged": True, "pattern": pattern}
176
- return {"flagged": False}
177
- ```
178
-
179
- ```javascript
180
- const SUSPICIOUS_PATTERNS = [
181
- 'ignore previous instructions', 'ignore all prior',
182
- 'you are now', 'system prompt', 'reveal your instructions',
183
- 'act as', 'pretend you are', 'do not follow',
184
- 'disregard', 'new instructions:',
185
- ];
186
-
187
- function checkInjectionPatterns(userInput) {
188
- const inputLower = userInput.toLowerCase();
189
- for (const pattern of SUSPICIOUS_PATTERNS) {
190
- if (inputLower.includes(pattern)) {
191
- logSecurityEvent('injection_pattern_detected', { pattern });
192
- return { flagged: true, pattern };
193
- }
194
- }
195
- return { flagged: false };
196
- }
197
- ```
198
-
199
-
200
- ## Anti-patterns
201
-
202
- - **String concatenation for prompts.** Never use f-strings or template literals to build prompts.
203
- - **Client-side-only validation.** Validation must happen server-side.
204
- - **Blocklist-only approach.** Blocklists are defense-in-depth, not primary controls.
205
- - **Silent truncation.** Return an error on length violations; truncation changes meaning.
206
-
207
- ## Edge cases
208
-
209
- - **Indirect injection via documents.** Apply same sanitization to extracted document text.
210
- - **Multi-turn conversations.** Cumulative length limits on conversation context.
211
- - **Multimodal inputs.** Images may contain text visible to vision models.
212
- - **Tool/function calling.** Combine with human-oversight.md for tool-using systems.
@@ -1,207 +0,0 @@
1
- ---
2
- id: pii-handling
3
- title: PII and sensitive data protection
4
- controls:
5
- owasp: [LLM02]
6
- nist: [MAP-2.1, MEASURE-2.10]
7
- iso42001: [Annex-A.7, Annex-A.4]
8
- min_risk_tier: all
9
- system_traits: [processes-pii, handles-financial, handles-health, handles-proprietary, handles-minors]
10
- ---
11
-
12
- ## What this addresses
13
-
14
- LLMs can memorize and regurgitate training data, echo PII from context windows, and leak sensitive information through creative prompting. OWASP LLM02 covers sensitive information disclosure — the risk that your system inadvertently reveals personal data, financial records, health information, or proprietary content.
15
-
16
- ## Implementation patterns
17
-
18
- ### Pattern 1: PII detection and redaction before LLM call
19
-
20
- ```python
21
- import re
22
-
23
- PII_PATTERNS = {
24
- "ssn": re.compile(r'\b\d{3}-\d{2}-\d{4}\b'),
25
- "email": re.compile(r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b'),
26
- "phone": re.compile(r'\b(?:\+1[-.]?)?\(?\d{3}\)?[-.]?\d{3}[-.]?\d{4}\b'),
27
- "credit_card": re.compile(r'\b(?:\d{4}[-\s]?){3}\d{4}\b'),
28
- "dob": re.compile(r'\b(?:0[1-9]|1[0-2])/(?:0[1-9]|[12]\d|3[01])/(?:19|20)\d{2}\b'),
29
- }
30
-
31
- def redact_pii(text: str) -> tuple[str, dict]:
32
- """Returns (redacted_text, redaction_map) for potential restoration."""
33
- redaction_map = {}
34
- for pii_type, pattern in PII_PATTERNS.items():
35
- for i, match in enumerate(pattern.finditer(text)):
36
- placeholder = f"[{pii_type.upper()}_{i}]"
37
- redaction_map[placeholder] = match.group()
38
- text = text.replace(match.group(), placeholder, 1)
39
- return text, redaction_map
40
- ```
41
-
42
- ```javascript
43
- const PII_PATTERNS = {
44
- ssn: /\b\d{3}-\d{2}-\d{4}\b/g,
45
- email: /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/gi,
46
- phone: /\b(?:\+1[-.]?)?\(?\d{3}\)?[-.]?\d{3}[-.]?\d{4}\b/g,
47
- creditCard: /\b(?:\d{4}[-\s]?){3}\d{4}\b/g,
48
- };
49
-
50
- function redactPii(text) {
51
- const redactionMap = {};
52
- for (const [piiType, pattern] of Object.entries(PII_PATTERNS)) {
53
- let i = 0;
54
- text = text.replace(pattern, (match) => {
55
- const placeholder = '[' + piiType.toUpperCase() + '_' + i + ']';
56
- redactionMap[placeholder] = match;
57
- i++;
58
- return placeholder;
59
- });
60
- }
61
- return { text, redactionMap };
62
- }
63
- ```
64
-
65
-
66
- ### Pattern 2: Data minimization — send only what's needed
67
-
68
- ```python
69
- def prepare_context_for_llm(claim: dict) -> str:
70
- """Send only the fields the LLM needs. Never the full record."""
71
- # CORRECT: select specific fields
72
- context = {
73
- "claim_description": claim["description"],
74
- "claim_type": claim["type"],
75
- "date_filed": claim["date_filed"]
76
- }
77
- # WRONG: sending everything
78
- # context = claim # Includes SSN, address, policy details, etc.
79
- return json.dumps(context)
80
- ```
81
-
82
- ```javascript
83
- function prepareContextForLlm(claim) {
84
- // CORRECT: select specific fields
85
- return JSON.stringify({
86
- claimDescription: claim.description,
87
- claimType: claim.type,
88
- dateFiled: claim.dateFiled,
89
- });
90
- // WRONG: JSON.stringify(claim) — includes SSN, address, etc.
91
- }
92
- ```
93
-
94
-
95
- ### Pattern 3: Output filtering — catch PII in LLM responses
96
-
97
- ```python
98
- def filter_output_pii(llm_response: str) -> str:
99
- """Scan LLM output for PII that shouldn't be there."""
100
- for pii_type, pattern in PII_PATTERNS.items():
101
- matches = pattern.findall(llm_response)
102
- if matches:
103
- log_security_event("pii_in_output", pii_type=pii_type, count=len(matches))
104
- llm_response = pattern.sub(f"[REDACTED_{pii_type.upper()}]", llm_response)
105
- return llm_response
106
- ```
107
-
108
- ```javascript
109
- function filterOutputPii(llmResponse) {
110
- for (const [piiType, pattern] of Object.entries(PII_PATTERNS)) {
111
- const matches = llmResponse.match(pattern);
112
- if (matches) {
113
- logSecurityEvent('pii_in_output', { piiType, count: matches.length });
114
- llmResponse = llmResponse.replace(pattern, '[REDACTED_' + piiType.toUpperCase() + ']');
115
- }
116
- }
117
- return llmResponse;
118
- }
119
- ```
120
-
121
-
122
- ### Pattern 4: Separate PII storage from LLM-accessible data
123
-
124
- ```python
125
- # Architecture pattern: PII lives in a separate store the LLM cannot access
126
- class SecureDataLayer:
127
- def __init__(self, pii_store, llm_context_store):
128
- self.pii_store = pii_store # Encrypted, access-controlled
129
- self.llm_context_store = llm_context_store # Redacted, LLM-safe
130
-
131
- def prepare_for_llm(self, record_id: str) -> dict:
132
- """Fetch only LLM-safe fields."""
133
- return self.llm_context_store.get(record_id)
134
-
135
- def get_full_record(self, record_id: str, requester: str) -> dict:
136
- """Full record requires authentication and audit logging."""
137
- log_access("pii_access", record_id=record_id, requester=requester)
138
- return self.pii_store.get(record_id)
139
- ```
140
-
141
- ```javascript
142
- class SecureDataLayer {
143
- constructor(piiStore, llmContextStore) {
144
- this.piiStore = piiStore; // Encrypted, access-controlled
145
- this.llmContextStore = llmContextStore; // Redacted, LLM-safe
146
- }
147
-
148
- async prepareForLlm(recordId) {
149
- return this.llmContextStore.get(recordId);
150
- }
151
-
152
- async getFullRecord(recordId, requester) {
153
- logAccess('pii_access', { recordId, requester });
154
- return this.piiStore.get(recordId);
155
- }
156
- }
157
- ```
158
-
159
-
160
- ### Pattern 5: Logging without PII
161
-
162
- ```python
163
- def log_llm_interaction(input_text: str, output_text: str, metadata: dict):
164
- """Log the interaction for audit, but never log raw PII."""
165
- redacted_input, _ = redact_pii(input_text)
166
- redacted_output, _ = redact_pii(output_text)
167
- audit_log.info({
168
- "trace_id": metadata["trace_id"],
169
- "input_hash": hashlib.sha256(input_text.encode()).hexdigest(),
170
- "input_redacted": redacted_input,
171
- "output_redacted": redacted_output,
172
- "model_version": metadata["model_version"],
173
- "timestamp": datetime.utcnow().isoformat()
174
- })
175
- ```
176
-
177
- ```javascript
178
- const crypto = require('crypto');
179
-
180
- function logLlmInteraction(inputText, outputText, metadata) {
181
- const { text: redactedInput } = redactPii(inputText);
182
- const { text: redactedOutput } = redactPii(outputText);
183
- auditLog.info({
184
- traceId: metadata.traceId,
185
- inputHash: crypto.createHash('sha256').update(inputText).digest('hex'),
186
- inputRedacted: redactedInput,
187
- outputRedacted: redactedOutput,
188
- modelVersion: metadata.modelVersion,
189
- timestamp: new Date().toISOString(),
190
- });
191
- }
192
- ```
193
-
194
-
195
- ## Anti-patterns
196
-
197
- - **Sending full database records to the LLM.** Only send the fields needed for the task.
198
- - **Logging raw inputs/outputs containing PII.** Always redact before logging.
199
- - **Relying on the system prompt to prevent PII disclosure.** Prompts are not security controls.
200
- - **Storing PII and LLM-accessible data in the same store.** Separate by design.
201
-
202
- ## Edge cases
203
-
204
- - **PII in non-obvious formats.** Names embedded in email addresses, addresses in free text, medical record numbers. Consider using a dedicated NER model for high-risk systems.
205
- - **Cross-language PII.** Phone numbers, addresses, and ID formats vary by country. Regex patterns need locale awareness.
206
- - **PII in images.** If processing multimodal input, images of documents contain PII that bypasses text-based redaction.
207
- - **Children's data (COPPA/GDPR).** Requires explicit parental consent mechanisms and stricter data minimization. See handles-minors trait.
@@ -1,217 +0,0 @@
1
- ---
2
- id: rate-limiting
3
- title: Rate limiting and resource control
4
- controls:
5
- owasp: [LLM10]
6
- nist: [MEASURE-2.6, MANAGE-2.4]
7
- iso42001: [Clause-8.2]
8
- min_risk_tier: all
9
- system_traits: [is-external, is-high-volume, is-agentic]
10
- ---
11
-
12
- ## What this addresses
13
-
14
- OWASP LLM10 covers unbounded consumption — excessive resource usage leading to denial of service, financial exploitation ("denial of wallet"), or model theft through extraction attacks.
15
-
16
- ## Implementation patterns
17
-
18
- ### Pattern 1: Per-user rate limiting
19
-
20
- ```python
21
- from functools import wraps
22
- import time
23
-
24
- class RateLimiter:
25
- def __init__(self, max_requests: int, window_seconds: int):
26
- self.max_requests = max_requests
27
- self.window_seconds = window_seconds
28
- self.requests = {} # user_id -> [timestamps]
29
-
30
- def check(self, user_id: str) -> bool:
31
- now = time.time()
32
- user_requests = self.requests.get(user_id, [])
33
- # Remove expired entries
34
- user_requests = [t for t in user_requests if now - t < self.window_seconds]
35
- if len(user_requests) >= self.max_requests:
36
- return False
37
- user_requests.append(now)
38
- self.requests[user_id] = user_requests
39
- return True
40
-
41
- # Configure per endpoint
42
- api_limiter = RateLimiter(max_requests=60, window_seconds=60)
43
- llm_limiter = RateLimiter(max_requests=20, window_seconds=60)
44
- ```
45
-
46
- ```javascript
47
- class RateLimiter {
48
- constructor(maxRequests, windowSeconds) {
49
- this.maxRequests = maxRequests;
50
- this.windowSeconds = windowSeconds;
51
- this.requests = new Map();
52
- }
53
-
54
- check(userId) {
55
- const now = Date.now() / 1000;
56
- const userRequests = (this.requests.get(userId) || [])
57
- .filter(t => now - t < this.windowSeconds);
58
- if (userRequests.length >= this.maxRequests) return false;
59
- userRequests.push(now);
60
- this.requests.set(userId, userRequests);
61
- return true;
62
- }
63
- }
64
-
65
- const apiLimiter = new RateLimiter(60, 60);
66
- const llmLimiter = new RateLimiter(20, 60);
67
- ```
68
-
69
-
70
- ### Pattern 2: Token budget enforcement
71
-
72
- ```python
73
- class TokenBudget:
74
- def __init__(self, daily_limit: int, per_request_limit: int):
75
- self.daily_limit = daily_limit
76
- self.per_request_limit = per_request_limit
77
-
78
- def check_and_deduct(self, user_id: str, estimated_tokens: int) -> bool:
79
- if estimated_tokens > self.per_request_limit:
80
- return False
81
- daily_usage = self.get_daily_usage(user_id)
82
- if daily_usage + estimated_tokens > self.daily_limit:
83
- log_event("daily_token_limit_reached", user=user_id)
84
- return False
85
- self.record_usage(user_id, estimated_tokens)
86
- return True
87
-
88
- budget = TokenBudget(daily_limit=100_000, per_request_limit=4_000)
89
- ```
90
-
91
- ```javascript
92
- class TokenBudget {
93
- constructor(dailyLimit, perRequestLimit) {
94
- this.dailyLimit = dailyLimit;
95
- this.perRequestLimit = perRequestLimit;
96
- }
97
-
98
- async checkAndDeduct(userId, estimatedTokens) {
99
- if (estimatedTokens > this.perRequestLimit) return false;
100
- const dailyUsage = await this.getDailyUsage(userId);
101
- if (dailyUsage + estimatedTokens > this.dailyLimit) {
102
- logEvent('daily_token_limit_reached', { user: userId });
103
- return false;
104
- }
105
- await this.recordUsage(userId, estimatedTokens);
106
- return true;
107
- }
108
- }
109
- ```
110
-
111
-
112
- ### Pattern 3: Cost monitoring and alerting
113
-
114
- ```python
115
- class CostMonitor:
116
- def __init__(self, hourly_budget: float, daily_budget: float):
117
- self.hourly_budget = hourly_budget
118
- self.daily_budget = daily_budget
119
-
120
- def record_and_check(self, cost: float) -> dict:
121
- self.record(cost)
122
- hourly_total = self.get_hourly_total()
123
- daily_total = self.get_daily_total()
124
-
125
- alerts = []
126
- if hourly_total > self.hourly_budget * 0.8:
127
- alerts.append({"level": "warning", "message": f"80% of hourly budget used: {hourly_total:.2f}"})
128
- if hourly_total > self.hourly_budget:
129
- alerts.append({"level": "critical", "message": "Hourly budget exceeded — throttling"})
130
- self.enable_throttle()
131
- if daily_total > self.daily_budget:
132
- alerts.append({"level": "emergency", "message": "Daily budget exceeded — circuit breaker"})
133
- self.trip_circuit_breaker()
134
-
135
- return {"cost": cost, "hourly_total": hourly_total, "daily_total": daily_total, "alerts": alerts}
136
- ```
137
-
138
- ```javascript
139
- class CostMonitor {
140
- constructor(hourlyBudget, dailyBudget) {
141
- this.hourlyBudget = hourlyBudget;
142
- this.dailyBudget = dailyBudget;
143
- }
144
-
145
- async recordAndCheck(cost) {
146
- await this.record(cost);
147
- const hourlyTotal = await this.getHourlyTotal();
148
- const dailyTotal = await this.getDailyTotal();
149
- const alerts = [];
150
- if (hourlyTotal > this.hourlyBudget * 0.8)
151
- alerts.push({ level: 'warning', message: '80% of hourly budget used' });
152
- if (hourlyTotal > this.hourlyBudget) {
153
- alerts.push({ level: 'critical', message: 'Hourly budget exceeded' });
154
- await this.enableThrottle();
155
- }
156
- if (dailyTotal > this.dailyBudget) {
157
- alerts.push({ level: 'emergency', message: 'Daily budget exceeded' });
158
- await this.tripCircuitBreaker();
159
- }
160
- return { cost, hourlyTotal, dailyTotal, alerts };
161
- }
162
- }
163
- ```
164
-
165
-
166
- ### Pattern 4: Request timeout
167
-
168
- ```python
169
- import asyncio
170
-
171
- async def call_llm_with_timeout(messages: list, timeout: int = 30) -> dict:
172
- try:
173
- result = await asyncio.wait_for(
174
- client.chat.completions.create(model=MODEL, messages=messages),
175
- timeout=timeout
176
- )
177
- return {"success": True, "result": result}
178
- except asyncio.TimeoutError:
179
- log_event("llm_timeout", timeout=timeout)
180
- return {"success": False, "error": "timeout", "fallback": default_safe_response()}
181
- ```
182
-
183
- ```javascript
184
- async function callLlmWithTimeout(messages, timeout = 30000) {
185
- const controller = new AbortController();
186
- const timer = setTimeout(() => controller.abort(), timeout);
187
- try {
188
- const result = await client.chat.completions.create(
189
- { model: MODEL, messages },
190
- { signal: controller.signal }
191
- );
192
- clearTimeout(timer);
193
- return { success: true, result };
194
- } catch (e) {
195
- clearTimeout(timer);
196
- if (e.name === 'AbortError') {
197
- logEvent('llm_timeout', { timeout });
198
- return { success: false, error: 'timeout', fallback: defaultSafeResponse() };
199
- }
200
- throw e;
201
- }
202
- }
203
- ```
204
-
205
-
206
- ## Anti-patterns
207
-
208
- - **No rate limits on LLM endpoints.** Every endpoint must have limits.
209
- - **Same limits for all users.** Tier your limits by user role and subscription.
210
- - **No cost monitoring.** LLM costs can spike unexpectedly. Monitor and alert.
211
- - **Unlimited context windows.** Cap the conversation history sent to the LLM.
212
-
213
- ## Edge cases
214
-
215
- - **Distributed attacks.** Rate limit by API key, not just IP address.
216
- - **Legitimate burst traffic.** Allow temporary bursts with backpressure, don't hard-block.
217
- - **Cost estimation accuracy.** Token counts for prompts and completions differ. Estimate both.