An AI course mini project demonstrating every layer of a production-grade Agentic RAG system. Uses the Marvel Cinematic Universe as the knowledge domain β rich, fun, and with a built-in proof of RAG's value (post-2023 MCU content the LLM has never seen).
Fully local β no cloud, no API keys, no cost after setup. Swap to OpenAI in one .env line.
Stack: Ollama + ChromaDB + LlamaIndex + Streamlit | Tests: 199 passing | Pages: 7
- What Problem Does This Solve?
- Why the MCU Is the Perfect Demo Domain
- The RAG Pipeline β 10 Steps Explained
- The Agentic Layer β How It Works
- System Architecture
- Quick Start
- Configuration (.env)
- App Pages
- Running Tests
- Project Structure
- Data Sources
- Tech Stack
Large Language Models are trained on static snapshots of the internet. Once deployed, they know nothing about events after their training cutoff. Ask llama3.1:8b about Deadpool & Wolverine (August 2024) or Thunderbolts* (May 2025) and it will either hallucinate or say "I don't know."
RAG (Retrieval-Augmented Generation) fixes this by giving the LLM a real-time reference library. Instead of relying on memorised training data, the model retrieves relevant documents from a knowledge base and uses them as grounding evidence for its answer. The LLM becomes an intelligent reader rather than a memorised reciter.
But not all RAG is equal. Naive RAG β embed the query, find the nearest vectors, stuff them into a prompt β works for simple questions. It fails on:
- Multi-hop questions ("What happened between Phase 3 and Phase 5?")
- Character-specific questions polluted by unrelated content
- Keyword-critical searches ("Who is the Red Hulk in Brave New World?") where semantic similarity misses exact-match terms
- Questions requiring self-assessment ("Is this answer actually grounded in what I retrieved?")
Advanced RAG + Agentic RAG address all of these. MarvelMind demonstrates the complete progression β from naive retrieval to a reasoning agent that decides which tools to use, how many times to search, and whether its own answer meets quality standards.
The MCU provides a uniquely compelling knowledge domain for an AI course showcase:
1. Built-in proof of RAG's value. Films and shows released after the LLM's training cutoff (Captain America: Brave New World, Feb 2025; Daredevil: Born Again, Mar 2025; The Fantastic Four: First Steps, Jul 2025) are complete blind spots for the model. The same query β "Who is Thaddeus Ross in Brave New World?" β gets a hallucinated answer without RAG and a grounded, cited answer with it. The contrast is instant and dramatic.
2. Naturally structured for agent tools. MCU knowledge organises itself exactly the way agent tools do β by character, by film, by Phase. "Tell me about Thor" β search_by_character. "What happened in Phase 3?" β search_by_phase. "Compare Thor and Captain America" β two separate tool calls. The domain teaches tool selection intuitively.
3. Rich, multi-source knowledge. Wikipedia gives structured overviews. MCU Fandom Wiki gives deep lore. HuggingFace datasets give dialogue and facts. Three different sources, three different styles β real ingestion and deduplication challenges.
4. Engaging for students. Building a RAG system over tax law or logistics manuals is accurate but dull. Building it over the MCU means every test query is interesting, every demo is fun, and the system's quality is immediately obvious to anyone in the room.
Every query through the QA Chat, Character Dive, Timeline Explorer, and Quiz Mode pages (and every tool call made by agents) passes through this pipeline. In QA Chat and Agent Mode, conversation history from the current session is also available to the pipeline for pronoun resolution.
User Query
β
βΌ Step 1: Query Rewriting
β LLM rewrites the query for better retrieval
β
βΌ Step 2: Multi-Query Expansion
β Generate 2 additional query variants β 3 queries total
β
ββββββββββββββββββββββββββββββββββββββββββββ
βΌ Step 3: BM25 Search βΌ Step 4: Vector Search
β Exact keyword matching β Semantic embedding similarity
β (rank-bm25) β (ChromaDB + nomic-embed-text)
ββββββββββββββββ¬ββββββββββββββββββββ
β
βΌ Step 5: Reciprocal Rank Fusion
β Merge and re-rank results from both indices
β
βΌ Step 6: CrossEncoder Reranking
β Neural model scores query-chunk relevance pairs
β
βΌ Step 7: Top-5 Chunks Selected
β
βΌ Step 8: Prompt Assembly
β Inject chunks as grounding context
β
βΌ Step 9: LLM Generation
β Ollama streams the grounded answer
β
βΌ Step 10: Evaluation
Faithfulness score + Relevancy score displayed
Raw user queries are often ambiguous or colloquial. "Who beat Thanos?" is harder to retrieve for than "Which Avengers defeated Thanos in Avengers: Endgame?". Before retrieval, an LLM call rewrites the query to be more explicit and retrieval-optimised, while preserving quoted proper nouns (character names, film titles) that must appear verbatim.
When conversation history is available (QA Chat and Agent Mode), the rewriter also resolves pronouns against recent exchanges before retrieval. If the user asks "Does he have a girlfriend?" immediately after asking "Who is Thor?", the rewriter uses a formatted {history_block} injected into the rewrite prompt to resolve "he" β "Thor" before the rewritten query hits the retrieval pipeline. This prevents pronoun-driven conversation drift.
A single rewritten query might miss relevant content phrased differently. The system generates 2 additional variants of the query (3 total) and runs all three through the full hybrid pipeline independently (BM25 + Vector + RRF + CrossEncoder per variant). The three sets of CrossEncoder-ranked results are deduplicated and merged by rerank score. This dramatically improves recall β a chunk that ranks #15 for one phrasing might rank #2 for another.
BM25 (Best Matching 25) is the gold standard algorithm for keyword-based document retrieval, used by Elasticsearch and Solr. It extends TF-IDF with document length normalisation. Given the query "Red Hulk", BM25 finds every chunk containing those exact tokens β no matter how semantically distant a vector embedding might consider them.
The BM25 index is pre-built from all knowledge base chunks and persisted as a pickle file. A custom tokeniser preserves hyphenated names ("Spider-Man", "T'Challa") and MCU acronyms ("S.H.I.E.L.D.") that generic tokenisers split incorrectly. Scores are normalised to [0, 1].
Each chunk is embedded into a 768-dimensional dense vector using nomic-embed-text. At query time, the query is also embedded and ChromaDB finds the nearest neighbours using L2 (Euclidean) distance β equivalent to cosine similarity ranking since all vectors are L2-normalised. Scores are converted to 1/(1+L2_distance). This captures semantic meaning β "Sorcerer Supreme" will match "Doctor Strange" even without exact keyword overlap.
Vector search excels at conceptual questions ("What is Tony Stark's character arc?") but can fail for keyword-critical lookups where exact terminology matters.
BM25 and vector search return two separate ranked lists of chunks. They score on different scales (BM25 is normalised 0β1 by term frequency; vector search returns 1/(1+L2_distance) scores). Naively averaging scores is meaningless.
RRF merges ranked lists without needing comparable scores. For each chunk, it computes:
RRF_score(chunk) = Ξ£ 1 / (k + rank_in_list_i)
where k = 60 (standard constant that dampens the impact of very high-ranked results). A chunk ranked #1 in both lists scores much higher than one ranked #1 in only one list. Chunks retrieved by both methods are rewarded; chunks found by only one method are still included but ranked lower.
Each of the 3 query variants runs its own complete hybrid pipeline (BM25 + Vector + 2-list RRF + CrossEncoder β top 5). The three independent top-5 results (up to 15 unique chunks) are then merged by deduplication and sorted by CrossEncoder rerank score.
The top results from RRF are passed to a CrossEncoder neural model (cross-encoder/ms-marco-MiniLM-L-6-v2). Unlike vector embeddings (which encode query and chunk independently), a CrossEncoder takes the (query, chunk) pair as a single input and scores their relevance jointly. This full attention across both texts gives much higher accuracy than dot-product similarity.
The CrossEncoder is the quality gate β it selects the best 5 chunks from the RRF output to pass to the LLM. It runs locally via sentence-transformers with no API call. Fallback: if the CrossEncoder fails (first load, memory pressure), RRF order is used instead.
The top 5 reranked chunks are formatted with source metadata (title, section, page) and injected into a mode-specific prompt template. The template instructs the LLM to answer only from the provided context, cite its sources, and admit uncertainty if the answer isn't in the retrieved material.
This grounding is the core RAG contract: the LLM can't hallucinate facts not present in the retrieved chunks.
llama3.1:8b runs locally via Ollama with:
temperature: 0.1β low randomness for factual answersnum_ctx: 8192β 8K token context window (Ollama default is only 2048)- Streaming enabled for QA Chat (tokens appear word by word)
After generation, two metrics are computed and displayed:
Faithfulness: An LLM judge rates whether every claim in the answer is supported by the retrieved chunks. It uses a 1β5 scale (1 = hallucinated, 5 = fully grounded), normalised to [0, 1]. Answers scoring below 0.4 trigger the agent's self-correction loop.
Relevancy: Average cosine similarity between the query embedding and each retrieved chunk's embedding. Measures whether the retrieved context was actually relevant to the question (not just whether the answer uses it).
Both metrics run locally β no external evaluation API.
The static 10-step pipeline is powerful but inflexible. Every query, regardless of complexity, follows the same path. An agent changes this: it decides what to do, step by step.
ReAct (Reasoning + Acting) is the agent loop that powers the system. The model alternates between:
- THOUGHT: "I need to find Iron Man's powers specifically, not general MCU info"
- ACTION: Call
search_by_character(character_name="Iron Man") - OBSERVATION: Retrieval returns 5 relevant chunks
- THOUGHT: "Now I also need context about his tech evolution"
- ACTION: Call
search_mcu_knowledge(query="Iron Man suit upgrades") - OBSERVATION: 5 more chunks retrieved
- FINAL ANSWER: Synthesised from all retrieved evidence
This loop runs for a maximum of 5 iterations (configurable). If the cap is hit, the agent synthesises an answer from whatever it has accumulated.
llama3.1:8b supports native tool-calling via Ollama's OpenAI-compatible API. When the model decides to call a tool, it returns a structured tool_calls field in the response instead of text β no prompt-engineering hack required.
For complex intents, a single general agent is suboptimal. The OrchestratorAgent classifies the query's intent first, then routes to a specialist:
| Intent | Agent | Specialist tools |
|---|---|---|
character |
CharacterAgent | search_by_character + search_mcu_knowledge |
phase |
TimelineAgent | search_by_phase + search_mcu_knowledge |
comparison |
ComparisonAgent | search_by_character + search_by_film + search_mcu_knowledge |
quiz |
QuizAgent | search_mcu_knowledge + search_by_character + evaluate_answer |
film / general |
MCUReActAgent | All 5 tools, max 5 iterations |
The Orchestrator uses a single LLM text-generation call for routing β not tool-calling. This is intentional: routing is a classification task, not a retrieval task. A simple prompt asking "Is this query about a character, phase, film, comparison, quiz, or general?" is cheaper, faster, and more reliable on an 8B model than using tool-calling for the decision.
ConversationBuffer (short-term): The last 5 Q&A exchanges are stored in session state. The buffer serves two distinct purposes:
-
Pronoun resolution β before the orchestrator sees a query,
rewrite_query(query, history=buf_history)uses a{history_block}injected into the rewrite prompt to resolve pronouns like "he", "she", or "they" into named entities. "Does he have a girlfriend?" after "Who is Thor?" becomes "Does Thor have a girlfriend?" in the rewritten query. -
Agent context β
_buf.get_context()is passed asconversation_contexttoorchestrator.run(), which threads it through to every specialist agent (CharacterAgent,TimelineAgent,ComparisonAgent,QuizAgent, andMCUReActAgent). Insiderun_react_loop(), the context is prepended to the agent'seffective_systemprompt asf"{conversation_context}\n\n{system_prompt}". Every agent in the routing tree sees the same conversation context β not just the general-purpose fallback. Maximum 2,000 characters to stay within the context budget.
SessionMemoryStore (long-term): MCU entity mentions (character names, film titles, Phase references) are extracted from each exchange and stored in a ChromaDB collection (agent_memory), keyed by session ID. On each new query, the most semantically relevant past memories are recalled and appended to the conversation_context alongside the buffer. This enables genuine cross-session context.
After producing a final answer, the agent checks faithfulness. If the score falls below 0.4, it automatically retries once with a broader query ("MCU " + original_query), retrieves additional chunks, and re-synthesises the answer. The corrected flag is recorded in the trace. Maximum 1 self-correction to prevent infinite loops.
AgentCache: Query results are cached in an in-memory LRU cache (128 entries, 1-hour TTL). Cache keys are SHA-256 hashes of normalised (lowercase, stripped) query text. Cache hits skip the entire ReAct loop. Cached results return a shallow copy, preventing mutation of the cached value.
AgentMetrics: Every run records total queries, average iterations, average latency, cache hit rate, self-corrections, and per-tool call counts. These feed the live KPI panel on the Home page.
Structured Logging: Every agent decision β tool calls, faithfulness checks, cache hits, self-corrections, aborts β is logged as structured JSON via structlog. Searchable, parseable, production-ready.
User Query
β
βΌ
OrchestratorAgent (intent classification β single LLM call)
βββ "character" β CharacterAgent (search_by_character + search_mcu_knowledge)
βββ "phase" β TimelineAgent (search_by_phase + search_mcu_knowledge)
βββ "comparison" β ComparisonAgent (search_by_character + search_by_film + search_mcu_knowledge)
βββ "quiz" β QuizAgent (search_mcu_knowledge + search_by_character + evaluate_answer)
βββ "film" β MCUReActAgent (all 5 tools, max 5 iterations)
βββ "general" β MCUReActAgent (all 5 tools, max 5 iterations)
β
βΌ
run_react_loop(conversation_context=β¦) β shared core used by ALL agents
β
βββ [Context inject] conversation_context prepended to effective_system prompt
βββ [Cache lookup] AgentCache (LRU, 128 entries, 1-hour TTL)
βββ [Ollama call] tool_calls or final answer
βββ [Tool dispatch] execute_tool() β hybrid_retrieve() / vector_search() / evaluate()
βββ [Self-correct] faithfulness < 0.4 β retry once with broader query
βββ [Cache store] on first successful answer
βββ [Metrics] AgentMetrics.record_run()
β
βΌ
AgentResult (answer + AgentTrace + chunks + context)
β
βΌ
Streamlit UI β Thought/Action/Observation trace, KPI panel, memory sidebar
Conversation context injection (Agent Mode):
pages/6_Agent_Mode.py
βββ rewrite_query(q, history=buf_history) β pronoun resolution
βββ orchestrator.run(q_resolved,
conversation_context=recalled + buf) β threaded to ALL agents
β
βββ CharacterAgent.run(conversation_context=β¦)
βββ TimelineAgent.run(conversation_context=β¦)
βββ ComparisonAgent.run(conversation_context=β¦)
βββ QuizAgent.run(conversation_context=β¦)
βββ MCUReActAgent.run(conversation_context=β¦)
βββ run_react_loop(conversation_context=β¦)
β effective_system = context + "\n\n" + system_prompt
Each tool call invokes hybrid retrieval (steps 3β7 of the RAG pipeline):
tool call(query)
β BM25 search β
β vector search β€ β RRF fusion β CrossEncoder reranking β top-5 chunks
β
β format_context(chunks) β appended to agent message history
Note: Query rewriting and multi-query expansion (steps 1β2) happen at the page level before the orchestrator is called, not inside individual tool calls.
- Ollama installed and running
- Python 3.11+ with uv package manager
- ~4 GB disk for models + ~500 MB for knowledge base
# 1. Clone / navigate to the project
cd python-agentic-rag-demo
# 2. Install all dependencies
uv sync
# 3. Set up environment
cp .env.example .env
# Edit .env if needed β defaults work for Ollama out of the box
# 4. Pull Ollama models (one-time, ~5GB total)
ollama pull llama3.1:8b
ollama pull nomic-embed-text
# 5. Build the knowledge base
# Downloads ~50K MCU chunks from Wikipedia, Fandom, HuggingFace (~5-10 mins)
uv run python scripts/ingest.py
# 6. Launch the app
uv run streamlit run Home.pyNavigate to http://localhost:8501 β all status indicators on the Home page should be green.
# In .env:
LLM_PROVIDER=openai
OPENAI_API_KEY=sk-...
OPENAI_MODEL=gpt-4o-mini
OPENAI_EMBED_MODEL=text-embedding-3-smallThe config and constants are fully wired for OpenAI. Client code integration is a planned extension.
Copy .env.example to .env. All values have safe defaults β the app works without editing.
| Variable | Default | Description |
|---|---|---|
LLM_PROVIDER |
ollama |
Active provider: ollama or openai |
OLLAMA_BASE_URL |
http://localhost:11434 |
Ollama server URL |
LLM_MODEL |
llama3.1:8b |
Ollama chat model |
EMBED_MODEL |
nomic-embed-text |
Ollama embedding model |
OLLAMA_NUM_CTX |
8192 |
Context window in tokens (Ollama default: 2048; llama3.1:8b max: 131072) |
OPENAI_API_KEY |
(empty) | OpenAI API key |
OPENAI_MODEL |
gpt-4o-mini |
OpenAI chat model |
OPENAI_EMBED_MODEL |
text-embedding-3-small |
OpenAI embedding model |
AGENT_MAX_ITERATIONS |
5 |
ReAct loop hard cap per query |
AGENT_MIN_FAITHFULNESS |
0.4 |
Faithfulness threshold triggering self-correction |
CACHE_MAX_SIZE |
128 |
LRU cache capacity (number of cached queries) |
CACHE_TTL_SECONDS |
3600 |
Cache TTL (1 hour) |
LOG_LEVEL |
INFO |
structlog output level (DEBUG/INFO/WARNING/ERROR) |
| Page | What you can do |
|---|---|
| π Home | Check system status (Ollama, embeddings, knowledge base), view live Agent KPIs (queries, latency, cache hit rate), see pipeline overview |
| π¬ QA Chat | Ask anything about the MCU β streaming answers with source citations and faithfulness/relevancy scores. Toggle Agent Mode for full ReAct trace |
| π§ Quiz Mode | AI-generated MCU trivia from the knowledge base. Questions are synthesised from retrieved chunks β the LLM can't make up unsupported facts |
| π¦Έ Character Dive | Deep-dive profile for any MCU character. Enter a name, get a structured profile (powers, films, relationships, key moments) sourced from the knowledge base |
| π Timeline Explorer | Temporal queries β "What happened between Infinity War and Endgame?", "List Phase 5 events in order". Phase-filtered retrieval |
| π¬ RAG Insights | Educational mode β every intermediate step visible. See the rewritten queries, BM25 results vs vector results, RRF merging, CrossEncoder scores, and evaluation metrics side by side |
| π€ Agent Mode | Free-form queries routed through the full multi-agent system. Live Thought/Action/Observation trace, memory panel, KPI display, conversation history |
All 199 tests run without Ollama β the LLM is fully mocked.
# Full suite
uv run pytest tests/ -v
# Just unit tests (faster)
uv run pytest tests/unit/ -v
# Specific suite
uv run pytest tests/unit/test_cache_and_logging.py -v
uv run pytest tests/integration/test_golden.py -v| Suite | What it tests |
|---|---|
unit/test_tools.py |
Tool schemas (flat, correct types), search wrapper dispatch |
unit/test_react.py |
ReAct loop logic, iteration cap, trace collection, graceful abort |
unit/test_pipeline.py |
All 5 RAG pipeline modes (regression: existing pages unbroken) |
unit/test_orchestrator.py |
Intent classification correctness, routing to correct specialist |
unit/test_specialists.py |
All 4 specialists produce correctly shaped AgentResult |
unit/test_memory.py |
ConversationBuffer rolling eviction, SessionMemoryStore entity extraction |
unit/test_cache_and_logging.py |
LRU eviction, TTL expiry, thread safety, AgentMetrics accumulation |
integration/test_golden.py |
20 canonical MCU questions with expected tool selections |
python-agentic-rag-demo/
βββ Home.py # Streamlit home + live KPI panel
βββ pages/
β βββ 1_π¬_QA_Chat.py
β βββ 2_π§ _Quiz_Mode.py
β βββ 3_π¦Έ_Character_Dive.py
β βββ 4_π
_Timeline_Explorer.py
β βββ 5_π¬_RAG_Insights.py
β βββ 6_π€_Agent_Mode.py
βββ src/mcu_rag/
β βββ config.py # All constants, env-var driven via python-dotenv
β βββ agents/
β β βββ base.py # AgentResult, AgentTrace, AgentStep dataclasses
β β βββ react_agent.py # run_react_loop() + MCUReActAgent β the shared core
β β βββ orchestrator.py # OrchestratorAgent (intent β specialist routing)
β β βββ cache.py # LRU AgentCache (TTL, thread-safe, copy-on-return)
β β βββ metrics.py # AgentMetrics KPI accumulator
β β βββ logging_config.py # structlog JSON structured logging
β β βββ memory/
β β β βββ conversation_buffer.py # Short-term rolling Q&A buffer
β β β βββ session_store.py # ChromaDB-backed entity memory
β β βββ specialists/
β β βββ character_agent.py
β β βββ timeline_agent.py
β β βββ quiz_agent.py
β β βββ comparison_agent.py
β βββ tools/
β β βββ registry.py # Ollama tool schemas + execute_tool() dispatcher
β β βββ search_tools.py # Callable tool functions wrapping retrieval
β βββ generation/
β β βββ llm.py # generate(), stream_generate(), is_ollama_running()
β β βββ pipeline.py # RAGPipeline β coordinates all 10 steps
β β βββ prompts.py # All prompt templates (RAG + all agents)
β βββ retrieval/
β β βββ hybrid.py # hybrid_retrieve() β the full 10-step pipeline
β β βββ vector_store.py # ChromaDB client + vector_search()
β β βββ bm25_retriever.py # BM25Retriever with MCU-aware tokeniser
β βββ evaluation/
β β βββ scorer.py # faithfulness_score(), chunk_relevancy()
β βββ ingestion/
β βββ wiki_scraper.py # Wikipedia article scraper
β βββ fandom_scraper.py # MCU Fandom Wiki scraper (MediaWiki API)
β βββ hf_loader.py # HuggingFace dataset loader
β βββ pdf_loader.py # Live PDF ingestion from Streamlit upload
βββ scripts/
β βββ ingest.py # One-time knowledge base builder
βββ tests/
β βββ conftest.py # Fixtures: sample_chunks, mock_ollama_*
β βββ unit/ # 7 unit test files
β βββ integration/
β βββ test_golden.py # 20 canonical MCU questions
βββ data/ # Gitignored β created by ingest.py
β βββ chroma_db/
βββ docs/
β βββ ARCHITECTURE.md # Technical deep dive β how & why every decision was made
βββ .env # Local config (gitignored)
βββ .env.example # Config template (committed)
βββ pyproject.toml
βββ CLAUDE.md # Claude Code conventions
βββ README.md
| Source | Content | Approx. chunks |
|---|---|---|
| Wikipedia API | 40+ character articles, 30+ film articles, MCU concept pages | ~15K |
| MCU Fandom Wiki | Deep character lore, events, objects, locations | ~20K |
| HuggingFace Datasets | Manvith/Marvel_dataset (facts), ismaildlml/Jarvis-MCU-Dialogues |
~15K |
All data is downloaded at ingestion time. Nothing is committed to git. The BM25 index and ChromaDB collection are rebuilt from scratch by scripts/ingest.py.
| Component | Technology | Why |
|---|---|---|
| LLM | llama3.1:8b via Ollama |
Free, local, native tool-calling, 131K context |
| Embeddings | nomic-embed-text via Ollama |
768-dim, 8K context, fast on CPU |
| Vector Store | ChromaDB | Persistent, local, no server required |
| RAG Framework | LlamaIndex | Document loading, chunking, index management |
| Keyword Search | rank-bm25 |
Gold standard BM25, pure Python, fast |
| Reranking | sentence-transformers CrossEncoder |
State-of-the-art relevance scoring, local |
| Agent Tool Calling | Ollama native tools API (OpenAI-compatible) | No LangChain dependency, direct control |
| Structured Logging | structlog | JSON output, searchable, production-ready |
| UI | Streamlit | Rapid prototyping, native streaming, session state |
| Package Manager | uv | 10β100Γ faster than pip, lockfile, venv management |
| Testing | pytest + monkeypatch | Zero Ollama required, fast, deterministic |
For a detailed explanation of why each technology and design decision was made, see docs/ARCHITECTURE.md.
MarvelMind β Built for Custom Generative AI Systems for Enterprises course mini project | All Marvel content referenced for educational purposes only.