All projects

Generative AI / RAG Platform

Agentic research workspace

Knowledge Base RAG

An agentic document research workspace. PydanticAI agents work through a typed research graph over an application-owned ResearchState: they search authorized sources, read original PDF pages, extract values and hand the arithmetic to code, then answer with citations you can open.

Agents decide what to look for. The application owns the state, the tools, the maths and the release.
View repository PydanticAI, typed research graph, ResearchState, local-first reference system
120 distinct long-document questions103/120
Accepted outcomes81 source-correct answers, 4 qualified calculations and 18 correct refusals, each question counted once and checked against the original PDF.
120k tokens, at most six tool attempts10 REQUESTS, 240 S
Bounded research budgetThe profile used for recent document runs, with a stop after two rounds without progress and a 60-second finalization reserve. They are server-side limits that a user request cannot widen.
Reasoning effort set per stage10 AGENT ROLES
Typed PydanticAI stagesReading and extraction run light; planning, source selection, quantity checks, scope judgment and finalization run at medium effort.
Latest recorded run2,125 TESTS
Backend test suiteThe normal suite makes no paid provider calls; a separate target runs the local-model checks.

Research is a controlled loop, not a longer prompt

Questions over complex tables, charts and scanned PDFs need evidence that is found, read from the right place and computed correctly. Agents handle the semantic work: interpreting the question, naming what is missing, choosing source regions, extracting data and judging whether a result answers what was asked.

Everything that has to be trustworthy stays in application code: the typed research state, authorization, tool permissions, request, token and time budgets, arithmetic, stopping rules and the checks that gate a release. The model is called where a semantic decision is needed, not for what code can do.

What the workspace does

Ask across documents, tables, charts and scanned pages. The workflow finds the sources, collects missing evidence, reads original page images when it has to and computes in application code, inside explicit budgets.

Agentic research

  • A short path when the retrieved text already answers the question
  • Focused research for a concrete gap: search, read a page, inspect a PDF, extract values
  • Original page images for quantitative reads of image-only PDF pages
  • Arithmetic, counts and list ordering run in application code

Evidence and trust

  • Tenant and role filters apply before reranking and generation
  • Every tool call rechecks authorized sources and document versions
  • The model can cite only evidence it was shown; unknown, hidden or cross-tenant references are rejected
  • Source, value and question-scope checks run before an answer is released

Research workspace

  • Numbered citations that open the passage, the page and the claim relationship
  • Inspect mode: retrieval candidates, reranker scores, security decisions, timing and traces
  • Research library: starred answers, pinned evidence, source-linked notes, projects and collections
  • Markdown export, with browser storage scoped per tenant and user

Retrieval and ingestion

  • Dense and BM25 search, rank fusion and multilingual BGE reranking
  • Table-aware PDF ingestion, with Tesseract OCR in English and Turkish for scanned pages
  • Turkish and English questions against documents in either language
  • Ollama, OpenAI or Claude behind one provider setting

One question through the typed research graph

The graph is application-controlled: PydanticAI makes typed agent calls, and the application owns every transition between them. Prepared calculations and known transitions execute directly, so the model is only called where a semantic decision is needed.

  1. 01

    Scoped retrieval

    Tenant and role filters constrain dense and BM25 search. Rank fusion and BGE reranking select passages, and section-aware assembly keeps tables next to their headings and captions.

  2. 02

    Authorized evidence ledger

    Admitted evidence becomes one ledger that the rest of the run reads from, so no later step can introduce a source the user was not allowed to see.

  3. 03

    A typed decision

    A PydanticAI agent reads a question-specific projection of the research state and either proposes a cited answer or names the piece of evidence that is missing.

  4. 04

    The tool and budget gate

    A named evidence gap becomes one narrow operation. The application validates its arguments, the source access and the remaining request, token, tool and time budget before it runs. Checked results go back into ResearchState and the agent decides again, until the evidence is enough or the loop stops making progress.

  5. 05

    Checked inputs

    Extraction returns typed labels, values, units, periods and source witnesses. For image-only pages the original page image is read, and an independent check covers the inputs and their coverage.

  6. 06

    Calculation in code

    Prepared operands and formulas run in application code: arithmetic, item counts, total-versus-distinct comparisons, label selection and list ordering. No model invents the result.

  7. 07

    Independent finalization

    Research can stop while successful extraction and calculation results stay available, so a closed loop never throws away work that already succeeded.

  8. 08

    Release checks

    Source, value and question-scope checks run before release. The result is a cited answer or an explicit statement of the evidence limits.

ResearchState is a typed Pydantic structure created and updated by application code, not a model-written summary. It holds the task, evidence needs, source selections, checked observations, calculations, coverage, unresolved issues and execution events, and each agent receives only a projection of it.

Narrow tools, clear responsibilities

