mirror of
https://github.com/arsvendg/Stirling-PDF.git
synced 2026-07-15 19:10:47 +02:00
Flesh out RAG system (#6197)
# Description of Changes
Flesh out the RAG system and connect it to the PDF Question Agent so it
can respond to questions about PDFs of an extremely large size.
I'd expect lots more work will need to be done to finish off the RAG
system to really be what we need, but this should be a reasonable start
which will let us connect it to tools and have the ingestion mostly
handled automatically. I'm leaving file deletion and proper file ID
management to be done in a future PR. We also need to consider whether
all tools should retrieve content exclusively via RAG, or whether it's
beneficial to have tools sometimes fetch the direct content and other
times fetch it from RAG.
A diagram of the expected interaction is as follows:
```mermaid
sequenceDiagram
autonumber
actor U as User
participant FE as Frontend<br/>(ChatPanel)
participant J as Java<br/>(AiWorkflowService)
participant O as Engine:<br/>OrchestratorAgent
participant QA as Engine:<br/>PdfQuestionAgent
participant RAG as Engine:<br/>RagService + SqliteVecStore
participant V as VoyageAI<br/>(embeddings)
participant L as LLM<br/>(Claude / etc.)
U->>FE: types "Summarise this PDF"<br/>(PDF already uploaded)
FE->>J: POST /api/v1/ai/orchestrate/stream<br/>multipart: fileInputs[], userMessage
Note over J: ByteHashFileIdStrategy<br/>id = sha256(bytes)[:16]
J->>O: POST /api/v1/orchestrator<br/>{ files:[{id,name}], userMessage }
O->>L: route via fast model
L-->>O: delegate_pdf_question
O->>QA: PdfQuestionRequest
loop for each file
QA->>RAG: has_collection(file.id)
RAG-->>QA: false
end
QA-->>O: NeedIngestResponse(files_to_ingest)
O-->>J: { outcome:"need_ingest", filesToIngest:[...] }
Note over J: onNeedIngest
loop per file
J->>J: PDFBox: extract page text
J->>O: POST /api/v1/rag/documents<br/>(long-running timeout)
O->>RAG: chunk + stage documents
O->>V: embed_documents (batches of 256)
V-->>O: embeddings
O->>RAG: add_documents
O-->>J: { chunks_indexed: N }
end
Note over J: retry with resumeWith=pdf_question
J->>O: POST /api/v1/orchestrator
Note over O: fast-path to PdfQuestionAgent
O->>QA: PdfQuestionRequest
Note over QA: build RagCapability<br/>pinned to file IDs
QA->>L: run(prompt) with search_knowledge tool
loop up to max_searches
L->>QA: search_knowledge(query)
QA->>V: embed_query
V-->>QA: query vector
QA->>RAG: search(vector, collections=[file.id])
RAG-->>QA: top-k chunks
QA-->>L: formatted chunks
end
Note over QA: once budget spent,<br/>prepare() hides the tool
L-->>QA: PdfQuestionAnswerResponse
QA-->>O: answer
O-->>J: { outcome:"answer", answer, evidence }
J-->>FE: SSE "result"
FE->>U: assistant bubble
```
This commit is contained in:
@@ -6,7 +6,7 @@ from typing import Literal, assert_never
|
||||
from pydantic import Field, model_validator
|
||||
|
||||
from stirling.contracts.ledger import Verdict
|
||||
from stirling.models import OPERATIONS, ApiModel, ToolEndpoint
|
||||
from stirling.models import OPERATIONS, ApiModel, FileId, ToolEndpoint
|
||||
from stirling.models.agent_tool_models import AGENT_OPERATIONS, AgentToolId, AnyParamModel, AnyToolId
|
||||
|
||||
|
||||
@@ -50,6 +50,7 @@ class WorkflowOutcome(StrEnum):
|
||||
|
||||
ANSWER = "answer"
|
||||
NEED_CONTENT = "need_content"
|
||||
NEED_INGEST = "need_ingest"
|
||||
NOT_FOUND = "not_found"
|
||||
PLAN = "plan"
|
||||
NEED_CLARIFICATION = "need_clarification"
|
||||
@@ -94,12 +95,30 @@ class ConversationMessage(ApiModel):
|
||||
content: str
|
||||
|
||||
|
||||
class AiFile(ApiModel):
|
||||
"""A file the user has supplied, identified by both a stable id and a display name.
|
||||
|
||||
The id is opaque to the engine: Java generates it (content hash, file path, UUID, etc.)
|
||||
and the engine uses it as the RAG collection key for any agent that indexes content.
|
||||
The name is used in user-facing prompts and responses.
|
||||
"""
|
||||
|
||||
id: FileId = Field(min_length=1)
|
||||
name: str = Field(min_length=1)
|
||||
|
||||
|
||||
def format_conversation_history(conversation_history: list[ConversationMessage]) -> str:
|
||||
if not conversation_history:
|
||||
return "None"
|
||||
return "\n".join(f"- {message.role}: {message.content}" for message in conversation_history)
|
||||
|
||||
|
||||
def format_file_names(files: list[AiFile]) -> str:
|
||||
if not files:
|
||||
return "No file names were provided."
|
||||
return ", ".join(file.name for file in files)
|
||||
|
||||
|
||||
class PdfTextSelection(ApiModel):
|
||||
page_number: int | None = None
|
||||
text: str
|
||||
@@ -111,7 +130,7 @@ class ExtractedFileText(ApiModel):
|
||||
|
||||
|
||||
class NeedContentFileRequest(ApiModel):
|
||||
file_name: str
|
||||
file: AiFile
|
||||
page_numbers: list[int] = Field(default_factory=list)
|
||||
content_types: list[PdfContentType]
|
||||
|
||||
@@ -146,6 +165,20 @@ class MathAuditorToolReportArtifact(ApiModel):
|
||||
ToolReportArtifact = MathAuditorToolReportArtifact
|
||||
|
||||
|
||||
class NeedIngestResponse(ApiModel):
|
||||
"""Signal that the listed files must be ingested into RAG before the agent can continue.
|
||||
|
||||
Java's handling: for each file, extract the requested content types, POST to
|
||||
``/api/v1/rag/documents`` keyed by ``file.id``, then retry the original request.
|
||||
"""
|
||||
|
||||
outcome: Literal[WorkflowOutcome.NEED_INGEST] = WorkflowOutcome.NEED_INGEST
|
||||
resume_with: SupportedCapability
|
||||
reason: str
|
||||
files_to_ingest: list[AiFile]
|
||||
content_types: list[PdfContentType] = Field(default_factory=list)
|
||||
|
||||
|
||||
class ToolOperationStep(ApiModel):
|
||||
kind: Literal[StepKind.TOOL] = StepKind.TOOL
|
||||
tool: AnyToolId
|
||||
|
||||
Reference in New Issue
Block a user