| import httpx | |
| def clean_error_message(e: Exception, action: str) -> str: | |
| """ | |
| Produce a short, actionable status message for a failed API call. | |
| Never surfaces raw exception/HTTP text (stack traces, MDN links, etc.) | |
| to end users — those are confusing and unprofessional in a live demo. | |
| """ | |
| if isinstance(e, httpx.HTTPStatusError): | |
| status = e.response.status_code | |
| if status == 500: | |
| return ( | |
| f"{action} failed — the server hit an internal error. This is often caused by " | |
| "a source text too large for the model's context window, or a temporary resource " | |
| "issue. Try a smaller token count or try again in a moment." | |
| ) | |
| if status in (502, 503, 504): | |
| return f"{action} failed — the server is temporarily unavailable (HTTP {status}). Try again in a moment." | |
| return f"{action} failed — the server returned an error (HTTP {status})." | |
| if isinstance(e, (httpx.ConnectError, httpx.ConnectTimeout)): | |
| return f"{action} failed — could not connect to the service. It may be waking up from sleep; try again shortly." | |
| if isinstance(e, (httpx.ReadTimeout, httpx.TimeoutException)): | |
| return f"{action} failed — the request timed out. Try a smaller request, or try again." | |
| return f"{action} failed — an unexpected error occurred." | |