0
0
Prompt Engineering / GenAIml~10 mins

Error handling and rate limits in Prompt Engineering / GenAI - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to catch an error when the API call fails.

Prompt Engineering / GenAI
try:
    response = api_call()
except [1]:
    print("API call failed")
Drag options to blanks, or click blank then click option'
AKeyError
BValueError
CTimeoutError
DException
Attempts:
3 left
💡 Hint
Common Mistakes
Using a specific error that may not catch all API failures.
2fill in blank
medium

Complete the code to check if the API response status code indicates rate limiting.

Prompt Engineering / GenAI
if response.status_code == [1]:
    print("Rate limit exceeded. Please wait.")
Drag options to blanks, or click blank then click option'
A404
B429
C200
D500
Attempts:
3 left
💡 Hint
Common Mistakes
Confusing 429 with 404 or 500 status codes.
3fill in blank
hard

Fix the error in the code to retry the API call after a delay when rate limited.

Prompt Engineering / GenAI
import time

if response.status_code == 429:
    time.sleep([1])
    response = api_call()
Drag options to blanks, or click blank then click option'
A0.5
B-1
C5
D"5"
Attempts:
3 left
💡 Hint
Common Mistakes
Passing a string instead of a number to time.sleep.
Using negative sleep time.
4fill in blank
hard

Fill both blanks to handle API errors and retry with exponential backoff.

Prompt Engineering / GenAI
max_retries = 3
retry_delay = 1
for attempt in range(max_retries):
    response = api_call()
    if response.status_code == 200:
        break
    elif response.status_code == [1]:
        time.sleep(retry_delay)
        retry_delay [2] 2
Drag options to blanks, or click blank then click option'
A429
B*=
C+=
D500
Attempts:
3 left
💡 Hint
Common Mistakes
Using '+=' instead of '*=' for exponential backoff.
Checking wrong status codes.
5fill in blank
hard

Fill all three blanks to log errors, handle rate limits, and raise exceptions after retries.

Prompt Engineering / GenAI
import logging

max_retries = 2
retry_delay = 1
for i in range(max_retries + 1):
    response = api_call()
    if response.status_code == 200:
        break
    elif response.status_code == [1]:
        logging.warning(f"Rate limit hit, retrying in {retry_delay} seconds")
        time.sleep(retry_delay)
        retry_delay [2] 2
    else:
        logging.error(f"API error: {response.status_code}")
        raise [3]("API call failed")
Drag options to blanks, or click blank then click option'
A429
B*=
CException
DValueError
Attempts:
3 left
💡 Hint
Common Mistakes
Raising wrong exception type.
Using wrong operator for retry_delay.
Checking incorrect status code.