Skip to content

About

Mini RAG in Python with a Dash of Agentic Flair πŸš€

Topics

Resources

Stars

3 stars

Watchers

0 watching

Forks

Latest commit

Β 

History

2 Commits

Folders and files

NameName
Last commit message
Last commit date
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

MarvelMind β€” MCU Agentic RAG Showcase

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


Table of Contents

  1. What Problem Does This Solve?
  2. Why the MCU Is the Perfect Demo Domain
  3. The RAG Pipeline β€” 10 Steps Explained
  4. The Agentic Layer β€” How It Works
  5. System Architecture
  6. Quick Start
  7. Configuration (.env)
  8. App Pages
  9. Running Tests
  10. Project Structure
  11. Data Sources
  12. Tech Stack

1. What Problem Does This Solve?

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.


2. Why the MCU Is the Perfect Demo Domain

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.


3. The RAG Pipeline β€” 10 Steps Explained

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

Step 1: Query Rewriting

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.

Step 2: Multi-Query Expansion

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.

Step 3: BM25 Keyword Search

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].

Step 4: Vector Search (Semantic Search)

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.

Step 5: Reciprocal Rank Fusion (RRF)

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.

Step 6: CrossEncoder Reranking

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.

Step 7 & 8: Chunk Selection and Prompt Assembly

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.

Step 9: LLM Generation

llama3.1:8b runs locally via Ollama with:

  • temperature: 0.1 β€” low randomness for factual answers
  • num_ctx: 8192 β€” 8K token context window (Ollama default is only 2048)
  • Streaming enabled for QA Chat (tokens appear word by word)

Step 10: Evaluation (LLM-as-Judge)

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.


4. The Agentic Layer β€” How It Works

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.

The ReAct Pattern

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.

The Multi-Agent Team

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.

Memory

ConversationBuffer (short-term): The last 5 Q&A exchanges are stored in session state. The buffer serves two distinct purposes:

  1. 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.

  2. Agent context β€” _buf.get_context() is passed as conversation_context to orchestrator.run(), which threads it through to every specialist agent (CharacterAgent, TimelineAgent, ComparisonAgent, QuizAgent, and MCUReActAgent). Inside run_react_loop(), the context is prepended to the agent's effective_system prompt as f"{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.

Self-Correction

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.

Caching and Observability

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.


5. System Architecture

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.


6. Quick Start

Prerequisites

  • Ollama installed and running
  • Python 3.11+ with uv package manager
  • ~4 GB disk for models + ~500 MB for knowledge base

Setup

# 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.py

Navigate to http://localhost:8501 β€” all status indicators on the Home page should be green.

OpenAI mode (future)

# In .env:
LLM_PROVIDER=openai
OPENAI_API_KEY=sk-...
OPENAI_MODEL=gpt-4o-mini
OPENAI_EMBED_MODEL=text-embedding-3-small

The config and constants are fully wired for OpenAI. Client code integration is a planned extension.


7. Configuration (.env)

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)

8. App Pages

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

9. Running Tests

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

10. Project Structure

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

11. Data Sources

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.


12. Tech Stack

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.

About

Mini RAG in Python with a Dash of Agentic Flair πŸš€

Topics

Resources

Stars

3 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages