Table of Contents
- Confirmed decisions
- Verified data sources
- Architecture
- Repository layout
- API / tool contracts
- Implementation task list
- Lab guide steps
- Risks & gotchas
- Validation plan
- Out of scope
Course capstone for 105532-AI day 5: a microservice application combining MCP, RAG, LLM, LangChain, and a Streamlit dashboard, deployable with Docker Compose and plain Kubernetes manifests. Primary deliverable is documentation + runnable skeleton — students (with AI agents) fill in the logic.
Working directory: /home/cfreire/Documents/2026/105532-AI/PREP/day5/final_project (currently contains only url.md).
Confirmed decisions
| Decision | Choice |
|---|---|
| Deliverable | Docs + skeleton (runnable stubs with # TODO(student) markers; students fill logic) |
| LLM | Ollama container in the cluster, no API keys (day2/day4 consistency) |
| RAG corpus | INE accidents indicator data turned into text chunks at ingestion (data-grounded, no static corpus) |
| MCP | FastMCP with streamable-http transport + in-memory TTL cache (evolution of day5/ipma/ipma_mcp.py) |
| Services | 3 app services + Ollama: dashboard, ipma-mcp, accidents-rag-api, ollama (INE proxy merged into rag-api) |
| Deployment | docker compose up primary path + plain K8s YAML for k3s/minikube (no Helm) |
| Dashboard | Single Streamlit page with tabs: Acidentes / Meteorologia / RAG Chat |
| Vector store | ChromaDB (persistent volume) + Ollama embeddings (nomic-embed-text) |
| Scaffolding | TODO stubs + numbered lab guide with acceptance checks per step |
| Doc language | English (matches day5 docs); Portuguese data labels kept as-is from upstream |
Verified data sources (live-tested 2026-11-12)
- INE accidents
https://www.ine.pt/ine/json_indicador/pindica.jsp?op=2&varcd=0012774&lang=PT- Returns
[ { IndicadorCod, IndicadorDsg, UltimoPref: "2024", DataUltimoAtualizacao, Dados: { "<year>": [ { geocod, geodsg, dim_3, dim_3_t, dim_4, dim_4_t, ind_string, valor } ] } } ] dim_3_t= accident type (mortais / não mortais);dim_4_t= road type (Autoestradas, Vias nacionais…). Geography covers municipalities (geodsg= concelho name) and NUTS aggregates — both appear in the same response.- Payload ≈ 1 MB for the latest year → must TTL-cache; update cadence is annual.
- Returns
- IPMA precipitation CSV
https://api.ipma.pt/open-data/observation/climate/precipitation/prec-p1d-continental-obssup-idw-concelhos-20d.csv- Columns:
time, zname, zid, mean_maxprate, std_maxprate, min_maxprate, max_maxprate, percentile_*_maxprate, mean_tp, std_tp, min_tp, max_tp, percentile_*_tp. One row per concelho per day, last 20 days.tp= daily precipitation total.
- Columns:
- IPMA stations/observations (already implemented in
day5/ipma/ipma_mcp.py):.../stations/stations.jsonand.../stations/observations.json(dict keyed by ISO timestamp →{station_id: measurements}),-99.0= nodata.
Data caveat (must be stated in docs): INE accidents are annual aggregates; IPMA precipitation covers only the last 20 days. A rain-vs-accidents time correlation is impossible with these endpoints. The optional stretch goal is instead a name-join map: choropleth of 2024 accidents per concelho overlaid/matched with current 20-day precipitation by geodsg ≈ zname (normalizing accents/case).
Architecture
┌─────────────────────────────┐
Browser ──────►│ dashboard (Streamlit) :8501│
└──────┬──────────────┬───────┘
HTTP/JSON │ │ MCP client (fastmcp.Client)
▼ ▼
┌───────────────────────────┐ ┌──────────────────────┐
│ accidents-rag-api :8000 │ │ ipma-mcp :8001/mcp │
│ FastAPI │ │ FastMCP http + TTL │
│ • INE proxy + TTL cache │ │ • stations/obs tools│
│ • ingest → ChromaDB (PVC)│ │ • precipitation tool│
│ • LangChain RAG /ask │ └──────────┬───────────┘
└──────┬─────────────┬──────┘ │ httpx
│ │ ▼
│ ▼ api.ipma.pt (CSV + GeoJSON/JSON)
│ ollama :11434
│ • qwen chat model
│ • nomic-embed-text
▼
dados.gov.pt / INE pindica API
- Ports: dashboard 8501, accidents-rag-api 8000, ipma-mcp 8001 (streamable-http at
/mcp), ollama 11434. - Dashboard is an MCP client (fastmcp
Client("http://ipma-mcp:8001/mcp")) and a REST client of accidents-rag-api. - ChromaDB persists in a named volume inside accidents-rag-api; Ollama models in another volume.
Repository layout (to create)
final_project/
├── README.md # project brief, architecture diagram, quickstart, grading checklist
├── AGENTS.md # how AI agents should implement/extend this project
├── url.md # (exists) data sources
├── .env.example # all env vars documented
├── docker-compose.yml
├── docs/
│ ├── architecture.md # services, data flow, ports, env vars, failure modes
│ ├── concepts.md # MCP / RAG / LangChain / FastMCP recap, links to day1–5 notes
│ ├── lab_guide.md # numbered steps with TODO markers + acceptance checks
│ └── kubernetes.md # k3s/minikube deployment walkthrough
├── ipma-mcp/
│ ├── Dockerfile, pyproject.toml, README.md
│ └── app/server.py # adapted from day5/ipma/ipma_mcp.py; TODO: http transport, precipitation tool
├── accidents-rag-api/
│ ├── Dockerfile, pyproject.toml, README.md
│ └── app/
│ ├── main.py # FastAPI routes (stubs)
│ ├── ine_client.py # TODO: fetch + TTL cache + normalize INE JSON
│ ├── ingest.py # TODO: chunking + ChromaDB upsert (LangChain)
│ └── rag.py # TODO: retriever + Ollama chain (LangChain)
├── dashboard/
│ ├── Dockerfile, pyproject.toml, README.md
│ └── app/
│ ├── Home.py # st.tabs: Acidentes | Meteorologia | RAG Chat
│ ├── tab_accidents.py # TODO: charts from accidents-rag-api
│ ├── tab_weather.py # TODO: fastmcp Client → ipma-mcp tools
│ └── tab_chat.py # TODO: st.chat_input → POST /ask
└── k8s/
├── namespace.yaml, configmap.yaml
├── ollama.yaml # Deployment + Service + PVC
├── ipma-mcp.yaml, accidents-rag-api.yaml (incl. Chroma PVC), dashboard.yaml
API / tool contracts (skeleton stubs must document these)
ipma-mcp tools (reuse day5 list_stations, get_latest_observations, get_station_observations as working code; new tool is the TODO):
get_precipitation_last_days(concelho: str | None = None, days: int = 7) -> dict— from TTL-cached CSV (TTL 3600 s; dataset refreshes daily), filtered byznamewith accent/case-insensitive match.
accidents-rag-api (FastAPI):
GET /health→{"status": "ok"}GET /accidents?year=&geodsg=&dim3=&dim4=→ normalized records from TTL-cached INE JSON (TTL 86400 s; data is annual)GET /accidents/summary→ totals by year, top-N concelhos, latest metadata (UltimoPref,DataUltimoAtualizacao)POST /ingest→ builds text chunks from cached INE data, embeds via Ollama, upserts into ChromaDB; returns document count. One chunk per (year, geodsg): PT text like “Em 2024, em Guimarães (Braga): 32 acidentes com vítimas não mortais em Autoestradas; …”. Metadata:{year, geocod, geodsg, dim3, dim4}.POST /ask {"question": ...}→ LangChain retriever (ChromaDB) +langchain-ollamachat model; returns{answer, sources: [chunk metadata]}.
Dashboard tabs:
- Acidentes: KPIs (total latest year, vs previous), bar chart top concelhos, filter by dim3/dim4 — all via
accidents-rag-api. - Meteorologia: station picker → latest observations; concelho picker → precipitation last N days — via MCP client.
- RAG Chat:
st.chat_input, POST/ask, render answer + sources.
Env vars (all in .env.example): OLLAMA_BASE_URL, OLLAMA_MODEL (default qwen3.5:4b, matching day4 benchmark models), OLLAMA_EMBED_MODEL (default nomic-embed-text), INE_ACCIDENTS_URL, IPMA_PRECIP_URL, IPMA_OBS_URL, IPMA_STATIONS_URL, OBS_CACHE_TTL=300, PRECIP_CACHE_TTL=3600, INE_CACHE_TTL=86400, CHROMA_DIR=/data/chroma, ACCIDENTS_API_URL=http://accidents-rag-api:8000, IPMA_MCP_URL=http://ipma-mcp:8001/mcp.
Implementation task list (ordered)
- Docs first:
README.md(brief + architecture + quickstart),docs/architecture.md,AGENTS.md(project rules: uv for venvs, keep upstream PT labels, comment style, no secrets, verify by running services). Include the annual-vs-20-days data caveat and the MCP client/HTTP service distinction. - Skeleton + packaging: directory tree above; each
pyproject.tomlpinned (fastmcp>=2,<3,fastapi,uvicorn,httpx,langchain,langchain-ollama,chromadb,streamlit,pandas,requests); one Dockerfile per service (python:3.12-slim, non-root, uv or pip install). - ipma-mcp: copy day5
ipma_mcp.pyas the base (stations/observations tools work as-is), switch entrypoint tomcp.run(transport="http", host="0.0.0.0", port=8001), addget_precipitation_last_daysas TODO stub (CSV parse helper may be provided working; the tool wiring is the TODO). - accidents-rag-api stubs:
ine_client.py(TODO: fetch + cache + normalize),ingest.py(TODO: chunk builder + Chroma upsert),rag.py(TODO: retriever + chain),main.pywith FastAPI routes raisingNotImplementedErrorin TODO bodies but/healthworking. - dashboard stubs:
Home.pywith workingst.tabsshell; each tab file renders a placeholder and has TODO bodies; provide workingask()/fetch_json()helpers as examples. - docker-compose.yml + .env.example: 4 services, volumes (
chroma-data,ollama-models), healthchecks (ollama via/api/tags), internal network, only dashboard published. - k8s/ manifests + docs/kubernetes.md: namespace
road-safety, ConfigMap for env, Deployments (1 replica each), ClusterIP Services, PVCs for chroma + ollama models, dashboard exposed via NodePort 30501; walkthrough for k3s and minikube. - docs/lab_guide.md: numbered student steps (see below), each with TODO pointer + acceptance check.
- Validation (see below) and fix anything broken.
Lab guide steps (student journey, one acceptance check each)
- Compose up the skeleton — all containers healthy,
curl /healthworks, Streamlit shell loads. - Pull models —
docker compose exec ollama ollama pull qwen3.5:4b nomic-embed-textsucceeds. - Implement INE client —
GET /accidents?geodsg=Guimarãesreturns normalized records; second call served from cache (log line). - Implement ingest —
POST /ingestreports e.g. ~1k+ documents; chroma volume non-empty. - Implement RAG —
POST /ask {"question":"Quantos acidentes com vítimas em Guimarães em 2024?"}returns grounded answer + sources (32, per live check). - Add MCP precipitation tool —
fastmcp inspectoror MCP client lists the new tool; call returns Águeda rows. - Dashboard tabs — charts render from the API; weather tab shows MCP tool output; chat tab answers with sources.
- Kubernetes stage —
kubectl apply -f k8s/on k3s/minikube; dashboard reachable on NodePort; pod restart keeps Chroma data (PVC).
Risks & gotchas (document in AGENTS.md / lab guide)
- INE payload ≈ 1 MB, annual cadence — cache aggressively; do not refetch per request; parse defensively (
valoris a string). - FastMCP http transport — pin
fastmcp>=2,<3; endpoint ishttp://host:8001/mcp; dashboard must run the async MCP client inside Streamlit’s event loop (provide helper usingasyncio.run). - Ollama first boot — model pull is slow/large; PVC mandatory; set
OLLAMA_KEEP_ALIVEto avoid reload latency in demos. - langchain-ollama, not langchain-openai, for
ChatOllama/OllamaEmbeddings. - Chroma persistence — without the volume,
/ingestwork is lost on restart (compose + PVC in k8s). - Name-join stretch:
geodsgvsznamediffer in accents/case; normalize before matching; label the map clearly (different time scales). - No secrets — all upstream APIs are open; do not introduce keys.
Validation plan (implementer must run)
docker compose build && docker compose up -d— all healthy.curl localhost:8000/health;curl "localhost:8000/accidents?year=2024&geodsg=Porto"(after step-3 implementation).- MCP:
npx @modelcontextprotocol/inspectoragainsthttp://localhost:8001/mcpor a smallfastmcp.Clientscript — list tools, call precipitation tool. POST /ingestthenPOST /askwith the Guimarães question — expect grounded answer citing the chunk.- Streamlit at
localhost:8501— all three tabs render with data. - Kubernetes (if available):
kubectl apply -f k8s/ && kubectl get pods -n road-safety— all Running; restart a pod, confirm Chroma data persists.
Out of scope
- Helm/kustomize packaging, CI/CD, authentication, horizontal scaling, Redis/pgvector alternatives, rain-vs-accidents statistical correlation, non-INE accident micro-data.