Platform for stateful agents: AI with advanced memory that can learn and self-improve over time.
feat: catch asyncio cancellations from app in stream response (#4112)
cthomasb230b5faf5d5
diff --git a/letta/errors.py b/letta/errors.pyindex b057bc401..52db7c004 100644--- a/letta/errors.py+++ b/letta/errors.py@@ -76,6 +76,10 @@ class LettaUserNotFoundError(LettaError):"""Error raised when a user is not found."""+class LettaUnexpectedStreamCancellationError(LettaError):+ """Error raised when a streaming request is terminated unexpectedly."""++class LLMError(LettaError):passdiff --git a/letta/server/rest_api/streaming_response.py b/letta/server/rest_api/streaming_response.pyindex a8d0f2454..c8e48d2ca 100644--- a/letta/server/rest_api/streaming_response.py+++ b/letta/server/rest_api/streaming_response.py@@ -10,6 +10,7 @@ import anyiofrom fastapi.responses import StreamingResponsefrom starlette.types import Send+from letta.errors import LettaUnexpectedStreamCancellationErrorfrom letta.log import get_loggerfrom letta.schemas.enums import JobStatusfrom letta.schemas.letta_ping import LettaPing@@ -288,33 +289,11 @@ class StreamingResponseWithStatusCode(StreamingResponse):# Handle client timeouts (should throw error to inform user)except asyncio.CancelledError as exc:- logger.warning("Stream was cancelled due to client timeout or unexpected disconnection")+ logger.warning("Stream was terminated due to unexpected cancellation from server")# Handle unexpected cancellation with errormore_body = False- error_resp = {"error": {"message": "Request was unexpectedly cancelled (likely due to client timeout or disconnection)"}}- error_event = f"event: error\ndata: {json.dumps(error_resp)}\n\n".encode(self.charset)- if not self.response_started:- await send(- {- "type": "http.response.start",- "status": 408, # Request Timeout- "headers": self.raw_headers,- }- )- raise- if self._client_connected:- try:- await send(- {- "type": "http.response.body",- "body": error_event,- "more_body": more_body,- }- )- except anyio.ClosedResourceError:- self._client_connected = Falsecapture_sentry_exception(exc)- return+ raise LettaUnexpectedStreamCancellationError("Stream was terminated due to unexpected cancellation from server")except Exception as exc:logger.exception("Unhandled Streaming Error")