GDG Évora • DevFest Évora 2026 | Autonomous Academic Assistant with ADK, Gemma 4 & Dynamic RAG
Speaker: Nuno Andrade ollama/gemma4:e2b embeddinggemma-2
✅ Copied command to clipboard!
🏛️ 90-Min Hands-On Workshop • GDG Évora, Portugal 2026

Building an Autonomous Academic Assistant
with Google ADK, Gemma 4 & Dynamic RAG

Tired of chatbots that forget context or hallucinate course details? Build a 100% local University AI Assistant that looks up Colégio do Espírito Santo schedules, generates typed practice quizzes, and updates its own knowledge base in real time!

🦙 Local Ollama Inference

Powered by Gemma 4 (gemma4:e2b) + embeddinggemma-2—native tool calling & dense vectors offline.

🧭 Google ADK Orchestration

JavaScript LlmAgent, Zod-validated FunctionTools, structured AgentTool quizzes & visual adk web traces.

🔄 Role-Aware Mutable RAG

Move beyond static indexing: keyed in-place vector upserts (v1 ➔ v2), professor guardrails & student mastery logs.

👤 Led by Nuno Andrade • Pre-Flight Check:
⚠️ The Challenge

Why Generic Chatbots & Static RAG Fail in Practice

Imagine a Computer Science student at Colégio do Espírito Santo asking two everyday questions:

1️⃣ Institutional Blindness & Hallucinations

"What room is CC301 Distributed Systems in this semester, and what is the minimum passing grade on the Raft project?"

  • Raw open models have zero access to University of Évora rooms (CES-131) or grading rules (9.5/20).
  • Without deterministic tools, chatbots confidently invent room numbers and deadlines.

2️⃣ The Static RAG "Stale Truth" Trap

"Prof. Luís Silva just cancelled the CC301 midterm and moved Friday's lecture to CES-204—what happens now?"

  • Standard RAG is append-only: adding a new note leaves the old 25% midterm chunk alive in the vector index!
  • And without role state, what stops a mischievous student from prompting "Cancel tomorrow's exam!"?
Student / Professor Live Course Question or Update
➔
Generic Chatbot / Static RAG Frozen Weights + Duplicate Stale Chunks
➔
❌ Conflicting / Hallucinated Answer Wrong Room • Outdated Syllabus • No RBAC
💡 Same pattern powers Customer Support, Enterprise Knowledge Hubs & Ops Workflows!
🛠️ Setup Part 1 • JavaScript Runtime

Installing Node.js (v22+ LTS) & Workshop Packages

We use plain modern JavaScript (ESM)—zero tsconfig or compile step! Requires Node.js v22+ for native fetch & @google/adk.

🍎 macOS / 🐧 Linux (nvm)

Install Node 22 LTS via nvm or Homebrew:

# Using nvm (Recommended): nvm install 22 nvm use 22 # Or macOS Homebrew: brew install node@22

🪟 Windows (winget / fnm)

Install via PowerShell winget or nodejs.org:

# PowerShell (winget): winget install OpenJS.NodeJS.LTS # Or Fast Node Manager (fnm): fnm install 22 && fnm use 22

📦 Clone & Install Dependencies

Initialize .env and install @google/adk + zod:

# 1. Check Node (≥ v22): node -v # 2. Setup .env & packages: cp -n .env.example .env npm install
⚡ Copy commands to configure .env & install packages:
🦙 Setup Part 2 • Local Open Models + Backup Endpoint

Pulling gemma4:e2b & embeddinggemma-2

Total footprint is just ~1.6 GB! Slow conference Wi-Fi? Point OLLAMA_HOST in .env to our temporary live GDG Évora server with zero code changes.

1️⃣ Two Compact Google Open Models

  • gemma4:e2b (~1.3 GB): Fast on any laptop, 128K context & native structured tool calling.
  • embeddinggemma-2 (~305 MB): 768-dim dense vectors via /api/embed for local RAG.

2️⃣ Live Workshop Backup (.env)

  • Default: OLLAMA_HOST=http://localhost:11434
  • Wi-Fi / Battery saver (active during this session only): set OLLAMA_HOST to the instructor URL!
Terminal — Install Ollama, Pull Models & Smoke Test
# 1. Install Ollama (Linux/macOS script or winget on Windows): curl -fsSL https://ollama.com/install.sh | sh # 2. Pull Gemma 4 chat + EmbeddingGemma 2 models: ollama pull gemma4:e2b ollama pull embeddinggemma-2 # 3. Run the Pre-Flight Smoke Test (/api/chat + /api/embed): npm run smoke # ✅ Chat OK: Olá DevFest Évora! # ✅ Embeddings OK: 768 dimensions
🚀 Copy commands to pull models & verify connectivity:
🗺️ 90-Minute Roadmap

