diff --git a/src/paperless_ai/chat.py b/src/paperless_ai/chat.py index edcf969a50..95cc309680 100644 --- a/src/paperless_ai/chat.py +++ b/src/paperless_ai/chat.py @@ -1,6 +1,7 @@ import json import logging from collections.abc import AsyncIterator +from contextlib import aclosing from typing import TYPE_CHECKING from asgiref.sync import sync_to_async @@ -118,13 +119,16 @@ async def stream_chat_with_documents( output_language: str | None = None, ) -> AsyncIterator[str]: try: - async for chunk in _stream_chat_with_documents( - query_str, - documents, - unrestricted=unrestricted, - output_language=output_language, - ): - yield chunk + async with aclosing( + _stream_chat_with_documents( + query_str, + documents, + unrestricted=unrestricted, + output_language=output_language, + ), + ) as chunks: + async for chunk in chunks: + yield chunk except Exception as e: logger.exception("Failed to stream document chat response: %s", e) yield CHAT_ERROR_MESSAGE @@ -150,8 +154,15 @@ async def _stream_chat_with_documents( logger.debug("Document chat query: %s", query_str) response_stream = await response_synthesizer.asynthesize(query_str, top_nodes) - async for chunk in response_stream.async_response_gen(): - yield chunk + # llama-index forwards chunks without closing what it reads from, so own + # the provider stream here. Exit order closes the forwarder, then the + # provider stream, so a disconnect releases the LLM request immediately. + async with ( + aclosing(response_stream.response_gen), + aclosing(response_stream.async_response_gen()) as chunks, + ): + async for chunk in chunks: + yield chunk if references: yield _format_chat_metadata_trailer(references) diff --git a/src/paperless_ai/tests/test_chat.py b/src/paperless_ai/tests/test_chat.py index 7ae034ba65..c2e8e7eaab 100644 --- a/src/paperless_ai/tests/test_chat.py +++ b/src/paperless_ai/tests/test_chat.py @@ -86,7 +86,13 @@ def fake_response_stream(chunks: list[str]) -> MagicMock: for chunk in chunks: yield chunk - return MagicMock(async_response_gen=response_gen) + async def async_response_gen() -> AsyncIterator[str]: + async for chunk in stream.response_gen: + yield chunk + + stream = MagicMock(async_response_gen=async_response_gen) + stream.response_gen = response_gen() + return stream def _fake_documents_queryset(pks: list[int]) -> MagicMock: diff --git a/src/paperless_ai/tests/test_chat_cancellation.py b/src/paperless_ai/tests/test_chat_cancellation.py new file mode 100644 index 0000000000..8474928cf6 --- /dev/null +++ b/src/paperless_ai/tests/test_chat_cancellation.py @@ -0,0 +1,50 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING +from unittest.mock import AsyncMock +from unittest.mock import MagicMock +from unittest.mock import patch + +import pytest + +from paperless_ai.chat import stream_chat_with_documents + +if TYPE_CHECKING: + from collections.abc import AsyncIterator + + +@pytest.mark.asyncio +async def test_closing_after_a_chunk_closes_the_provider_stream() -> None: + provider_closed = False + + async def provider_stream() -> AsyncIterator[str]: + nonlocal provider_closed + try: + yield "first" + yield "second" + finally: + provider_closed = True + + provider = provider_stream() + + # Like llama-index, forward chunks without closing the stream read from + async def async_response_gen() -> AsyncIterator[str]: + async for chunk in provider: + yield chunk + + response_stream = MagicMock(async_response_gen=async_response_gen) + response_stream.response_gen = provider + synthesizer = MagicMock(asynthesize=AsyncMock(return_value=response_stream)) + references = [{"id": 1, "title": "Doc"}] + + with patch( + "paperless_ai.chat._prepare_chat", + return_value=(synthesizer, [], references), + ): + chunks = stream_chat_with_documents("Any info?", MagicMock()) + assert await anext(chunks) == "first" + await chunks.aclose() + + assert provider_closed + with pytest.raises(StopAsyncIteration): + await anext(chunks)