Compare commits

..
Author SHA1 Message Date
stumpylog 053aaad28d Chore: switch sqlite-vec to the paperless-ngx patched wheels
They are built from a patched fork that carries
upstream PRs including NEON on Linux arm64, memory-safety fixes and
performance improvements for both reading and cosine ranking
2026-11-22 14:18:15 -08:00
9 changed files with 214 additions and 557 deletions

No files matched your search

+7 -1
View File
@@ -71,7 +71,7 @@ dependencies = [
"scikit-learn~=1.9.0",
"sentence-transformers>=5.6.1",
"setproctitle~=1.3.4",
"sqlite-vec==0.1.9",
"sqlite-vec==0.1.10+paperless.3",
"tantivy~=0.26.0",
"tika-client[httpx]~=1.0",
"torch>=2.13,<2.15",
@@ -164,6 +164,12 @@ psycopg-c = [
{ url = "https://github.com/paperless-ngx/builder/releases/download/psycopg-trixie-3.3.8/psycopg_c-3.3.8-cp314-cp314-manylinux_2_38_x86_64.whl", marker = "sys_platform == 'linux' and platform_machine == 'x86_64' and python_version == '3.14'" },
{ url = "https://github.com/paperless-ngx/builder/releases/download/psycopg-trixie-3.3.8/psycopg_c-3.3.8-cp314-cp314-manylinux_2_38_aarch64.whl", marker = "sys_platform == 'linux' and platform_machine == 'aarch64' and python_version == '3.14'" },
]
# Patched sqlite-vec builds
sqlite-vec = [
{ url = "https://github.com/paperless-ngx/builder/releases/download/sqlite-vec-0.1.10%2Bpaperless.3/sqlite_vec-0.1.10%2Bpaperless.3-py3-none-manylinux_2_29_x86_64.whl", marker = "sys_platform == 'linux' and platform_machine == 'x86_64'" },
{ url = "https://github.com/paperless-ngx/builder/releases/download/sqlite-vec-0.1.10%2Bpaperless.3/sqlite_vec-0.1.10%2Bpaperless.3-py3-none-manylinux_2_29_aarch64.whl", marker = "sys_platform == 'linux' and platform_machine == 'aarch64'" },
{ url = "https://github.com/paperless-ngx/builder/releases/download/sqlite-vec-0.1.10%2Bpaperless.3/sqlite_vec-0.1.10%2Bpaperless.3-py3-none-macosx_11_0_arm64.whl", marker = "sys_platform == 'darwin' and platform_machine == 'arm64'" },
]
torch = [
{ index = "pytorch-cpu" },
]
+74 -7
View File
@@ -9,11 +9,12 @@ from rest_framework import status
from rest_framework.test import APIClient
from rest_framework.test import APITestCase
from documents.views import _iterate_in_sync_thread
from paperless_testing.factories import UserFactory
from paperless_testing.permissions import grant_global
if TYPE_CHECKING:
from collections.abc import AsyncIterator
from collections.abc import Generator
from django.contrib.auth.models import User
from pytest_mock import MockerFixture
@@ -58,11 +59,6 @@ class TestChatStreamingViewInputValidation(APITestCase):
reaches the Django request the middleware sees.
"""
chunks = [f"token{i} " for i in range(40)]
async def answer() -> AsyncIterator[str]:
for chunk in chunks:
yield chunk
with (
mock.patch(
"documents.views.AIConfig",
@@ -70,7 +66,7 @@ class TestChatStreamingViewInputValidation(APITestCase):
),
mock.patch(
"paperless_ai.chat.stream_chat_with_documents",
return_value=answer(),
return_value=(c for c in chunks),
),
):
resp = self.client.post(
@@ -167,3 +163,74 @@ class TestChatStreamingViewUnrestrictedFlag:
assert (
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"]
+28 -5
View File
@@ -7,7 +7,9 @@ import tempfile
import zipfile
from collections import Counter
from collections import deque
from collections.abc import AsyncIterator
from collections.abc import Callable
from collections.abc import Generator
from datetime import datetime
from datetime import timedelta
from http import HTTPStatus
@@ -27,6 +29,7 @@ from urllib.parse import urlparse
import httpx
import magic
import pathvalidate
from asgiref.sync import sync_to_async
from django.conf import settings
from django.contrib.auth.models import Group
from django.contrib.auth.models import User
@@ -2416,6 +2419,24 @@ 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]]):
q = serializers.CharField(required=True, max_length=4000)
document_id = serializers.IntegerField(required=False, allow_null=True)
@@ -2475,11 +2496,13 @@ class ChatStreamingView(GenericAPIView[Any]):
)
return StreamingHttpResponse(
stream_chat_with_documents(
query_str=question,
documents=documents,
unrestricted=unrestricted,
output_language=output_language,
_iterate_in_sync_thread(
stream_chat_with_documents(
query_str=question,
documents=documents,
unrestricted=unrestricted,
output_language=output_language,
),
),
content_type="text/event-stream",
)
+1 -4
View File
@@ -1,4 +1,3 @@
import asyncio
import ipaddress
import socket
from collections.abc import Collection
@@ -176,9 +175,7 @@ class PinnedHostAsyncHTTPTransport(httpx.AsyncHTTPTransport):
self.allow_internal = allow_internal
async def handle_async_request(self, request: httpx.Request) -> httpx.Response:
# Resolving the host blocks, so keep it off the event loop
request = await asyncio.to_thread(
_rewrite_request_to_pinned_ip,
request = _rewrite_request_to_pinned_ip(
request,
allow_internal=self.allow_internal,
)
-60
View File
@@ -1,19 +1,11 @@
from __future__ import annotations
import asyncio
from typing import TYPE_CHECKING
from unittest import mock
import httpx
import pytest
from paperless.network import PinnedHostAsyncHTTPTransport
from paperless.network import PinnedHostHTTPTransport
from paperless.network import is_public_ip
if TYPE_CHECKING:
from pytest_mock import MockerFixture
def test_pinned_host_transport_blocks_internal_rebinding():
transport = PinnedHostHTTPTransport(allow_internal=False)
@@ -59,58 +51,6 @@ def test_pinned_host_transport_rewrites_to_vetted_ip():
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(
"address",
[
+36 -136
View File
@@ -1,11 +1,7 @@
import json
import logging
from collections.abc import AsyncIterator
from typing import TYPE_CHECKING
from typing import NamedTuple
import sys
from asgiref.sync import sync_to_async
from django.db import connections
from django.db.models import QuerySet
from documents.models import Document
@@ -21,10 +17,6 @@ from paperless_ai.prompts.context import ChatQaPromptContext
from paperless_ai.prompts.context import ChatRefinePromptContext
from paperless_ai.prompts.render import render_prompt
if TYPE_CHECKING:
from llama_index.core.response_synthesizers import BaseSynthesizer
from llama_index.core.schema import NodeWithScore
logger = logging.getLogger("paperless_ai.chat")
CHAT_METADATA_DELIMITER = "\n\n__PAPERLESS_CHAT_METADATA__"
@@ -111,138 +103,38 @@ def _format_chat_metadata_trailer(references: list[dict[str, int | str]]) -> str
)
async def stream_chat_with_documents(
def stream_chat_with_documents(
query_str: str,
documents: QuerySet[Document],
*,
unrestricted: bool = False,
output_language: str | None = None,
) -> AsyncIterator[str]:
):
try:
async for chunk in _stream_chat_with_documents(
yield from _stream_chat_with_documents(
query_str,
documents,
unrestricted=unrestricted,
output_language=output_language,
):
yield chunk
)
except Exception as e:
logger.exception("Failed to stream document chat response: %s", e)
yield CHAT_ERROR_MESSAGE
async def _stream_chat_with_documents(
def _stream_chat_with_documents(
query_str: str,
documents: QuerySet[Document],
*,
unrestricted: bool = False,
output_language: str | None = None,
) -> AsyncIterator[str]:
prepared = await sync_to_async(_prepare_chat)(
query_str,
documents,
unrestricted=unrestricted,
output_language=output_language,
)
if prepared is None:
):
if not documents.exists():
yield CHAT_NO_CONTENT_MESSAGE
return
logger.debug("Document chat query: %s", query_str)
try:
first_chunk, chunks = 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 = await _start_answer(
prepared.fallback_synthesizer,
query_str,
prepared.top_nodes,
)
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]]:
"""Begin the answer and pull its first chunk, so a server rejecting the prompt
surfaces here, before anything has been streamed to the user."""
response_stream = await synthesizer.asynthesize(query_str, top_nodes)
chunks = response_stream.async_response_gen()
return await anext(chunks, None), chunks
def _build_synthesizer(
config: AIConfig,
llm: object,
output_language: str | None,
*,
chunk_size: int,
) -> "BaseSynthesizer":
from llama_index.core.prompts import PromptTemplate
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
config = AIConfig()
@@ -258,6 +150,8 @@ def _prepare_chat(
# Hold the shared read lock only while reading the index, so the compaction
# 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:
if permitted_ids is not None:
filters = _permitted_documents_filter(store, permitted_ids)
@@ -285,29 +179,35 @@ def _prepare_chat(
if not top_nodes:
logger.warning("No nodes found for the given documents.")
return None
yield CHAT_NO_CONTENT_MESSAGE
return
client = AIClient()
references = _get_document_references(documents, top_nodes)
client = AIClient()
# Chunk size limit equal to the context size lets llama_index pack the retrieved
# chunks into as few LLM calls as the window allows, instead of one call per
# embedding-sized chunk.
synthesizer = _build_synthesizer(
config,
client.llm,
output_language,
chunk_size=config.llm_context_size,
)
fallback_synthesizer = _build_synthesizer(
config,
client.llm,
output_language,
chunk_size=config.llm_embedding_chunk_size,
prompt_template = PromptTemplate(template=_build_chat_prompt(output_language))
refine_template = PromptTemplate(template=_build_refine_prompt(output_language))
response_synthesizer = get_response_synthesizer(
llm=client.llm,
prompt_helper=get_rag_prompt_helper(
chunk_size=config.llm_embedding_chunk_size,
context_size=config.llm_context_size,
),
text_qa_template=prompt_template,
refine_template=refine_template,
streaming=True,
)
# No ORM access happens while the answer streams, so hand the pooled DB
# connection back now rather than pin it for the whole stream. See #12976.
connections.close_all()
logger.debug("Document chat query: %s", query_str)
# Release the pooled DB connection for the slow streaming LLM response
# so it is not pinned for the whole stream; see paperless_ai.db and
# #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()
return _PreparedChat(synthesizer, fallback_synthesizer, top_nodes, references)
if references:
yield _format_chat_metadata_trailer(references)
+26 -55
View File
@@ -4,12 +4,10 @@ import json
from contextlib import contextmanager
from typing import TYPE_CHECKING
from typing import Any
from unittest.mock import AsyncMock
from unittest.mock import MagicMock
from unittest.mock import patch
import pytest
from asgiref.sync import async_to_sync
from django.db.models.signals import post_init
from django.utils import timezone
from llama_index.core import settings as llama_settings
@@ -28,7 +26,6 @@ from paperless_ai.chat import stream_chat_with_documents
from paperless_testing.factories import DocumentFactory
if TYPE_CHECKING:
from collections.abc import AsyncIterator
from collections.abc import Iterator
from pathlib import Path
@@ -69,26 +66,6 @@ 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
return MagicMock(async_response_gen=response_gen)
def _fake_documents_queryset(pks: list[int]) -> MagicMock:
qs = MagicMock()
qs.exists.return_value = bool(pks)
@@ -193,19 +170,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.asynthesize = AsyncMock(
return_value=fake_response_stream(["chunk1", "chunk2"]),
)
mock_synthesizer.synthesize.return_value = mock_response_stream
with patch(
"llama_index.core.retrievers.VectorIndexRetriever",
return_value=mock_retriever_instance,
):
output = collect(stream_chat_with_documents("What is this?", documents))
output = list(stream_chat_with_documents("What is this?", documents))
mock_retriever_instance.retrieve.assert_called_once_with("What is this?")
mock_synthesizer.asynthesize.assert_awaited_once_with(
mock_synthesizer.synthesize.assert_called_once_with(
"What is this?",
mock_retriever_instance.retrieve.return_value,
)
@@ -259,19 +236,20 @@ def test_stream_chat_with_multiple_documents_retrieval(patch_embed_nodes) -> Non
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.asynthesize = AsyncMock(
return_value=fake_response_stream(["chunk1", "chunk2"]),
)
mock_synthesizer.synthesize.return_value = mock_response_stream
with patch(
"llama_index.core.retrievers.VectorIndexRetriever",
return_value=mock_retriever_instance,
):
output = collect(stream_chat_with_documents("What's up?", documents))
output = list(stream_chat_with_documents("What's up?", documents))
mock_retriever_instance.retrieve.assert_called_once_with("What's up?")
mock_synthesizer.asynthesize.assert_awaited_once_with(
mock_synthesizer.synthesize.assert_called_once_with(
"What's up?",
mock_retriever_instance.retrieve.return_value,
)
@@ -288,9 +266,7 @@ def test_stream_chat_with_multiple_documents_retrieval(patch_embed_nodes) -> Non
def test_stream_chat_empty_document_list() -> None:
with patch("paperless_ai.chat.load_or_build_index") as mock_load_index:
output = collect(
stream_chat_with_documents("Any info?", Document.objects.none()),
)
output = list(stream_chat_with_documents("Any info?", Document.objects.none()))
mock_load_index.assert_not_called()
assert output == ["Sorry, I couldn't find any content to answer your question."]
@@ -310,7 +286,7 @@ def test_stream_chat_no_matching_nodes() -> None:
mock_index.vector_store.get_nodes.return_value = []
mock_load_index.return_value = mock_index
output = collect(
output = list(
stream_chat_with_documents("Any info?", _fake_documents_queryset([1])),
)
@@ -341,7 +317,7 @@ def test_stream_chat_unexpected_failure_returns_generic_error(caplog) -> None:
)
mock_retriever_cls.return_value = mock_retriever
output = collect(
output = list(
stream_chat_with_documents("Any info?", _fake_documents_queryset([1])),
)
@@ -391,7 +367,7 @@ class TestStreamChatRetrieval:
) -> None:
doc = DocumentFactory.create(content="hello world")
# Nothing indexed for this document yet.
out = collect(
out = list(
chat.stream_chat_with_documents(
"question?",
Document.objects.filter(pk=doc.pk),
@@ -414,7 +390,7 @@ class TestStreamChatRetrieval:
indexing.llm_index_add_or_update_document(included)
indexing.llm_index_add_or_update_document(excluded)
collect(
list(
chat.stream_chat_with_documents(
"question?",
Document.objects.filter(pk=included.pk),
@@ -443,7 +419,7 @@ class TestStreamChatRetrieval:
document = DocumentFactory.create(content="indexed document content")
indexing.llm_index_add_or_update_document(document)
collect(
list(
chat.stream_chat_with_documents(
"question?",
Document.objects.filter(pk=document.pk),
@@ -479,7 +455,7 @@ class TestStreamChatRetrieval:
deleted_at=timezone.now(),
)
collect(
list(
chat.stream_chat_with_documents(
"question?",
Document.objects.filter(pk=kept.pk),
@@ -511,7 +487,7 @@ class TestStreamChatRetrieval:
indexing.llm_index_add_or_update_document(doc)
permitted = Document.objects.filter(pk__in=[docs[0].pk, docs[1].pk])
collect(chat.stream_chat_with_documents("question?", permitted))
list(chat.stream_chat_with_documents("question?", permitted))
metadata_filter = captured_filters[0].filters[0]
assert metadata_filter.operator == FilterOperator.NIN
@@ -544,21 +520,16 @@ class TestStreamChatRetrieval:
synthesizer = mocker.patch(
"llama_index.core.response_synthesizers.get_response_synthesizer",
).return_value
synthesizer.asynthesize = AsyncMock(
return_value=fake_response_stream(["chunk"]),
)
synthesizer.synthesize.return_value.response_gen = iter(["chunk"])
collect(
list(
chat.stream_chat_with_documents(
"question?",
Document.objects.filter(pk=permitted_doc.pk),
),
)
synthesizer.asynthesize.assert_awaited_once_with(
"question?",
[permitted_node],
)
synthesizer.synthesize.assert_called_once_with("question?", [permitted_node])
@pytest.mark.django_db
def test_get_document_references_only_queries_referenced_documents(
@@ -641,9 +612,9 @@ class TestChatReadLock:
]
)
def asynthesize(*_args: object) -> MagicMock:
def synthesize(*_args: object) -> object:
events.append("synthesize")
return fake_response_stream(["chunk"])
return mocker.MagicMock(response_gen=iter(["chunk"]))
mocker.patch("paperless_ai.chat.read_store", fake_read_store)
mocker.patch("paperless_ai.chat.AIClient")
@@ -654,9 +625,9 @@ class TestChatReadLock:
)
mocker.patch(
"llama_index.core.response_synthesizers.get_response_synthesizer",
).return_value.asynthesize = AsyncMock(side_effect=asynthesize)
).return_value.synthesize.side_effect = synthesize
collect(
list(
stream_chat_with_documents(
"What is this?",
Document.objects.filter(pk=document.pk),
@@ -1,282 +0,0 @@
"""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
Generated
+42 -7
View File
@@ -2562,7 +2562,9 @@ dependencies = [
{ name = "scikit-learn" },
{ name = "sentence-transformers" },
{ name = "setproctitle" },
{ name = "sqlite-vec" },
{ name = "sqlite-vec", version = "0.1.10+paperless.3", source = { url = "https://github.com/paperless-ngx/builder/releases/download/sqlite-vec-0.1.10%2Bpaperless.3/sqlite_vec-0.1.10%2Bpaperless.3-py3-none-macosx_11_0_arm64.whl" }, marker = "sys_platform != 'linux'" },
{ name = "sqlite-vec", version = "0.1.10+paperless.3", source = { url = "https://github.com/paperless-ngx/builder/releases/download/sqlite-vec-0.1.10%2Bpaperless.3/sqlite_vec-0.1.10%2Bpaperless.3-py3-none-manylinux_2_29_aarch64.whl" }, marker = "platform_machine != 'x86_64' and sys_platform == 'linux'" },
{ name = "sqlite-vec", version = "0.1.10+paperless.3", source = { url = "https://github.com/paperless-ngx/builder/releases/download/sqlite-vec-0.1.10%2Bpaperless.3/sqlite_vec-0.1.10%2Bpaperless.3-py3-none-manylinux_2_29_x86_64.whl" }, marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" },
{ name = "tantivy" },
{ name = "tika-client", extra = ["httpx"] },
{ name = "torch", version = "2.14.0", source = { registry = "https://download.pytorch.org/whl/cpu" }, marker = "sys_platform != 'linux'" },
@@ -2721,7 +2723,10 @@ requires-dist = [
{ name = "scikit-learn", specifier = "~=1.9.0" },
{ name = "sentence-transformers", specifier = ">=5.6.1" },
{ name = "setproctitle", specifier = "~=1.3.4" },
{ name = "sqlite-vec", specifier = "==0.1.9" },
{ name = "sqlite-vec", marker = "(platform_machine != 'aarch64' and platform_machine != 'arm64' and platform_machine != 'x86_64') or (platform_machine == 'aarch64' and sys_platform == 'darwin') or (platform_machine == 'x86_64' and sys_platform == 'darwin') or (platform_machine == 'arm64' and sys_platform == 'linux') or (sys_platform != 'darwin' and sys_platform != 'linux')", specifier = "==0.1.10+paperless.3" },
{ name = "sqlite-vec", marker = "platform_machine == 'arm64' and sys_platform == 'darwin'", url = "https://github.com/paperless-ngx/builder/releases/download/sqlite-vec-0.1.10%2Bpaperless.3/sqlite_vec-0.1.10%2Bpaperless.3-py3-none-macosx_11_0_arm64.whl" },
{ name = "sqlite-vec", marker = "platform_machine == 'aarch64' and sys_platform == 'linux'", url = "https://github.com/paperless-ngx/builder/releases/download/sqlite-vec-0.1.10%2Bpaperless.3/sqlite_vec-0.1.10%2Bpaperless.3-py3-none-manylinux_2_29_aarch64.whl" },
{ name = "sqlite-vec", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'", url = "https://github.com/paperless-ngx/builder/releases/download/sqlite-vec-0.1.10%2Bpaperless.3/sqlite_vec-0.1.10%2Bpaperless.3-py3-none-manylinux_2_29_x86_64.whl" },
{ name = "tantivy", specifier = "~=0.26.0" },
{ name = "tika-client", extras = ["httpx"], specifier = "~=1.0" },
{ name = "torch", specifier = ">=2.13,<2.15", index = "https://download.pytorch.org/whl/cpu" },
@@ -4108,12 +4113,42 @@ asyncio = [
[[package]]
name = "sqlite-vec"
version = "0.1.9"
source = { registry = "https://pypi.org/simple" }
version = "0.1.10+paperless.3"
source = { url = "https://github.com/paperless-ngx/builder/releases/download/sqlite-vec-0.1.10%2Bpaperless.3/sqlite_vec-0.1.10%2Bpaperless.3-py3-none-macosx_11_0_arm64.whl" }
resolution-markers = [
"python_full_version >= '3.15' and platform_machine == 'arm64' and platform_python_implementation == 'CPython' and sys_platform == 'darwin'",
"python_full_version < '3.15' and platform_machine == 'arm64' and platform_python_implementation == 'CPython' and sys_platform == 'darwin'",
]
wheels = [
{ url = "https://files.pythonhosted.org/packages/a4/3d/3677e0cd2f92e5ebc43cd29fbf565b75582bff1ccfa0b8327c7508e1084f/sqlite_vec-0.1.9-py3-none-macosx_11_0_arm64.whl", hash = "sha256:1d52e30513bae4cc9778ddbf6145610434081be4c3afe57cd877893bad9f6b6c", size = 165434, upload-time = "2026-03-31T08:02:32.712Z" },
{ url = "https://files.pythonhosted.org/packages/00/d4/f2b936d3bdc38eadcbd2a87875815db36430fab0363182ba5d12cd8e0b51/sqlite_vec-0.1.9-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:4e921e592f24a5f9a18f590b6ddd530eb637e2d474e3b1972f9bbeb773aa3cb9", size = 160076, upload-time = "2026-03-31T08:02:33.796Z" },
{ url = "https://files.pythonhosted.org/packages/6f/ad/6afd073b0f817b3e03f9e37ad626ae341805891f23c74b5292818f49ac63/sqlite_vec-0.1.9-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux1_x86_64.whl", hash = "sha256:1515727990b49e79bcaf75fdee2ffc7d461f8b66905013231251f1c8938e7786", size = 163388, upload-time = "2026-03-31T08:02:34.888Z" },
{ url = "https://github.com/paperless-ngx/builder/releases/download/sqlite-vec-0.1.10%2Bpaperless.3/sqlite_vec-0.1.10%2Bpaperless.3-py3-none-macosx_11_0_arm64.whl", hash = "sha256:8cd483975df4e833cfa10d3026bb6a7e71be2cbe3fcb7546952178849d45fa03" },
]
[[package]]
name = "sqlite-vec"
version = "0.1.10+paperless.3"
source = { url = "https://github.com/paperless-ngx/builder/releases/download/sqlite-vec-0.1.10%2Bpaperless.3/sqlite_vec-0.1.10%2Bpaperless.3-py3-none-manylinux_2_29_aarch64.whl" }
resolution-markers = [
"python_full_version >= '3.15' and platform_machine == 'aarch64' and platform_python_implementation == 'CPython' and sys_platform == 'linux'",
"python_full_version == '3.14.*' and platform_machine == 'aarch64' and platform_python_implementation == 'CPython' and sys_platform == 'linux'",
"python_full_version == '3.12.*' and platform_machine == 'aarch64' and platform_python_implementation == 'CPython' and sys_platform == 'linux'",
"(python_full_version < '3.12' and platform_machine == 'aarch64' and platform_python_implementation == 'CPython' and sys_platform == 'linux') or (python_full_version == '3.13.*' and platform_machine == 'aarch64' and platform_python_implementation == 'CPython' and sys_platform == 'linux')",
]
wheels = [
{ url = "https://github.com/paperless-ngx/builder/releases/download/sqlite-vec-0.1.10%2Bpaperless.3/sqlite_vec-0.1.10%2Bpaperless.3-py3-none-manylinux_2_29_aarch64.whl", hash = "sha256:71508033874aef98ef1a4006b4e1675be9bd9f866b3444491db480ce870a62c2" },
]
[[package]]
name = "sqlite-vec"
version = "0.1.10+paperless.3"
source = { url = "https://github.com/paperless-ngx/builder/releases/download/sqlite-vec-0.1.10%2Bpaperless.3/sqlite_vec-0.1.10%2Bpaperless.3-py3-none-manylinux_2_29_x86_64.whl" }
resolution-markers = [
"python_full_version >= '3.15' and platform_machine == 'x86_64' and platform_python_implementation == 'CPython' and sys_platform == 'linux'",
"python_full_version == '3.14.*' and platform_machine == 'x86_64' and platform_python_implementation == 'CPython' and sys_platform == 'linux'",
"python_full_version == '3.12.*' and platform_machine == 'x86_64' and platform_python_implementation == 'CPython' and sys_platform == 'linux'",
"(python_full_version < '3.12' and platform_machine == 'x86_64' and platform_python_implementation == 'CPython' and sys_platform == 'linux') or (python_full_version == '3.13.*' and platform_machine == 'x86_64' and platform_python_implementation == 'CPython' and sys_platform == 'linux')",
]
wheels = [
{ url = "https://github.com/paperless-ngx/builder/releases/download/sqlite-vec-0.1.10%2Bpaperless.3/sqlite_vec-0.1.10%2Bpaperless.3-py3-none-manylinux_2_29_x86_64.whl", hash = "sha256:9c8972c37295498460223ed592e6d8ab8e81d093604e645821fd36ec4ca30090" },
]
[[package]]