Skip to document
← SynapseAbdul Moiz / Engineering studies Download PDF
Contents 12 chapters + figures

A technical study of multi-agent document intelligence

Engineering answers you can trace.

From a raw document to a cited answer: the architecture, retrieval decisions, GPU pipeline, visual artifacts, and evaluation behind a multi-tenant research workspace.

  • Agentic RAG
  • Document AI
  • GPU workers
  • Evaluation

Part I / The problem

01

Research software should show its work.

Synapse addresses a familiar failure in document-based AI: an answer sounds convincing, but the reader cannot tell which passage supports it, whether a table was read correctly, or whether important evidence was missed. The product is a research workspace, not just a prompt box over a vector database.

A user connects a collection of documents, waits for structured ingestion, and asks questions across one or many files. The answer should preserve the relationship between claims, source chunks, pages, and relevant figures. Teams can collaborate over explicitly shared libraries while personal conversations remain separate.

InputSystem responsibilityOutput
PDFs and connected Google Drive librariesPreserve layout, text, visuals, and document identitySearchable, attributed evidence
A question and its conversation contextSelect a retrieval strategy and test evidence coverageA grounded answer with citations
A visual or relationship-building requestAcquire source data, validate a specification, retain provenanceCharts, diagrams, and knowledge graphs
Synapse document library with processing statuses
Figure 1. Libraries are the unit of connected knowledge. Processing status makes ingestion visible before chat begins.

Part II / The system

02

Three planes, different responsibilities.

The system separates a responsive edge product, a GPU execution plane, and durable shared state. Next.js 16 and React 19 provide the interface. OpenNext hosts the application on Cloudflare Workers, where route handlers proxy authenticated requests, manage product state, and connect to object storage and email services.

FastAPI exposes chat, pipeline, agent, and graph services on a dedicated compute host. Ingestion is queue-backed rather than tied to a long browser request. Worker processes perform specialized stages, while the reasoning layer assembles evidence and answers. Supabase Postgres holds the tenant model, job state, conversation records, and pgvector embeddings. Cloudflare R2 holds raw and derived files.

System architectureSynapse / System map
At the edgeGPU application serverShared state & models
Web applicationNext.js 16 · React 19
Cloudflare WorkerOpenNext host · API proxy
FastAPI layerchat · agent · graph · pipeline
Worker poolsync · layout · OCR/VLM · chunk · embed · cluster
Retrieval & reasoningcorrective multi-agent loop
Model APIsOpenAI · OpenRouter
Embedding & rerankBGE encoder · cross-encoder
Supabase + pgvectortenants · jobs · vectors · chat
Cloudflare R2documents · derived artefacts
Next.js at the edge, a FastAPI/GPU execution plane, and durable shared state remain independently scalable.

One upload, two persistence layers

A file is stored in R2 and a durable preprocessing job is created in Postgres. Workers claim the job's stages and persist intermediate outputs. This keeps expensive layout, OCR, captioning, and embedding work outside the edge request lifetime. Chat can then retrieve the processed representation without re-parsing the entire collection on every question.

PlaneOwnsDoes not own
Edge applicationUser experience, authenticated API routes, library and team workflowsLong-running GPU inference
Compute serviceDocument processing, retrieval, reasoning, artifact generationThe browser's local presentation state
Shared stateTenant records, job state, embeddings, source and derived artifactsDecisions about the truth of a generated answer

Part II / The system

03

A document is more than extracted text.

Flattening a PDF into one text string discards the structure that often carries its meaning. A heading changes the interpretation of a passage; a table encodes relationships; a figure can be the only evidence for a result. Synapse turns source files into a structured intermediate representation before retrieval.

Document ingestionSynapse / System map
SourceStructure & extractionSearch representation
Syncfetch files from source
Layout parserDocLayout-YOLO regions
Text extractionborn-digital + scanned
Image captioningfigures & tables via VLM
Chunkingbuild text IR
EmbeddingBGE vectors to pgvector
Clusteringtopical groups
Artefacts persisted → Cloudflare R2 + Supabase / pgvector
Queue-driven stages persist text, layout, visual artefacts, embeddings, and clusters as work advances.
StageResponsibilityRetained representation
SyncFetch source files and prepare page inputsDocument identity and source artifacts
LayoutDetect regions with DocLayout-YOLOParagraph, heading, table, figure, and other region boundaries
Text extractionRead born-digital text and OCR scanned contentText associated with document/page context
Image captioningDescribe or transcribe visual regions using a VLMCaptions, visual artifacts, and source links
ChunkingConstruct retrieval-sized pieces with contextual and visual linksText chunks with attribution
EmbeddingEncode text and persist vectorspgvector records linked to the underlying chunks
ClusteringOrganize related content into topical groupsSemantic groupings over the processed library