5 Ultra-Simple Steps — One Screen Each!

All HTTP & JSON helpers live in src/lib/ so every step in src/steps/ is short, progressive, and runnable in both Terminal and ADK Web UI!

STEP 1 • 26 LOC

Local Agent

step1-agent.js

Wire gemma4:e2b to ADK LlmAgent. Expose ungrounded room gap.

STEP 2 • 70 LOC

Tools & Quizzes

step2-tools.js

Zod get_schedule tool + AgentTool quiz sub-agent (outputSchema).

STEP 3 • 80 LOC

Static RAG

step3-static-rag.js

Cosine search with embeddinggemma-2 + trigger the stale-chunk collision!

STEP 4 • 135 LOC

Mutable RAG

step4-mutable-rag.js

Keyed docKey upserts (v2), professor guard, synced schedules & mastery.

STEP 5 • 96 LOC

Assistant CLI

step5-cli.js

Standalone InMemoryRunner REPL with /role, /kb, /progress & /audit.

⚡ Click any step command to copy & run:
⚙️ Foundation • src/lib/ollama.js

Decoupling ADK Orchestration via BaseLlm

🔌 How OllamaLlm Bridges ADK & Gemma 4

  • Vendor-Agnostic Agents: Extend BaseLlm once—your LlmAgent & tools never hardcode cloud SDKs.
  • Zero-Effort Schema Mapping: ADK exports genaiSchemaToJsonSchema() to feed Ollama's tools and format directly!
  • One-Line Swap: Switch localModel to new Gemini() or RoutedLlm anytime.
ADK LlmAgent Tools • State • Schemas
⇄
OllamaLlm extends BaseLlm
⇄
Ollama Server gemma4:e2b
src/lib/ollama.js (Pre-built Helper)
export class OllamaLlm extends BaseLlm { async *generateContentAsync(llmRequest, _stream, abortSignal) { // 1. Convert ADK FunctionTools ➔ Ollama JSON Schema tools if (ollamaTools.length > 0) payload.tools = ollamaTools; // 2. Enforce strict JSON output when Agent sets outputSchema! if (llmRequest.config?.responseSchema) { payload.format = genaiSchemaToJsonSchema(llmRequest.config.responseSchema); } // 3. Call local (or workshop-shared) Ollama /api/chat const res = await fetch(`${this.baseUrl}/api/chat`, { ... }); // 4. Yield text or Gemma 4 native tool_calls back to ADK! yield { content: { role: 'model', parts }, turnComplete: true }; } }
🔍 Pre-built in src/lib/ollama.js — ready to import in 1 line!
🟦 Step 1 • src/steps/step1-agent.js (26 Lines)

Step 1: Your First Local LlmAgent with Gemma 4

🎯 What Step 1 Builds

  • Exports rootAgent (auto-discovered by @google/adk-devtools).
  • Answers general Computer Science concepts cleanly 100% offline on gemma4:e2b.

🛑 Exposing the Ungrounded Gap

