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
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.
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.
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.
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.
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.
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.
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.
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.
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.
Operation
Responsibility
Boundary
Search
Find missing passages in the authorized document scope.
Cannot expand tenant access or write an answer.
Read
Open admitted chunks or one bounded physical PDF page.
Keeps source identity, version, headings and page context.
Inspect
Locate PDF tables, image regions and structural elements.
Returns locations; reading values is the extractor's job.
Extract
Return structured values or item inventories with source witnesses.
Cannot guess unreadable values, calculate the result or write the final answer.
Calculate / count
Execute 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.
Stage
What it does
Reasoning
Research / Reader
Reads the research state and chooses the next step: a cited answer, or one narrow tool call.
low
Evidence extraction
Extracts typed values and item inventories, each with its source witnesses.
low
Extraction checker
Checks extracted evidence against the source before anything depends on it.
low
Need planner
Turns the question into the evidence it needs.
medium
Source selector
Chooses the numeric and contextual sources a need depends on.
medium
Quantity collector
Collects the labelled quantities a calculation needs.
medium
Quantity checker
Judges input accuracy, coverage and the chosen operation separately.
medium
Answer repair
Applies a bounded repair when a check names a specific problem.
medium
Scope validator / judge
Judges whether the claims and their evidence answer the question as asked.
medium
Finalizer
Writes 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-owned
Model 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.
01
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.
ControlCalculate or countapplication code, no model
saves results
ServiceIndependent finalizationworks from saved results
verifies
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.
04
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.
BoundaryAuthorized source pageimmutable PDF version
usable native text?
ServiceText referencesnative text usable
AnalyzerOriginal page imageimage-only or unreliable text
PersistenceAnswered-question ledgereach question counted once
projects
ObservabilityInspect mode and Jaegercandidates, scores, timing
renders
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: 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.jpgInspect 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.jpgRetrieval 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.jpgSource-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.jpgProjects: 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.
Outcome
Questions
What it means
Source-correct answers
81
The published answer matches the original PDF on independent review.
Qualified calculations
4
An interpreted calculation, published together with the interpretation it depends on.
Correct refusals
18
Questions the source cannot answer, where the system said so instead of guessing.
Unresolved
17
Open questions, kept on the record for the next iteration.
A few recorded answers show the range, from a single read to a checked calculation:
Question
Source-supported answer
Run
Costco FY2021 total liabilities
USD 41,190 million
20.41 s, 3 model calls
Costco FY2021 debt to EBITDA, including current long-term debt and lease liabilities
1.344× = (799 + 6692 + 3916) / (6708 + 1781)
68.02 s, 9 model calls
Other-company directorships held by three directors
30, with total and distinct-company counts agreeing
61.63 s, 7 model calls
Germanwings tweets minus Lufthansa tweets
12 = 24 − 12; reading the original image corrected an indexed 42 to 12
42.16 s, 6 model calls
Selected evidence
Question coverage, research budgets, tests and the trust boundary, each reported on its own surface.
Evidence slice
Current result
What it covers
Agentic question coverage
103/120 accepted outcomes
81 source-correct answers, 4 qualified calculations and 18 correct refusals across 120 distinct long-document questions, each counted once.
Research budget
10 requests, 120k tokens, 240 s
The 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 tests
2,125 passed
Latest recorded run. The normal suite makes no paid provider calls; a separate target runs the checks that use a local model.
Trust boundary
Verified references only
Unknown, 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
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.