Each operation exposes only its own fields. The application validates tool arguments and source access before anything runs, and numeric sources and contextual sources are tracked separately so a table value travels with the evidence explaining which entity or definition it belongs to.

OperationResponsibilityBoundary
SearchFind missing passages in the authorized document scope.Cannot expand tenant access or write an answer.
ReadOpen admitted chunks or one bounded physical PDF page.Keeps source identity, version, headings and page context.
InspectLocate PDF tables, image regions and structural elements.Returns locations; reading values is the extractor's job.
ExtractReturn structured values or item inventories with source witnesses.Cannot guess unreadable values, calculate the result or write the final answer.
Calculate / countExecute a permitted formula or count checked source items.Requires source-backed inputs; no arbitrary code execution.

Ten agent roles, each with its own reasoning effort

The semantic work is split across small, typed roles rather than one large agent. Reasoning effort is set per stage: lighter for reading and extraction, medium for the decisions that interpret the question, select sources, judge quantities and verify scope.

StageWhat it doesReasoning
Research / ReaderReads the research state and chooses the next step: a cited answer, or one narrow tool call.low
Evidence extractionExtracts typed values and item inventories, each with its source witnesses.low
Extraction checkerChecks extracted evidence against the source before anything depends on it.low
Need plannerTurns the question into the evidence it needs.medium
Source selectorChooses the numeric and contextual sources a need depends on.medium
Quantity collectorCollects the labelled quantities a calculation needs.medium
Quantity checkerJudges input accuracy, coverage and the chosen operation separately.medium
Answer repairApplies a bounded repair when a check names a specific problem.medium
Scope validator / judgeJudges whether the claims and their evidence answer the question as asked.medium
FinalizerWrites the answer from saved results.medium

The application owns what must be right

Access control answers which sources a user may reach. Model trust answers what an agent may do with them. The application treats these as different boundaries, and a typed proposal only becomes state or work after it is validated.

Application-ownedModel or untrusted
  • Identity, role and tenant resolution
  • Source and version access, rechecked on every tool call
  • Graph transitions, tool permissions and stopping rules
  • Request, token, tool and time budgets that user requests cannot widen
  • Calculations and counts
  • Source, value and question-scope verification before release
  • Retrieved text, titles, headings and source names
  • Instruction-looking text inside documents
  • A model proposal until it is validated as state or work
  • Extracted values until the input check passes
  • Image readings and semantic judgments until they are checked
  • Generated answer text before release

Retrieved content is untrusted data and gold answers never reach runtime generation or verification. Normal telemetry carries bounded metadata; raw questions, answers and model outputs need explicit forensic capture settings.

Architecture

Scoped retrieval produces an authorized evidence ledger. A typed research graph reads it through ResearchState, gates each tool call on authorization and budget, reads values from text or the original page image, calculates in code and releases only after source, value and scope checks. A separate path builds compatible index versions before switching the active alias.

Filesystem and Notion sources are parsed, chunked and fingerprinted into a versioned Qdrant collection before the active alias moves. An authenticated request receives a server-owned tenant and document scope, and dense and BM25 retrieval, rank fusion and BGE reranking run inside it, producing an authorized evidence ledger. PydanticAI agents read a task-specific projection of an application-owned ResearchState and either propose a cited answer or name a missing piece of evidence. A named gap becomes one narrow search, read, inspect or extract operation, validated against authorization and the remaining budget before it runs. Quantitative values are read from text or, for image-only pages, from the original page image, checked independently and calculated in application code. Research can stop while saved results still reach finalization, and source, value and question-scope checks gate every release. OpenTelemetry spans connect each stage so a lost or rejected value can be located.

Versioned index lifecycle

Source changes build and validate a compatible collection before the active alias moves.

Filesystem and Notion source documents Parse, OCR, Chunk, Fingerprint. Parse, OCR, Chunk, Fingerprint writes inactive version Versioned Qdrant collection. Versioned Qdrant collection validates, then activates kb_active alias.

  1. BoundaryFilesystemPDF, Markdown
    BoundaryNotionAPI connector
  2. ControlParse, OCR, Chunk, Fingerprinttable-aware PDFs, content + pipeline identity
  3. PersistenceVersioned Qdrant collectiondense + BM25, not yet active
  4. Persistencekb_active aliascurrent searchable index

Authorized retrieval

Identity and tenant scope constrain the candidate set before relevance scoring or any model call.

Research workspace question FastAPI access layer. FastAPI access layer scopes retrieval Dense + BM25, rank fusion. Dense + BM25, rank fusion reranks BGE multilingual reranker. BGE multilingual reranker admits Authorized evidence ledger.

  1. ClientResearch workspaceReact, HTTP + SSE
  2. ControlFastAPI access layeridentity, role, tenant, documents
  3. PersistenceDense + BM25, rank fusioninside the authorized scope
  4. AnalyzerBGE multilingual rerankersection-aware assembly
  5. BoundaryAuthorized evidence ledgerrequest-scoped support units

