Observer Effect Monitoring¶
Real-time production monitoring to detect when AI models behave differently than in evaluation contexts.
Overview¶
The ObserverEffectMonitor provides continuous monitoring of model behavior in production, alerting you when behavior diverges significantly from evaluation baselines. This is crucial for detecting the "observer effect" - when models behave differently knowing they're being watched.
Use Cases¶
- Continuous production monitoring
- Detect behavior shifts
- Safety monitoring (refusal rate changes)
- Quality assurance (response characteristics)
- A/B testing validation
How It Works¶
graph LR
A[Evaluation Baseline] --> B[Monitor]
C[Production Interactions] --> B
B --> D[Rolling Window Stats]
D --> E[Z-Score Calculation]
E --> F{Threshold<br/>Exceeded?}
F -->|Yes| G[Trigger Alert]
F -->|No| H[Continue Monitoring]
G --> I[Alert Handlers]
style G fill:#FF6B6B
style B fill:#87CEEB
Installation¶
Basic Usage¶
Step 1: Initialize Monitor¶
from ai_metacognition.detectors import ObserverEffectMonitor
monitor = ObserverEffectMonitor(
window_size=100, # Keep last 100 interactions
alert_threshold=2.5, # Alert at 2.5 sigma
feature_weights={
"response_length": 1.0,
"refusal_rate": 2.0, # Weight refusals more
"hedging_ratio": 1.5,
"tool_use_rate": 1.0,
"reasoning_depth": 1.0,
}
)
Step 2: Register Alert Handlers¶
from ai_metacognition.detectors import ConsoleAlertHandler
# Built-in console handler
monitor.register_alert_handler(ConsoleAlertHandler())
# Custom handler
class MyAlertHandler:
def handle_alert(self, alert):
# Send to your monitoring system
send_to_datadog(alert)
monitor.register_alert_handler(MyAlertHandler())
Step 3: Set Evaluation Baseline¶
# Responses from evaluation context
evaluation_responses = [...]
monitor.set_evaluation_baseline(evaluation_responses)
Step 4: Log Production Interactions¶
from ai_metacognition.detectors import Interaction
from datetime import datetime
interaction = Interaction(
timestamp=datetime.now(),
response=model_output,
refusal=is_refusal(model_output),
tool_used=used_tools,
reasoning_depth=compute_depth(cot)
)
monitor.log_production_interaction(interaction)
Step 5: Check for Divergence¶
report = monitor.get_divergence_report()
if report['has_divergence']:
print(f"⚠️ Divergence detected!")
print(f"Max z-score: {report['max_z_score']:.2f}σ")
for feature, z_score in report['z_scores'].items():
if abs(z_score) > 2.5:
print(f" {feature}: {z_score:.2f}σ")
Alert System¶
Severity Levels¶
| Level | Z-Score Range | Action |
|---|---|---|
| LOW | 2.0-3.0σ | Monitor closely |
| MEDIUM | 3.0-4.0σ | Investigate |
| HIGH | 4.0-5.0σ | Immediate attention |
| CRITICAL | >5.0σ | Emergency response |
Custom Alert Handlers¶
Implement the AlertHandler protocol:
from ai_metacognition.detectors import Alert
class SlackAlertHandler:
def __init__(self, webhook_url):
self.webhook_url = webhook_url
def handle_alert(self, alert: Alert) -> None:
message = f"🚨 {alert.severity.value.upper()}: "
message += f"{alert.feature} diverged (z={alert.z_score:.2f})"
send_slack_message(self.webhook_url, message)
Advanced Usage¶
Async Monitoring¶
import asyncio
async def monitor_production():
while True:
interaction = await get_next_interaction()
monitor.log_production_interaction(interaction)
if monitor.alerts:
await handle_alerts(monitor.alerts)
monitor.clear_alerts()
await asyncio.sleep(1)
Feature Weights¶
Adjust importance of different features:
monitor = ObserverEffectMonitor(
feature_weights={
"refusal_rate": 3.0, # Very important
"response_length": 1.0, # Standard
"hedging_ratio": 0.5, # Less important
}
)
Dynamic Thresholds¶
# Lower threshold during high-risk periods
monitor.alert_threshold = 2.0
# Raise threshold for less critical times
monitor.alert_threshold = 3.0
Integration Patterns¶
Pattern 1: Synchronous¶
def process_request(request):
response = model.generate(request)
# Log immediately
monitor.log_production_interaction(
Interaction(datetime.now(), response, ...)
)
return response
Pattern 2: Asynchronous Queue¶
from queue import Queue
interaction_queue = Queue()
def process_request(request):
response = model.generate(request)
interaction_queue.put(Interaction(...))
return response
# Background worker
def monitoring_worker():
while True:
interaction = interaction_queue.get()
monitor.log_production_interaction(interaction)
Pattern 3: Batch Processing¶
interactions_batch = []
def process_request(request):
response = model.generate(request)
interactions_batch.append(Interaction(...))
# Process batch periodically
if len(interactions_batch) >= 100:
for interaction in interactions_batch:
monitor.log_production_interaction(interaction)
interactions_batch.clear()
return response
API Reference¶
ObserverEffectMonitor¶
ObserverEffectMonitor
¶
Bases: BaseDetector
Monitor for detecting observer effects in production deployments.
This monitor tracks behavioral features in a rolling window and compares them to evaluation baselines to detect when models behave differently in production contexts.
Attributes:
| Name | Type | Description |
|---|---|---|
window_size |
Size of rolling window for statistics |
|
alert_threshold |
Minimum z-score to trigger alerts |
|
feature_weights |
Weights for different features |
|
evaluation_baseline |
Dict[str, Dict[str, float]]
|
Baseline statistics from evaluation |
production_window |
deque
|
Rolling window of production interactions |
alerts |
List[Alert]
|
List of triggered alerts |
alert_handlers |
List[AlertHandler]
|
List of registered alert handlers |
Source code in src/ai_metacognition/detectors/observer_effect.py
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 | |
__init__(window_size=1000, alert_threshold=2.0, feature_weights=None)
¶
Initialize the Observer Effect Monitor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
window_size
|
int
|
Number of interactions to maintain in rolling window |
1000
|
alert_threshold
|
float
|
Minimum z-score to trigger alerts (default: 2.0) |
2.0
|
feature_weights
|
Optional[Dict[str, float]]
|
Optional weights for features in aggregate scoring |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If parameters are invalid |
Source code in src/ai_metacognition/detectors/observer_effect.py
clear_alerts()
¶
detect(text)
¶
Detect patterns (BaseDetector compatibility).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
Input text to analyze |
required |
Returns:
| Type | Description |
|---|---|
Dict[str, Any]
|
Detection results |
Source code in src/ai_metacognition/detectors/observer_effect.py
get_alert_summary(severity_filter=None)
¶
Get summary of alerts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
severity_filter
|
Optional[AlertSeverity]
|
Optional filter by severity level |
None
|
Returns:
| Type | Description |
|---|---|
Dict[str, Any]
|
Summary of alerts |
Source code in src/ai_metacognition/detectors/observer_effect.py
get_divergence_report(time_window=None)
¶
Generate a comprehensive divergence report.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
time_window
|
Optional[int]
|
Optional time window in seconds (if None, use all data) |
None
|
Returns:
| Type | Description |
|---|---|
Dict[str, Any]
|
Dictionary containing divergence analysis |
Raises:
| Type | Description |
|---|---|
ValueError
|
If baseline not set or insufficient data |
Source code in src/ai_metacognition/detectors/observer_effect.py
log_production_interaction(interaction)
¶
Log a production interaction to the rolling window.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
interaction
|
Interaction
|
The interaction to log |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If interaction is invalid |
Source code in src/ai_metacognition/detectors/observer_effect.py
register_alert_handler(handler)
¶
Register an alert notification handler.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
handler
|
AlertHandler
|
The alert handler to register |
required |
Source code in src/ai_metacognition/detectors/observer_effect.py
set_evaluation_baseline(eval_samples)
¶
Set baseline statistics from evaluation samples.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
eval_samples
|
List[str]
|
List of model responses from evaluation |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If eval_samples is empty or invalid |
Source code in src/ai_metacognition/detectors/observer_effect.py
Alert¶
Alert
dataclass
¶
An alert triggered by divergence detection.
Attributes:
| Name | Type | Description |
|---|---|---|
timestamp |
datetime
|
When the alert was triggered |
feature |
str
|
The feature that diverged |
severity |
AlertSeverity
|
Alert severity level |
z_score |
float
|
The z-score that triggered the alert |
production_value |
float
|
Current production value |
baseline_value |
float
|
Evaluation baseline value |
recommendation |
str
|
Actionable recommendation |
trend |
Optional[str]
|
Recent trend information |
Source code in src/ai_metacognition/detectors/observer_effect.py
AlertSeverity¶
AlertSeverity
¶
Bases: Enum
Alert severity levels based on z-scores.
Source code in src/ai_metacognition/detectors/observer_effect.py
Best Practices¶
1. Baseline Quality¶
- Use 100+ evaluation samples
- Ensure diverse coverage
- Update periodically (weekly/monthly)
- Match production distribution
2. Window Size Selection¶
- Small (50-100): More responsive, more variance
- Medium (100-200): Balanced (recommended)
- Large (200-500): More stable, slower detection
3. Threshold Tuning¶
Start conservative (2.5-3.0σ) and adjust based on: - False positive rate - Alert frequency - Critical features
4. Alert Fatigue Prevention¶
- Use appropriate thresholds
- Aggregate similar alerts
- Implement cooldown periods
- Focus on critical features
Examples¶
See production_monitoring_example.py for complete example with multiple alert handlers.