Implement defensive programming by wrapping potentially failing operations in safe methods that provide fallback behavior. Critical operations should never cause the main functionality to fail due to secondary concerns like formatting, logging, or auxiliary processing.
Key principles:
Example implementation:
# Instead of direct operation that could fail
"x-litellm-response-cost": str(round(response_cost, 6))
# Use safe helper method with fallback
def safe_round_cost(cost: float) -> str:
try:
return str(round(cost, 6))
except Exception:
return str(cost) # fallback to original value
"x-litellm-response-cost": safe_round_cost(response_cost)
This approach prevents secondary failures from cascading and breaking primary functionality, while still attempting the preferred operation when possible.
Enter the URL of a public GitHub repository