mirror of
https://github.com/paperless-ngx/paperless-ngx.git
synced 2026-11-25 06:31:19 +00:00
Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c703309010 | ||
|
|
82be2b6d86 | ||
|
|
29ccfe92fd | ||
|
|
72e9c01566 |
No files matched your search
@@ -9,12 +9,11 @@ from rest_framework import status
|
|||||||
from rest_framework.test import APIClient
|
from rest_framework.test import APIClient
|
||||||
from rest_framework.test import APITestCase
|
from rest_framework.test import APITestCase
|
||||||
|
|
||||||
from documents.views import _iterate_in_sync_thread
|
|
||||||
from paperless_testing.factories import UserFactory
|
from paperless_testing.factories import UserFactory
|
||||||
from paperless_testing.permissions import grant_global
|
from paperless_testing.permissions import grant_global
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
from collections.abc import Generator
|
from collections.abc import AsyncIterator
|
||||||
|
|
||||||
from django.contrib.auth.models import User
|
from django.contrib.auth.models import User
|
||||||
from pytest_mock import MockerFixture
|
from pytest_mock import MockerFixture
|
||||||
@@ -59,6 +58,11 @@ class TestChatStreamingViewInputValidation(APITestCase):
|
|||||||
reaches the Django request the middleware sees.
|
reaches the Django request the middleware sees.
|
||||||
"""
|
"""
|
||||||
chunks = [f"token{i} " for i in range(40)]
|
chunks = [f"token{i} " for i in range(40)]
|
||||||
|
|
||||||
|
async def answer() -> AsyncIterator[str]:
|
||||||
|
for chunk in chunks:
|
||||||
|
yield chunk
|
||||||
|
|
||||||
with (
|
with (
|
||||||
mock.patch(
|
mock.patch(
|
||||||
"documents.views.AIConfig",
|
"documents.views.AIConfig",
|
||||||
@@ -66,7 +70,7 @@ class TestChatStreamingViewInputValidation(APITestCase):
|
|||||||
),
|
),
|
||||||
mock.patch(
|
mock.patch(
|
||||||
"paperless_ai.chat.stream_chat_with_documents",
|
"paperless_ai.chat.stream_chat_with_documents",
|
||||||
return_value=(c for c in chunks),
|
return_value=answer(),
|
||||||
),
|
),
|
||||||
):
|
):
|
||||||
resp = self.client.post(
|
resp = self.client.post(
|
||||||
@@ -163,74 +167,3 @@ class TestChatStreamingViewUnrestrictedFlag:
|
|||||||
assert (
|
assert (
|
||||||
mocked_stream_chat.call_args.kwargs["unrestricted"] is expected_unrestricted
|
mocked_stream_chat.call_args.kwargs["unrestricted"] is expected_unrestricted
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
class TestIterateInSyncThread:
|
|
||||||
@pytest.fixture
|
|
||||||
def events(self) -> list[str]:
|
|
||||||
return []
|
|
||||||
|
|
||||||
@pytest.fixture
|
|
||||||
def chunks(self, events: list[str]) -> Generator[str, None, None]:
|
|
||||||
def generate() -> Generator[str, None, None]:
|
|
||||||
try:
|
|
||||||
for chunk in ("first", "second"):
|
|
||||||
events.append(f"produced {chunk}")
|
|
||||||
yield chunk
|
|
||||||
finally:
|
|
||||||
events.append("closed")
|
|
||||||
|
|
||||||
return generate()
|
|
||||||
|
|
||||||
def test_yields_each_chunk_before_pulling_the_next(
|
|
||||||
self,
|
|
||||||
chunks: Generator[str, None, None],
|
|
||||||
events: list[str],
|
|
||||||
) -> None:
|
|
||||||
"""
|
|
||||||
GIVEN:
|
|
||||||
- A sync generator wrapped for async iteration
|
|
||||||
WHEN:
|
|
||||||
- The wrapper is consumed
|
|
||||||
THEN:
|
|
||||||
- Each chunk is delivered before the next one is generated,
|
|
||||||
rather than the whole generator being drained up front
|
|
||||||
"""
|
|
||||||
|
|
||||||
async def consume() -> None:
|
|
||||||
async for chunk in _iterate_in_sync_thread(chunks):
|
|
||||||
events.append(f"received {chunk}")
|
|
||||||
|
|
||||||
async_to_sync(consume)()
|
|
||||||
|
|
||||||
assert events == [
|
|
||||||
"produced first",
|
|
||||||
"received first",
|
|
||||||
"produced second",
|
|
||||||
"received second",
|
|
||||||
"closed",
|
|
||||||
]
|
|
||||||
|
|
||||||
def test_closing_early_closes_the_source_generator(
|
|
||||||
self,
|
|
||||||
chunks: Generator[str, None, None],
|
|
||||||
events: list[str],
|
|
||||||
) -> None:
|
|
||||||
"""
|
|
||||||
GIVEN:
|
|
||||||
- A sync generator wrapped for async iteration
|
|
||||||
WHEN:
|
|
||||||
- The consumer closes the wrapper after the first chunk, as
|
|
||||||
happens when the client disconnects
|
|
||||||
THEN:
|
|
||||||
- The source generator is closed, so its cleanup runs
|
|
||||||
"""
|
|
||||||
|
|
||||||
async def consume_one() -> None:
|
|
||||||
wrapper = _iterate_in_sync_thread(chunks)
|
|
||||||
await anext(wrapper)
|
|
||||||
await wrapper.aclose()
|
|
||||||
|
|
||||||
async_to_sync(consume_one)()
|
|
||||||
|
|
||||||
assert events == ["produced first", "closed"]
|
|
||||||
+5
-28
@@ -7,9 +7,7 @@ import tempfile
|
|||||||
import zipfile
|
import zipfile
|
||||||
from collections import Counter
|
from collections import Counter
|
||||||
from collections import deque
|
from collections import deque
|
||||||
from collections.abc import AsyncIterator
|
|
||||||
from collections.abc import Callable
|
from collections.abc import Callable
|
||||||
from collections.abc import Generator
|
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from datetime import timedelta
|
from datetime import timedelta
|
||||||
from http import HTTPStatus
|
from http import HTTPStatus
|
||||||
@@ -29,7 +27,6 @@ from urllib.parse import urlparse
|
|||||||
import httpx
|
import httpx
|
||||||
import magic
|
import magic
|
||||||
import pathvalidate
|
import pathvalidate
|
||||||
from asgiref.sync import sync_to_async
|
|
||||||
from django.conf import settings
|
from django.conf import settings
|
||||||
from django.contrib.auth.models import Group
|
from django.contrib.auth.models import Group
|
||||||
from django.contrib.auth.models import User
|
from django.contrib.auth.models import User
|
||||||
@@ -2419,24 +2416,6 @@ class DocumentViewSet(
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
async def _iterate_in_sync_thread(
|
|
||||||
chunks: Generator[str, None, None],
|
|
||||||
) -> AsyncIterator[str]:
|
|
||||||
"""Serve a blocking sync generator to an ASGI server chunk by chunk.
|
|
||||||
|
|
||||||
Under ASGI, Django drains a sync iterator with ``sync_to_async(list)``
|
|
||||||
before sending anything. Pull each chunk in the request's sync thread
|
|
||||||
instead, where the generator's ORM access belongs.
|
|
||||||
"""
|
|
||||||
sentinel = object() # StopIteration can't cross an asyncio Future
|
|
||||||
next_chunk = sync_to_async(next)
|
|
||||||
try:
|
|
||||||
while (chunk := await next_chunk(chunks, sentinel)) is not sentinel:
|
|
||||||
yield chunk
|
|
||||||
finally:
|
|
||||||
await sync_to_async(chunks.close)()
|
|
||||||
|
|
||||||
|
|
||||||
class ChatStreamingSerializer(serializers.Serializer[dict[str, Any]]):
|
class ChatStreamingSerializer(serializers.Serializer[dict[str, Any]]):
|
||||||
q = serializers.CharField(required=True, max_length=4000)
|
q = serializers.CharField(required=True, max_length=4000)
|
||||||
document_id = serializers.IntegerField(required=False, allow_null=True)
|
document_id = serializers.IntegerField(required=False, allow_null=True)
|
||||||
@@ -2496,13 +2475,11 @@ class ChatStreamingView(GenericAPIView[Any]):
|
|||||||
)
|
)
|
||||||
|
|
||||||
return StreamingHttpResponse(
|
return StreamingHttpResponse(
|
||||||
_iterate_in_sync_thread(
|
stream_chat_with_documents(
|
||||||
stream_chat_with_documents(
|
query_str=question,
|
||||||
query_str=question,
|
documents=documents,
|
||||||
documents=documents,
|
unrestricted=unrestricted,
|
||||||
unrestricted=unrestricted,
|
output_language=output_language,
|
||||||
output_language=output_language,
|
|
||||||
),
|
|
||||||
),
|
),
|
||||||
content_type="text/event-stream",
|
content_type="text/event-stream",
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import asyncio
|
||||||
import ipaddress
|
import ipaddress
|
||||||
import socket
|
import socket
|
||||||
from collections.abc import Collection
|
from collections.abc import Collection
|
||||||
@@ -175,7 +176,9 @@ class PinnedHostAsyncHTTPTransport(httpx.AsyncHTTPTransport):
|
|||||||
self.allow_internal = allow_internal
|
self.allow_internal = allow_internal
|
||||||
|
|
||||||
async def handle_async_request(self, request: httpx.Request) -> httpx.Response:
|
async def handle_async_request(self, request: httpx.Request) -> httpx.Response:
|
||||||
request = _rewrite_request_to_pinned_ip(
|
# Resolving the host blocks, so keep it off the event loop
|
||||||
|
request = await asyncio.to_thread(
|
||||||
|
_rewrite_request_to_pinned_ip,
|
||||||
request,
|
request,
|
||||||
allow_internal=self.allow_internal,
|
allow_internal=self.allow_internal,
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -1,11 +1,19 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
from typing import TYPE_CHECKING
|
||||||
from unittest import mock
|
from unittest import mock
|
||||||
|
|
||||||
import httpx
|
import httpx
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
|
from paperless.network import PinnedHostAsyncHTTPTransport
|
||||||
from paperless.network import PinnedHostHTTPTransport
|
from paperless.network import PinnedHostHTTPTransport
|
||||||
from paperless.network import is_public_ip
|
from paperless.network import is_public_ip
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from pytest_mock import MockerFixture
|
||||||
|
|
||||||
|
|
||||||
def test_pinned_host_transport_blocks_internal_rebinding():
|
def test_pinned_host_transport_blocks_internal_rebinding():
|
||||||
transport = PinnedHostHTTPTransport(allow_internal=False)
|
transport = PinnedHostHTTPTransport(allow_internal=False)
|
||||||
@@ -51,6 +59,58 @@ def test_pinned_host_transport_rewrites_to_vetted_ip():
|
|||||||
assert response.status_code == 200
|
assert response.status_code == 200
|
||||||
|
|
||||||
|
|
||||||
|
class TestPinnedHostAsyncHTTPTransport:
|
||||||
|
def test_blocks_internal_rebinding(self, mocker: MockerFixture) -> None:
|
||||||
|
"""
|
||||||
|
GIVEN:
|
||||||
|
- A hostname that resolves to a loopback address
|
||||||
|
WHEN:
|
||||||
|
- The async transport sends a request to it
|
||||||
|
THEN:
|
||||||
|
- The request is refused as a non-public address
|
||||||
|
"""
|
||||||
|
mocker.patch(
|
||||||
|
"paperless.network.resolve_hostname_ips",
|
||||||
|
return_value=["127.0.0.1"],
|
||||||
|
)
|
||||||
|
transport = PinnedHostAsyncHTTPTransport(allow_internal=False)
|
||||||
|
request = httpx.Request("GET", "http://example.com/test")
|
||||||
|
|
||||||
|
with pytest.raises(httpx.ConnectError, match="non-public address"):
|
||||||
|
asyncio.run(transport.handle_async_request(request))
|
||||||
|
|
||||||
|
def test_rewrites_to_vetted_ip(self, mocker: MockerFixture) -> None:
|
||||||
|
"""
|
||||||
|
GIVEN:
|
||||||
|
- A hostname that resolves to a public address
|
||||||
|
WHEN:
|
||||||
|
- The async transport sends a request to it
|
||||||
|
THEN:
|
||||||
|
- The connection goes to that address, keeping the original Host
|
||||||
|
header and TLS SNI hostname
|
||||||
|
"""
|
||||||
|
mocker.patch(
|
||||||
|
"paperless.network.resolve_hostname_ips",
|
||||||
|
return_value=["93.184.216.34"],
|
||||||
|
)
|
||||||
|
sent = mocker.patch.object(
|
||||||
|
httpx.AsyncHTTPTransport,
|
||||||
|
"handle_async_request",
|
||||||
|
autospec=True,
|
||||||
|
side_effect=lambda _self, req: httpx.Response(200, request=req),
|
||||||
|
)
|
||||||
|
transport = PinnedHostAsyncHTTPTransport(allow_internal=False)
|
||||||
|
request = httpx.Request("GET", "https://example.com:8443/test")
|
||||||
|
|
||||||
|
response = asyncio.run(transport.handle_async_request(request))
|
||||||
|
|
||||||
|
assert response.status_code == 200
|
||||||
|
rewritten = sent.call_args.args[1]
|
||||||
|
assert str(rewritten.url) == "https://93.184.216.34:8443/test"
|
||||||
|
assert rewritten.headers["Host"] == "example.com:8443"
|
||||||
|
assert rewritten.extensions["sni_hostname"] == "example.com"
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize(
|
@pytest.mark.parametrize(
|
||||||
"address",
|
"address",
|
||||||
[
|
[
|
||||||
|
|||||||
+150
-40
@@ -1,7 +1,12 @@
|
|||||||
import json
|
import json
|
||||||
import logging
|
import logging
|
||||||
import sys
|
from collections.abc import AsyncIterator
|
||||||
|
from contextlib import aclosing
|
||||||
|
from typing import TYPE_CHECKING
|
||||||
|
from typing import NamedTuple
|
||||||
|
|
||||||
|
from asgiref.sync import sync_to_async
|
||||||
|
from django.db import connections
|
||||||
from django.db.models import QuerySet
|
from django.db.models import QuerySet
|
||||||
|
|
||||||
from documents.models import Document
|
from documents.models import Document
|
||||||
@@ -17,6 +22,11 @@ from paperless_ai.prompts.context import ChatQaPromptContext
|
|||||||
from paperless_ai.prompts.context import ChatRefinePromptContext
|
from paperless_ai.prompts.context import ChatRefinePromptContext
|
||||||
from paperless_ai.prompts.render import render_prompt
|
from paperless_ai.prompts.render import render_prompt
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from llama_index.core.llms import LLM
|
||||||
|
from llama_index.core.response_synthesizers import BaseSynthesizer
|
||||||
|
from llama_index.core.schema import NodeWithScore
|
||||||
|
|
||||||
logger = logging.getLogger("paperless_ai.chat")
|
logger = logging.getLogger("paperless_ai.chat")
|
||||||
|
|
||||||
CHAT_METADATA_DELIMITER = "\n\n__PAPERLESS_CHAT_METADATA__"
|
CHAT_METADATA_DELIMITER = "\n\n__PAPERLESS_CHAT_METADATA__"
|
||||||
@@ -103,38 +113,146 @@ def _format_chat_metadata_trailer(references: list[dict[str, int | str]]) -> str
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def stream_chat_with_documents(
|
async def stream_chat_with_documents(
|
||||||
query_str: str,
|
query_str: str,
|
||||||
documents: QuerySet[Document],
|
documents: QuerySet[Document],
|
||||||
*,
|
*,
|
||||||
unrestricted: bool = False,
|
unrestricted: bool = False,
|
||||||
output_language: str | None = None,
|
output_language: str | None = None,
|
||||||
):
|
) -> AsyncIterator[str]:
|
||||||
try:
|
try:
|
||||||
yield from _stream_chat_with_documents(
|
async with aclosing(
|
||||||
query_str,
|
_stream_chat_with_documents(
|
||||||
documents,
|
query_str,
|
||||||
unrestricted=unrestricted,
|
documents,
|
||||||
output_language=output_language,
|
unrestricted=unrestricted,
|
||||||
)
|
output_language=output_language,
|
||||||
|
),
|
||||||
|
) as chunks:
|
||||||
|
async for chunk in chunks:
|
||||||
|
yield chunk
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.exception("Failed to stream document chat response: %s", e)
|
logger.exception("Failed to stream document chat response: %s", e)
|
||||||
yield CHAT_ERROR_MESSAGE
|
yield CHAT_ERROR_MESSAGE
|
||||||
|
|
||||||
|
|
||||||
def _stream_chat_with_documents(
|
async def _stream_chat_with_documents(
|
||||||
query_str: str,
|
query_str: str,
|
||||||
documents: QuerySet[Document],
|
documents: QuerySet[Document],
|
||||||
*,
|
*,
|
||||||
unrestricted: bool = False,
|
unrestricted: bool = False,
|
||||||
output_language: str | None = None,
|
output_language: str | None = None,
|
||||||
):
|
) -> AsyncIterator[str]:
|
||||||
if not documents.exists():
|
prepared = await sync_to_async(_prepare_chat)(
|
||||||
|
query_str,
|
||||||
|
documents,
|
||||||
|
unrestricted=unrestricted,
|
||||||
|
output_language=output_language,
|
||||||
|
)
|
||||||
|
if prepared is None:
|
||||||
yield CHAT_NO_CONTENT_MESSAGE
|
yield CHAT_NO_CONTENT_MESSAGE
|
||||||
return
|
return
|
||||||
|
|
||||||
|
logger.debug("Document chat query: %s", query_str)
|
||||||
|
try:
|
||||||
|
first_chunk, chunks, provider_stream = await _start_answer(
|
||||||
|
prepared.synthesizer,
|
||||||
|
query_str,
|
||||||
|
prepared.top_nodes,
|
||||||
|
)
|
||||||
|
except Exception as e:
|
||||||
|
if not _is_bad_request(e):
|
||||||
|
raise
|
||||||
|
logger.warning(
|
||||||
|
"The LLM server rejected the prompt (%s). Retrying with smaller "
|
||||||
|
"prompts. Set PAPERLESS_AI_LLM_CONTEXT_SIZE to the context size the "
|
||||||
|
"LLM server actually uses to avoid the extra request.",
|
||||||
|
e,
|
||||||
|
)
|
||||||
|
first_chunk, chunks, provider_stream = await _start_answer(
|
||||||
|
prepared.fallback_synthesizer,
|
||||||
|
query_str,
|
||||||
|
prepared.top_nodes,
|
||||||
|
)
|
||||||
|
|
||||||
|
# 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(provider_stream), aclosing(chunks):
|
||||||
|
if first_chunk is not None:
|
||||||
|
yield first_chunk
|
||||||
|
async for chunk in chunks:
|
||||||
|
yield chunk
|
||||||
|
|
||||||
|
if prepared.references:
|
||||||
|
yield _format_chat_metadata_trailer(prepared.references)
|
||||||
|
|
||||||
|
|
||||||
|
class _PreparedChat(NamedTuple):
|
||||||
|
synthesizer: "BaseSynthesizer"
|
||||||
|
# Packs the retrieved chunks by the embedding chunk size, as chat did before
|
||||||
|
# it filled the context window. Used when the server rejects the larger prompt.
|
||||||
|
fallback_synthesizer: "BaseSynthesizer"
|
||||||
|
top_nodes: list["NodeWithScore"]
|
||||||
|
references: list[dict[str, int | str]]
|
||||||
|
|
||||||
|
|
||||||
|
def _is_bad_request(exc: Exception) -> bool:
|
||||||
|
return getattr(exc, "status_code", None) == 400
|
||||||
|
|
||||||
|
|
||||||
|
async def _start_answer(
|
||||||
|
synthesizer: "BaseSynthesizer",
|
||||||
|
query_str: str,
|
||||||
|
top_nodes: list["NodeWithScore"],
|
||||||
|
) -> tuple[str | None, AsyncIterator[str], AsyncIterator[str]]:
|
||||||
|
"""Begin the answer and pull its first chunk, so a server rejecting the prompt
|
||||||
|
surfaces here, before anything has been streamed to the user. Also returns the
|
||||||
|
provider stream, which the caller must close."""
|
||||||
|
response_stream = await synthesizer.asynthesize(query_str, top_nodes)
|
||||||
|
chunks = response_stream.async_response_gen()
|
||||||
|
return await anext(chunks, None), chunks, response_stream.response_gen
|
||||||
|
|
||||||
|
|
||||||
|
def _build_synthesizer(
|
||||||
|
config: AIConfig,
|
||||||
|
llm: "LLM",
|
||||||
|
output_language: str | None,
|
||||||
|
*,
|
||||||
|
chunk_size: int,
|
||||||
|
) -> "BaseSynthesizer":
|
||||||
from llama_index.core.prompts import PromptTemplate
|
from llama_index.core.prompts import PromptTemplate
|
||||||
from llama_index.core.response_synthesizers import get_response_synthesizer
|
from llama_index.core.response_synthesizers import get_response_synthesizer
|
||||||
|
|
||||||
|
return get_response_synthesizer(
|
||||||
|
llm=llm,
|
||||||
|
prompt_helper=get_rag_prompt_helper(
|
||||||
|
chunk_size=chunk_size,
|
||||||
|
context_size=config.llm_context_size,
|
||||||
|
),
|
||||||
|
text_qa_template=PromptTemplate(template=_build_chat_prompt(output_language)),
|
||||||
|
refine_template=PromptTemplate(
|
||||||
|
template=_build_refine_prompt(output_language),
|
||||||
|
),
|
||||||
|
streaming=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _prepare_chat(
|
||||||
|
query_str: str,
|
||||||
|
documents: QuerySet[Document],
|
||||||
|
*,
|
||||||
|
unrestricted: bool,
|
||||||
|
output_language: str | None,
|
||||||
|
) -> _PreparedChat | None:
|
||||||
|
"""Everything before the answer streams, all of it blocking: ORM queries,
|
||||||
|
the index read lock and its thread-bound sqlite connection, the query
|
||||||
|
embedding, and building the LLM client. Returns None when there is no
|
||||||
|
content to answer from.
|
||||||
|
"""
|
||||||
|
if not documents.exists():
|
||||||
|
return None
|
||||||
|
|
||||||
from llama_index.core.retrievers import VectorIndexRetriever
|
from llama_index.core.retrievers import VectorIndexRetriever
|
||||||
|
|
||||||
config = AIConfig()
|
config = AIConfig()
|
||||||
@@ -150,8 +268,6 @@ def _stream_chat_with_documents(
|
|||||||
|
|
||||||
# Hold the shared read lock only while reading the index, so the compaction
|
# Hold the shared read lock only while reading the index, so the compaction
|
||||||
# swap cannot replace the database file while this connection is open.
|
# swap cannot replace the database file while this connection is open.
|
||||||
# Everything after retrieval works on the nodes already in memory, so a slow
|
|
||||||
# LLM stream never holds the lock.
|
|
||||||
with read_store() as store:
|
with read_store() as store:
|
||||||
if permitted_ids is not None:
|
if permitted_ids is not None:
|
||||||
filters = _permitted_documents_filter(store, permitted_ids)
|
filters = _permitted_documents_filter(store, permitted_ids)
|
||||||
@@ -179,35 +295,29 @@ def _stream_chat_with_documents(
|
|||||||
|
|
||||||
if not top_nodes:
|
if not top_nodes:
|
||||||
logger.warning("No nodes found for the given documents.")
|
logger.warning("No nodes found for the given documents.")
|
||||||
yield CHAT_NO_CONTENT_MESSAGE
|
return None
|
||||||
return
|
|
||||||
|
|
||||||
client = AIClient()
|
|
||||||
|
|
||||||
references = _get_document_references(documents, top_nodes)
|
references = _get_document_references(documents, top_nodes)
|
||||||
|
|
||||||
prompt_template = PromptTemplate(template=_build_chat_prompt(output_language))
|
client = AIClient()
|
||||||
refine_template = PromptTemplate(template=_build_refine_prompt(output_language))
|
# Chunk size limit equal to the context size lets llama_index pack the retrieved
|
||||||
response_synthesizer = get_response_synthesizer(
|
# chunks into as few LLM calls as the window allows, instead of one call per
|
||||||
llm=client.llm,
|
# embedding-sized chunk.
|
||||||
prompt_helper=get_rag_prompt_helper(
|
synthesizer = _build_synthesizer(
|
||||||
chunk_size=config.llm_embedding_chunk_size,
|
config,
|
||||||
context_size=config.llm_context_size,
|
client.llm,
|
||||||
),
|
output_language,
|
||||||
text_qa_template=prompt_template,
|
chunk_size=config.llm_context_size,
|
||||||
refine_template=refine_template,
|
)
|
||||||
streaming=True,
|
fallback_synthesizer = _build_synthesizer(
|
||||||
|
config,
|
||||||
|
client.llm,
|
||||||
|
output_language,
|
||||||
|
chunk_size=config.llm_embedding_chunk_size,
|
||||||
)
|
)
|
||||||
|
|
||||||
logger.debug("Document chat query: %s", query_str)
|
# No ORM access happens while the answer streams, so hand the pooled DB
|
||||||
# Release the pooled DB connection for the slow streaming LLM response
|
# connection back now rather than pin it for the whole stream. See #12976.
|
||||||
# so it is not pinned for the whole stream; see paperless_ai.db and
|
connections.close_all()
|
||||||
# #12976.
|
|
||||||
with db_connection_released():
|
|
||||||
response_stream = response_synthesizer.synthesize(query_str, top_nodes)
|
|
||||||
for chunk in response_stream.response_gen:
|
|
||||||
yield chunk
|
|
||||||
sys.stdout.flush()
|
|
||||||
|
|
||||||
if references:
|
return _PreparedChat(synthesizer, fallback_synthesizer, top_nodes, references)
|
||||||
yield _format_chat_metadata_trailer(references)
|
|
||||||
@@ -4,10 +4,12 @@ import json
|
|||||||
from contextlib import contextmanager
|
from contextlib import contextmanager
|
||||||
from typing import TYPE_CHECKING
|
from typing import TYPE_CHECKING
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
from unittest.mock import AsyncMock
|
||||||
from unittest.mock import MagicMock
|
from unittest.mock import MagicMock
|
||||||
from unittest.mock import patch
|
from unittest.mock import patch
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
|
from asgiref.sync import async_to_sync
|
||||||
from django.db.models.signals import post_init
|
from django.db.models.signals import post_init
|
||||||
from django.utils import timezone
|
from django.utils import timezone
|
||||||
from llama_index.core import settings as llama_settings
|
from llama_index.core import settings as llama_settings
|
||||||
@@ -26,6 +28,7 @@ from paperless_ai.chat import stream_chat_with_documents
|
|||||||
from paperless_testing.factories import DocumentFactory
|
from paperless_testing.factories import DocumentFactory
|
||||||
|
|
||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
|
from collections.abc import AsyncIterator
|
||||||
from collections.abc import Iterator
|
from collections.abc import Iterator
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
@@ -66,6 +69,32 @@ def assert_chat_output(
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def collect(chunks: AsyncIterator[str]) -> list[str]:
|
||||||
|
"""Drain the chat stream from sync test code. Its blocking setup then runs
|
||||||
|
on the test's own thread, inside the test's DB transaction."""
|
||||||
|
|
||||||
|
async def drain() -> list[str]:
|
||||||
|
return [chunk async for chunk in chunks]
|
||||||
|
|
||||||
|
return async_to_sync(drain)()
|
||||||
|
|
||||||
|
|
||||||
|
def fake_response_stream(chunks: list[str]) -> MagicMock:
|
||||||
|
"""An AsyncStreamingResponse stand-in yielding ``chunks``."""
|
||||||
|
|
||||||
|
async def response_gen() -> AsyncIterator[str]:
|
||||||
|
for chunk in chunks:
|
||||||
|
yield chunk
|
||||||
|
|
||||||
|
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:
|
def _fake_documents_queryset(pks: list[int]) -> MagicMock:
|
||||||
qs = MagicMock()
|
qs = MagicMock()
|
||||||
qs.exists.return_value = bool(pks)
|
qs.exists.return_value = bool(pks)
|
||||||
@@ -170,19 +199,19 @@ def test_stream_chat_with_one_document_retrieval(
|
|||||||
),
|
),
|
||||||
]
|
]
|
||||||
|
|
||||||
mock_response_stream = MagicMock()
|
|
||||||
mock_response_stream.response_gen = iter(["chunk1", "chunk2"])
|
|
||||||
mock_synthesizer = mock_get_response_synthesizer.return_value
|
mock_synthesizer = mock_get_response_synthesizer.return_value
|
||||||
mock_synthesizer.synthesize.return_value = mock_response_stream
|
mock_synthesizer.asynthesize = AsyncMock(
|
||||||
|
return_value=fake_response_stream(["chunk1", "chunk2"]),
|
||||||
|
)
|
||||||
|
|
||||||
with patch(
|
with patch(
|
||||||
"llama_index.core.retrievers.VectorIndexRetriever",
|
"llama_index.core.retrievers.VectorIndexRetriever",
|
||||||
return_value=mock_retriever_instance,
|
return_value=mock_retriever_instance,
|
||||||
):
|
):
|
||||||
output = list(stream_chat_with_documents("What is this?", documents))
|
output = collect(stream_chat_with_documents("What is this?", documents))
|
||||||
|
|
||||||
mock_retriever_instance.retrieve.assert_called_once_with("What is this?")
|
mock_retriever_instance.retrieve.assert_called_once_with("What is this?")
|
||||||
mock_synthesizer.synthesize.assert_called_once_with(
|
mock_synthesizer.asynthesize.assert_awaited_once_with(
|
||||||
"What is this?",
|
"What is this?",
|
||||||
mock_retriever_instance.retrieve.return_value,
|
mock_retriever_instance.retrieve.return_value,
|
||||||
)
|
)
|
||||||
@@ -236,20 +265,19 @@ def test_stream_chat_with_multiple_documents_retrieval(patch_embed_nodes) -> Non
|
|||||||
MagicMock(metadata={"document_id": str(doc2.pk), "title": "Document 2"}),
|
MagicMock(metadata={"document_id": str(doc2.pk), "title": "Document 2"}),
|
||||||
]
|
]
|
||||||
|
|
||||||
mock_response_stream = MagicMock()
|
|
||||||
mock_response_stream.response_gen = iter(["chunk1", "chunk2"])
|
|
||||||
|
|
||||||
mock_synthesizer = mock_get_response_synthesizer.return_value
|
mock_synthesizer = mock_get_response_synthesizer.return_value
|
||||||
mock_synthesizer.synthesize.return_value = mock_response_stream
|
mock_synthesizer.asynthesize = AsyncMock(
|
||||||
|
return_value=fake_response_stream(["chunk1", "chunk2"]),
|
||||||
|
)
|
||||||
|
|
||||||
with patch(
|
with patch(
|
||||||
"llama_index.core.retrievers.VectorIndexRetriever",
|
"llama_index.core.retrievers.VectorIndexRetriever",
|
||||||
return_value=mock_retriever_instance,
|
return_value=mock_retriever_instance,
|
||||||
):
|
):
|
||||||
output = list(stream_chat_with_documents("What's up?", documents))
|
output = collect(stream_chat_with_documents("What's up?", documents))
|
||||||
|
|
||||||
mock_retriever_instance.retrieve.assert_called_once_with("What's up?")
|
mock_retriever_instance.retrieve.assert_called_once_with("What's up?")
|
||||||
mock_synthesizer.synthesize.assert_called_once_with(
|
mock_synthesizer.asynthesize.assert_awaited_once_with(
|
||||||
"What's up?",
|
"What's up?",
|
||||||
mock_retriever_instance.retrieve.return_value,
|
mock_retriever_instance.retrieve.return_value,
|
||||||
)
|
)
|
||||||
@@ -266,7 +294,9 @@ def test_stream_chat_with_multiple_documents_retrieval(patch_embed_nodes) -> Non
|
|||||||
|
|
||||||
def test_stream_chat_empty_document_list() -> None:
|
def test_stream_chat_empty_document_list() -> None:
|
||||||
with patch("paperless_ai.chat.load_or_build_index") as mock_load_index:
|
with patch("paperless_ai.chat.load_or_build_index") as mock_load_index:
|
||||||
output = list(stream_chat_with_documents("Any info?", Document.objects.none()))
|
output = collect(
|
||||||
|
stream_chat_with_documents("Any info?", Document.objects.none()),
|
||||||
|
)
|
||||||
mock_load_index.assert_not_called()
|
mock_load_index.assert_not_called()
|
||||||
assert output == ["Sorry, I couldn't find any content to answer your question."]
|
assert output == ["Sorry, I couldn't find any content to answer your question."]
|
||||||
|
|
||||||
@@ -286,7 +316,7 @@ def test_stream_chat_no_matching_nodes() -> None:
|
|||||||
mock_index.vector_store.get_nodes.return_value = []
|
mock_index.vector_store.get_nodes.return_value = []
|
||||||
mock_load_index.return_value = mock_index
|
mock_load_index.return_value = mock_index
|
||||||
|
|
||||||
output = list(
|
output = collect(
|
||||||
stream_chat_with_documents("Any info?", _fake_documents_queryset([1])),
|
stream_chat_with_documents("Any info?", _fake_documents_queryset([1])),
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -317,7 +347,7 @@ def test_stream_chat_unexpected_failure_returns_generic_error(caplog) -> None:
|
|||||||
)
|
)
|
||||||
mock_retriever_cls.return_value = mock_retriever
|
mock_retriever_cls.return_value = mock_retriever
|
||||||
|
|
||||||
output = list(
|
output = collect(
|
||||||
stream_chat_with_documents("Any info?", _fake_documents_queryset([1])),
|
stream_chat_with_documents("Any info?", _fake_documents_queryset([1])),
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -367,7 +397,7 @@ class TestStreamChatRetrieval:
|
|||||||
) -> None:
|
) -> None:
|
||||||
doc = DocumentFactory.create(content="hello world")
|
doc = DocumentFactory.create(content="hello world")
|
||||||
# Nothing indexed for this document yet.
|
# Nothing indexed for this document yet.
|
||||||
out = list(
|
out = collect(
|
||||||
chat.stream_chat_with_documents(
|
chat.stream_chat_with_documents(
|
||||||
"question?",
|
"question?",
|
||||||
Document.objects.filter(pk=doc.pk),
|
Document.objects.filter(pk=doc.pk),
|
||||||
@@ -390,7 +420,7 @@ class TestStreamChatRetrieval:
|
|||||||
indexing.llm_index_add_or_update_document(included)
|
indexing.llm_index_add_or_update_document(included)
|
||||||
indexing.llm_index_add_or_update_document(excluded)
|
indexing.llm_index_add_or_update_document(excluded)
|
||||||
|
|
||||||
list(
|
collect(
|
||||||
chat.stream_chat_with_documents(
|
chat.stream_chat_with_documents(
|
||||||
"question?",
|
"question?",
|
||||||
Document.objects.filter(pk=included.pk),
|
Document.objects.filter(pk=included.pk),
|
||||||
@@ -419,7 +449,7 @@ class TestStreamChatRetrieval:
|
|||||||
document = DocumentFactory.create(content="indexed document content")
|
document = DocumentFactory.create(content="indexed document content")
|
||||||
indexing.llm_index_add_or_update_document(document)
|
indexing.llm_index_add_or_update_document(document)
|
||||||
|
|
||||||
list(
|
collect(
|
||||||
chat.stream_chat_with_documents(
|
chat.stream_chat_with_documents(
|
||||||
"question?",
|
"question?",
|
||||||
Document.objects.filter(pk=document.pk),
|
Document.objects.filter(pk=document.pk),
|
||||||
@@ -455,7 +485,7 @@ class TestStreamChatRetrieval:
|
|||||||
deleted_at=timezone.now(),
|
deleted_at=timezone.now(),
|
||||||
)
|
)
|
||||||
|
|
||||||
list(
|
collect(
|
||||||
chat.stream_chat_with_documents(
|
chat.stream_chat_with_documents(
|
||||||
"question?",
|
"question?",
|
||||||
Document.objects.filter(pk=kept.pk),
|
Document.objects.filter(pk=kept.pk),
|
||||||
@@ -487,7 +517,7 @@ class TestStreamChatRetrieval:
|
|||||||
indexing.llm_index_add_or_update_document(doc)
|
indexing.llm_index_add_or_update_document(doc)
|
||||||
permitted = Document.objects.filter(pk__in=[docs[0].pk, docs[1].pk])
|
permitted = Document.objects.filter(pk__in=[docs[0].pk, docs[1].pk])
|
||||||
|
|
||||||
list(chat.stream_chat_with_documents("question?", permitted))
|
collect(chat.stream_chat_with_documents("question?", permitted))
|
||||||
|
|
||||||
metadata_filter = captured_filters[0].filters[0]
|
metadata_filter = captured_filters[0].filters[0]
|
||||||
assert metadata_filter.operator == FilterOperator.NIN
|
assert metadata_filter.operator == FilterOperator.NIN
|
||||||
@@ -520,16 +550,21 @@ class TestStreamChatRetrieval:
|
|||||||
synthesizer = mocker.patch(
|
synthesizer = mocker.patch(
|
||||||
"llama_index.core.response_synthesizers.get_response_synthesizer",
|
"llama_index.core.response_synthesizers.get_response_synthesizer",
|
||||||
).return_value
|
).return_value
|
||||||
synthesizer.synthesize.return_value.response_gen = iter(["chunk"])
|
synthesizer.asynthesize = AsyncMock(
|
||||||
|
return_value=fake_response_stream(["chunk"]),
|
||||||
|
)
|
||||||
|
|
||||||
list(
|
collect(
|
||||||
chat.stream_chat_with_documents(
|
chat.stream_chat_with_documents(
|
||||||
"question?",
|
"question?",
|
||||||
Document.objects.filter(pk=permitted_doc.pk),
|
Document.objects.filter(pk=permitted_doc.pk),
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
|
|
||||||
synthesizer.synthesize.assert_called_once_with("question?", [permitted_node])
|
synthesizer.asynthesize.assert_awaited_once_with(
|
||||||
|
"question?",
|
||||||
|
[permitted_node],
|
||||||
|
)
|
||||||
|
|
||||||
@pytest.mark.django_db
|
@pytest.mark.django_db
|
||||||
def test_get_document_references_only_queries_referenced_documents(
|
def test_get_document_references_only_queries_referenced_documents(
|
||||||
@@ -612,9 +647,9 @@ class TestChatReadLock:
|
|||||||
]
|
]
|
||||||
)
|
)
|
||||||
|
|
||||||
def synthesize(*_args: object) -> object:
|
def asynthesize(*_args: object) -> MagicMock:
|
||||||
events.append("synthesize")
|
events.append("synthesize")
|
||||||
return mocker.MagicMock(response_gen=iter(["chunk"]))
|
return fake_response_stream(["chunk"])
|
||||||
|
|
||||||
mocker.patch("paperless_ai.chat.read_store", fake_read_store)
|
mocker.patch("paperless_ai.chat.read_store", fake_read_store)
|
||||||
mocker.patch("paperless_ai.chat.AIClient")
|
mocker.patch("paperless_ai.chat.AIClient")
|
||||||
@@ -625,9 +660,9 @@ class TestChatReadLock:
|
|||||||
)
|
)
|
||||||
mocker.patch(
|
mocker.patch(
|
||||||
"llama_index.core.response_synthesizers.get_response_synthesizer",
|
"llama_index.core.response_synthesizers.get_response_synthesizer",
|
||||||
).return_value.synthesize.side_effect = synthesize
|
).return_value.asynthesize = AsyncMock(side_effect=asynthesize)
|
||||||
|
|
||||||
list(
|
collect(
|
||||||
stream_chat_with_documents(
|
stream_chat_with_documents(
|
||||||
"What is this?",
|
"What is this?",
|
||||||
Document.objects.filter(pk=document.pk),
|
Document.objects.filter(pk=document.pk),
|
||||||
|
|||||||
@@ -0,0 +1,51 @@
|
|||||||
|
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 _PreparedChat
|
||||||
|
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=_PreparedChat(synthesizer, 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)
|
||||||
@@ -0,0 +1,282 @@
|
|||||||
|
"""Chat answers are generated from all retrieved chunks in as few LLM calls as the
|
||||||
|
configured context window allows, and fall back to the embedding chunk size when the
|
||||||
|
server rejects the larger prompt."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
from types import SimpleNamespace
|
||||||
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
import openai
|
||||||
|
import pytest
|
||||||
|
from asgiref.sync import async_to_sync
|
||||||
|
from llama_index.core.llms import CompletionResponse
|
||||||
|
from llama_index.core.llms import MockLLM
|
||||||
|
from llama_index.core.schema import NodeWithScore
|
||||||
|
from llama_index.core.schema import TextNode
|
||||||
|
from llama_index.core.utils import get_tokenizer
|
||||||
|
from pydantic import PrivateAttr
|
||||||
|
|
||||||
|
from documents.models import Document
|
||||||
|
from paperless_ai.chat import CHAT_ERROR_MESSAGE
|
||||||
|
from paperless_ai.chat import stream_chat_with_documents
|
||||||
|
from paperless_ai.indexing import RAG_NUM_OUTPUT
|
||||||
|
from paperless_testing.factories import DocumentFactory
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from collections.abc import Callable
|
||||||
|
from collections.abc import Iterator
|
||||||
|
|
||||||
|
import pytest_mock
|
||||||
|
|
||||||
|
CHUNK_COUNT = 5
|
||||||
|
# About 900 tokens for the estimator llama_index uses, so five of them fit in the
|
||||||
|
# default 8192 window but not in the default 1024 token chunk size limit.
|
||||||
|
CHUNK_TEXT = " ".join(["word"] * 900)
|
||||||
|
|
||||||
|
|
||||||
|
def _bad_request() -> openai.BadRequestError:
|
||||||
|
request = httpx.Request("POST", "http://llm.invalid/v1/completions")
|
||||||
|
return openai.BadRequestError(
|
||||||
|
"request exceeds the available context size",
|
||||||
|
response=httpx.Response(400, request=request),
|
||||||
|
body=None,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class ScriptedLLM(MockLLM):
|
||||||
|
"""Records every prompt it is sent and fails on request, the way a real server
|
||||||
|
does: eagerly for a plain completion, lazily on the first token of a stream."""
|
||||||
|
|
||||||
|
_prompts: list[str] = PrivateAttr(default_factory=list)
|
||||||
|
_max_prompt_chars: int | None = PrivateAttr(default=None)
|
||||||
|
_error: Exception | None = PrivateAttr(default=None)
|
||||||
|
_tokens_before_error: int = PrivateAttr(default=0)
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
*,
|
||||||
|
max_prompt_chars: int | None = None,
|
||||||
|
error: Exception | None = None,
|
||||||
|
tokens_before_error: int = 0,
|
||||||
|
) -> None:
|
||||||
|
super().__init__()
|
||||||
|
self._max_prompt_chars = max_prompt_chars
|
||||||
|
self._error = error
|
||||||
|
self._tokens_before_error = tokens_before_error
|
||||||
|
|
||||||
|
@property
|
||||||
|
def prompts(self) -> list[str]:
|
||||||
|
return self._prompts
|
||||||
|
|
||||||
|
def _failure(self, prompt: str) -> Exception | None:
|
||||||
|
if self._max_prompt_chars is not None and len(prompt) > self._max_prompt_chars:
|
||||||
|
return _bad_request()
|
||||||
|
return self._error
|
||||||
|
|
||||||
|
def complete(
|
||||||
|
self,
|
||||||
|
prompt: str,
|
||||||
|
formatted: bool = False, # noqa: FBT001, FBT002 (mirrors the base class)
|
||||||
|
**kwargs: object,
|
||||||
|
) -> CompletionResponse:
|
||||||
|
self._prompts.append(prompt)
|
||||||
|
failure = self._failure(prompt)
|
||||||
|
if failure is not None:
|
||||||
|
raise failure
|
||||||
|
return CompletionResponse(text="answer")
|
||||||
|
|
||||||
|
def stream_complete(
|
||||||
|
self,
|
||||||
|
prompt: str,
|
||||||
|
formatted: bool = False, # noqa: FBT001, FBT002 (mirrors the base class)
|
||||||
|
**kwargs: object,
|
||||||
|
) -> Iterator[CompletionResponse]:
|
||||||
|
self._prompts.append(prompt)
|
||||||
|
failure = self._failure(prompt)
|
||||||
|
|
||||||
|
def generate() -> Iterator[CompletionResponse]:
|
||||||
|
for index in range(self._tokens_before_error):
|
||||||
|
yield CompletionResponse(text="partial", delta=f"partial{index}")
|
||||||
|
if failure is not None:
|
||||||
|
raise failure
|
||||||
|
yield CompletionResponse(text="answer", delta="answer")
|
||||||
|
|
||||||
|
return generate()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def run_chat(
|
||||||
|
mocker: pytest_mock.MockerFixture,
|
||||||
|
) -> Callable[..., list[str]]:
|
||||||
|
"""Stream one chat question through the real synthesizer, with retrieval,
|
||||||
|
the index and the AI configuration stubbed."""
|
||||||
|
|
||||||
|
def run(llm: ScriptedLLM, *, context_size: int = 8192) -> list[str]:
|
||||||
|
document = DocumentFactory.create(title="Test Document", content="ignored")
|
||||||
|
nodes = [
|
||||||
|
NodeWithScore(
|
||||||
|
node=TextNode(
|
||||||
|
text=CHUNK_TEXT,
|
||||||
|
metadata={"document_id": str(document.pk), "title": "Test"},
|
||||||
|
),
|
||||||
|
score=0.9,
|
||||||
|
)
|
||||||
|
for _ in range(CHUNK_COUNT)
|
||||||
|
]
|
||||||
|
retriever = mocker.MagicMock()
|
||||||
|
retriever.retrieve.return_value = nodes
|
||||||
|
|
||||||
|
mocker.patch("paperless_ai.chat.read_store")
|
||||||
|
mocker.patch("paperless_ai.chat.load_or_build_index")
|
||||||
|
mocker.patch(
|
||||||
|
"paperless_ai.chat.AIConfig",
|
||||||
|
return_value=SimpleNamespace(
|
||||||
|
llm_context_size=context_size,
|
||||||
|
llm_embedding_chunk_size=1024,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
mocker.patch("paperless_ai.chat.AIClient").return_value.llm = llm
|
||||||
|
mocker.patch(
|
||||||
|
"llama_index.core.retrievers.VectorIndexRetriever",
|
||||||
|
return_value=retriever,
|
||||||
|
)
|
||||||
|
|
||||||
|
async def drain() -> list[str]:
|
||||||
|
return [
|
||||||
|
chunk
|
||||||
|
async for chunk in stream_chat_with_documents(
|
||||||
|
"What is this?",
|
||||||
|
Document.objects.filter(pk=document.pk),
|
||||||
|
)
|
||||||
|
]
|
||||||
|
|
||||||
|
# Driven from sync test code so the blocking setup runs on the test's own
|
||||||
|
# thread, inside the test's DB transaction.
|
||||||
|
return async_to_sync(drain)()
|
||||||
|
|
||||||
|
return run
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.django_db
|
||||||
|
class TestChunkMerging:
|
||||||
|
def test_retrieved_chunks_are_answered_in_a_single_llm_call(
|
||||||
|
self,
|
||||||
|
run_chat: Callable[..., list[str]],
|
||||||
|
) -> None:
|
||||||
|
"""
|
||||||
|
GIVEN five retrieved chunks that together fit the configured context window
|
||||||
|
WHEN a chat question is answered
|
||||||
|
THEN the LLM is called once, with every chunk in the prompt
|
||||||
|
"""
|
||||||
|
llm = ScriptedLLM()
|
||||||
|
|
||||||
|
output = run_chat(llm, context_size=8192)
|
||||||
|
|
||||||
|
assert CHAT_ERROR_MESSAGE not in output
|
||||||
|
assert len(llm.prompts) == 1
|
||||||
|
assert llm.prompts[0].count(CHUNK_TEXT) == CHUNK_COUNT
|
||||||
|
|
||||||
|
def test_small_context_window_spreads_the_chunks_over_several_calls(
|
||||||
|
self,
|
||||||
|
run_chat: Callable[..., list[str]],
|
||||||
|
) -> None:
|
||||||
|
"""
|
||||||
|
GIVEN a context window too small for all the retrieved chunks at once
|
||||||
|
WHEN a chat question is answered
|
||||||
|
THEN the chunks are spread over several LLM calls
|
||||||
|
AND every prompt leaves room in the window for the answer
|
||||||
|
"""
|
||||||
|
context_size = 4096
|
||||||
|
tokenize = get_tokenizer()
|
||||||
|
llm = ScriptedLLM()
|
||||||
|
|
||||||
|
output = run_chat(llm, context_size=context_size)
|
||||||
|
|
||||||
|
assert CHAT_ERROR_MESSAGE not in output
|
||||||
|
assert len(llm.prompts) > 1
|
||||||
|
assert all(
|
||||||
|
len(tokenize(prompt)) <= context_size - RAG_NUM_OUTPUT
|
||||||
|
for prompt in llm.prompts
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.django_db
|
||||||
|
class TestContextWindowFallback:
|
||||||
|
def test_rejected_prompt_is_retried_with_the_embedding_chunk_size(
|
||||||
|
self,
|
||||||
|
run_chat: Callable[..., list[str]],
|
||||||
|
caplog: pytest.LogCaptureFixture,
|
||||||
|
) -> None:
|
||||||
|
"""
|
||||||
|
GIVEN a server whose real context window is smaller than the configured one
|
||||||
|
WHEN the merged prompt is rejected with a bad request
|
||||||
|
THEN the question is answered again from smaller prompts
|
||||||
|
AND a warning names the context size setting
|
||||||
|
"""
|
||||||
|
max_prompt_chars = 12_000
|
||||||
|
llm = ScriptedLLM(max_prompt_chars=max_prompt_chars)
|
||||||
|
|
||||||
|
with caplog.at_level(logging.WARNING, logger="paperless_ai.chat"):
|
||||||
|
output = run_chat(llm, context_size=8192)
|
||||||
|
|
||||||
|
assert CHAT_ERROR_MESSAGE not in output
|
||||||
|
assert "answer" in output
|
||||||
|
assert len(llm.prompts[0]) > max_prompt_chars
|
||||||
|
assert all(len(prompt) <= max_prompt_chars for prompt in llm.prompts[1:])
|
||||||
|
assert "PAPERLESS_AI_LLM_CONTEXT_SIZE" in caplog.text
|
||||||
|
|
||||||
|
def test_a_rejection_of_the_retry_yields_the_generic_error(
|
||||||
|
self,
|
||||||
|
run_chat: Callable[..., list[str]],
|
||||||
|
) -> None:
|
||||||
|
"""
|
||||||
|
GIVEN a server that rejects every prompt
|
||||||
|
WHEN a chat question is answered
|
||||||
|
THEN the merged prompt is retried exactly once
|
||||||
|
AND the user gets the generic error message
|
||||||
|
"""
|
||||||
|
llm = ScriptedLLM(max_prompt_chars=0)
|
||||||
|
|
||||||
|
output = run_chat(llm)
|
||||||
|
|
||||||
|
assert output == [CHAT_ERROR_MESSAGE]
|
||||||
|
assert len(llm.prompts) == 2
|
||||||
|
|
||||||
|
def test_other_errors_are_not_retried(
|
||||||
|
self,
|
||||||
|
run_chat: Callable[..., list[str]],
|
||||||
|
caplog: pytest.LogCaptureFixture,
|
||||||
|
) -> None:
|
||||||
|
"""
|
||||||
|
GIVEN an LLM that fails with something other than a bad request
|
||||||
|
WHEN a chat question is answered
|
||||||
|
THEN there is no retry
|
||||||
|
AND the user gets the generic error message
|
||||||
|
"""
|
||||||
|
llm = ScriptedLLM(error=RuntimeError("provider is down"))
|
||||||
|
|
||||||
|
with caplog.at_level(logging.WARNING, logger="paperless_ai.chat"):
|
||||||
|
output = run_chat(llm)
|
||||||
|
|
||||||
|
assert output == [CHAT_ERROR_MESSAGE]
|
||||||
|
assert len(llm.prompts) == 1
|
||||||
|
assert "PAPERLESS_AI_LLM_CONTEXT_SIZE" not in caplog.text
|
||||||
|
|
||||||
|
def test_a_failure_after_tokens_were_streamed_is_not_retried(
|
||||||
|
self,
|
||||||
|
run_chat: Callable[..., list[str]],
|
||||||
|
) -> None:
|
||||||
|
"""
|
||||||
|
GIVEN an answer that has started streaming to the user
|
||||||
|
WHEN the stream then fails with a bad request
|
||||||
|
THEN the answer is not started over
|
||||||
|
"""
|
||||||
|
llm = ScriptedLLM(error=_bad_request(), tokens_before_error=1)
|
||||||
|
|
||||||
|
output = run_chat(llm)
|
||||||
|
|
||||||
|
assert output == ["partial0", CHAT_ERROR_MESSAGE]
|
||||||
|
assert len(llm.prompts) == 1
|
||||||
Reference in new issue
Block a user