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)
Online / query pipeline (serving) · quiry.py
How the two halves connect
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 -ciwwith the filename pattern%(playlist_index)s - %(title)s.%(ext)s. -ciwmeans continue, ignore errors, overwrite, so re-runs are idempotent.- Files in
video/are actually namedtutorialN.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=...)..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"}}]).
json.loads() runs. On a parse failure the raw output is
printed and the loop continues with the next file.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.jsonsuffix filter, so a non-JSON file would crash it. - Keeps only segments with non-empty text.
create_embedding(text)POSTs tohttp://localhost:11434/api/embeddingswith{"model":"bge-m3","prompt":text}. It makes 3 attempts with a 5 s sleep, then raisesConnectionError.- Builds
{id, title, text, embedding, start, end}records with a global incrementingidacross all files. - Writes one
processed_data/<base>_embeddings.jsonper source file. read_chunks.pyis the same idea but writes a pandas CSV withoutstart/end. It is superseded and git-ignored.
Stage 3: Vector store quiry.py · lazy init
quiry.pyjoblib.load()processed_data/*.json, skip chunks with no embedding, collect
texts[], embeddings[], metadata[] (source_file, title, start,
end), cast to float32joblib.dump() for next timeStaleness 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, thenembed_query()against the same Ollama endpoint (no retry), then.reshape(1,-1).cosine_similarity(query_vec, embeddings)[0], thenargsort()[-TOP_K:][::-1]withTOP_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
- Answer only from the provided chunks.
- Quote or paraphrase the chunks.
- Always cite video title and timestamps.
- Use student-friendly language.
- Use no outside knowledge.
- Never mention embeddings or scores.
- 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
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
.envare git-ignored, so data must be regenerated.