The diagram presents the logical stage order. Extraction and captioning have separate worker paths after layout; their outputs are brought into the representation used for chunking. Individual stage processes let the worker planner balance model-heavy tasks against the host's available VRAM rather than loading every model in every process.

Part III / Execution

04

Specialists for structure; configuration for reasoning.

The model roster separates document perception from text reasoning. A layout detector locates regions, an OCR system reads text, a vision-language model handles visual content, and retrieval uses a dense encoder with an optional cross-encoder reranker. Reasoning roles can select different model identifiers through configuration.

RoleModel / configurationImplementation note
Layout detectionDocLayout-YOLO / DocStructBench weightsRegion-aware document parsing
OCRSurya; optional GLM-OCR fallbackScanned-text extraction alongside born-digital parsing
Remote VLMqwen/qwen2.5-vl-72b-instructDefault caption API identifier through OpenRouter
Local VLMQwen/Qwen2-VL-2B-InstructLocal configuration path when used
EmbeddingBAAI/bge-large-en-v1.5Default dense encoder; 1024-dimensional vectors
Inline rerankingBAAI/bge-reranker-v2-m3Gated by retrieval configuration
Worker rerankingBAAI/bge-reranker-baseWorker-mode default; configurable separately
ReasoningCHAT_GPT_MODEL plus per-role overridesPlanner, extractor, critic, grader, verifier, and synthesis configuration

Part III / Execution

05

Retrieval follows the question.

A precise lookup and a comparison across many documents need different retrieval behavior. The planner classifies the request, rewrites it when useful, and decomposes complex questions into sub-queries. Spotlight questions can remain narrow; comparison, aggregation, multi-hop, and multi-entity questions may need broader evidence and follow-up searches.

The runtime fans out retrieval, combines dense and lexical candidates where enabled, expands neighboring chunks, and applies cross-encoder reranking. Retrieved material is distilled into an evidence brief while preserving attribution. A relevance/sufficiency grader and a completeness critic can identify gaps before synthesis. These checks are bounded by the selected reasoning mode.

Grounded chatSynapse / System map
QuestionCorrective retrievalGrounded outcome
User questionplain-language request
Plannerclassify · rewrite · decompose
Hybrid retrievalvector + keyword search · RRF
Rerank passagescross-encoder selects top evidence
Grade evidencerelevant and sufficient?
Compose answercitation per supported claim
or
Abstain / retrieve againnever force an unsupported answer
Weak evidence loops back through retrieval; sufficient evidence advances to a cited answer.
RoleDecision or output
PlannerIntent, query class, rewritten query, and decomposition
RetrieverRanked source passages and associated evidence
ExtractorA compact, source-anchored evidence brief
Retrieval graderWhether the evidence is relevant and sufficient
Gap finder / completeness criticMissing entities, attributes, or bridging questions
SynthesizerAn answer grounded in the consolidated evidence
Faithfulness verifierUnsupported claims and a possible correction pass

Depth is a budget, not a promise of quality

UI mode / API valueCritic roundsSub-queriesBreadthAnswer token cap
Fast / low001.0x1600
Balanced / medium121.25x3200
Deep / high241.5x5500

The runtime can lower these limits with environment caps. More searches or critic calls consume latency and model budget; they do not guarantee a better answer. The useful question is whether a deeper mode recovers missing evidence on a defined evaluation slice.

Part III / Execution

06

A citation is part of the answer contract.

The synthesizer emits references that the server resolves to real source records. Citation and visual markers connect the narrative to retrieved chunks and visual artifacts; the client renders them as inspectable source chips and figure cards. This makes the evidence path available to the reader instead of hiding it behind a generic filename.

Evidence-linked answer representation
Question
  -> retrieved chunks + document/page identity
  -> distilled evidence brief
  -> answer with [[CITE:n]] and [[VISUAL:id]] markers
  -> resolved source records and visual artifacts
  -> inspectable citation chips and inline figures

