Skip to content

armgit / letta

Public Imported from GitHub
0

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.py
index 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):
pass
diff --git a/letta/server/rest_api/streaming_response.py b/letta/server/rest_api/streaming_response.py
index a8d0f2454..c8e48d2ca 100644
--- a/letta/server/rest_api/streaming_response.py
+++ b/letta/server/rest_api/streaming_response.py
@@ -10,6 +10,7 @@ import anyio
from fastapi.responses import StreamingResponse
from starlette.types import Send
+from letta.errors import LettaUnexpectedStreamCancellationError
from letta.log import get_logger
from letta.schemas.enums import JobStatus
from 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 error
more_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 = False
capture_sentry_exception(exc)
- return
+ raise LettaUnexpectedStreamCancellationError("Stream was terminated due to unexpected cancellation from server")
except Exception as exc:
logger.exception("Unhandled Streaming Error")