Lab 29: Building a Simple Custom Chat UI Challenge
Goalโ
In this lab, you will build a standalone HTML/JavaScript chat frontend that connects to ADK's native FastAPI backend (uv run adk api_server), creates sessions via REST, and streams live token-by-token responses over /run_sse.
Step 1: Create the Backend Agent (ui_agent)โ
Environment setup:
- 1-Click Launch (Browser): Open in GitHub CodespacesOpen in Google Cloud Shell
- Local machine: If you're continuing the course in sequence,
cdinto theadk-trainingproject you created in Module 2 and skip the block below -- your environment and dependencies already carry forward. If you're starting fresh at this module, create that project first:uv init adk-training --python 3.10 && cd adk-training
uv add "google-adk>=2.1.0" python-dotenv- DevContainer / Codespaces (Alternative): If you opened this repository in a DevContainer or GitHub Codespaces, Python 3.11,
uv,gcloud, and all core ADK dependencies are pre-installed in your container environment.
-
Navigate to your
adk-trainingworkspace directory and scaffoldui_agent:cd /path/to/your/adk-training
uv run adk create ui_agentadk createprompts you for a model and backend (Google AI Studio or Vertex AI) and generatesui_agent/__init__.py,ui_agent/agent.py,ui_agent/.env, andui_agent/.gitignore. -
Implement
ui_agent/agent.py: Openui_agent/agent.pyand replace its contents with:from google.adk import Agent
root_agent = Agent(
model="gemini-3.8-flash",
name="ui_agent",
instruction="You are a helpful and friendly assistant.",
) -
Verify
ui_agent/.env: Confirm your API key (GOOGLE_API_KEY) or Vertex AI settings (GOOGLE_GENAI_USE_ENTERPRISE=1,GOOGLE_CLOUD_PROJECT,GOOGLE_CLOUD_LOCATION) are configured insideui_agent/.env.
Step 2: Create the Isolated Frontend Client (frontend/index.html)โ
-
Create a separate
frontend/folder insideadk-training:cd /path/to/your/adk-training
mkdir -p frontendSecurity Best Practice โ Never serve static files from inside
ui_agent/! Runningpython3 -m http.serverinsideui_agent/exposes every file in that directory over HTTP โ includingui_agent/.envand your API keys! Keeping static web assets in a separatefrontend/folder ensures backend secrets are never reachable by a browser. -
Complete
frontend/index.html: Exercise: Createfrontend/index.htmlusing the starter skeleton below and complete# TODO: 1,# TODO: 2, and# TODO: 3inside thesubmithandler.Pay close attention to three real-world SSE streaming details:
- Enable incremental token streaming: Include
"streaming": truein the/run_sseJSON body (without it,RunAgentRequest.streamingdefaults tofalseand waits until the entire response finishes!). - Buffer split TCP chunks: Network reads can split an SSE
data: {...}\nline mid-packet. Accumulate decoded text in abufferstring, split by'\n', and keep the trailing partial line withbuffer = lines.pop(). - Prevent duplicate final messages: With
"streaming": true, ADK emits incremental chunks markedeventData.partial === trueand finishes the turn with one final aggregatedEvent(!eventData.partial) containing the entire response text. Only append a non-partial event's text if no partial chunks were already streamed for that step!
- Enable incremental token streaming: Include
<!-- frontend/index.html (Starter Code) -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ADK Custom UI</title>
<style>
body { font-family: sans-serif; display: flex; flex-direction: column; height: 100vh; margin: 0; }
#chat-container { flex: 1; overflow-y: auto; padding: 20px; display: flex; flex-direction: column; }
.message { margin-bottom: 15px; padding: 10px 14px; border-radius: 10px; max-width: 80%; white-space: pre-wrap; }
.user { background-color: #dcf8c6; align-self: flex-end; }
.assistant { background-color: #f1f0f0; align-self: flex-start; }
#input-form { display: flex; padding: 20px; border-top: 1px solid #ccc; }
input { flex: 1; padding: 10px; border: 1px solid #ccc; border-radius: 5px; }
button { padding: 10px 20px; margin-left: 10px; border: none; background-color: #007bff; color: white; border-radius: 5px; cursor: pointer; }
</style>
</head>
<body>
<div id="chat-container"></div>
<form id="input-form">
<input type="text" id="message-input" placeholder="Type your message..." autocomplete="off">
<button type="submit">Send</button>
</form>
<script>
const API_BASE_URL = 'http://localhost:8000';
const APP_NAME = 'ui_agent';
const chatContainer = document.getElementById('chat-container');
const inputForm = document.getElementById('input-form');
const messageInput = document.getElementById('message-input');
// Simple client-side IDs for this lab (use localStorage in production).
const userId = 'student-user';
const sessionId = `session-${Date.now()}`;
let sessionReady = null;
// Provided: `/run_sse` requires an existing session on the server.
// Uses ADK's non-deprecated `POST /apps/{app_name}/users/{user_id}/sessions` route.
function ensureSession() {
if (!sessionReady) {
sessionReady = fetch(`${API_BASE_URL}/apps/${APP_NAME}/users/${userId}/sessions`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ session_id: sessionId }),
}).then((res) => {
if (!res.ok) {
sessionReady = null;
throw new Error(`Session creation failed: ${res.status}`);
}
return res.json();
});
}
return sessionReady;
}
inputForm.addEventListener('submit', async (e) => {
e.preventDefault();
const query = messageInput.value.trim();
if (!query) return;
addMessage(query, 'user');
messageInput.value = '';
const assistantMessageDiv = addMessage('...', 'assistant');
try {
await ensureSession();
// TODO: 1. Send a POST request via `fetch` to `${API_BASE_URL}/run_sse`
// with `Content-Type: application/json` and a JSON body containing:
// - app_name: APP_NAME
// - user_id: userId
// - session_id: sessionId
// - streaming: true (REQUIRED so ADK streams tokens incrementally!)
// - new_message: { role: "user", parts: [{ text: query }] }
const response = ...;
if (!response.ok) {
throw new Error(`HTTP error ${response.status}`);
}
// TODO: 2. Obtain a stream reader (`response.body.getReader()`),
// a `new TextDecoder()`, and initialize state variables:
// `let buffer = '';`, `let fullResponse = '';`, and `let hasStreamedPartials = false;`
// TODO: 3. Write a `while (true)` loop calling `await reader.read()`:
// - Break when `done` is true.
// - Append `decoder.decode(value, { stream: true })` to `buffer`,
// split `buffer` on `'\n'`, and save the incomplete tail with `buffer = lines.pop()`.
// - For each line starting with `'data: '`, parse the JSON payload after `'data: '`.
// - Extract text from non-thought parts (`eventData.content?.parts`).
// - If `eventData.partial` is truthy: set `hasStreamedPartials = true` and append the text chunk to `fullResponse`.
// - Else (`!eventData.partial`, the final aggregated event): ONLY append the text if `!hasStreamedPartials`, then reset `hasStreamedPartials = false`.
// - Update `assistantMessageDiv.textContent = fullResponse` and scroll `chatContainer` to the bottom.
} catch (error) {
assistantMessageDiv.textContent = 'Error: Could not connect to the agent.';
console.error('Error:', error);
}
});
function addMessage(text, role) {
const messageDiv = document.createElement('div');
messageDiv.classList.add('message', role);
messageDiv.textContent = text;
chatContainer.appendChild(messageDiv);
chatContainer.scrollTop = chatContainer.scrollHeight;
return messageDiv;
}
</script>
</body>
</html>
Step 3: Run the Full-Stack Applicationโ
-
Terminal 1 โ Start the ADK API Server from the parent
adk-trainingdirectory:cd /path/to/your/adk-training
uv run adk api_server --allow_origins="*"adk api_serverstarts onhttp://127.0.0.1:8000by default and discoversui_agentinsideadk-training/.- Note on CORS: Because your frontend (
http://localhost:8081) and API server (http://localhost:8000) run on different ports, browsers enforce Cross-Origin Resource Sharing (CORS).--allow_origins="*"is convenient for local development; in production, always lock it down to your exact frontend origin (e.g.,--allow_origins=https://app.example.com).
-
Terminal 2 โ Serve the isolated
frontend/directory on port8081:cd /path/to/your/adk-training/frontend
python3 -m http.server 8081
Step 4: Test Your Custom UIโ
- Open the Client: Navigate to
http://localhost:8081in your browser. - Verify Live Streaming & Memory:
- Ask "Write a short 4-line poem about distributed systems." Watch tokens stream into the assistant bubble progressively, and verify the poem appears once (not duplicated when the stream closes!).
- Follow up with "Now translate the second line into French." Because
sessionIdis reused across turns, the agent remembers the poem from Turn 1.
Having Trouble?โ
If you get stuck, check lab-solution.md or unlock the Reference Solution Vault below.
Lab Summaryโ
You have built a full-stack custom chat UI backed by ADK's native FastAPI server:
- Served
ui_agentheadlessly from the parentadk-trainingworkspace viauv run adk api_server --allow_origins="*". - Isolated static frontend assets in
frontend/so.envcredentials are never exposed over HTTP. - Created sessions with the non-deprecated
POST /apps/ui_agent/users/{user_id}/sessionsendpoint and streamed incremental tokens via/run_ssewith"streaming": true, line buffering, andpartialdeduplication.
Self-Reflection Questionsโ
- The ADK server sends events using Server-Sent Events (SSE). What are the advantages of SSE for a chat application compared to a traditional request-response model?
- Our simple client generates a new
sessionIdevery time the page loads. What problems would this cause in a real application, and how would you solve it (e.g., using cookies orlocalStorage)? - This lab uses the native ADK API. What are the potential benefits of using a higher-level framework like the AG-UI Protocol and CopilotKit for a more complex, production-ready application?
๐ Reference Solution Vaultโ
Official Solution Vault โ Module 29
Locked Challenge โ Active Pedagogical Socratic Gate