<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by james mwai on Medium]]></title>
        <description><![CDATA[Stories by james mwai on Medium]]></description>
        <link>https://medium.com/@jmwai?source=rss-288731f633a0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*yhoOfe7aoZW4gF4m.jpeg</url>
            <title>Stories by james mwai on Medium</title>
            <link>https://medium.com/@jmwai?source=rss-288731f633a0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 07:58:23 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jmwai/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to add agentic functionality to an online store using ADK]]></title>
            <link>https://medium.com/@jmwai/how-to-add-agentic-functionality-to-an-online-store-using-adk-3a8f67c20203?source=rss-288731f633a0------2</link>
            <guid isPermaLink="false">https://medium.com/p/3a8f67c20203</guid>
            <dc:creator><![CDATA[james mwai]]></dc:creator>
            <pubDate>Mon, 22 Sep 2025 21:05:43 GMT</pubDate>
            <atom:updated>2025-09-25T13:39:00.447Z</atom:updated>
            <content:encoded><![CDATA[<p>This tutorial shows how you can add agentic behavior to an online store using Google’s Agent Development Kit (ADK). We used the Online Boutique which is an open source cloud-first microservices demo application available here (<a href="https://github.com/GoogleCloudPlatform/microservices-demo">https://github.com/GoogleCloudPlatform/microservices-demo</a>) and added a new agent-gateway microservice. The full agent-gateway code can be found here <a href="https://github.com/jmwai/gke-hackathon-microservices-demo">https://github.com/jmwai/gke-hackathon-microservices-demo</a></p><p>This project was part of the GKE Turns 10 Hackathon <a href="https://gketurns10.devpost.com/">https://gketurns10.devpost.com/</a></p><p>In this tutorial, you will learn how to setup an adk app using fastapi, compose agents with automatic delegation, wire tools for vector search and cart operations, persist short‑term state, and integrate the agents with an existing frontend.</p><ul><li>Repository roots used here:<a href="https://github.com/jmwai/gke-hackathon-microservices-demo">https://github.com/jmwai/gke-hackathon-microservices-demo</a></li><li>Agents Gateway: src/agents-gateway/</li><li>Frontend: src/frontend/</li><li>Product Catalog Service: src/productcatalogservice/</li></ul><h3>What you’ll build</h3><ul><li>Product Discovery agent (text/image search)</li><li>Shopping Assistant (root) that delegates to:</li><li>search_agent</li><li>cart_agent with add to cart, get cart, place order tools</li><li>Session/state handling using VertexAI agent engine</li><li>Adding RAG using AlloyDb to enable similarity and image search for product discovery</li></ul><h3>Tech Stack</h3><ul><li>Google Kubernetes Engine</li><li>Vertex AI</li><li>Agent Development Kit</li><li>FastAPI</li><li>AlloyDB</li></ul><h3>Architecture at a glance</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6PkLRW_-iguVabAukWcBcg.png" /></figure><p>ADK concepts we’ll use:</p><ul><li>Agent: an LLM policy with instructions and optional sub‑agents</li><li>Tool: a Python function (wrapped as FunctionTool) that the agent can call</li><li>Session/State: per‑user context across turns</li><li>Callbacks: hooks to mutate args/results and persist state</li><li>Auto‑delegation: a root agent can transfer control to sub‑agents</li></ul><h3>1) Quick start</h3><p>The original micro-services demo has instructions on how to run the system on a cluster or on GKE — <a href="https://github.com/GoogleCloudPlatform/microservices-demo/blob/main/docs/development-guide.md">https://github.com/GoogleCloudPlatform/microservices-demo/blob/main/docs/development-guide.md</a></p><p>Local run (Agents Gateway):</p><pre>python -m venv .venv &amp;&amp; source .venv/bin/activate<br>pip install -r src/agents-gateway/requirements.txt<br>uvicorn src.agents-gateway.app.main:app --reload --host 0.0.0.0 --port 8080</pre><p>Kubernetes deploy (excerpt):</p><pre>kubectl apply -f kubernetes-manifests/agents-gateway.yaml<br>kubectl rollout status deployment/agents-gateway</pre><p>Environment (examples):</p><pre>export PROJECT_ID=&quot;&lt;project&gt;&quot;<br>export REGION=&quot;&lt;region&gt;&quot;<br>export ALLOYDB_CLUSTER_NAME=&quot;alloybd-cluster&quot;<br>export ALLOYDB_INSTANCE_NAME=&quot;primary-instance&quot;<br>export ALLOYDB_DATABASE_NAME=&quot;postgres&quot;<br>export ALLOYDB_SECRET_NAME=&quot;alloydb-secret&quot;</pre><h3>2) Build the Agents Gateway</h3><p>Entry point: src/agents-gateway/app/main.py Adk comes with a fastapi helper that you can use to bootstrap and agent app</p><pre>from google.adk.cli.fast_api import get_fast_api_app<br>from google.adk.memory import VertexAiMemoryBankService<br>from google.adk.sessions import VertexAiSessionService<br><br>agent_engine = get_or_create_agent_engine(&quot;your-agent-engine-name)<br>agent_engine_id = agent_engine.resource_name<br><br>SESSION_SERVICE_URI = f&quot;agentengine://{agent_engine_id}&quot;<br>MEMORY_BANK_SERVICE_URI = f&quot;agentengine://{agent_engine_id}&quot;<br><br>AGENT_DIR = os.path.dirname(os.path.abspath(__file__))<br>ALLOWED_ORIGINS = [&quot;http://localhost&quot;, &quot;http://localhost:8080&quot;, &quot;*&quot;]<br>SERVE_WEB_INTERFACE = False<br><br>app: FastAPI = get_fast_api_app(<br>    agents_dir=AGENT_DIR,<br>    session_service_uri=SESSION_SERVICE_URI,<br>    memory_service_uri=MEMORY_BANK_SERVICE_URI,<br>    allow_origins=ALLOWED_ORIGINS,<br>    web=SERVE_WEB_INTERFACE,<br>    trace_to_cloud=True,<br>)<br></pre><p>Agents are discovered because every agent package exports a root_agent from agent.py.</p><h3>3) Product Discovery agent</h3><p>The discovery agent exposes text and image tools that query AlloyDB with pgvector. We clamp result counts and (optionally) cache text results in Redis.</p><p>File: src/agents-gateway/app/product_discovery_agent/tools.py (snippets)</p><pre>from google.adk.tools import FunctionTool<br><br>def text_vector_search(query: str, filters: dict, top_k: int) -&gt; list[dict]:<br>    # 1. Embed the incoming text and wrap it in pgvector literal syntax<br>    vec = _embed_text_1408(query)<br>    qvec = vector_literal(vec)<br><br>    # 2. Build WHERE clause and parameter list (category filter is optional)<br>    where = [&quot;product_embedding IS NOT NULL&quot;]<br>    params: List[Any] = [qvec]<br>    if isinstance(filters, dict):<br>        category = filters.get(&quot;category&quot;)<br>        if category:<br>            where.append(&quot;categories ILIKE %s&quot;)<br>            params.append(f&quot;%{category}%&quot;)<br><br>    # 3. Prepare the nearest-neighbor SQL query<br>    sql = f&quot;&quot;&quot;<br>        SELECT<br>            id,<br>            name,<br>            description,<br>            picture,<br>            COALESCE(product_image_url, picture) AS product_image_url,<br>            COALESCE((price_usd_units + (price_usd_nanos / 1e9))::float8, 0.0) AS price,<br>            (product_embedding &lt;=&gt; %s::vector) AS distance<br>        FROM catalog_items<br>        WHERE {&#39; AND &#39;.join(where)}<br>        ORDER BY distance ASC<br>        LIMIT %s<br>    &quot;&quot;&quot;<br>    params.append(top_k)<br><br>    # 4. Execute the query and shape the rows into dicts<br>    conn = get_conn()<br>    try:<br>        cur = conn.cursor()<br>        try:<br>            cur.execute(sql, params)<br>            results: List[Dict[str, Any]] = []<br>            for row in cur.fetchall():<br>                price_val = row[5]<br>                price = float(price_val) if isinstance(price_val, (Decimal, int, float)) else float(price_val or 0)<br>                results.append(<br>                    {<br>                        &quot;id&quot;: row[0],<br>                        &quot;name&quot;: row[1],<br>                        &quot;description&quot;: row[2],<br>                        &quot;picture&quot;: row[3],<br>                        &quot;product_image_url&quot;: row[4],<br>                        &quot;price&quot;: price,<br>                        &quot;distance&quot;: float(row[6]),<br>                    }<br>                )<br>            return results<br>        finally:<br>            cur.close()<br>    finally:<br>        put_conn(conn)<br>def image_vector_search(image_bytes: bytes, filters: dict, top_k: int) -&gt; list[dict]:<br>    # Embed image (1408‑d), run pgvector query, return rows<br>    ...<br>text_search_tool = FunctionTool(pd_text_search)<br>image_search_tool = FunctionTool(pd_image_search)</pre><h3>4) Shopping Assistant with auto‑delegation</h3><p>The shopping assistant is a root LLM agent that delegates to a search_agent and a cart_agent (cart ops + order placement).</p><p>File: src/agents-gateway/app/shopping_assistant_agent/agent.py (snippet)</p><pre>from google.adk.agents import LlmAgent<br>from .search_agent import search_agent<br>from .cart_agent import cart_agent<br><br>root_agent = LlmAgent(<br>    name=&quot;shopping_assistant_agent&quot;,<br>    description=&quot;Coordinator that delegates to search_agent and cart_agent&quot;,<br>    instruction=recommendation.INSTRUCTION,<br>    model=&quot;gemini-2.5-pro&quot;,<br>    sub_agents=[cart_agent, search_agent],<br>    before_model_callback=before_model_callback,<br>)</pre><p>The agent uses the instructions to make routing decisions. Here is sample root agent prompt</p><pre>INSTRUCTION = &quot;&quot;&quot;You are the root Shopping Assistant coordinating a team. Route requests to the right sub-agent and ensure outputs follow the schema.<br>You have specialized sub-agents:<br>1. search_agent: Finds and presents up to 5 numbered products for discovery queries (text/image). Delegate discovery to this agent.<br>2. cart_agent: Manages cart actions (&quot;add the Nth&quot;, &quot;add item&quot;, &quot;show cart&quot;, &quot;place order&quot;, &quot;checkout&quot;). Resolves ordinals from the latest results and performs add_to_cart + get_cart + place_order. Delegate cart operations and order placement to this agent.<br>Analyze the user&#39;s query. If the user asks to find/browse/recommend/filter products, delegate to search_agent. If the user asks to add items to cart, show cart, place orders, checkout, or references items by number (1 to 5), delegate to cart_agent.<br>For anything else, respond appropriately or state you cannot handle it.</pre><p>File: src/agents-gateway/app/shopping_assistant_agent/search_agent.py (snippet)</p><pre>from google.adk.agents import Agent<br>from .prompts import search as search_prompt<br>from .tools import text_search_tool, image_search_tool<br><br>search_agent = Agent(<br>    name=&quot;search_agent&quot;,<br>    description=&quot;Finds and presents up to 5 numbered products&quot;,<br>    instruction=search_prompt.INSTRUCTION,<br>    model=&quot;gemini-2.5-flash&quot;,<br>    tools=[text_search_tool, image_search_tool],<br>    output_schema=ShoppingAssistantOutput,<br>    output_key=&quot;shopping_recommendations&quot;,<br>    before_model_callback=before_model_callback,<br>    before_tool_callback=before_tool_callback,<br>    after_tool_callback=after_tool_callback,<br>)</pre><blockquote><strong><em>Here is the sample search agent instructions</em></strong></blockquote><blockquote><em>INSTRUCTION = “””You are the search_agent. Your sole task is to find products and present up to 5 results.</em></blockquote><blockquote><em>Rules:</em></blockquote><blockquote><em>- Use text_search_tool (or image_search_tool if the user provided an image) to find products.</em></blockquote><blockquote><em>- Return at most 5 items, numbered 1..5, each with a short one-line description and a brief summary.</em></blockquote><blockquote><em>- Encourage the user to refer to items by number for cart actions.</em></blockquote><blockquote><em>- Do not add items to cart. If the user asks to add, respond briefly that cart actions are handled by another agent.</em></blockquote><blockquote><em>Output schema:</em></blockquote><blockquote><em>- Use ShoppingAssistantOutput with action=”recommend”, recommendations=[…], recommendation_summary, summary.</em></blockquote><blockquote><em>Examples (structure only):</em></blockquote><blockquote><em>{</em></blockquote><blockquote><em>“shopping_recommendations”: {</em></blockquote><blockquote><em>“action”: “recommend”,</em></blockquote><blockquote><em>“summary”: “Found 5 trail running shoes.”,</em></blockquote><blockquote><em>“recommendations”: [ {“id”:”SHOEX…”,”name”:”…”,”description”:”…”,”picture”:”…”,”price”: 5.0, “distance”:0.12} ],</em></blockquote><blockquote><em>“recommendation_summary”: “Lightweight, good traction for rocky terrain.”</em></blockquote><blockquote><em>}</em></blockquote><blockquote><em>}</em></blockquote><h3>5) Tools for the shopping assistant</h3><p>We wrap search, cart, and order operations as tools. The assistant limits search results to 5.</p><p>File: src/agents-gateway/app/shopping_assistant_agent/tools.py (snippets)</p><pre>from google.adk.tools import FunctionTool<br>from google.adk.tools.tool_context import ToolContext<br><br>def text_search_tool(query: str, top_k: int, filters: dict):<br>    k = min(5, get_settings().API_TOP_K_MAX)<br>    return text_vector_search(query, filters or {}, k)<br>def image_search_tool(image_base64: str, mime_type: str, top_k: int, filters: dict):<br>    k = min(5, get_settings().API_TOP_K_MAX)<br>    return image_vector_search(base64.b64decode(image_base64), filters or {}, k)<br>def add_to_cart(number: int, tool_context: ToolContext) -&gt; dict:<br>    # Resolve user_id from context<br>    user_id = _extract_user_id(tool_context) or tool_context.state.get(&quot;user_id&quot;)<br>    # Resolve ordinal → product_id from last_results in state<br>    # POST /api/cart/add then GET /api/cart and return normalized cart<br>    ...<br>def get_cart(tool_context: ToolContext) -&gt; dict:<br>    # Use same user_id resolution; GET /api/cart and return enriched cart<br>    ...<br>def place_order(tool_context: ToolContext) -&gt; dict:<br>    # Pre‑check cart not empty; POST /api/checkout; return order meta<br>    ...<br>add_to_cart_tool = FunctionTool(add_to_cart)<br>get_cart_tool = FunctionTool(get_cart)<br>place_order_tool = FunctionTool(place_order)</pre><h3>6) State, sessions, and callbacks</h3><p>We keep short‑term search state so the user can say “add the second item.” The pattern is:</p><ol><li>After a search tool runs, store a compact shopping.last_results (first 5 only).</li><li>Before a new search, clear any stale last_results so results don’t accumulate.</li><li>Use a per‑user fallback store to bridge session re‑creation.</li></ol><p>File: src/agents-gateway/app/shopping_assistant_agent/state.py (snippet)</p><pre>LAST_RESULTS_KEY = &quot;last_results&quot;<br><br>def set_last_results(ctx, items: list[dict], query: str) -&gt; None:<br>    # Persist first 5 only<br>    state = _get_state_container(ctx)<br>    shopping = _ensure_root(state)<br>    shopping[LAST_RESULTS_KEY] = {<br>        &quot;items&quot;: items[:5],<br>        &quot;query&quot;: query,<br>        &quot;created_at&quot;: datetime.now(timezone.utc).isoformat(),<br>    }</pre><p>File: src/agents-gateway/app/shopping_assistant_agent/callbacks.py (snippets)</p><pre>def before_tool_callback(callback_context=None, tool=None, tool_args=None, **kwargs):<br>    # Clear old results when a new search starts<br>    if str(getattr(tool, &quot;name&quot;, tool)) in (&quot;text_search_tool&quot;, &quot;image_search_tool&quot;):<br>        st = getattr(callback_context, &quot;state&quot;, None)<br>        if isinstance(st, dict):<br>            shopping = st.get(&quot;shopping&quot;, {})<br>            shopping[&quot;last_results&quot;] = {&quot;items&quot;: [], &quot;query&quot;: &quot;&quot;, &quot;created_at&quot;: st.get(&quot;timestamp&quot;, &quot;&quot;)}<br>            st[&quot;shopping&quot;] = shopping<br><br>def after_tool_callback(callback_context=None, tool=None, tool_response=None, **kwargs):<br>    # Persist the compact last_results after search (first 5 only)<br>    items = tool_response if isinstance(tool_response, list) else []<br>    compact = [{&quot;id&quot;: p.get(&quot;id&quot;), &quot;name&quot;: p.get(&quot;name&quot;), &quot;brief&quot;: (p.get(&quot;description&quot;) or &#39;&#39;)[:80]} for p in items[:5]]<br>    set_last_results(callback_context, compact, query=&quot;&quot;)</pre><h3>7) Frontend integration</h3><p>Create a session and run the agent:</p><pre>#create a session<br>POST /apps/shopping_assistant_agent/users/&lt;user&gt;/sessions<br>Content-Type: application/json<br>{&quot;state&quot;: {&quot;user_id&quot;: &quot;&lt;user&gt;&quot;}}<br><br>#interact with the agent<br>POST /run<br>Content-Type: application/json<br><br>{<br>  &quot;appName&quot;: &quot;shopping_assistant_agent&quot;,<br>  &quot;userId&quot;: &quot;&lt;user&gt;&quot;,<br>  &quot;sessionId&quot;: &quot;&lt;same-session-id&gt;&quot;,<br>  &quot;newMessage&quot;: {&quot;role&quot;: &quot;user&quot;, &quot;parts&quot;: [{&quot;text&quot;: &quot;recommend running shoes&quot;}]},<br>  &quot;streaming&quot;: false<br>}</pre><p>API helpers (frontend excerpts):</p><pre>// Force database for product details/search consistency<br>func (fe *frontendServer) addDatabaseHeader(ctx context.Context) context.Context {<br>    return metadata.AppendToOutgoingContext(ctx, &quot;use-database&quot;, &quot;true&quot;)<br>}</pre><pre>// Enriched cart API (name, price, image, totals)<br>// GET /api/cart?userId=...</pre><p>Cart clear after successful checkout (frontend):</p><pre>// apiCheckout: after generating confirmation<br>_ = fe.emptyCart(r.Context(), req.UserId) // best-effort demo clear</pre><h3>Key source files</h3><ul><li>Agents Gateway: src/agents-gateway/app/main.py</li><li>Product Discovery: app/product_discovery_agent/tools.py</li><li>Shopping Assistant: app/shopping_assistant_agent/agent.py, search_agent.py, cart_agent.py, tools.py, callbacks.py, state.py</li><li>Frontend integration: src/frontend/handlers.go, src/frontend/rpc.go</li><li>Product Catalog selective routing: src/productcatalogservice/</li></ul><p><strong>Key Resources</strong></p><ul><li>Agent Development Kit <a href="https://google.github.io/adk-docs/">https://google.github.io/adk-docs/</a></li><li>Google Kubernetes Engine <a href="https://cloud.google.com/kubernetes-engine?hl=en">https://cloud.google.com/kubernetes-engine?hl=en</a></li><li>Vertex AI Agent Engine <a href="https://cloud.google.com/vertex-ai/generative-ai/docs/agent-engine/overview">https://cloud.google.com/vertex-ai/generative-ai/docs/agent-engine/overview</a></li><li>AlloyDB <a href="https://cloud.google.com/products/alloydb?hl=en">https://cloud.google.com/products/alloydb?hl=en</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a8f67c20203" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>