@aigis-ai/cli 2.0.1 → 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.
- package/README.md +58 -188
- package/aigis-ai-cli-2.0.1.tgz +0 -0
- package/package.json +1 -1
- package/cli-python/LICENSE +0 -21
- package/cli-python/README.md +0 -32
- package/cli-python/aigis_cli/SKILL.md +0 -70
- package/cli-python/aigis_cli/__init__.py +0 -3
- package/cli-python/aigis_cli/__pycache__/__init__.cpython-313.pyc +0 -0
- package/cli-python/aigis_cli/__pycache__/annotate.cpython-313.pyc +0 -0
- package/cli-python/aigis_cli/__pycache__/build.cpython-313.pyc +0 -0
- package/cli-python/aigis_cli/__pycache__/checksum.cpython-313.pyc +0 -0
- package/cli-python/aigis_cli/__pycache__/classify.cpython-313.pyc +0 -0
- package/cli-python/aigis_cli/__pycache__/cli.cpython-313.pyc +0 -0
- package/cli-python/aigis_cli/__pycache__/fetch.cpython-313.pyc +0 -0
- package/cli-python/aigis_cli/__pycache__/init_ide.cpython-313.pyc +0 -0
- package/cli-python/aigis_cli/__pycache__/keywords.cpython-313.pyc +0 -0
- package/cli-python/aigis_cli/__pycache__/search.cpython-313.pyc +0 -0
- package/cli-python/aigis_cli/annotate.py +0 -45
- package/cli-python/aigis_cli/auto_verify.py +0 -518
- package/cli-python/aigis_cli/build.py +0 -470
- package/cli-python/aigis_cli/checksum.py +0 -22
- package/cli-python/aigis_cli/classify.py +0 -192
- package/cli-python/aigis_cli/cli.py +0 -618
- package/cli-python/aigis_cli/content/index/audit-scan.md +0 -217
- package/cli-python/aigis_cli/content/index/auto-verify-rules.json +0 -439
- package/cli-python/aigis_cli/content/index/context-rules.json +0 -90
- package/cli-python/aigis_cli/content/index/frameworks.md +0 -82
- package/cli-python/aigis_cli/content/index/guardrails.json +0 -23
- package/cli-python/aigis_cli/content/index/taxonomy.md +0 -81
- package/cli-python/aigis_cli/content/resolvers/triggers.json +0 -229
- package/cli-python/aigis_cli/content/skills/areas/audit-logging.md +0 -176
- package/cli-python/aigis_cli/content/skills/areas/bias-monitoring.md +0 -172
- package/cli-python/aigis_cli/content/skills/areas/confidence-scoring.md +0 -180
- package/cli-python/aigis_cli/content/skills/areas/data-integrity.md +0 -257
- package/cli-python/aigis_cli/content/skills/areas/explainability.md +0 -174
- package/cli-python/aigis_cli/content/skills/areas/fallback-patterns.md +0 -200
- package/cli-python/aigis_cli/content/skills/areas/human-oversight.md +0 -220
- package/cli-python/aigis_cli/content/skills/areas/input-validation.md +0 -380
- package/cli-python/aigis_cli/content/skills/areas/monitoring.md +0 -207
- package/cli-python/aigis_cli/content/skills/areas/output-sanitization.md +0 -183
- package/cli-python/aigis_cli/content/skills/areas/pii-handling.md +0 -189
- package/cli-python/aigis_cli/content/skills/areas/prompt-security.md +0 -153
- package/cli-python/aigis_cli/content/skills/areas/rag-security.md +0 -230
- package/cli-python/aigis_cli/content/skills/areas/rate-limiting.md +0 -246
- package/cli-python/aigis_cli/content/skills/areas/supply-chain.md +0 -193
- package/cli-python/aigis_cli/content/skills/core.md +0 -62
- package/cli-python/aigis_cli/content/skills/infrastructure/logging.md +0 -202
- package/cli-python/aigis_cli/content/skills/infrastructure/rate-limiting.md +0 -169
- package/cli-python/aigis_cli/content/skills/infrastructure/secrets.md +0 -167
- package/cli-python/aigis_cli/content/skills/workflows/fastapi-llm.md +0 -86
- package/cli-python/aigis_cli/content/templates/ai-impact-assessment.md +0 -54
- package/cli-python/aigis_cli/content/templates/intended-purpose-doc.md +0 -39
- package/cli-python/aigis_cli/content/templates/risk-characterization.md +0 -34
- package/cli-python/aigis_cli/content/templates/third-party-assessment.md +0 -41
- package/cli-python/aigis_cli/content/verify/checklist-audit-logging.md +0 -13
- package/cli-python/aigis_cli/content/verify/checklist-bias-monitoring.md +0 -13
- package/cli-python/aigis_cli/content/verify/checklist-confidence-scoring.md +0 -13
- package/cli-python/aigis_cli/content/verify/checklist-data-integrity.md +0 -12
- package/cli-python/aigis_cli/content/verify/checklist-explainability.md +0 -13
- package/cli-python/aigis_cli/content/verify/checklist-fallback-patterns.md +0 -13
- package/cli-python/aigis_cli/content/verify/checklist-human-oversight.md +0 -14
- package/cli-python/aigis_cli/content/verify/checklist-input-validation.md +0 -16
- package/cli-python/aigis_cli/content/verify/checklist-monitoring.md +0 -13
- package/cli-python/aigis_cli/content/verify/checklist-output-sanitization.md +0 -14
- package/cli-python/aigis_cli/content/verify/checklist-pii-handling.md +0 -14
- package/cli-python/aigis_cli/content/verify/checklist-prompt-security.md +0 -13
- package/cli-python/aigis_cli/content/verify/checklist-rag-security.md +0 -12
- package/cli-python/aigis_cli/content/verify/checklist-rate-limiting.md +0 -13
- package/cli-python/aigis_cli/content/verify/checklist-supply-chain.md +0 -13
- package/cli-python/aigis_cli/fetch.py +0 -232
- package/cli-python/aigis_cli/init_ide.py +0 -159
- package/cli-python/aigis_cli/keywords.py +0 -73
- package/cli-python/aigis_cli/search.py +0 -69
- package/cli-python/aigis_cli.egg-info/PKG-INFO +0 -59
- package/cli-python/aigis_cli.egg-info/SOURCES.txt +0 -56
- package/cli-python/aigis_cli.egg-info/dependency_links.txt +0 -1
- package/cli-python/aigis_cli.egg-info/entry_points.txt +0 -2
- package/cli-python/aigis_cli.egg-info/requires.txt +0 -6
- package/cli-python/aigis_cli.egg-info/top_level.txt +0 -1
- package/cli-python/dist/aigis_cli-1.0.3-py3-none-any.whl +0 -0
- package/cli-python/dist/aigis_cli-1.0.3.tar.gz +0 -0
- package/cli-python/pyproject.toml +0 -49
|
@@ -1,176 +0,0 @@
|
|
|
1
|
-
---
|
|
2
|
-
id: audit-logging
|
|
3
|
-
title: Audit logging and traceability
|
|
4
|
-
controls:
|
|
5
|
-
owasp: []
|
|
6
|
-
nist: [MEASURE-2.8, MANAGE-4.1, MANAGE-4.3]
|
|
7
|
-
iso42001: [Clause-9.1, Annex-A.6]
|
|
8
|
-
min_risk_tier: all
|
|
9
|
-
system_traits: [uses-llm]
|
|
10
|
-
---
|
|
11
|
-
|
|
12
|
-
## What this addresses
|
|
13
|
-
|
|
14
|
-
Every AI system needs an audit trail. NIST MANAGE 4.1 requires post-deployment monitoring with mechanisms for evaluating system behavior. ISO 42001 Clause 9.1 requires systematic monitoring and measurement. Without structured logging, you cannot debug failures, investigate incidents, demonstrate compliance, or detect drift.
|
|
15
|
-
|
|
16
|
-
## Implementation patterns
|
|
17
|
-
|
|
18
|
-
### Pattern 1: Structured log entry for every LLM interaction
|
|
19
|
-
|
|
20
|
-
```python
|
|
21
|
-
import uuid
|
|
22
|
-
from datetime import datetime
|
|
23
|
-
|
|
24
|
-
def create_audit_entry(
|
|
25
|
-
input_text: str,
|
|
26
|
-
output_text: str,
|
|
27
|
-
model_version: str,
|
|
28
|
-
user_id: str,
|
|
29
|
-
**kwargs
|
|
30
|
-
) -> dict:
|
|
31
|
-
return {
|
|
32
|
-
"trace_id": str(uuid.uuid4()),
|
|
33
|
-
"timestamp": datetime.utcnow().isoformat() + "Z",
|
|
34
|
-
"model_version": model_version,
|
|
35
|
-
"model_provider": kwargs.get("provider", "unknown"),
|
|
36
|
-
"user_id": user_id,
|
|
37
|
-
"input_hash": hashlib.sha256(input_text.encode()).hexdigest(),
|
|
38
|
-
"input_token_count": count_tokens(input_text),
|
|
39
|
-
"output_token_count": count_tokens(output_text),
|
|
40
|
-
"output_redacted": redact_pii(output_text)[0], # Never log raw PII
|
|
41
|
-
"latency_ms": kwargs.get("latency_ms"),
|
|
42
|
-
"status": kwargs.get("status", "success"),
|
|
43
|
-
"confidence_score": kwargs.get("confidence"),
|
|
44
|
-
"controls_applied": kwargs.get("controls", []),
|
|
45
|
-
"override_status": kwargs.get("override", None),
|
|
46
|
-
}
|
|
47
|
-
```
|
|
48
|
-
|
|
49
|
-
```javascript
|
|
50
|
-
const crypto = require('crypto');
|
|
51
|
-
const { v4: uuidv4 } = require('uuid');
|
|
52
|
-
|
|
53
|
-
function createAuditEntry(inputText, outputText, modelVersion, userId, opts = {}) {
|
|
54
|
-
return {
|
|
55
|
-
traceId: uuidv4(),
|
|
56
|
-
timestamp: new Date().toISOString(),
|
|
57
|
-
modelVersion,
|
|
58
|
-
modelProvider: opts.provider || 'unknown',
|
|
59
|
-
userId,
|
|
60
|
-
inputHash: crypto.createHash('sha256').update(inputText).digest('hex'),
|
|
61
|
-
inputTokenCount: countTokens(inputText),
|
|
62
|
-
outputTokenCount: countTokens(outputText),
|
|
63
|
-
outputRedacted: redactPii(outputText).text,
|
|
64
|
-
latencyMs: opts.latencyMs,
|
|
65
|
-
status: opts.status || 'success',
|
|
66
|
-
confidenceScore: opts.confidence,
|
|
67
|
-
controlsApplied: opts.controls || [],
|
|
68
|
-
overrideStatus: opts.override || null,
|
|
69
|
-
};
|
|
70
|
-
}
|
|
71
|
-
```
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
### Pattern 2: Trace ID propagation
|
|
75
|
-
|
|
76
|
-
```python
|
|
77
|
-
import contextvars
|
|
78
|
-
|
|
79
|
-
trace_id_var = contextvars.ContextVar('trace_id')
|
|
80
|
-
|
|
81
|
-
def set_trace_id():
|
|
82
|
-
tid = str(uuid.uuid4())
|
|
83
|
-
trace_id_var.set(tid)
|
|
84
|
-
return tid
|
|
85
|
-
|
|
86
|
-
def get_trace_id() -> str:
|
|
87
|
-
return trace_id_var.get("no-trace-id")
|
|
88
|
-
|
|
89
|
-
# Use in every log call, API response, and error message
|
|
90
|
-
# This allows correlating a single request across all system components
|
|
91
|
-
```
|
|
92
|
-
|
|
93
|
-
```javascript
|
|
94
|
-
const { AsyncLocalStorage } = require('async_hooks');
|
|
95
|
-
const traceStorage = new AsyncLocalStorage();
|
|
96
|
-
|
|
97
|
-
function setTraceId() {
|
|
98
|
-
const traceId = crypto.randomUUID();
|
|
99
|
-
traceStorage.enterWith(traceId);
|
|
100
|
-
return traceId;
|
|
101
|
-
}
|
|
102
|
-
|
|
103
|
-
function getTraceId() {
|
|
104
|
-
return traceStorage.getStore() || 'no-trace-id';
|
|
105
|
-
}
|
|
106
|
-
```
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
### Pattern 3: Decision audit trail
|
|
110
|
-
|
|
111
|
-
```python
|
|
112
|
-
def log_decision(decision: dict, context: dict):
|
|
113
|
-
"""Log every AI-influenced decision with full context."""
|
|
114
|
-
audit_log.info({
|
|
115
|
-
"event_type": "ai_decision",
|
|
116
|
-
"trace_id": get_trace_id(),
|
|
117
|
-
"decision": {
|
|
118
|
-
"action": decision["recommendation"],
|
|
119
|
-
"confidence": decision["confidence"],
|
|
120
|
-
"model_version": decision["model_version"],
|
|
121
|
-
},
|
|
122
|
-
"context": {
|
|
123
|
-
"input_summary": context.get("summary"), # Not raw input
|
|
124
|
-
"controls_applied": context.get("controls"),
|
|
125
|
-
"risk_tier": context.get("risk_tier"),
|
|
126
|
-
},
|
|
127
|
-
"compliance": {
|
|
128
|
-
"nist_controls": ["MANAGE-4.1"],
|
|
129
|
-
"iso_clause": "9.1",
|
|
130
|
-
"human_reviewable": True
|
|
131
|
-
}
|
|
132
|
-
})
|
|
133
|
-
```
|
|
134
|
-
|
|
135
|
-
```javascript
|
|
136
|
-
function logDecision(decision, context) {
|
|
137
|
-
auditLog.info({
|
|
138
|
-
eventType: 'ai_decision',
|
|
139
|
-
traceId: getTraceId(),
|
|
140
|
-
decision: {
|
|
141
|
-
action: decision.recommendation,
|
|
142
|
-
confidence: decision.confidence,
|
|
143
|
-
modelVersion: decision.modelVersion,
|
|
144
|
-
},
|
|
145
|
-
context: {
|
|
146
|
-
inputSummary: context.summary,
|
|
147
|
-
controlsApplied: context.controls,
|
|
148
|
-
riskTier: context.riskTier,
|
|
149
|
-
},
|
|
150
|
-
compliance: {
|
|
151
|
-
nistControls: [MANAGE-4.1'],
|
|
152
|
-
isoClause: '9.1',
|
|
153
|
-
humanReviewable: true,
|
|
154
|
-
},
|
|
155
|
-
});
|
|
156
|
-
}
|
|
157
|
-
```
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
## Anti-patterns
|
|
161
|
-
|
|
162
|
-
- **Logging raw PII.** Always redact before logging. See pii-handling.md.
|
|
163
|
-
- **Unstructured log messages.** Use structured JSON logs with consistent fields.
|
|
164
|
-
- **No trace ID.** Every request must have a trace ID that propagates through all components.
|
|
165
|
-
- **Logging only errors.** Log all interactions, not just failures. You need the baseline to detect anomalies.
|
|
166
|
-
|
|
167
|
-
## Edge cases
|
|
168
|
-
|
|
169
|
-
- **Log volume at scale.** At high volume, consider sampling non-critical logs while keeping 100% of error and decision logs.
|
|
170
|
-
- **Log retention and compliance.** Different regulations require different retention periods. Configure per data type.
|
|
171
|
-
- **Cross-system correlation.** If the AI system calls external services, propagate trace IDs via headers.
|
|
172
|
-
|
|
173
|
-
## Related infrastructure
|
|
174
|
-
|
|
175
|
-
- `aigis infra logging` — `structlog` JSON-to-stdout setup with a concrete `REDACT_KEYS` list, plus integration patterns for Datadog/New Relic/Honeycomb, CloudWatch, Sentry (with the `max_request_body_size='never'` warning), and OpenTelemetry/OTLP.
|
|
176
|
-
- `aigis infra secrets` — keep API keys and connection strings out of the structured fields you log.
|
|
@@ -1,172 +0,0 @@
|
|
|
1
|
-
---
|
|
2
|
-
id: bias-monitoring
|
|
3
|
-
title: Bias monitoring and fairness
|
|
4
|
-
controls:
|
|
5
|
-
owasp: []
|
|
6
|
-
nist: [MAP-2.3, MEASURE-2.11, MEASURE-3.1]
|
|
7
|
-
iso42001: [Clause-6.1, Annex-C]
|
|
8
|
-
min_risk_tier: medium
|
|
9
|
-
system_traits: [influences-decisions, handles-health, handles-financial, generates-content, handles-minors]
|
|
10
|
-
---
|
|
11
|
-
|
|
12
|
-
## What this addresses
|
|
13
|
-
|
|
14
|
-
NIST MEASURE 2.11 requires evaluation of fairness and bias. AI systems can produce systematically different outcomes for different demographic groups, even without explicit demographic data, through proxy features like zip code, writing style, or name. This file covers the technical infrastructure for detecting and monitoring bias.
|
|
15
|
-
|
|
16
|
-
## Implementation patterns
|
|
17
|
-
|
|
18
|
-
### Pattern 1: Fairness-enabling metadata in logs
|
|
19
|
-
|
|
20
|
-
```python
|
|
21
|
-
def log_with_fairness_fields(decision: dict, context: dict):
|
|
22
|
-
"""Include fields that enable fairness auditing downstream."""
|
|
23
|
-
audit_entry = {
|
|
24
|
-
"trace_id": get_trace_id(),
|
|
25
|
-
"decision": decision,
|
|
26
|
-
# Fairness-relevant metadata (NOT protected characteristics directly)
|
|
27
|
-
"fairness_audit_fields": {
|
|
28
|
-
"claim_type": context.get("claim_type"),
|
|
29
|
-
"region": context.get("region"),
|
|
30
|
-
"submission_channel": context.get("channel"), # web, phone, agent
|
|
31
|
-
"input_language": detect_language(context.get("input_text", "")),
|
|
32
|
-
"input_length_bucket": bucket_length(context.get("input_text", "")),
|
|
33
|
-
}
|
|
34
|
-
}
|
|
35
|
-
audit_log.info(audit_entry)
|
|
36
|
-
```
|
|
37
|
-
|
|
38
|
-
```javascript
|
|
39
|
-
function logWithFairnessFields(decision, context) {
|
|
40
|
-
auditLog.info({
|
|
41
|
-
traceId: getTraceId(),
|
|
42
|
-
decision,
|
|
43
|
-
fairnessAuditFields: {
|
|
44
|
-
claimType: context.claimType,
|
|
45
|
-
region: context.region,
|
|
46
|
-
submissionChannel: context.channel,
|
|
47
|
-
inputLanguage: detectLanguage(context.inputText || ''),
|
|
48
|
-
inputLengthBucket: bucketLength(context.inputText || ''),
|
|
49
|
-
},
|
|
50
|
-
});
|
|
51
|
-
}
|
|
52
|
-
```
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
### Pattern 2: Output distribution monitoring
|
|
56
|
-
|
|
57
|
-
```python
|
|
58
|
-
class BiasMonitor:
|
|
59
|
-
def __init__(self, alert_threshold: float = 0.15):
|
|
60
|
-
self.alert_threshold = alert_threshold
|
|
61
|
-
|
|
62
|
-
def check_distribution(self, period: str = "7d") -> list:
|
|
63
|
-
"""Compare score distributions across demographic segments."""
|
|
64
|
-
decisions = self.load_decisions(period)
|
|
65
|
-
alerts = []
|
|
66
|
-
|
|
67
|
-
for field in FAIRNESS_AUDIT_FIELDS:
|
|
68
|
-
segments = group_by(decisions, field)
|
|
69
|
-
for seg_a, seg_b in combinations(segments.keys(), 2):
|
|
70
|
-
scores_a = [d["severity_score"] for d in segments[seg_a]]
|
|
71
|
-
scores_b = [d["severity_score"] for d in segments[seg_b]]
|
|
72
|
-
disparity = abs(mean(scores_a) - mean(scores_b))
|
|
73
|
-
|
|
74
|
-
if disparity > self.alert_threshold:
|
|
75
|
-
alerts.append({
|
|
76
|
-
"field": field,
|
|
77
|
-
"segment_a": seg_a,
|
|
78
|
-
"segment_b": seg_b,
|
|
79
|
-
"disparity": disparity,
|
|
80
|
-
"sample_size_a": len(scores_a),
|
|
81
|
-
"sample_size_b": len(scores_b),
|
|
82
|
-
})
|
|
83
|
-
return alerts
|
|
84
|
-
```
|
|
85
|
-
|
|
86
|
-
```javascript
|
|
87
|
-
class BiasMonitor {
|
|
88
|
-
constructor(alertThreshold = 0.15) {
|
|
89
|
-
this.alertThreshold = alertThreshold;
|
|
90
|
-
}
|
|
91
|
-
|
|
92
|
-
async checkDistribution(period = '7d') {
|
|
93
|
-
const decisions = await this.loadDecisions(period);
|
|
94
|
-
const alerts = [];
|
|
95
|
-
for (const field of FAIRNESS_AUDIT_FIELDS) {
|
|
96
|
-
const segments = groupBy(decisions, field);
|
|
97
|
-
const keys = Object.keys(segments);
|
|
98
|
-
for (let i = 0; i < keys.length; i++) {
|
|
99
|
-
for (let j = i + 1; j < keys.length; j++) {
|
|
100
|
-
const scoresA = segments[keys[i]].map(d => d.severityScore);
|
|
101
|
-
const scoresB = segments[keys[j]].map(d => d.severityScore);
|
|
102
|
-
const disparity = Math.abs(mean(scoresA) - mean(scoresB));
|
|
103
|
-
if (disparity > this.alertThreshold) {
|
|
104
|
-
alerts.push({ field, segmentA: keys[i], segmentB: keys[j],
|
|
105
|
-
disparity, sampleSizeA: scoresA.length, sampleSizeB: scoresB.length });
|
|
106
|
-
}
|
|
107
|
-
}
|
|
108
|
-
}
|
|
109
|
-
}
|
|
110
|
-
return alerts;
|
|
111
|
-
}
|
|
112
|
-
}
|
|
113
|
-
```
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
### Pattern 3: Periodic fairness reports
|
|
117
|
-
|
|
118
|
-
```python
|
|
119
|
-
def generate_fairness_report(period: str = "30d") -> dict:
|
|
120
|
-
monitor = BiasMonitor()
|
|
121
|
-
alerts = monitor.check_distribution(period)
|
|
122
|
-
override_analysis = monitor.analyze_override_patterns(period)
|
|
123
|
-
|
|
124
|
-
return {
|
|
125
|
-
"period": period,
|
|
126
|
-
"generated_at": datetime.utcnow().isoformat(),
|
|
127
|
-
"distribution_alerts": alerts,
|
|
128
|
-
"override_patterns": override_analysis,
|
|
129
|
-
"total_decisions": monitor.count_decisions(period),
|
|
130
|
-
"nist_control": "MEASURE-2.11",
|
|
131
|
-
"iso_clause": "Clause-6.1",
|
|
132
|
-
"recommendation": "review_required" if alerts else "no_action_needed"
|
|
133
|
-
}
|
|
134
|
-
```
|
|
135
|
-
|
|
136
|
-
```javascript
|
|
137
|
-
async function generateFairnessReport(period = '30d') {
|
|
138
|
-
const monitor = new BiasMonitor();
|
|
139
|
-
const alerts = await monitor.checkDistribution(period);
|
|
140
|
-
const overrideAnalysis = await monitor.analyzeOverridePatterns(period);
|
|
141
|
-
return {
|
|
142
|
-
period,
|
|
143
|
-
generatedAt: new Date().toISOString(),
|
|
144
|
-
distributionAlerts: alerts,
|
|
145
|
-
overridePatterns: overrideAnalysis,
|
|
146
|
-
totalDecisions: await monitor.countDecisions(period),
|
|
147
|
-
nistControl: MEASURE-2.11',
|
|
148
|
-
isoClause: Clause-6.1',
|
|
149
|
-
recommendation: alerts.length ? 'review_required' : 'no_action_needed',
|
|
150
|
-
};
|
|
151
|
-
}
|
|
152
|
-
```
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
## Anti-patterns
|
|
156
|
-
|
|
157
|
-
- **Collecting protected characteristics directly.** Use proxy-free fairness audit fields.
|
|
158
|
-
- **One-time bias testing.** Bias must be monitored continuously, not just at launch.
|
|
159
|
-
- **Only measuring accuracy.** Equal accuracy doesn't mean equal outcomes. Measure disparate impact.
|
|
160
|
-
- **Ignoring override patterns.** If humans override AI decisions more for one group, that signals bias.
|
|
161
|
-
|
|
162
|
-
## Related files
|
|
163
|
-
|
|
164
|
-
- **audit-logging.md:** Fairness audit fields (Pattern 1) must be included in the structured log entries defined in audit-logging.md Pattern 1. The fairness fields are additional metadata in the same audit log, not a separate logging system.
|
|
165
|
-
- **human-oversight.md:** Override patterns are a key bias signal. Track human override rates per segment using human-oversight.md Pattern 4 (override mechanism) data, analyzed through bias-monitoring.md Pattern 2 (distribution monitoring).
|
|
166
|
-
- **confidence-scoring.md:** Bias may manifest as systematically lower confidence for certain groups. Cross-reference confidence distributions with fairness audit fields.
|
|
167
|
-
|
|
168
|
-
## Edge cases
|
|
169
|
-
|
|
170
|
-
- **Intersectional bias.** Bias may only appear at the intersection of two dimensions (e.g., region + claim type).
|
|
171
|
-
- **Small sample sizes.** Statistical tests need sufficient data per segment. Flag when samples are too small.
|
|
172
|
-
- **Feedback loops.** If biased outputs influence future training data, bias compounds over time.
|
|
@@ -1,180 +0,0 @@
|
|
|
1
|
-
---
|
|
2
|
-
id: confidence-scoring
|
|
3
|
-
title: Confidence scoring and misinformation prevention
|
|
4
|
-
controls:
|
|
5
|
-
owasp: [LLM09]
|
|
6
|
-
nist: [MAP-2.2, MEASURE-2.5, MEASURE-2.9]
|
|
7
|
-
iso42001: [Annex-A.8]
|
|
8
|
-
min_risk_tier: all
|
|
9
|
-
system_traits: [influences-decisions, is-external, generates-content]
|
|
10
|
-
---
|
|
11
|
-
|
|
12
|
-
## What this addresses
|
|
13
|
-
|
|
14
|
-
OWASP LLM09 covers misinformation — confident but incorrect LLM outputs (hallucinations, fabricated citations, false facts). When decisions are based on unverified LLM output, consequences can be severe. This file covers confidence metadata, grounding, and uncertainty disclosure.
|
|
15
|
-
|
|
16
|
-
## Implementation patterns
|
|
17
|
-
|
|
18
|
-
### Pattern 1: Structured confidence in every response
|
|
19
|
-
|
|
20
|
-
```python
|
|
21
|
-
class LLMResponse:
|
|
22
|
-
def __init__(self, content: dict, raw_response: str):
|
|
23
|
-
self.content = content
|
|
24
|
-
self.confidence = self.compute_confidence(raw_response)
|
|
25
|
-
self.grounded = self.check_grounding(content)
|
|
26
|
-
|
|
27
|
-
def compute_confidence(self, raw: str) -> dict:
|
|
28
|
-
return {
|
|
29
|
-
"score": self.extract_confidence_score(raw),
|
|
30
|
-
"level": self.categorize(self.extract_confidence_score(raw)),
|
|
31
|
-
"factors": self.identify_uncertainty_factors(raw)
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
def categorize(self, score: float) -> str:
|
|
35
|
-
if score >= 0.8: return "high"
|
|
36
|
-
if score >= 0.5: return "medium"
|
|
37
|
-
return "low"
|
|
38
|
-
|
|
39
|
-
def to_response(self) -> dict:
|
|
40
|
-
return {
|
|
41
|
-
**self.content,
|
|
42
|
-
"confidence": self.confidence,
|
|
43
|
-
"grounded": self.grounded,
|
|
44
|
-
"disclaimer": self.generate_disclaimer()
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
def generate_disclaimer(self) -> str | None:
|
|
48
|
-
if self.confidence["level"] == "low":
|
|
49
|
-
return "This assessment has low confidence. Human review recommended."
|
|
50
|
-
return None
|
|
51
|
-
```
|
|
52
|
-
|
|
53
|
-
```javascript
|
|
54
|
-
class LlmResponse {
|
|
55
|
-
constructor(content, rawResponse) {
|
|
56
|
-
this.content = content;
|
|
57
|
-
this.confidence = this.computeConfidence(rawResponse);
|
|
58
|
-
this.grounded = this.checkGrounding(content);
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
computeConfidence(raw) {
|
|
62
|
-
const score = this.extractConfidenceScore(raw);
|
|
63
|
-
return {
|
|
64
|
-
score,
|
|
65
|
-
level: score >= 0.8 ? 'high' : score >= 0.5 ? 'medium' : 'low',
|
|
66
|
-
factors: this.identifyUncertaintyFactors(raw),
|
|
67
|
-
};
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
toResponse() {
|
|
71
|
-
return {
|
|
72
|
-
...this.content,
|
|
73
|
-
confidence: this.confidence,
|
|
74
|
-
grounded: this.grounded,
|
|
75
|
-
disclaimer: this.confidence.level === 'low'
|
|
76
|
-
? 'This assessment has low confidence. Human review recommended.' : null,
|
|
77
|
-
};
|
|
78
|
-
}
|
|
79
|
-
}
|
|
80
|
-
```
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
### Pattern 2: RAG-based grounding verification
|
|
84
|
-
|
|
85
|
-
```python
|
|
86
|
-
def verify_grounding(llm_output: str, retrieved_sources: list) -> dict:
|
|
87
|
-
"""Check if LLM claims are supported by retrieved documents."""
|
|
88
|
-
claims = extract_claims(llm_output)
|
|
89
|
-
grounded_claims = 0
|
|
90
|
-
ungrounded_claims = []
|
|
91
|
-
|
|
92
|
-
for claim in claims:
|
|
93
|
-
supported = any(
|
|
94
|
-
is_supported_by(claim, source["content"])
|
|
95
|
-
for source in retrieved_sources
|
|
96
|
-
)
|
|
97
|
-
if supported:
|
|
98
|
-
grounded_claims += 1
|
|
99
|
-
else:
|
|
100
|
-
ungrounded_claims.append(claim)
|
|
101
|
-
|
|
102
|
-
grounding_ratio = grounded_claims / len(claims) if claims else 0
|
|
103
|
-
return {
|
|
104
|
-
"grounding_ratio": grounding_ratio,
|
|
105
|
-
"total_claims": len(claims),
|
|
106
|
-
"ungrounded_claims": ungrounded_claims,
|
|
107
|
-
"fully_grounded": len(ungrounded_claims) == 0
|
|
108
|
-
}
|
|
109
|
-
```
|
|
110
|
-
|
|
111
|
-
```javascript
|
|
112
|
-
function verifyGrounding(llmOutput, retrievedSources) {
|
|
113
|
-
const claims = extractClaims(llmOutput);
|
|
114
|
-
const ungroundedClaims = [];
|
|
115
|
-
let groundedCount = 0;
|
|
116
|
-
|
|
117
|
-
for (const claim of claims) {
|
|
118
|
-
const supported = retrievedSources.some(
|
|
119
|
-
source => isSupportedBy(claim, source.content)
|
|
120
|
-
);
|
|
121
|
-
if (supported) groundedCount++;
|
|
122
|
-
else ungroundedClaims.push(claim);
|
|
123
|
-
}
|
|
124
|
-
|
|
125
|
-
return {
|
|
126
|
-
groundingRatio: claims.length ? groundedCount / claims.length : 0,
|
|
127
|
-
totalClaims: claims.length,
|
|
128
|
-
ungroundedClaims,
|
|
129
|
-
fullyGrounded: ungroundedClaims.length === 0,
|
|
130
|
-
};
|
|
131
|
-
}
|
|
132
|
-
```
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
### Pattern 3: Never present LLM output as definitive fact
|
|
136
|
-
|
|
137
|
-
```python
|
|
138
|
-
def format_for_display(assessment: dict) -> dict:
|
|
139
|
-
"""Frame AI output as a recommendation, not a fact."""
|
|
140
|
-
return {
|
|
141
|
-
"header": "AI-assisted assessment", # Not "Assessment Result"
|
|
142
|
-
"body": assessment["content"],
|
|
143
|
-
"confidence_indicator": assessment["confidence"]["level"],
|
|
144
|
-
"source_attribution": assessment.get("sources", []),
|
|
145
|
-
"footer": "This is an AI-generated recommendation. "
|
|
146
|
-
"Final decisions should be made by qualified personnel."
|
|
147
|
-
}
|
|
148
|
-
```
|
|
149
|
-
|
|
150
|
-
```javascript
|
|
151
|
-
function formatForDisplay(assessment) {
|
|
152
|
-
return {
|
|
153
|
-
header: 'AI-assisted assessment', // Not "Assessment Result"
|
|
154
|
-
body: assessment.content,
|
|
155
|
-
confidenceIndicator: assessment.confidence.level,
|
|
156
|
-
sourceAttribution: assessment.sources || [],
|
|
157
|
-
footer: 'This is an AI-generated recommendation. '
|
|
158
|
-
+ 'Final decisions should be made by qualified personnel.',
|
|
159
|
-
};
|
|
160
|
-
}
|
|
161
|
-
```
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
## Anti-patterns
|
|
165
|
-
|
|
166
|
-
- **Presenting LLM output without confidence metadata.** Always include confidence.
|
|
167
|
-
- **"The AI determined..." framing.** Use "The AI suggests..." or "Based on available data..."
|
|
168
|
-
- **No source attribution.** When using RAG, cite the sources that informed the response.
|
|
169
|
-
- **Binary confidence (just confident/not confident).** Use a spectrum with actionable thresholds.
|
|
170
|
-
|
|
171
|
-
## Related files
|
|
172
|
-
|
|
173
|
-
- **human-oversight.md:** When confidence is low, route to human review. Implement human-oversight.md Pattern 2 (decision gate with confidence threshold) to automatically flag low-confidence outputs for human review rather than auto-processing them.
|
|
174
|
-
- **monitoring.md:** Confidence scores should be tracked over time. Use monitoring.md Pattern 1 (key metrics dashboard) to monitor mean confidence and alert when it drops, which may signal model degradation or data drift.
|
|
175
|
-
|
|
176
|
-
## Edge cases
|
|
177
|
-
|
|
178
|
-
- **Calibration.** LLM confidence scores are often miscalibrated. Validate against ground truth periodically.
|
|
179
|
-
- **Confident hallucinations.** LLMs can be confidently wrong. Grounding verification catches this better than self-reported confidence.
|
|
180
|
-
- **Downstream automation.** If another system consumes the confidence score, ensure it respects low-confidence flags.
|