Source attribution and correctness are different measurements. A cited passage may be real but irrelevant, or a sentence may overstate what the passage establishes. That is why retrieval relevance, answer correctness, citation quality, and honesty are evaluated separately rather than combined into a single unqualified 'accuracy' number.

Synapse chat interface displaying an answer and source area
Figure 2. The answer surface keeps sources alongside the response so the reader can inspect the supporting material.

Part III / Execution

07

From an answer to a reusable artifact.

Agent mode handles requests whose output is not only prose. It plans the task, acquires data through parsing and retrieval, chooses an artifact form, and builds a Vega-Lite or Mermaid specification. Validation and a bounded repair path sit between specification generation and delivery.

Agent modeSynapse / System map
GoalBuildValidateDeliver
User goallibraries · file · request
Planintent · data · artefact
Acquire dataexact re-parse + retrieval
Build the specVega-Lite or Mermaid
Validate & repairschema checks · one repair pass
Renderinteractive + downloadable
Narrateresult · assumptions · sources
Data values are bound in code rather than authored by the model, keeping visuals tied to source evidence.

Numerical data is bound by code rather than left for the model to invent. The generated specification describes how the data should be presented; it is not permission to fabricate the underlying values. A narrative explains the result, assumptions, and sources after the artifact is produced.

Synapse generated visual artifacts
Figure 3. Visual outputs are delivered inside the workspace rather than as disconnected model text.

Part III / Execution

08

Relationships retain their provenance.

The graph pipeline starts with processed library content, extracts entities and relationships, resolves duplicate names, and builds nodes and edges with confidence and source references. The resulting graph is persisted and served to the interface for exploration.

Knowledge-graph constructionSynapse / System map
EvidenceEntity pipelineInteractive graph
Processed librarychunks + captions
Extractentities & relations per chunk
Resolvemerge duplicates · normalize names
Build graphnodes · edges · confidence
Serveinteractive graph in the web app
Provenance retained → graph node / edge → source passage
Every node and edge retains provenance back to the source chunk stored with the graph in Supabase.

A graph is another representation of the evidence, not an independent source of truth. Entity resolution can merge distinct subjects; extraction can infer a relationship that a passage does not actually state. Retaining the originating chunk allows a user to inspect a graph claim and provides a basis for targeted evaluation of extraction and resolution quality.

Synapse interactive knowledge graph
Figure 4. Graph exploration offers a relationship-oriented view of the processed collection.

Part IV / Platform boundaries

09

Collaboration does not mean unrestricted access.

Organizations, members, roles, libraries, conversations, and sharing relationships are modeled explicitly. Personal chats remain private, while shared team conversations can use libraries from participating organizations only through the sharing workflow. Postgres row-level security is part of the data boundary.

Core data modelSynapse / System map
TenantKnowledgeConversation & graph
organizationtenant boundary
usermember of an organization
libraryconnected collection
documentfile + processing status
chunk_embeddingtext chunk + vector
chat_threadqueries a library
chat_messageanswer + citations
graph_node / edgeentities + relationships
Rows are scoped to an organization and protected with row-level security.

Every access path still needs to enforce the caller's permissions: listing files, retrieving chunks, resolving citation previews, downloading artifacts, and accessing graphs. In particular, server-side service-role access must be paired with application authorization; database RLS by itself does not prove a service-role request is correctly scoped.

  • Treat library sharing as an explicit grant, not an implicit consequence of joining a conversation.
  • Test organization isolation on retrieval and artifact endpoints as well as the UI.
  • Retain document and chunk identity when evidence moves between agents.
  • Do not publish secret keys or infer security certification from the presence of an RLS policy.

Part V / Evidence and evaluation

10

Measure retrieval before judging the answer.

The evaluation harness uses DOUBLE-BENCH-oriented methodology with single-hop and multi-hop questions. Its full ingestion path converts sampled page images into PDFs and runs the actual parsing, captioning, chunking, embedding, and clustering pipeline. A cheaper OCR-text path starts at chunking and must be reported as a different ingestion condition.

Evaluation designSynapse / System map
DatasetRetrievalAnswersOperations
DOUBLE-BENCHsingle-hop + multi-hop documents
Retrieval passhit@1 · hit@3 · hit@5
Deep answer passbounded agentic queries
Dual judgesanswer correctness review
RAGAS + citationsgrounding · honesty · recall
Efficiencylatency · throughput · spend
The harness defines the dataset, retrieval, answer-quality, grounding, and operational measurements shown in the result snapshots below.

