#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere
TypeScript dockerhacktoberfestjavapdfpdf-converterpdf-editorpdf-manipulationpdf-mergerpdf-ocrpdf-toolspdf-web-appspdfmergerself-hosted
Show the planner only the operations that match the request (#7774)
Anthony Stirling175082b7635e
diff --git a/engine/.env b/engine/.envindex 1a90ad8c18..80958d80c9 100644--- a/engine/.env+++ b/engine/.env@@ -48,6 +48,11 @@ STIRLING_RAG_TOP_K=20# rather than chain more searches.STIRLING_RAG_MAX_SEARCHES=5+# How many operations the edit planner sees, ranked against the request by embedding+# similarity. The full catalogue overruns a local model's context window. Set 0 to+# disable ranking and show every operation.+STIRLING_PLANNER_SHORTLIST_SIZE=20+# Chunked reasoner settings: how big each per-worker slice is (in characters),# how many workers may run in parallel against the fast model, and how long# any single worker is allowed to wait for a response before being abandoned.diff --git a/engine/src/stirling/agents/pdf_edit.py b/engine/src/stirling/agents/pdf_edit.pyindex b89a044b88..42ad76aa94 100644--- a/engine/src/stirling/agents/pdf_edit.py+++ b/engine/src/stirling/agents/pdf_edit.py@@ -27,7 +27,15 @@ from stirling.contracts import ()from stirling.logging import Prettyfrom stirling.models import OPERATIONS, ApiModel, ParamToolModel, ToolEndpoint-from stirling.services import AppRuntime, ToolChainStep, blocking, language_directive, validate_tool_chain+from stirling.services import (+ AppRuntime,+ OperationRanker,+ ToolChainStep,+ blocking,+ language_directive,+ retrieval_query,+ validate_tool_chain,+)logger = logging.getLogger(__name__)@@ -175,6 +183,7 @@ class PdfEditAgent:def __init__(self, runtime: AppRuntime) -> None:self.runtime = runtimeself.parameter_selector = PdfEditParameterSelector(runtime)+ self.shortlist: OperationRanker = runtime.operation_shortlistasync def orchestrate(self, request: OrchestratorRequest) -> PdfEditResponse:"""Entry point for the orchestrator delegate — adapts the orchestrator's@@ -277,12 +286,19 @@ class PdfEditAgent:repair_note: str = "",) -> PdfEditPlanOutput:can_request_content = allow_need_content and not has_page_text(request.page_text)+ available = list(supported_operations)+ candidates = await self.shortlist.select(+ retrieval_query(request.user_message, request.conversation_history),+ available,+ self.runtime.settings.planner_shortlist_size,+ )+ logger.info("[pdf-edit] showing %d of %d operations", len(candidates), len(available))agent = self._build_selection_agent(- supported_operations,+ candidates,unavailable_operations,allow_need_content=can_request_content,)- return await agent.select(self._build_selection_prompt(request, supported_operations, repair_note))+ return await agent.select(self._build_selection_prompt(request, candidates, repair_note))def _build_selection_agent(self,diff --git a/engine/src/stirling/api/bootstrap.py b/engine/src/stirling/api/bootstrap.pyindex 241578438e..bc41cf3437 100644--- a/engine/src/stirling/api/bootstrap.py+++ b/engine/src/stirling/api/bootstrap.py@@ -20,6 +20,7 @@ from stirling.agents.pdf_comment import PdfCommentAgentfrom stirling.config import AppSettingsfrom stirling.documents import DocumentService, EmbeddingServicefrom stirling.services import AppRuntime, build_runtime+from stirling.services.operation_shortlist import OperationShortlist@dataclass(frozen=True)@@ -44,6 +45,7 @@ def build_app_state(fast_model: Model | None = None,smart_model: Model | None = None,embedder: EmbeddingService | None = None,+ operation_shortlist: OperationShortlist | None = None,) -> AppState:"""Build the runtime and every agent from ``settings``."""runtime = build_runtime(@@ -52,6 +54,7 @@ def build_app_state(fast_model=fast_model,smart_model=smart_model,embedder=embedder,+ operation_shortlist=operation_shortlist,)return AppState(runtime=runtime,diff --git a/engine/src/stirling/api/routes/config.py b/engine/src/stirling/api/routes/config.pyindex cc06a8d87e..9fb6fdf62a 100644--- a/engine/src/stirling/api/routes/config.py+++ b/engine/src/stirling/api/routes/config.py@@ -169,6 +169,7 @@ def apply_to_app(app: FastAPI, request: ConfigPushRequest) -> tuple[AppSettings,documents=runtime.documents,fast_model=fast_model,smart_model=smart_model,+ operation_shortlist=runtime.operation_shortlist,)app.state.settings = effectiveapply_app_state(app.state, new_state)diff --git a/engine/src/stirling/config/settings.py b/engine/src/stirling/config/settings.pyindex d0cf6eba2f..d753884592 100644--- a/engine/src/stirling/config/settings.py+++ b/engine/src/stirling/config/settings.py@@ -50,6 +50,10 @@ class AppSettings(BaseSettings):rag_chunk_overlap: int = Field(validation_alias="STIRLING_RAG_CHUNK_OVERLAP")rag_default_top_k: int = Field(validation_alias="STIRLING_RAG_TOP_K")rag_max_searches: int = Field(validation_alias="STIRLING_RAG_MAX_SEARCHES")++ # How many of the catalogue's operations the edit planner is shown. The full list+ # overruns a local model's context; 0 disables ranking and shows every operation.+ planner_shortlist_size: int = Field(default=20, validation_alias="STIRLING_PLANNER_SHORTLIST_SIZE")documents_reaper_interval_seconds: int = Field(default=900,validation_alias="STIRLING_DOCUMENTS_REAPER_INTERVAL_SECONDS",diff --git a/engine/src/stirling/services/__init__.py b/engine/src/stirling/services/__init__.pyindex 618c2f8fef..251b63d5e1 100644--- a/engine/src/stirling/services/__init__.py+++ b/engine/src/stirling/services/__init__.py@@ -1,6 +1,7 @@"""Shared services used by the Stirling AI runtime."""from .language import language_directive, set_reply_locale+from .operation_shortlist import OperationRanker, OperationShortlist, retrieval_queryfrom .progress import (ProgressEmitter,emit_progress,@@ -13,6 +14,8 @@ from .tracking import current_user_id, require_current_user_id, setup_posthog_tr__all__ = ["AppRuntime",+ "OperationRanker",+ "OperationShortlist","ProgressEmitter","ToolChainStep","ToolDiagnostic",@@ -24,6 +27,7 @@ __all__ = ["language_directive","require_current_user_id","reset_progress_emitter",+ "retrieval_query","set_progress_emitter","set_reply_locale","setup_posthog_tracking",diff --git a/engine/src/stirling/services/operation_shortlist.py b/engine/src/stirling/services/operation_shortlist.pynew file mode 100644index 0000000000..cc293397dd--- /dev/null+++ b/engine/src/stirling/services/operation_shortlist.py@@ -0,0 +1,107 @@+"""Narrows the operation catalogue to the candidates worth showing the planner."""++from __future__ import annotations++import asyncio+import logging+from collections.abc import Callable+from typing import Protocol++from stirling.contracts.common import ConversationMessage+from stirling.models import OPERATIONS, ToolEndpoint++logger = logging.getLogger(__name__)++QUERY_HISTORY_TURNS = 4+QUERY_TURN_CHARS = 500+++class TextEmbedder(Protocol):+ """The slice of an embedding service the shortlist needs; ``EmbeddingService`` satisfies it."""++ async def embed_documents(self, texts: list[str]) -> list[list[float]]: ...++ async def embed_query(self, text: str) -> list[float]: ...+++class OperationRanker(Protocol):+ """The ranking surface the planner depends on; :class:`OperationShortlist` is the implementation."""++ async def select(self, query: str, operations: list[ToolEndpoint], limit: int) -> list[ToolEndpoint]: ...+++def retrieval_text(operation: ToolEndpoint) -> str:+ model = OPERATIONS[operation]+ description = (model.model_json_schema().get("description") or "").strip()+ parameters = [(field.description or "").strip() for field in model.model_fields.values() if field.description]+ return f"{operation.name.replace('_', ' ').lower()}. {description} {' '.join(parameters)}".strip()+++def retrieval_query(message: str, conversation_history: list[ConversationMessage]) -> str:+ """The text to rank operations against: the recent turns plus the current message.++ A follow-up like "do the same to the other file" names no operation, so ranking it alone+ retrieves an arbitrary twenty. The history is truncated because an embedded query that is+ mostly transcript ranks on the transcript rather than on what the user just asked for.+ """+ turns = [+ turn.content.strip()[:QUERY_TURN_CHARS]+ for turn in conversation_history[-QUERY_HISTORY_TURNS:]+ if turn.content.strip()+ ]+ return "\n".join([*turns, message])+++def _cosine(left: list[float], right: list[float]) -> float:+ dot = sum(a * b for a, b in zip(left, right, strict=True))+ left_norm = sum(a * a for a in left) ** 0.5+ right_norm = sum(b * b for b in right) ** 0.5+ return dot / (left_norm * right_norm) if left_norm and right_norm else 0.0+++class OperationShortlist:+ """Ranks the catalogue against a request, caching the catalogue's embedding.++ One instance is shared by every request through :class:`AppRuntime`, so the catalogue is+ embedded once rather than once per planning call. ``resolve_embedder`` is called on each+ ``select`` rather than captured, because an admin config push swaps the embedder onto the+ live document service; the cache is dropped when it returns a different one.+ """++ def __init__(self, resolve_embedder: Callable[[], TextEmbedder]) -> None:+ self._resolve_embedder = resolve_embedder+ self._vectors: dict[ToolEndpoint, list[float]] | None = None+ self._vectors_embedder: TextEmbedder | None = None+ self._lock = asyncio.Lock()++ async def _catalogue_vectors(self, embedder: TextEmbedder) -> dict[ToolEndpoint, list[float]]:+ async with self._lock:+ if self._vectors is None or self._vectors_embedder is not embedder:+ operations = list(OPERATIONS)+ embeddings = await embedder.embed_documents([retrieval_text(op) for op in operations])+ self._vectors = dict(zip(operations, embeddings, strict=True))+ self._vectors_embedder = embedder+ return self._vectors++ async def select(+ self,+ query: str,+ operations: list[ToolEndpoint],+ limit: int,+ ) -> list[ToolEndpoint]:+ """The ``limit`` operations closest to ``query``, or all of them if ranking is unavailable.++ Falling back to the full list keeps a planner that would otherwise work on a deployment+ with no reachable embedding provider, at the cost of a much larger prompt.+ """+ if limit <= 0 or len(operations) <= limit:+ return operations+ embedder = self._resolve_embedder()+ try:+ vectors = await self._catalogue_vectors(embedder)+ query_vector = await embedder.embed_query(query)+ except Exception: # noqa: BLE001 - any embedding failure should fall back, never fail planning+ logger.warning("[pdf-edit] operation ranking unavailable, showing the full catalogue", exc_info=True)+ return operations+ ranked = sorted(operations, key=lambda op: -_cosine(query_vector, vectors[op]))+ return ranked[:limit]diff --git a/engine/src/stirling/services/runtime.py b/engine/src/stirling/services/runtime.pyindex 02ca83b5e4..39ceac4819 100644--- a/engine/src/stirling/services/runtime.py+++ b/engine/src/stirling/services/runtime.py@@ -28,6 +28,7 @@ from stirling.documents import (PgVectorStore,SqliteVecStore,)+from stirling.services.operation_shortlist import OperationShortlistlogger = logging.getLogger(__name__)@@ -147,6 +148,7 @@ class AppRuntime:fast_model: Modelsmart_model: Modeldocuments: DocumentService+ operation_shortlist: OperationShortlist@propertydef fast_model_settings(self) -> ModelSettings:@@ -212,6 +214,7 @@ def build_runtime(fast_model: Model | None = None,smart_model: Model | None = None,embedder: EmbeddingService | None = None,+ operation_shortlist: OperationShortlist | None = None,) -> AppRuntime:"""Assemble the shared runtime; the keyword args let a config-push reuse the live store and inject built models."""fast = fast_model if fast_model is not None else _build_model(settings.fast_model_name)@@ -222,11 +225,17 @@ def build_runtime(# One semaphore across both tiers: the cap protects the provider account# and process resources, which the tiers share.model_semaphore = asyncio.Semaphore(settings.model_max_concurrency)+ document_service = documents if documents is not None else _build_documents(settings, embedder)return AppRuntime(settings=settings,fast_model=ConcurrencyLimitedModel(fast, model_semaphore),smart_model=ConcurrencyLimitedModel(smart, model_semaphore),- documents=documents if documents is not None else _build_documents(settings, embedder),+ documents=document_service,+ operation_shortlist=(+ operation_shortlist+ if operation_shortlist is not None+ else OperationShortlist(lambda: document_service.embedder)+ ),)diff --git a/engine/tests/test_operation_shortlist.py b/engine/tests/test_operation_shortlist.pynew file mode 100644index 0000000000..45453d4d99--- /dev/null+++ b/engine/tests/test_operation_shortlist.py@@ -0,0 +1,135 @@+from __future__ import annotations++import pytest++from stirling.contracts import ConversationMessage+from stirling.models import OPERATIONS, ToolEndpoint+from stirling.services.operation_shortlist import (+ QUERY_HISTORY_TURNS,+ QUERY_TURN_CHARS,+ OperationShortlist,+ retrieval_query,+ retrieval_text,+)+++class StubEmbedder:+ """Embeds on a single axis: how often 'watermark' appears, so ranking is predictable."""++ def __init__(self, fail: bool = False) -> None:+ self.fail = fail+ self.document_calls = 0+ self.queries: list[str] = []++ @staticmethod+ def _vector(text: str) -> list[float]:+ return [float(text.lower().count("watermark")), 1.0]++ async def embed_documents(self, texts: list[str]) -> list[list[float]]:+ if self.fail:+ raise RuntimeError("embedding provider unreachable")+ self.document_calls += 1+ return [self._vector(text) for text in texts]++ async def embed_query(self, text: str) -> list[float]:+ if self.fail:+ raise RuntimeError("embedding provider unreachable")+ self.queries.append(text)+ return self._vector(text)+++async def test_returns_every_operation_when_the_limit_is_not_binding() -> None:+ shortlist = OperationShortlist(StubEmbedder) # never resolved: the limit short-circuits first+ operations = list(OPERATIONS)[:5]++ assert await shortlist.select("watermark this", operations, len(operations)) == operations+ assert await shortlist.select("watermark this", operations, 0) == operations+++async def test_narrows_to_the_closest_operations() -> None:+ embedder = StubEmbedder()+ shortlist = OperationShortlist(lambda: embedder)+ operations = list(OPERATIONS)++ selected = await shortlist.select("watermark watermark watermark", operations, 5)++ assert len(selected) == 5+ assert ToolEndpoint.ADD_WATERMARK in selected+++async def test_falls_back_to_the_full_catalogue_when_embedding_fails() -> None:+ embedder = StubEmbedder(fail=True)+ shortlist = OperationShortlist(lambda: embedder)+ operations = list(OPERATIONS)++ assert await shortlist.select("watermark this", operations, 5) == operations+++async def test_embeds_the_catalogue_once() -> None:+ embedder = StubEmbedder()+ shortlist = OperationShortlist(lambda: embedder)+ operations = list(OPERATIONS)++ await shortlist.select("watermark this", operations, 5)+ await shortlist.select("rotate this", operations, 5)++ assert embedder.document_calls == 1+++async def test_re_embeds_the_catalogue_when_the_embedder_is_swapped() -> None:+ embedders = [StubEmbedder(), StubEmbedder()]+ shortlist = OperationShortlist(lambda: embedders[-1])+ operations = list(OPERATIONS)++ await shortlist.select("watermark this", operations, 5)+ embedders.append(StubEmbedder())+ await shortlist.select("watermark this", operations, 5)++ assert [embedder.document_calls for embedder in embedders] == [0, 1, 1]+++def test_retrieval_text_carries_parameter_descriptions() -> None:+ text = retrieval_text(ToolEndpoint.ADD_WATERMARK)++ assert "add watermark" in text+ assert "opacity" in text.lower()+++def test_retrieval_query_carries_the_recent_conversation() -> None:+ query = retrieval_query(+ "do the same to the other file",+ [+ ConversationMessage(role="user", content="add a watermark saying DRAFT"),+ ConversationMessage(role="assistant", content="Watermarked report.pdf."),+ ],+ )++ assert "watermark" in query+ assert query.endswith("do the same to the other file")+++def test_retrieval_query_bounds_the_history_it_carries() -> None:+ history = [ConversationMessage(role="user", content=f"turn {index} " + "x" * 2_000) for index in range(10)]++ query = retrieval_query("rotate it", history)++ assert query.startswith(f"turn {len(history) - QUERY_HISTORY_TURNS} ")+ assert "turn 0" not in query+ assert len(query) <= QUERY_HISTORY_TURNS * (QUERY_TURN_CHARS + 1) + len("rotate it")+++async def test_a_follow_up_turn_still_ranks_the_operation_it_refers_to() -> None:+ embedder = StubEmbedder()+ shortlist = OperationShortlist(lambda: embedder)+ operations = list(OPERATIONS)+ history = [ConversationMessage(role="user", content="add a watermark saying DRAFT")]++ selected = await shortlist.select(retrieval_query("do the same to the other file", history), operations, 5)++ assert ToolEndpoint.ADD_WATERMARK in selecteddiff --git a/engine/tests/test_pdf_edit_agent.py b/engine/tests/test_pdf_edit_agent.pyindex 82680ab176..9a8a7ea037 100644--- a/engine/tests/test_pdf_edit_agent.py+++ b/engine/tests/test_pdf_edit_agent.py@@ -9,6 +9,7 @@ from stirling.agents import PdfEditAgent, PdfEditParameterSelector, PdfEditPlanSfrom stirling.agents.pdf_edit import PdfEditNeedContentSelection, PdfEditPlanOutputfrom stirling.contracts import (AiFile,+ ConversationMessage,EditCannotDoResponse,EditClarificationRequest,EditPlanResponse,@@ -397,6 +398,10 @@ async def test_pdf_edit_selection_agent_excludes_need_content_from_schema_when_nassert PdfEditNeedContentSelection not in _agent_output_types(cannot_request)+def _agent_system_prompt(agent: object) -> str:+ return "".join(getattr(getattr(agent, "agent"), "_system_prompts", ()))++def _agent_output_types(agent: object) -> list[type]:native = getattr(getattr(agent, "agent"), "output_type")return list(getattr(native, "outputs", []))@@ -696,3 +701,82 @@ async def test_pdf_edit_agent_composes_edit_text_with_other_operations(runtime:]assert isinstance(response.steps[0].parameters, EditTextParams)assert isinstance(response.steps[1].parameters, RotatePdfParams)+++class RecordingShortlist:+ """Stands in for the runtime shortlist: the test suite has no reachable embedding provider."""++ def __init__(self, selection: list[ToolEndpoint]) -> None:+ self.selection = selection+ self.calls: list[tuple[str, list[ToolEndpoint], int]] = []++ async def select(self, query: str, operations: list[ToolEndpoint], limit: int) -> list[ToolEndpoint]:+ self.calls.append((query, list(operations), limit))+ return self.selection+++async def test_pdf_edit_agent_shows_the_planner_only_the_shortlisted_operations(+ runtime: AppRuntime,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ from stirling.agents.pdf_edit import PdfEditSelectionAgent++ agent = PdfEditAgent(runtime)+ narrowed = [ToolEndpoint.ROTATE_PDF, ToolEndpoint.ADD_WATERMARK]+ agent.shortlist = RecordingShortlist(narrowed)+ recorded: list[tuple[PdfEditSelectionAgent, str]] = []++ async def record(self: PdfEditSelectionAgent, prompt: str) -> PdfEditPlanOutput:+ recorded.append((self, prompt))+ return _ANY_SELECTION++ monkeypatch.setattr(PdfEditSelectionAgent, "select", record)++ await agent._select_plan(PdfEditRequest(user_message="Rotate it."), list(OPERATIONS), [])++ selection_agent, user_prompt = recorded[0]+ system_prompt = _agent_system_prompt(selection_agent)+ for operation in narrowed:+ assert operation.name in system_prompt+ assert f"- {operation.name} " in user_prompt+ assert ToolEndpoint.SPLIT_PAGES.name not in system_prompt+ assert ToolEndpoint.SPLIT_PAGES.name not in user_prompt+++async def test_pdf_edit_agent_ranks_operations_against_the_conversation_not_just_the_last_message(+ runtime: AppRuntime,+) -> None:+ from stirling.agents.pdf_edit import PdfEditSelectionAgent++ agent = PdfEditAgent(runtime)+ shortlist = RecordingShortlist([ToolEndpoint.ADD_WATERMARK])+ agent.shortlist = shortlist++ def record(+ supported_operations: Iterable[ToolEndpoint],+ unavailable_operations: Iterable[ToolEndpoint],+ *,+ allow_need_content: bool,+ ) -> PdfEditSelectionAgent:+ raise _StopSelectionError()++ agent._build_selection_agent = record++ request = PdfEditRequest(+ user_message="do the same to the other file",+ conversation_history=[ConversationMessage(role="user", content="add a watermark saying DRAFT")],+ )+ with pytest.raises(_StopSelectionError):+ await agent._select_plan(request, list(OPERATIONS), [])++ query, operations, limit = shortlist.calls[0]+ assert "watermark" in query+ assert query.endswith("do the same to the other file")+ assert operations == list(OPERATIONS)+ assert limit == runtime.settings.planner_shortlist_size+++def test_pdf_edit_agents_share_the_runtime_shortlist(runtime: AppRuntime) -> None:+ assert PdfEditAgent(runtime).shortlist is PdfEditAgent(runtime).shortlist is runtime.operation_shortlist