Backend services for the Financial Document Intelligence Platform, an agentic financial-document analysis system built with FastAPI, LangGraph, LlamaIndex, PostgreSQL/pgvector, hybrid retrieval, and financial-data tools.
The backend handles:
- LangGraph-based query planning and orchestration
- Parallel document and financial-data workers
- Hybrid document retrieval with dense search + BM25 + RRF
- Cross-encoder reranking
- LlamaIndex-based document RAG and source-node handling
- Polygon financial-data access
- Citation-aware answer generation
- Server-Sent Events (SSE) streaming
- Local development infrastructure with PostgreSQL, LocalStack, and Arize Phoenix
SSE Chat Request
|
v
LangGraph Runtime
|
v
Planner
|
+---------------------------+
| |
v v
Document Worker Financial Data Worker
| |
v v
Hybrid Retrieval Polygon
|
Dense top-8 + BM25 top-8
|
v
RRF
|
v
RRF top-10 candidates
|
v
Cross-Encoder Reranker
|
v
Final top-5 chunks
|
+-------------+
|
v
Synthesizer
|
v
SSE Streaming Response
LangGraph is the only orchestration path. LlamaIndex remains intentionally used inside the document-RAG stack for retrieval integration, source-node handling, indexing/ingestion, and citation-aware synthesis.
The production document-retrieval pipeline is:
Dense retrieval (top-8)
+
BM25 retrieval (top-8)
|
v
Reciprocal Rank Fusion (RRF)
|
v
Top-10 candidates
|
v
BAAI/bge-reranker-v2-m3
|
v
Final top-5 chunks
RRF is used as the candidate-fusion stage, while the cross-encoder reranker performs final query-conditioned relevance ranking.
The reranker is loaded lazily once per application process and reused across requests. If reranking fails because of an inference exception, score-count mismatch, or non-finite score, production gracefully falls back to the original RRF top-5.
Common settings:
ENABLE_RERANKER=true RERANKER_MODEL=BAAI/bge-reranker-v2-m3 RERANKER_DEVICE=cpu
RERANKER_DEVICE=cpu is recommended for local macOS development to avoid PyTorch MPS instability. GPU deployments can use another supported device, such as cuda, without changing the retrieval logic.
Install pyenv and use it to install the Python version specified in .python-version.
Example:
curl https://pyenv.run | bashInstall Docker.
Docker is used locally for PostgreSQL, LocalStack, Phoenix, and supporting services.
From the backend directory:
poetry shell poetry install
Use .env.development as a template:
cp .env.development .env
Then load it into your shell:
set -a source .env set +a
At minimum, configure the services you plan to use, including:
OPENAI_API_KEY=... POLYGON_IO_API_KEY=... SEC_EDGAR_COMPANY_NAME=... SEC_EDGAR_EMAIL=... ENABLE_RERANKER=true RERANKER_MODEL=BAAI/bge-reranker-v2-m3 RERANKER_DEVICE=cpu
If you use non-local S3 storage, configure the relevant AWS credentials and bucket settings as well.
The SEC EDGAR identity fields should contain your own organization/name and email to comply with SEC access requirements.
make migrate
make run
This starts the local supporting services and runs the FastAPI backend directly on the host OS, which keeps local debugging straightforward.
The backend is available at:
http://localhost:8000
To populate the local environment with sample Amazon and Meta SEC filings:
make seed_db_local
If you need to reset the local database first:
make refresh_db
After seeding, restart the backend if necessary:
make run
You can inspect loaded documents at:
http://localhost:8000/api/document
For setup issues, see troubleshooting.md.
Local development starts Arize Phoenix for LLM and retrieval observability.
Open:
http://localhost:6006/
Phoenix can be used to inspect model calls, embedding activity, retrieval behavior, and other instrumented backend operations.
The backend uses a planner-worker-synthesizer design.
The planner decomposes a user request into one or more sub-questions and routes each task to the appropriate worker.
Supported routing includes:
documentfinancial_datahybrid
Independent work can run in parallel. Partial failures are handled so that one failed worker does not necessarily prevent successful evidence from other workers from being synthesized.
The document worker uses the LlamaIndex-backed RAG stack and the production hybrid retriever:
Dense + BM25 -> RRF -> Reranker -> Final Context
Retrieved nodes preserve source metadata such as document identity and page labels for downstream citation.
The financial-data worker uses Polygon-backed tools for quantitative and market-data questions.
Worker outputs are combined by the LangGraph synthesis stage and streamed to the client through SSE.
The scripts/ directory contains utilities for development, data loading, benchmarking, and maintenance.
The repository includes a REPL-style chat client for interacting with the backend without the frontend.
From the backend environment:
make chat
The script connects to the backend API and is useful for debugging request/response behavior.
The backend includes tooling for downloading SEC 10-K and 10-Q filings from EDGAR.
The downloader can:
- Download filings from SEC EDGAR
- Convert supported filings into PDF form
- Store the resulting documents in the configured S3-compatible storage
SEC EDGAR itself does not require an API key, but you should provide:
SEC_EDGAR_COMPANY_NAME=... SEC_EDGAR_EMAIL=...
to identify your client appropriately.
For direct downloader usage, inspect:
scripts/download_sec_pdf.py
Example:
python scripts/download_sec_pdf.py \ -o ~/mounted_folder \ --file-types="['10-Q','10-K']"
If you are writing directly to AWS S3 through a mounted filesystem, configure the AWS CLI and your preferred S3 mounting approach first.
The consolidated seed workflow is implemented in:
scripts/seed_db.py
It can:
- Download SEC 10-K / 10-Q filings
- Upload them to the configured S3 or LocalStack bucket
- Create/update corresponding document rows in PostgreSQL
- Prepare documents for downstream indexing and retrieval
Useful Makefile shortcuts include:
make seed_db make seed_db_preview make seed_db_local make seed_db_based_on_env
For local development, make seed_db_local loads the Amazon and Meta sample filings into LocalStack-backed storage and the local PostgreSQL database.
The retrieval stack was evaluated on a 120-query matched benchmark spanning Amazon and Meta 2025 10-K filings.
The frozen final pipeline achieved:
Hit@1: 0.783
Hit@5: 0.950
MRR@5: 0.850
Evaluation roles:
- Amazon 2025 10-K — Validation benchmark
- Meta 2025 10-K — Held-out test benchmark
The same production retrieval path was run across all 120 queries, and the final top-5 node ordering matched the validated benchmark implementation for 120/120 queries.
Benchmark assets live under:
benchmarks/retrieval/
Run the backend test suite with:
poetry run pytest
The test coverage includes:
- LangGraph orchestration
- planner routing
- document and financial-data workers
- hybrid retrieval
- RRF fusion
- reranking
- reranker fallback behavior
- metadata preservation
- SSE/chat execution
- benchmark/production retrieval parity
When modifying retrieval code, do not tune parameters against the held-out Meta test set.
Local make run starts Uvicorn in reload mode with a single serving worker. Reload mode uses a reloader parent plus a serving child process.
Because the reranker singleton is process-local, each new serving process initializes its own model instance when reranking is first used.
PyTorch MPS caused an intermittent hang with the BGE cross-encoder in local web-server execution. The backend therefore supports explicit reranker device selection.
For local macOS use:
RERANKER_DEVICE=cpu
This keeps reranking deterministic and avoids MPS-specific runtime instability.
The AgentCore Runtime image is intentionally separate from the FastAPI image. It
runs agentcore_app.py, whose SDK server provides the AgentCore /ping and
/invocations HTTP contract.
Build an ARM64 image from the backend directory:
docker buildx build \
--platform linux/arm64 \
--load \
-f Dockerfile.agentcore \
-t financial-document-agentcore:local \
.Confirm the loaded image architecture:
docker image inspect financial-document-agentcore:local \
--format '{{.Os}}/{{.Architecture}}'Run it with runtime configuration supplied externally. Do not bake secrets into the image.
docker run --rm \ --platform linux/arm64 \ -p 8080:8080 \ --env-file .env \ financial-document-agentcore:local
On hosts without ARM64 container support, Docker must be configured with ARM64
emulation. The deployment target remains linux/arm64.
Check the SDK health endpoint:
curl http://localhost:8080/ping
Invoke the streaming endpoint with the existing invocation payload shape:
curl -N \ -X POST http://localhost:8080/invocations \ -H 'Content-Type: application/json' \ -d '{ "question": "What changed in revenue?", "conversation": {"messages": [], "documents": []} }'
The container does not start FastAPI, run database migrations, or manage conversation persistence. Those remain application-layer responsibilities.
- FastAPI — API and SSE backend
- LangGraph — agentic planning, routing, parallel workers, synthesis
- LlamaIndex — document RAG, indexing, retrieval integration, source nodes
- PostgreSQL + pgvector — document metadata and vector storage
- BM25 — sparse lexical retrieval
- RRF — dense/sparse candidate fusion
- BGE reranker — cross-encoder relevance reranking
- Polygon — financial and market data
- LocalStack / S3 — document object storage
- Arize Phoenix — local LLM/retrieval observability
- Docker Compose — local supporting infrastructure