Typed research graph

Agents handle the semantic decision; the application owns state, tools, budgets, calculation and release.

ResearchState projects PydanticAI decision. PydanticAI decision evidence gap Tool and budget gate (authorization, arguments, budget). Tool and budget gate runs one operation Search and Read and Inspect, Extract. Search and Read and Inspect, Extract returns evidence Checked inputs. Checked inputs operands ready Calculate or count. Calculate or count saves results Independent finalization. Independent finalization verifies Source, value, scope checks.

  1. PersistenceResearchStatetyped, application-owned, task projections
  2. AnalyzerPydanticAI decisionenough evidence, or what is missing
  1. ControlTool and budget gateauthorization, arguments, budget
  2. ServiceSearchauthorized scope
    ServiceReadchunks or one page
    ServiceInspect, Extracttables, images, inventories
  1. ControlChecked inputslabels, values, units, witnesses
  2. ControlCalculate or countapplication code, no model
  1. ServiceIndependent finalizationworks from saved results
  2. OutputSource, value, scope checkscited answer or explicit limits

Checked evidence returns to ResearchStateThe agent decides again on the updated state. Research stops at six research requests or after two rounds without progress, where progress means a checked extraction, a corrected binding, a resolved ambiguity or a completed calculation, not just new text.

From a table cell to a checked answer

A quantitative read uses native text when it is usable and the original page image when it is not.

Authorized source page usable native text? Text references (native text usable). Authorized source page usable native text? Original page image (image-only or unreliable text). Text references and Original page image typed inputs Labels, values, units, periods. Labels, values, units, periods independent check Input and coverage review. Input and coverage review checked operands Application calculation. Application calculation answers Cited answer.

  1. BoundaryAuthorized source pageimmutable PDF version
  2. ServiceText referencesnative text usable
    AnalyzerOriginal page imageimage-only or unreliable text
  3. ControlLabels, values, units, periodswith source witnesses
  1. ControlInput and coverage reviewseparate from extraction
  2. ControlApplication calculationplus question-scope check
  3. OutputCited answeropenable in the workspace

Traces and evidence

Stage metadata and a source-verified answer ledger meet in the workspace's inspect mode.

OpenTelemetry spans and Answered-question ledger projects Inspect mode and Jaeger. Inspect mode and Jaeger renders Research workspace.

  1. ServiceOpenTelemetry spansretrieval, tools, validation
    PersistenceAnswered-question ledgereach question counted once
  2. ObservabilityInspect mode and Jaegercandidates, scores, timing
  3. ClientResearch workspaceanswer beside its evidence

Six reliability decisions

The model names the gap; the application decides what may run

PydanticAI agents handle the semantic work: interpreting the question, naming missing evidence, choosing source regions and judging whether a result answers it. A typed proposal is validated before it becomes state or executable work, because valid JSON is not proof of source truth.

A calculation is never a model's guess

Once operands and a formula are prepared they run directly in application code. Arithmetic, item counts and total-versus-distinct comparisons do not ask another model to produce the result, and computed answers keep their reviewed output units and explicit interpretation.

Image-only pages are read from the original image

Quantitative reads of image-only PDF pages are routed to the original page image. Category, series, period, unit and label-value relationships stay attached to each input, and an independent check reviews the inputs and their coverage, so every value is checked before a calculation depends on it.

Stopping research does not erase successful work

Research stop, extraction, review, finalization and release are separate statuses. A stopped loop can still yield a verified answer from saved results, and a budget or API failure is not treated as proof that the source has no answer.

Authorization is rechecked at every step

Server-side filters apply before reranking and generation, and each tool call revalidates the authorized sources and versions. Numeric sources and contextual sources are tracked apart, so a table value travels with the evidence naming the entity or definition it belongs to.

Results are counted once, and failures stay on the record

The answered-question ledger lists each question once, with its run, answer, latency and model-call count. A rerun does not raise the total, failed runs stay in the local history, and an operational stop is never presented as evidence that an answer is absent.

Product proof from the research workspace

These captures come from the public repository. Each one links to its source file so the interface and the evidence shown inside it can be inspected at full size.

Research workspace answering a pricing question with numbered citations and an evidence inspector showing the cited handbook page.
Research workspace: every answer carries numbered citations, and the evidence inspector opens the cited passage and its claim relationship.Open full-size image on GitHub Source: docs/assets/research-workspace.jpg
Inspect mode showing the reasoning steps, prompt budget, model finish state and stage timing behind an answer.
Inspect mode: the question as searched, retrieval and reranking counts, prompt budget, model state and validation sit beside the answer.Open full-size image on GitHub Source: docs/assets/inspect-why.jpg
Inspect mode retrieval tab listing retrieval candidates with their reranker scores.
Retrieval inspector: candidates and reranker scores, so a lost or misranked passage can be located instead of guessed at.Open full-size image on GitHub Source: docs/assets/inspect-retrieval.jpg
A research note linked to a specific page of a handbook source.
Source-linked notes: a note stays attached to the page it was written about, inside the research library.Open full-size image on GitHub Source: docs/assets/research-notes.jpg
A project grouping research sessions, notes and sources.
Projects: research sessions, notes and sources can be grouped, with browser storage scoped per tenant and user.Open full-size image on GitHub Source: docs/assets/projects.jpg

