Bird
Raised Fist0
Prompt Engineering / GenAIml~20 mins

Monitoring and observability in Prompt Engineering / GenAI - ML Experiment: Train & Evaluate

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Experiment - Monitoring and observability
Problem:You have a machine learning model deployed in production. The model's performance suddenly drops, but you don't know why because there is no monitoring or observability in place.
Current Metrics:No metrics are collected currently, so model accuracy and latency are unknown during deployment.
Issue:Lack of monitoring and observability makes it impossible to detect or diagnose performance issues in real time.
Your Task
Implement monitoring and observability to track model accuracy, latency, and resource usage in production. Set up alerts for performance drops.
Use only open-source tools or libraries.
Do not change the model architecture or training process.
Focus on adding monitoring without impacting model inference speed significantly.
Hint 1
Hint 2
Hint 3
Hint 4
Solution
Prompt Engineering / GenAI
import time
import random
from collections import deque

# Simulated model prediction function
def model_predict(input_data):
    # Simulate prediction latency
    time.sleep(random.uniform(0.01, 0.05))
    # Simulate prediction output
    return random.choice([0, 1])

# Monitoring class to track metrics
class ModelMonitor:
    def __init__(self, window_size=100):
        self.predictions = deque(maxlen=window_size)
        self.labels = deque(maxlen=window_size)
        self.latencies = deque(maxlen=window_size)

    def log_prediction(self, prediction, label, latency):
        self.predictions.append(prediction)
        self.labels.append(label)
        self.latencies.append(latency)

    def compute_accuracy(self):
        if not self.labels:
            return None
        correct = sum(p == l for p, l in zip(self.predictions, self.labels))
        return correct / len(self.labels)

    def compute_avg_latency(self):
        if not self.latencies:
            return None
        return sum(self.latencies) / len(self.latencies)

    def alert_if_needed(self):
        accuracy = self.compute_accuracy()
        avg_latency = self.compute_avg_latency()
        if accuracy is not None and accuracy < 0.7:
            print(f"ALERT: Accuracy dropped below threshold: {accuracy:.2f}")
        if avg_latency is not None and avg_latency > 0.04:
            print(f"ALERT: Latency too high: {avg_latency:.3f} seconds")

# Simulate streaming predictions with monitoring
monitor = ModelMonitor(window_size=50)

for i in range(200):
    input_data = i  # dummy input
    true_label = random.choice([0, 1])  # simulated true label

    start_time = time.time()
    pred = model_predict(input_data)
    latency = time.time() - start_time

    monitor.log_prediction(pred, true_label, latency)

    if i % 20 == 0 and i > 0:
        acc = monitor.compute_accuracy()
        avg_lat = monitor.compute_avg_latency()
        print(f"After {i} predictions - Accuracy: {acc:.2f}, Avg Latency: {avg_lat:.3f} sec")
        monitor.alert_if_needed()
Added a ModelMonitor class to track prediction accuracy and latency over a sliding window.
Logged prediction results and latency for each inference call.
Computed accuracy and average latency periodically.
Added alerts to notify when accuracy drops below 70% or latency exceeds 0.04 seconds.
Results Interpretation

Before: No metrics collected, no visibility into model performance.

After: Accuracy and latency metrics are tracked and printed every 20 predictions. Alerts notify when performance degrades.

Adding monitoring and observability allows you to detect and respond to model performance issues in production, improving reliability and trust.
Bonus Experiment
Extend monitoring to include input data distribution tracking to detect data drift.
💡 Hint
Calculate simple statistics like mean and variance of input features over time and alert if they change significantly.

Practice

(1/5)
1. What is the main purpose of monitoring in a software system?
easy
A. To check if the system is working right now
B. To predict future system failures
C. To change system configurations automatically
D. To write new features for the system

Solution

  1. Step 1: Understand monitoring's role

    Monitoring is about checking the current state of the system to see if it is working properly.
  2. Step 2: Compare options to definition

    Only To check if the system is working right now matches this purpose. Other options describe different activities like prediction, automation, or development.
  3. Final Answer:

    To check if the system is working right now -> Option A
  4. Quick Check:

    Monitoring = check current system state [OK]
Hint: Monitoring = check system now, not future or changes [OK]
Common Mistakes:
  • Confusing monitoring with observability
  • Thinking monitoring predicts future issues
  • Assuming monitoring changes system behavior
2. Which of the following is a correct example of a monitoring tool?
easy
A. Visual Studio Code
B. Prometheus
C. Dockerfile
D. GitHub

Solution

  1. Step 1: Identify monitoring tools

    Prometheus is a popular open-source monitoring tool used to collect and query metrics.
  2. Step 2: Check other options

    GitHub is for code hosting, Dockerfile is for container setup, and Visual Studio Code is a code editor, none are monitoring tools.
  3. Final Answer:

    Prometheus -> Option B
  4. Quick Check:

    Prometheus = monitoring tool [OK]
Hint: Prometheus is a classic monitoring tool name [OK]
Common Mistakes:
  • Confusing code tools with monitoring tools
  • Thinking Dockerfile is a monitoring tool
  • Mixing development tools with monitoring
3. Given this Prometheus query: up{job="api-server"} == 1, what does it show?
medium
A. The total number of api-server jobs
B. All api-server jobs that are down
C. All api-server jobs that are currently up (running)
D. The CPU usage of api-server jobs

Solution

  1. Step 1: Understand the query meaning

    The metric up is 1 when a target is up (running), 0 if down. The filter {job="api-server"} selects only api-server jobs.
  2. Step 2: Interpret the comparison

    The query checks where up == 1, so it shows api-server jobs currently running.
  3. Final Answer:

    All api-server jobs that are currently up (running) -> Option C
  4. Quick Check:

    up == 1 means running targets [OK]
Hint: up == 1 means service is running [OK]
Common Mistakes:
  • Thinking up == 1 means down
  • Confusing metric with count
  • Assuming it shows CPU usage
4. You see this error in your monitoring setup: error parsing query: unexpected token. What is the most likely cause?
medium
A. Server hardware failure
B. Network failure between server and client
C. Monitoring tool is not installed
D. Syntax error in the query expression

Solution

  1. Step 1: Analyze the error message

    The message says "error parsing query" and "unexpected token", which means the query syntax is wrong.
  2. Step 2: Rule out other causes

    Network failure, missing tool, or hardware failure would cause different errors, not parsing errors.
  3. Final Answer:

    Syntax error in the query expression -> Option D
  4. Quick Check:

    Parsing error = syntax mistake [OK]
Hint: Parsing errors mean syntax mistakes in queries [OK]
Common Mistakes:
  • Assuming network or hardware issues cause parsing errors
  • Ignoring the error message details
  • Thinking the tool is missing
5. You want to improve observability by adding tracing to your microservices. Which approach best helps you understand why requests fail inside your system?
hard
A. Use distributed tracing to follow requests across services
B. Add more CPU and memory to servers
C. Increase the frequency of monitoring alerts
D. Write more unit tests for each service

Solution

  1. Step 1: Understand observability and tracing

    Observability helps explain why things happen. Distributed tracing tracks requests across services to find where failures occur.
  2. Step 2: Evaluate options for observability

    Adding resources or alerts or tests does not directly show why requests fail inside the system.
  3. Final Answer:

    Use distributed tracing to follow requests across services -> Option A
  4. Quick Check:

    Tracing = understand request flow and failures [OK]
Hint: Tracing shows request path and failure reasons [OK]
Common Mistakes:
  • Confusing monitoring alerts with observability
  • Thinking hardware upgrades improve observability
  • Assuming tests replace tracing