Retrieval-only runs test whether the expected evidence is found without paying for answer synthesis and judging. Answer runs add dual judges, RAGAS-related measurements, citation checks, honesty/overconfidence, latency, throughput, and spend accounting. Persisted run records support aggregation and resuming work.

Page-level and document-level hits are not interchangeable

Rebuilt text PDFs may not preserve the benchmark's original page indices. A document-level match asks whether a retrieved passage belongs to the correct document. A page-level match asks a stricter question about the expected evidence page. The supplied graph below is explicitly document-level hit@5, not page-level retrieval accuracy.

Retrieval quality

Document-level hit@5

0.839Overall
1.0001-hop
1.0002-hop
0.7733-hop
0.857Born-digital
0.824Scanned
Document-level hit@5
Exact supplied results: 0.839 overall, perfect 1-hop and 2-hop retrieval, 0.773 for 3-hop, 0.857 for born-digital documents, and 0.824 for scans.

Answer quality

Dual-judge result distribution

CorrectPartially correctIncorrect
Judge B
70%12%18%
Judge A
80%14%6%
Judge A: 80% correct, 14% partially correct, 6% incorrect. Judge B: 70% correct, 12% partially correct, 18% incorrect.
MeasurementWhat it establishesWhat it does not establish
Document hit@5The correct source document appeared among the retrieved candidatesThe exact page was found, or the answer is correct
Judge distributionThe supplied judgments for the tested answer sliceUniversal reliability or an independently verified ground truth
Citation checksAgreement between claims, references, and supporting evidence under the metricA security guarantee or complete factual verification

Part VI / Operating the system

11

The job queue is part of the product.

Deployment viewSynapse / System map
BrowserCloudflareGCP GPU VM
Userweb browser
Cloudflare
synapse-webNext.js via OpenNext
R2 bucketdocuments + artefacts
GCP · NVIDIA L4
FastAPI servicechat · agent · graph · pipeline
Pipeline workerslayout · OCR/VLM · embed · cluster
Local modelsBGE encoder + reranker
The edge application talks to a dedicated GPU service while R2 and Supabase provide durable shared state.

The documented deployment uses Cloudflare for the edge application, R2 for artifacts, Supabase for shared state, and a dedicated GPU host such as an NVIDIA L4 VM. Worker planning responds to the available hardware and queued stages. API-only operation is possible when GPU workers are disabled.

Operational surfacePurpose
GET /healthLiveness of the API service
GET /readyConfiguration and GPU readiness checks
GET /hardwareHardware information and worker planning visibility
Processing jobs and stage recordsDurable progress and recovery context
Model and thinking-mode configurationExplicit cost, depth, and latency controls

Useful monitoring separates queue delay, stage execution time, model/API failures, retrieval behavior, and answer-generation latency. Model names, prompt versions, dataset identity, and run settings should accompany evaluation reports. Otherwise a score change cannot be attributed to a particular code, data, or model change.

Repository responsibility map

ModulesResponsibility
app / pipeline_api / worker_bootstrapService composition, pipeline control, and worker lifecycle
sync_worker / layout_worker / extraction_worker / caption_workerDocument acquisition and perception
chunk_worker / embed_worker / cluster_workerSearchable representations
chat_api / chat_agents / chat_runtime / chat_queueQuestion orchestration, role decisions, retrieval, and queued work
agent_api / agent_agents / agent_data / agent_specsArtifact planning, data acquisition, and specification construction
kg_extract / kg_resolve / kg_build / kg_apiKnowledge-graph construction and serving
evalDataset preparation, query runs, metrics, and reports

Closing / Engineering judgment

12

A system that exposes its assumptions.

The useful engineering lesson is not that more agents make a better product. It is that each responsibility has an explicit place: perception produces structure, retrieval produces candidate evidence, reasoning identifies gaps, synthesis produces a narrative, and evaluation tests those claims independently.

  • Preserve structure before building search: tables and figures are evidence, not decoration.
  • Bound autonomous work with runtime limits and observable stages.
  • Separate retrieval success, citation correctness, and answer quality.
  • Treat graphs and generated artifacts as derived views that still need provenance.
  • Report uncertainty, degraded checks, and benchmark scope instead of turning a demo into an unqualified reliability claim.