What 120 questions showed

The answered-question ledger tracks 120 distinct questions over long documents: 10-K filings, annual reports, research papers, manuals and survey releases. Each result is recorded once, with its run, answer, latency and model-call count. 103 of the 120 reached an accepted outcome.

OutcomeQuestionsWhat it means
Source-correct answers81The published answer matches the original PDF on independent review.
Qualified calculations4An interpreted calculation, published together with the interpretation it depends on.
Correct refusals18Questions the source cannot answer, where the system said so instead of guessing.
Unresolved17Open questions, kept on the record for the next iteration.

A few recorded answers show the range, from a single read to a checked calculation:

QuestionSource-supported answerRun
Costco FY2021 total liabilitiesUSD 41,190 million20.41 s, 3 model calls
Costco FY2021 debt to EBITDA, including current long-term debt and lease liabilities1.344× = (799 + 6692 + 3916) / (6708 + 1781)68.02 s, 9 model calls
Other-company directorships held by three directors30, with total and distinct-company counts agreeing61.63 s, 7 model calls
Germanwings tweets minus Lufthansa tweets12 = 24 − 12; reading the original image corrected an indexed 42 to 1242.16 s, 6 model calls

Selected evidence

Question coverage, research budgets, tests and the trust boundary, each reported on its own surface.

Evidence sliceCurrent resultWhat it covers
Agentic question coverage103/120 accepted outcomes81 source-correct answers, 4 qualified calculations and 18 correct refusals across 120 distinct long-document questions, each counted once.
Research budget10 requests, 120k tokens, 240 sThe profile used for recent document runs: at most six research tool attempts, a stop after two rounds without progress and a 60-second finalization reserve. These are configurable server-side limits that user requests cannot widen.
Backend tests2,125 passedLatest recorded run. The normal suite makes no paid provider calls; a separate target runs the checks that use a local model.
Trust boundaryVerified references onlyUnknown, hidden and cross-tenant source references are rejected before release, and tenant and role filters run before reranking and generation.

From a retrieval pipeline to an agentic research workspace

Production RAG Platform established the original PDF retrieval, hybrid search, reranking, citations, evaluation and tracing path. This project kept that foundation, added tenant-scoped knowledge operations, and then put a typed research graph on top of it.

Earlier boundaryOne corpus and a fixed answer path

Retrieve, rerank, generate and cite, with no tenant ACL and no operated index lifecycle.

Current boundaryAgentic research over authorized evidence

Scoped tools, page-image reading, calculation in code, independent checks and a workspace that opens every citation.

Current implementation

Agentic researchPydanticAI, typed research graph, application-owned ResearchState
WorkspaceReact, TypeScript, Vite, research library, inspect mode
APIFastAPI, HTTP, SSE, read-only UI aggregation
IdentityBearer tokens, tenant and document permissions, USER / OPERATOR / ADMIN roles
RetrievalQdrant dense + BM25 sparse, rank fusion, BGE multilingual reranker
ModelsOllama, OpenAI or Claude, Qwen3 embeddings, image-capable model for visual reads
IngestionTable-aware PDF parsing, Tesseract OCR (English, Turkish)
ObservabilityOpenTelemetry, Jaeger, bounded-metadata traces
RuntimePython 3.11+, Docker Compose

In short

What is Knowledge Base RAG?
Knowledge Base RAG is an agentic document research workspace. Tenant and role filters scope retrieval first; PydanticAI agents then read a task-specific projection of an application-owned ResearchState and either propose a cited answer or name the missing evidence. Each gap becomes one narrow search, read, inspect or extract operation checked against authorization and a request, token, tool and time budget, quantitative values are read from text or the original page image and calculated in application code, and source, value and question-scope checks gate the release.
What problem does Knowledge Base RAG solve?
A relevant chunk is not an answer, and a fluent model is not a calculator. Questions over complex tables, charts and scanned PDFs need evidence that is found, read from the right place and computed correctly, while access control and release policy stay outside the model. This project keeps the semantic work with agents and everything that must be trustworthy in application code: state, authorization, tool permissions, budgets, arithmetic and the final checks. It also keeps its results honest by counting each question once, keeping failed runs on the record and never reading an operational stop as proof that an answer is absent.

Deep dive

Open the full repository