Sometimes, when an AI tries to get information, it might fail. Handling these failures nicely helps the AI keep working without crashing or giving wrong answers.
Handling retrieval failures gracefully in Agentic AI
Start learning this pattern below
Jump into concepts and practice - no test required
class RetrievalHandler: def __init__(self, data_source): self.data_source = data_source def get_data(self, key): try: result = self.data_source.retrieve(key) if result is None: return self.handle_failure(key) return result except Exception as error: return self.handle_failure(key, error) def handle_failure(self, key, error=None): if error: print(f"Error retrieving {key}: {error}") else: print(f"No data found for {key}") # Return a safe default or message return "Data not available"
This class tries to get data and catches errors or missing data.
The handle_failure method manages what happens when retrieval fails.
class DummyDataSource: def retrieve(self, key): data = {"name": "Alice", "age": 30} return data.get(key) handler = RetrievalHandler(DummyDataSource()) print(handler.get_data("name")) # Returns 'Alice'
print(handler.get_data("address")) # Key missing, triggers graceful failure
class ErrorDataSource: def retrieve(self, key): raise RuntimeError("Connection lost") error_handler = RetrievalHandler(ErrorDataSource()) print(error_handler.get_data("name")) # Handles exception gracefully
This program shows how to handle missing data and errors when retrieving information from different sources.
class RetrievalHandler: def __init__(self, data_source): self.data_source = data_source def get_data(self, key): try: result = self.data_source.retrieve(key) if result is None: return self.handle_failure(key) return result except Exception as error: return self.handle_failure(key, error) def handle_failure(self, key, error=None): if error: print(f"Error retrieving {key}: {error}") else: print(f"No data found for {key}") return "Data not available" class DummyDataSource: def __init__(self): self.data = {"name": "Alice", "age": 30} def retrieve(self, key): return self.data.get(key) class ErrorDataSource: def retrieve(self, key): raise RuntimeError("Connection lost") print("-- Using DummyDataSource --") dummy_handler = RetrievalHandler(DummyDataSource()) print("Name:", dummy_handler.get_data("name")) print("Address:", dummy_handler.get_data("address")) print("\n-- Using ErrorDataSource --") error_handler = RetrievalHandler(ErrorDataSource()) print("Name:", error_handler.get_data("name"))
Time complexity depends on the data source retrieval method, usually O(1) for dictionary lookups.
Space complexity is minimal, just storing references to data sources and keys.
Common mistake: not catching exceptions, which can crash the program.
Use graceful failure handling to keep AI systems stable and user-friendly.
Always prepare for missing or error data when retrieving information.
Use try-except blocks and check for None to handle failures.
Return safe default values to keep your AI working smoothly.
Practice
Solution
Step 1: Understand retrieval failures
Retrieval failures happen when the AI cannot get the needed data, which can cause errors.Step 2: Importance of graceful handling
Handling failures gracefully means preventing crashes and keeping the AI working by managing errors properly.Final Answer:
To keep the AI running smoothly without crashing -> Option AQuick Check:
Graceful failure handling = prevent crashes [OK]
- Assuming failures speed up the AI
- Ignoring the need for default values
- Believing more data is always retrieved
Solution
Step 1: Identify try-except usage
try: data = retrieve_info() except Exception: data = None uses try-except to catch errors during retrieval and sets data to None if an error occurs.Step 2: Check other options for correctness
Options A, B, and C misuse syntax or logic for error handling.Final Answer:
try: data = retrieve_info() except Exception: data = None -> Option AQuick Check:
try-except for errors = try: data = retrieve_info() except Exception: data = None [OK]
- Using if without try-except for errors
- Misusing finally block to handle errors
- Incorrect conditional expressions
def get_data():
try:
return None
except:
return 'Error'
result = get_data() or 'Default'
print(result)Solution
Step 1: Analyze get_data function
The function returns None without raising an exception, so except block is skipped.Step 2: Evaluate result assignment
Since get_data() returns None (which is falsey), the expression uses 'Default' instead.Final Answer:
Default -> Option BQuick Check:
None or 'Default' = 'Default' [OK]
- Thinking None prints as 'None' string
- Assuming except block runs without error
- Confusing return values with exceptions
def fetch_data():
try:
data = retrieve()
except:
data = None
return data
result = fetch_data()
print(result)Solution
Step 1: Check function structure
The function calls retrieve() correctly and returns data, so no missing parentheses or return issues.Step 2: Analyze except block
The except block catches all exceptions without specifying which, which is bad practice and can hide bugs.Final Answer:
No specific exception caught in except block -> Option DQuick Check:
Use specific exceptions, not bare except [OK]
- Thinking missing parentheses cause error
- Ignoring importance of specific exceptions
- Assuming data is undefined
def get_user_info(user_id):
try:
info = retrieve_user(user_id)
if info is None:
return {'name': 'Guest', 'id': 0}
return info
except RetrievalError:
return {'name': 'Guest', 'id': 0}Solution
Step 1: Understand retrieval and failure cases
The function tries to get user info, checks if data is missing (None), and handles exceptions.Step 2: Evaluate handling strategy
Returning a default dictionary for missing or failed retrieval keeps AI stable and predictable.Final Answer:
Use try-except and return a default dict on failure or missing data -> Option CQuick Check:
Safe defaults on failure = Use try-except and return a default dict on failure or missing data [OK]
- Returning None and not handling later
- Raising errors without fallback
- Returning empty strings instead of structured defaults