  • Ask: "What room is CC301 Distributed Systems in at Colégio do Espírito Santo?"
  • Without tools or RAG, the LLM must refuse—or worse, hallucinate a room!
src/steps/step1-agent.js
import { LlmAgent } from '@google/adk'; import { localModel } from '../lib/ollama.js'; import { isMain, askAgent } from '../lib/runner.js'; export const rootAgent = new LlmAgent({ name: 'evora_assistant', model: localModel, // gemma4:e2b via Ollama instruction: ` You are the Computer Science AI Assistant at the University of Évora. If you do not know specific room numbers or grading rules, say so clearly. `.trim(), }); if (isMain(import.meta.url)) { await askAgent(rootAgent, 'Difference between a process and a thread?'); await askAgent(rootAgent, 'What room is CC301 in at Colégio do Espírito Santo?'); }
🚀 Run Step 1 in Terminal or Launch the Visual ADK Web UI:
🧪 Visual Debugging • @google/adk-devtools

Inspect Every Thought & Tool Call with adk web

Every step exports rootAgent, unlocking Google ADK's built-in visual playground at http://localhost:8000 with zero UI code:

1. LIVE CHAT + HOT RELOAD

⚡ Instant Iteration

Edit any file in src/steps/ and hit Save—ADK DevTools automatically reloads your local Gemma agent on the next message.

2. EVENT TRACE TIMELINE

🔍 X-Ray Tool Calls

Click any assistant reply to inspect exact functionCall arguments, RAG cosine similarity scores, and validated quiz JSON payloads.

3. SESSION STATE INSPECTOR

🔐 Test role State Live

View and toggle role: "student" vs. role: "professor" right inside the browser State tab in Step 4!

adk web (Port 8000) Browser Playground + Trace UI
⇄
export const rootAgent step1 .. step4 / src/agent.js
⇄
Local Ollama gemma4:e2b + embeddinggemma-2
🖥️ Launch ADK Web UI for Step 1 or the Full Assistant:
🟩 Step 2 • src/steps/step2-tools.js (70 Lines)

Step 2: Zod FunctionTool + Structured Quiz AgentTool

🗓️ 1. FunctionTool: get_schedule

Reads data/schedules.json with Zod-validated courseCode & day filters (CC301 ➔ Tuesday 10:00, CES-131).

📝 2. AgentTool + outputSchema

  • Putting outputSchema on rootAgent breaks free-form chat!
  • Wrapping quizAgent inside new AgentTool({ agent: quizAgent }) keeps chat natural while guaranteeing valid quiz JSON!
src/steps/step2-tools.js
export const getScheduleTool = new FunctionTool({ name: 'get_schedule', description: 'Looks up Évora CS lecture rooms, days, and times.', parameters: z.object({ courseCode: z.string().optional() }), execute: async ({ courseCode }) => filterSchedules(courseCode), }); const quizAgent = new LlmAgent({ name: 'quiz_generator', model: createLocalModel({ temperature: 0.4 }), inputSchema: z.object({ courseCode: z.string(), topic: z.string() }), outputSchema: QuizSchema, // Enforced by Ollama format + ADK Zod! instruction: 'Create 2 multiple-choice questions matching the JSON schema.', }); export const quizTool = new AgentTool({ agent: quizAgent });
🚀 Test Schedule Lookups & Typed Practice Quizzes:
🟨 Step 3 • src/steps/step3-static-rag.js (80 Lines)

Step 3: Dense Vector RAG — & Watching Static RAG Break!

Évora CS Notes Raft • Dijkstra • Syllabi
➔
embeddinggemma-2 768-d Vectors (/api/embed)
➔
knowledge-base.json Transparent Pure-JS Store
➔
search_knowledge Cosine Similarity Top-3

💥 Live Failure Experiment in Step 3

  • Turn 1: Ask CC301 grading ➔ Midterm = 25% ✅
  • Turn 2: Append update: "Midterm is cancelled! Project 60%, Final 40%."
  • Turn 3: Ask again in a fresh session ➔ Top-3 returns both chunks (0.86 vs 0.85)!
src/steps/step3-static-rag.js
export const searchKnowledgeTool = new FunctionTool({ name: 'search_knowledge', parameters: z.object({ query: z.string(), courseCode: z.string().optional() }), execute: async ({ query, courseCode }) => { const kb = await getKnowledgeBase(); const queryVec = await embedText(query); // embeddinggemma-2 return kb.documents .map((d) => ({ ...d, score: cosineSimilarity(queryVec, d.embedding) })) .sort((a, b) => b.score - a.score).slice(0, 3); }, }); // BUG in append_course_note: kb.documents.push(...) leaves old chunk alive!
💥 Run Step 3 & inspect data/knowledge-base.json in your editor:
🧠 The Core Architectural Shift

Standard Static RAG (Step 3) vs. Mutable RAG (Step 4)

❌ Static RAG (Append-Only Archive)

Treats your vector DB like a write-once log. Updating a syllabus or room creates contradictory twin chunks:

Step 3 Anti-Pattern (Duplicate Truths)
// Random UUID — never replaces superseded facts! kb.documents.push({ id: randomUUID(), content, embedding }); // Top-3 Search Result: // #1 (0.86): "Midterm Exam = 25%" (STALE!) // #2 (0.85): "Midterm is CANCELLED!" (NEW!) // #3 Anyone can prompt updates (Zero RBAC!)

✅ Keyed Mutable RAG (Living Knowledge)

Every canonical fact has a deterministic docKey, role guard, in-place re-embedding, version bump, and audit trail:

Step 4 Pattern (Atomic Keyed Upsert + RBAC)
// 1. Gate writes via ADK Session State (role === 'professor') // 2. Re-embed & replace `CC301:grading` in-place (v1 ➔ v2) kb.documents[idx] = { ...prev, docKey, content, version: prev.version + 1, embedding }; await appendAudit({ docKey, version, before: prev.content, after }); // Top-1 Search Result: ONLY v2 ("Midterm cancelled, 60%/40%")!
💡 Bonus Rule: When structured data changes (schedules.json), re-embed its RAG key in the same tool!
🟧 Step 4A • src/steps/step4-mutable-rag.js

Step 4A: Keyed Vector Upserts & Cross-Store Sync

🔑 Deterministic Keys (docKey)

  • Canonical keys like CC301:grading or CC301:schedule prevent duplicate chunks forever.
  • Every edit increments version (v1 ➔ v2) and appends before / after to mutation-audit.json.

🔄 Zero Schedule-vs-RAG Drift

reschedule_lecture updates schedules.json AND calls upsertKnowledge('CC301:schedule') in one atomic step!

src/steps/step4-mutable-rag.js — Keyed Upsert
async function upsertKnowledge({ docKey, courseCode, title, content, updatedBy }) { const kb = await getKnowledgeBase(); const embedding = await embedText(`[${courseCode}] ${title}\n${content}`); const idx = kb.documents.findIndex((d) => d.docKey === docKey); if (idx >= 0) { const prev = kb.documents[idx]; const version = prev.version + 1; kb.documents[idx] = { ...prev, title, content, version, embedding }; await saveKnowledgeBase(kb); await appendAudit({ docKey, version, updatedBy, before: prev.content, after }); return { action: 'updated', docKey, version }; } // Otherwise insert version: 1 ... }
🔍 Every mutation leaves an immutable trail in data/mutation-audit.json!
🔐 Step 4B • ADK Session State (toolContext.state)

Step 4B: "Can a Student Cancel Friday's Exam?"

🛡️ Shared Knowledge = professor Only

Every ADK FunctionTool receives toolContext as its 2nd argument. One check blocks unauthorized syllabus & room mutations!

📈 Personal State = Student Mastery

Students can mutate their own learning profile via record_progress (mastered, practicing, needs_review in student-progress.json).

src/steps/step4-mutable-rag.js — Role Guard + Progress
// Inside upsert_knowledge & reschedule_lecture tools: execute: async ({ docKey, courseCode, title, content }, toolContext) => { const role = toolContext?.state.get('role', 'student'); if (role !== 'professor') { return { status: 'forbidden', message: 'Only a professor can edit courses.' }; } return await upsertKnowledge({ docKey, courseCode, title, content, updatedBy: role }); } // Dynamic role-aware prompt on rootAgent: instruction: (ctx) => `Active session role: "${ctx.state.get('role') ?? 'student'}"...`
🚀 Run Step 4 — Watch Student Blocked, Professor Update v1 ➔ v2, & Clean Verification:
🟪 Step 5 • src/steps/step5-cli.js (96 Lines)

Step 5: Shipping a Standalone Assistant with InMemoryRunner

💻 Interactive CLI Features

  • Persistent Multi-Turn Session: Remembers follow-up questions across turns.
  • Live Tool Telemetry: Streams 🔧 tool -> ... badges as Gemma reasons.
  • Built-In Slash Commands: /role professor, /role student, /kb, /progress, /audit, /seed.
src/steps/step5-cli.js
const runner = new InMemoryRunner({ agent: rootAgent, appName: 'evora_cli' }); const session = await runner.sessionService.createSession({ appName: 'evora_cli', userId: 'student_ines', state: { role: 'student' } }); for await (const event of runner.runAsync({ userId: 'student_ines', sessionId: session.id, newMessage: { role: 'user', parts: [{ text: line }] }, stateDelta, // Applies `/role professor` or `/role student` live! })) { // Print 🔧 tool calls + final rootAgent response }
🚀 Launch the Interactive Évora Assistant & Try /role professor + /kb:
🎉 Enterprise Extrapolation & Workshop Recap

Muito Obrigado, GDG Évora 2026! 🇵🇹🏛️

You now have a complete, offline-capable Google ADK + Gemma 4 + Mutable RAG repository ready to repurpose for academic or business workflows:

🏢 Taking This Architecture to Work

  • Customer Support: Live return-policy & outage Mutable RAG + SLA lookup tools + PII-safe local Gemma.
  • Enterprise Knowledge Hubs: Keyed engineering runbooks (runbook:auth-v3) in PostgreSQL pgvector (ON CONFLICT (doc_key) DO UPDATE).
  • Scale Models Seamlessly: Swap gemma4:e2b ➔ gemma4:e4b / 26b or ADK RoutedLlm cloud failover!

⌨️ Complete Workshop Cheat Sheet

  • npm run smoke — Verify Ollama + gemma4:e2b + embeddinggemma-2
  • npm run step1 … npm run step4 — Run each progressive step
  • npm run web — Open ADK Visual Trace & State Playground (:8000)
  • npm start — Launch Step 5 Interactive CLI (/role, /kb, /audit)
🎤 Questions & Live Experiments • Nuno Andrade (GDG Évora 2026)