Back to Projects

RAGAI: Architecture and Workflow

A Gemini-powered Retrieval-Augmented Generation system over YouTube course audio. Audio is transcribed, translated, segmented, embedded, retrieved by similarity and turned into a grounded, cited answer.

Pipeline in one line: transcribe → translate → chunk → embed → retrieve → grounded answer.

1. High-level architecture

The system has two independent halves: an offline ingestion pipeline that is run once per batch of videos, and an online query pipeline that is run for every question.

Offline / batch pipeline (ingestion)

YouTube playlistaudioytplaylist.bat · yt-dlp -x --audio-format mp3
video/*.mp3raw audio
create_chunk.pyGemini 2.5 Flash · Files API upload · transcribe + translate + segment · strict JSON prompt
transcripts/*.json{title, segments:[{start, end, text}]}
read_chunks_json.pyOllama @ localhost:11434 · model bge-m3 · 3 retries, 5 s backoff
processed_data/*_embeddings.json[{id, title, text, embedding[1024], start, end}]
ingestion from playlist to embeddings
Animated walkthrough: ingestion from playlist to embeddings. Loops automatically.

Online / query pipeline (serving) · quiry.py

User queryinput() on the console
Embed queryOllama bge-m3 (no retry)
vector_db.jobliblazy load, or lazy build from processed_data/*.json · {texts[], embeddings[N,1024] float32, metadata[]}
Cosine similarity (scikit-learn) → top-K = 10exact brute-force search, no threshold
Context builderblocks of Title / Source / Time / Content
Gemini 2.5 Flash + strict grounding prompt7 hard rules, fixed output format
Console print + query_output.txt
input / assemblymodel or computestored dataoutput
a question becoming a grounded answer
Animated walkthrough: a question becoming a grounded answer. Loops automatically.

How the two halves connect

Playlist → MP3yt-dlp Geminitranscript JSON Ollama bge-m3embeddings JSON quiry.pyretrieve + answer offline, run per batchonline, run per question files on disk are the only interface between stages

2. Component inventory

# File Role Inputs Outputs
1 audioytplaylist.bat Media acquisition (Windows batch, yt-dlp) YouTube playlist URL video/*.mp3
2 create_chunk.py Transcription, translation, timestamped segmentation video/*.mp3 transcripts/<name>.json
3 read_chunks_json.py Active embedding stage transcripts/*.json processed_data/<name>_embeddings.json
4 read_chunks.py Legacy embedding stage (CSV, drops timestamps) transcripts/*.json processed_data/<name>.csv
5 quiry.py RAG query engine (retrieve + generate) processed_data/*.json, vector_db.joblib, user query stdout + query_output.txt
6 vector_db.joblib Serialized vector index (about 3.3 MB) built by quiry.py cache
7 .env GOOGLE_API_KEY via dotenv — —
8 tempCodeRunnerFile.py Empty artifact (VS Code runner) — —

Runtime dependencies: Python 3.9+, google-genai, python-dotenv, requests, numpy, scikit-learn, joblib, pandas (only for read_chunks.py), an Ollama server with bge-m3 pulled, and yt-dlp.

3. Stage-by-stage detail

Stage 0: Ingestion audioytplaylist.bat

  • Prompts for a playlist URL, then changes directory to the project folder.
  • Runs yt-dlp -x --audio-format mp3 --audio-quality 0 -ciw with the filename pattern %(playlist_index)s - %(title)s.%(ext)s.
  • -ciw means continue, ignore errors, overwrite, so re-runs are idempotent.
  • Files in video/ are actually named tutorialN.mp3, so they were renamed or placed manually after download.

Stage 1: Transcription and structured segmentation create_chunk.py

load_dotenv() then genai.Client(api_key=...).
For each .mp3 in video/, client.files.upload(file=path) returns an uri from the Gemini Files API.
generate_content(model="gemini-2.5-flash", contents=[PROMPT, {fileData:{fileUri, mimeType:"audio/mpeg"}}]).
The single prompt tells Gemini to transcribe fully, translate to clean English, write a summary title, and split the text into non-overlapping, non-empty, sentence- or idea-bounded segments with start/end seconds. It must return raw JSON only.
Code fences are stripped, then json.loads() runs. On a parse failure the raw output is printed and the loop continues with the next file.
Output is written to transcripts/<base>.json (indent=2, ensure_ascii=False).

Known bug: the script prints len(segments), which is the dict (always 2), instead of len(segments['segments']).

Stage 2: Embedding read_chunks_json.py

  • Reads every file in transcripts/. There is no .json suffix filter, so a non-JSON file would crash it.
  • Keeps only segments with non-empty text.
  • create_embedding(text) POSTs to http://localhost:11434/api/embeddings with {"model":"bge-m3","prompt":text}. It makes 3 attempts with a 5 s sleep, then raises ConnectionError.
  • Builds {id, title, text, embedding, start, end} records with a global incrementing id across all files.
  • Writes one processed_data/<base>_embeddings.json per source file.
  • read_chunks.py is the same idea but writes a pandas CSV without start/end. It is superseded and git-ignored.

Stage 3: Vector store quiry.py · lazy init

Start quiry.py
vector_db.joblib exists?
yes
joblib.load()
no
Walk processed_data/*.json, skip chunks with no embedding, collect texts[], embeddings[], metadata[] (source_file, title, start, end), cast to float32
joblib.dump() for next time

Staleness trap: the cache is never invalidated. After adding transcripts you must delete vector_db.joblib, or the new data stays invisible.

Stage 4: Retrieval

  • input() query, then embed_query() against the same Ollama endpoint (no retry), then .reshape(1,-1).
  • cosine_similarity(query_vec, embeddings)[0], then argsort()[-TOP_K:][::-1] with TOP_K = 10.
  • Exact brute-force NumPy/scikit-learn search: no ANN index and no minimum-score threshold.

Stage 5: Context assembly

Each of the top-10 hits becomes a block, and the blocks are joined with a blank line into context_text:

Title: <title>
Source: <source_file>
Time: <start> → <end>
Content: <text>

Stage 6: Grounded generation gemini-2.5-flash

The prompt enforces seven hard rules and a fixed output format (Explanation: then a Where it is taught: list). The result is printed and written to query_output.txt.

The seven grounding rules

  1. Answer only from the provided chunks.
  2. Quote or paraphrase the chunks.
  3. Always cite video title and timestamps.
  4. Use student-friendly language.
  5. Use no outside knowledge.
  6. Never mention embeddings or scores.
  7. Give a canned refusal for off-topic questions.

4. End-to-end data flow

Four commands run the whole system:

audioytplaylist.bat         →  video/*.mp3
python create_chunk.py      →  transcripts/*.json                 (Gemini: speech → JSON)
python read_chunks_json.py  →  processed_data/*_embeddings.json   (Ollama: text → vector)
python quiry.py             →  vector_db.joblib (built once) + query_output.txt
Location Shape Purpose
video/ *.mp3 Raw media
transcripts/ {title, segments[]} Human-readable, timestamped
processed_data/ [{id, title, text, embedding, start, end}] Embeddable
vector_db.joblib {texts[], embeddings[N,1024] f32, metadata[]} Queryable

5. Query sequence

User quiry.py Ollama bge-m3 joblib index Gemini query text embed_query(text) query vector [1024] load / build index embeddings + metadata cosine similarity, top-10,build context blocks PROMPT + context + question grounded answer with citations write query_output.txt print answer

6. Data contracts

Transcript (create_chunk.py output)

{
  "title": "str",
  "segments": [ { "start": 8.32, "end": 8.41, "text": "str" } ]
}

Embedding record (read_chunks_json.py output)

[ { "id": 0, "title": "str", "text": "str",
    "embedding": [ /* 1024 floats */ ],
    "start": 0.0, "end": 0.0 } ]

Vector store (vector_db.joblib)

{ "texts": [...], "embeddings": ndarray[N, 1024] float32,
  "metadata": [ { "source_file", "title", "start", "end" } ] }

7. Strengths, gaps and fixes

Strengths

  • Clean separation of offline ingest and online query.
  • Strict JSON-only prompt, fence stripping and per-file try/except make batch ingestion resilient.
  • Embedding retries with backoff against Ollama.
  • Timestamps are kept end-to-end, so citations are precise (for example 8.32 → 8.41).
  • Cached embeddings and index avoid repeated embedding cost.

Design characteristics

  • Exact search, so results are deterministic.
  • Local embeddings (Ollama) with a hosted LLM (Gemini).
  • Code-only repository: data directories, the batch file and .env are git-ignored, so data must be regenerated.