<?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 Henry Ruiz on Medium]]></title>
        <description><![CDATA[Stories by Henry Ruiz on Medium]]></description>
        <link>https://medium.com/@haruiz?source=rss-4a509f6a939e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*H-JRj9SU11WyWPlHpSO-3Q.jpeg</url>
            <title>Stories by Henry Ruiz on Medium</title>
            <link>https://medium.com/@haruiz?source=rss-4a509f6a939e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 20:56:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@haruiz/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[VisionOps Crew: A Multi-Agent Architecture for Computer Vision Operations Using Google ADK and the…]]></title>
            <link>https://medium.com/google-cloud/visionops-crew-a-multi-agent-architecture-for-computer-vision-operations-using-google-adk-and-the-595987fd96cc?source=rss-4a509f6a939e------2</link>
            <guid isPermaLink="false">https://medium.com/p/595987fd96cc</guid>
            <category><![CDATA[google-antigravity]]></category>
            <category><![CDATA[google-adk]]></category>
            <category><![CDATA[agents]]></category>
            <dc:creator><![CDATA[Henry Ruiz]]></dc:creator>
            <pubDate>Fri, 10 Jul 2026 00:00:30 GMT</pubDate>
            <atom:updated>2026-07-13T12:24:04.874Z</atom:updated>
            <content:encoded><![CDATA[<h3>VisionOps Crew: A Multi-Agent Architecture for Computer Vision Operations Using Google ADK and the Antigravity SDK</h3><p>Computer vision engineering remains a highly fragmented discipline. Building high-performing vision models often requires developers and practitioners to manually coordinate model and dataset discovery, local development environments, visual data inspection, notebook-based experimentation, hardware constraints, and implementation artifacts.</p><p><a href="https://github.com/OpenSciML/visionops_crew">visionops_crew</a> addresses this fragmented middle ground as a multi-agent assistant for practical computer vision workflows. It transforms open-ended objectives into actionable plans, identifies relevant models and datasets, evaluates visual data quality, assesses local hardware constraints, supports notebook-based prototyping, and produces implementation-ready artifacts.</p><p>Rather than requiring users to coordinate each tool and process independently, visionops_crew brings together a team of specialized agents within a unified multi-agent architecture built with the Google Agent Development Kit (ADK). The crew includes a task planner, computer vision researcher, data curator, ML engineer, web search capability, and an optional Antigravity SDK integration. Through Model Context Protocol (MCP) integrations and skill-based capabilities, these agents connect with specialized computer vision and AI tools-including Hugging Face, FiftyOne, and Jupyter-enabling research, data inspection, experimentation, and implementation to continuously inform one another throughout the computer vision lifecycle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WldmsJTaTq2o2ENhp3st1g.png" /></figure><h3>Introduction</h3><p>Building computer vision applications today requires coordinating a heterogeneous ecosystem, not simply training a model. A typical workflow spans model and dataset registries, local media storage, annotation schemas, visual inspection platforms, notebooks, accelerator-specific runtime constraints, and generated implementation artifacts. Each component maintains its own state, assumptions, and potential failure modes.</p><p>The most costly errors often emerge at the boundaries between these components. A dataset may load successfully while its semantic label field remains ambiguous. A model recommendation may be sound in principle yet incompatible with the available hardware. A notebook prototype may validate a preprocessing strategy without ever becoming part of a reusable training pipeline. These are not merely isolated coding mistakes; they are coordination failures across research, data, runtime, and implementation contexts.</p><p>visionops_crew is designed to close this gap. It is an orchestrated multi-agent assistant for computer vision operations, built with Google&#39;s Agent Development Kit (ADK), Model Context Protocol (MCP) integrations, skill-based capabilities, and a scoped Antigravity SDK integration for opt-in artifact generation. Its purpose is not to replace researchers, engineers, or practitioners, but to preserve task context while routing each step to the specialized agent or tool best equipped to gather evidence, inspect system state, conduct experimentation, or produce implementation-ready artifacts.</p><h3>What You Will Learn</h3><p>In this post, I examine the problem, architecture, and key implementation decisions behind visionops_crew. The discussion focuses on engineering patterns that researchers and technical practitioners can apply when building agentic systems for scientific and machine learning workflows:</p><ul><li><strong>Decomposing complex workflows into specialized agents</strong> with clearly defined responsibilities, tool boundaries, and failure modes that can be adapted across domains.</li><li><strong>Integrating the Antigravity SDK safely</strong> by placing it behind an explicit tool boundary controlled by the orchestrator.</li><li><strong>Extending agent capabilities through MCP and skills</strong> by providing structured access to external services, local tools, notebooks, and runtime environments-not only text generation and reasoning.</li><li><strong>Distributing reasoning while reducing context overhead</strong> by routing research, data inspection, runtime validation, and implementation decisions to the agents best suited to handle each part of the workflow.</li></ul><h3>Why Traditional Computer Vision Pipelines Break Down</h3><p>Computer vision projects are particularly vulnerable to coordination failures because their data, annotations, model architectures, and runtime environments are tightly interdependent. Unlike many text-based workflows, where tokenization and batching provide relatively consistent abstraction boundaries, visual machine learning workflows must account for:</p><ul><li><strong>Media representation:</strong> Raw images, videos, tiled rasters, frame sequences, and multispectral inputs require different loading strategies and preprocessing assumptions.</li><li><strong>Annotation semantics:</strong> Classification labels, bounding boxes, segmentation masks, keypoints, captions, and embeddings require distinct schemas, evaluation metrics, and validation procedures.</li><li><strong>Model-task alignment:</strong> A model tagged for image classification may still be unsuitable for a particular label space, visual domain, licensing requirement, or deployment target.</li><li><strong>Runtime constraints:</strong> CUDA, Apple Silicon MPS, CPU-only environments, numerical precision, and memory limitations directly affect model selection, feasible batch sizes, and implementation strategy.</li></ul><p>In a conventional workflow, practitioners must move manually between these contexts. They might browse Hugging Face to identify a suitable dataset or model backbone, download a subset locally, inspect its annotations in a visual exploration platform, write conversion code, prototype an approach in a notebook, and eventually translate those findings into a reusable training pipeline.</p><p>However, critical observations from one stage rarely propagate automatically to the next. A label imbalance discovered in FiftyOne may not be reflected in the training configuration. A hardware constraint identified in a terminal session may not influence model selection. A notebook visualization may never be linked to the specific dataset version that produced it. As a result, valuable context becomes fragmented across tools, increasing the risk of inconsistent assumptions and implementation errors.</p><p>The following diagram illustrates how this fragmentation appears across a typical computer vision lifecycle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fzuq6rSU_wELFrOLjFu6vw.png" /></figure><p>The underlying problem is context isolation. Researchers and practitioners may understand the relationships among the dataset schema, model family, and runtime constraints, but the individual tools involved do not share that context. <strong>visionops_crew</strong> addresses this gap by routing each stage through specialized agents while keeping the orchestrator responsible for preserving the task brief, consolidating evidence, tracking assumptions, and enforcing constraints across subsequent steps.</p><h3>System Design: The Multi-Agent Coordinator Architecture</h3><p>The application follows a hub-and-spoke architecture. At its center, the <strong>visionops_crew</strong> ADK application defines a root orchestrator that invokes specialized agents as tools. The orchestrator interprets objectives, routes tasks, preserves context, and synthesizes findings, while each specialist agent gathers evidence or performs actions within a clearly bounded domain.</p><p>This architecture is intentionally conservative. Giving a single monolithic agent access to every tool can blur responsibilities, allowing the same agent to search the web, modify local files, inspect datasets, and generate training code without clear boundaries between research, execution, and synthesis. In <strong>visionops_crew</strong>, tool access is partitioned according to each agent’s role. This separation makes prompts and behaviors easier to audit, reduces unintended tool use, and provides a clearer foundation for introducing confirmation gates around state-changing operations.</p><h3>Specialist Agents and Their Domains</h3><p>The assistant’s capabilities are distributed across specialized roles. Each role owns a bounded portion of the workflow and returns structured findings to the orchestrator:</p><p><strong>Vision Task Planner (</strong><strong>vision_task_planner):</strong> The planner translates broad requests into an operational task brief. It identifies the task type, expected annotation structure, missing constraints, appropriate evaluation metrics, execution risks, and recommended sequence of specialists. In research-oriented workflows, this establishes an explicit hypothesis about what must be observed and validated before implementation begins.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Fz3pQednoNa2YA-2.png" /></figure><p><strong>CV Research Agent (</strong><strong>cv_research):</strong> This specialist connects to the Hugging Face Hub through MCP. It retrieves relevant datasets, model cards, papers, Spaces, documentation, benchmark information, and licensing metadata. Its findings are treated as source-backed research evidence rather than local execution results.</p><p><strong>Data Curator Agent (</strong><strong>data_curator):</strong> This agent coordinates local, data-centric workflows. It can import Hugging Face datasets into FiftyOne, inspect dataset schemas, summarize label distributions, query samples, and launch the FiftyOne App for interactive visual inspection. Its purpose is to transform external dataset references into observable local evidence. Through direct tools and a local standard input/output (stdio) MCP session, it manages:</p><ul><li>load_huggingface_dataset: Downloads image or video samples from the Hugging Face Hub, materializes the assets on the local filesystem, and constructs structured FiftyOne datasets without requiring manually written import scripts.</li><li>open_fiftyone_dataset: Launches an interactive FiftyOne App session on a local port for visually inspecting annotations, identifying prediction errors, and exploring high-dimensional embeddings using UMAP or t-SNE projections.</li></ul><p><strong>ML Engineer (</strong><strong>ml_engineer):</strong> This agent owns implementation-oriented tasks, including hardware-aware training plans, code review, local file inspection, validation commands, and notebook-based prototyping. It loads two modular ADK skills: hardware-profiling for inspecting runtimes and accelerators, and jupyter-notebook for durable exploratory analysis. The notebook skill is backed by a Jupyter MCP gateway, enabling notebooks to be created, edited, executed, and inspected through structured tool calls rather than loosely coordinated shell commands.</p><p><strong>Google Search Agent (</strong><strong>google_search_agent):</strong> This agent provides up-to-date information from official documentation and other sources outside the Hugging Face ecosystem, including software releases, API changes, compatibility details, and implementation guidance.</p><p><strong>Antigravity Tool (</strong><strong>run_antigravity_agent):</strong> Antigravity is registered as an opt-in tool at the root orchestrator level. This placement is deliberate: it ensures that artifact generation, image creation, report drafting, and large implementation tasks remain explicit user decisions. The wrapper records artifact roots and tool results, denies file writes by default, and enables creation or editing policies only after receiving confirmation.</p><h3>Implementation Details: ADK and MCP Server Integration</h3><p>This architecture only works if the boundaries are concrete in code. visionops_crew implements those boundaries through ADK agent composition, MCP-backed tool registration, local runtime inspection, notebook skills, and explicit artifact controls.</p><h3>Orchestrator Setup</h3><p>The root orchestrator,visionops_orchestrator, is instantiated as a standard ADK Agent. The important design choice is that specialist agents are registered as callable tools via AgentTool. This keeps the user conversation anchored in one root agent while still allowing domain-specific prompts and toolsets behind each specialist.</p><pre>from google.adk.agents import Agent<br>from google.adk.apps.app import App<br>from google.adk.plugins import ReflectAndRetryToolPlugin<br>from google.adk.tools.agent_tool import AgentTool<br><br>from visionops_crew.agents.cv_research.agent import (<br>    root_agent as cv_research,<br>)<br>from visionops_crew.agents.data_curator.agent import (<br>    root_agent as data_curator,<br>)<br>from visionops_crew.agents.ml_engineer.agent import (<br>    root_agent as ml_engineer,<br>)<br>from visionops_crew.agents.vision_task_planner.agent import (<br>    root_agent as vision_task_planner,<br>)<br><br>search_agent = create_google_search_agent(<br>    model=os.getenv(<br>        &quot;GOOGLE_SEARCH_MODEL&quot;,<br>        os.getenv(&quot;VISIONOPS_ORCHESTRATOR_MODEL&quot;, DEFAULT_MODEL),<br>    )<br>)<br>root_agent = Agent(<br>    model=os.getenv(&quot;VISIONOPS_ORCHESTRATOR_MODEL&quot;, DEFAULT_MODEL),<br>    name=&quot;visionops_orchestrator&quot;,<br>    description=(<br>        &quot;A computer vision expert orchestrator that uses a planning specialist, &quot;<br>        &quot;Google Search, computer vision research, data curation, dataset &quot;<br>        &quot;operations, ML engineering support, and opt-in Antigravity super-agent &quot;<br>        &quot;support for robust CV workflows.&quot;<br>    ),<br>    instruction=VISIONOPS_CREW_ORCHESTRATOR_INSTRUCTION,<br>    tools=[<br>        run_antigravity_agent,<br>        AgentTool(agent=vision_task_planner),<br>        GoogleSearchAgentTool(agent=search_agent),<br>        AgentTool(agent=cv_research),<br>        AgentTool(agent=ml_engineer),<br>        AgentTool(agent=data_curator),<br>    ],<br>)</pre><h3>Integrating External Tools Such as Jupyter, FiftyOne, and Hugging Face through MCP and Skills</h3><p>After the orchestrator determines which specialist should act, the next question is how that agent interacts with the appropriate external system. visionops_crew addresses this through MCP toolsets and modular skills rather than embedding platform-specific behavior directly into the root agent. This keeps the integration boundaries explicit: tools are discovered through structured schemas, invoked through ADK, and scoped to the specialist responsible for that domain.</p><p>The Hugging Face integration uses a remote MCP gateway to support Hub-based research, including access to models, datasets, documentation, papers, and related metadata. The FiftyOne integration runs a local fiftyone-mcp subprocess over standard input/output (stdio), allowing the Data Curator to inspect datasets within the same Python environment as the ADK application. This separation gives each specialist access to the tools it needs while preventing unrelated agents from invoking capabilities outside their assigned responsibilities.</p><pre>from pathlib import Path<br>import sys<br>from google.adk.tools.mcp_tool.mcp_toolset import McpToolset<br>from google.adk.tools.mcp_tool.mcp_session_manager import (<br>    StdioConnectionParams,<br>    StdioServerParameters,<br>)<br><br>fiftyone_mcp_path = Path(sys.executable).with_name(&quot;fiftyone-mcp&quot;)<br><br>fiftyone_mcp_tools = McpToolset(<br>    connection_params=StdioConnectionParams(<br>        server_params=StdioServerParameters(<br>            command=str(fiftyone_mcp_path),<br>            env=dict(os.environ),<br>            cwd=str(Path(__file__).resolve().parent.parent),<br>        ),<br>        timeout=30.0,<br>    ),<br>)</pre><p>The McpToolset class queries the MCP server&#39;s tool schemas and registers the resulting operations inside the ADK agent&#39;s scope. In practice, this means the Data Curator can inspect local dataset state while the orchestrator remains focused on routing and synthesis, not on the details of FiftyOne&#39;s SDK calls.</p><h3>Local Hardware and Framework Auditing</h3><p>Once the relevant data and model context has been established, implementation recommendations must still align with the available runtime environment. Hardware and framework state is therefore treated as a first-class component of the workflow because it directly constrains feasible models, batch sizes, numerical precision, and training strategies. Any recommendation that overlooks memory capacity, accelerator compatibility, or installed framework versions remains incomplete.</p><p>The ml_engineer uses a modular ADK skill named hardware-profiling to inspect the platform available to the ADK runtime. Through the skill boundary, it invokes scripts/profiling_tools.py to collect information about the CPU, system memory, installed machine learning frameworks, framework versions, and available accelerator support. The agent uses this evidence to produce hardware-aware implementation guidance and select training parameters that are appropriate for the actual execution environment.</p><pre>def check_hardware_specification() -&gt; dict:<br>    &quot;&quot;&quot;Inspect local CPU, memory, and operating system platform details.&quot;&quot;&quot;<br>    info = {<br>        &quot;platform&quot;: {<br>            &quot;system&quot;: platform.system(),<br>            &quot;release&quot;: platform.release(),<br>            &quot;machine&quot;: platform.machine(),<br>            &quot;processor&quot;: platform.processor(),<br>            &quot;python&quot;: platform.python_version(),<br>            &quot;python_executable&quot;: os.sys.executable,<br>        },<br>        &quot;cpu&quot;: {&quot;logical_cores&quot;: os.cpu_count()},<br>        &quot;memory&quot;: {}<br>    }<br>    if platform.system() == &quot;Darwin&quot; and shutil.which(&quot;sysctl&quot;):<br>        memsize = subprocess.run([&quot;sysctl&quot;, &quot;-n&quot;, &quot;hw.memsize&quot;], capture_output=True, text=True).stdout.strip()<br>        if memsize.isdigit():<br>            info[&quot;memory&quot;][&quot;total_gb&quot;] = round(int(memsize) / (1024**3), 2)<br>    return info<br><br>def check_framework_availability() -&gt; dict:<br>    &quot;&quot;&quot;Inspect availability and versions of major ML and DL frameworks.&quot;&quot;&quot;<br>    # Dynamic checks for torch, jax, sklearn, tensorflow, transformers, timm, fiftyone...<br>    ...<br><br>def check_accelerator_availability() -&gt; dict:<br>    &quot;&quot;&quot;Inspect availability of hardware accelerators (CUDA/MPS/TPUs).&quot;&quot;&quot;<br>    # Checks nvidia-smi command and framework-specific device listings...<br>    ...</pre><p>This profiling does not attempt to characterize the user’s complete deployment environment. It only describes the runtime that the agent can directly observe. This distinction is important for researchers and practitioners who prototype locally but train or deploy on remote clusters. In such cases, the target hardware and runtime constraints must be provided explicitly in the task brief so that the resulting recommendations reflect the intended execution environment.</p><h3>Interactive Prototyping with Jupyter Notebooks</h3><p>After inspecting the runtime environment, the ML Engineer can use Jupyter notebooks to perform exploratory analysis and implementation checks without losing provenance. Rather than treating notebooks as temporary scratch space, visionops_crew manages them as structured, persistent, and auditable artifacts.</p><p>The ml_engineer accesses notebooks through the jupyter-notebook skill, backed by a standard input/output (stdio) MCP connection to jupyter-mcp-server@latest. This integration allows the agent to create, open, edit, execute, and inspect notebook cells through structured tool calls while preserving the complete notebook for subsequent review and reuse.</p><p>When beginning exploratory analysis or validating a training implementation, the agent can create or load a notebook-such as pytorch_image_classifier.ipynb -and add cells incrementally as the investigation progresses. The ADK wrapper configures the Jupyter MCP toolset over stdio as follows:</p><pre>from google.adk.tools.mcp_tool.mcp_toolset import McpToolset<br>from google.adk.tools.mcp_tool.mcp_session_manager import (<br>    StdioConnectionParams,<br>    StdioServerParameters,<br>)<br><br>jupyter_mcp_toolset = McpToolset(<br>    connection_params=StdioConnectionParams(<br>        server_params=StdioServerParameters(<br>            command=&quot;uvx&quot;,<br>            args=[&quot;jupyter-mcp-server@latest&quot;],<br>            env=dict(os.environ)<br>        ),<br>        timeout=30.0<br>    )<br>)</pre><p>Cell-level MCP tools-including insert_cell, edit_cell_source, execute_cell, and list_kernels -allow the agent to develop and validate prototypes incrementally. This is particularly valuable in research workflows because intermediate diagnostics, such as class-distribution histograms, sample grids, preprocessing checks, and training curves, remain directly associated with the code and execution context that produced them.</p><h3>Antigravity SDK as an Opt-In Orchestrator Tool</h3><p>The default workflow covers model and dataset research, local data inspection, runtime auditing, and notebook-based prototyping. Each activity follows a predictable route: model and dataset research remains assigned to the CV Research Agent, local dataset operations remain with the Data Curator, and notebook-based experimentation remains the responsibility of the ML Engineer.</p><p>The Antigravity SDK complements these specialist components as an opt-in tool exposed at the root orchestrator boundary. When explicitly requested by the user or selected by the orchestrator, Antigravity can inspect, validate, and oversee artifacts produced by other agents. It can also handle implementation-intensive tasks that benefit from more advanced, multi-step reasoning, such as generating image assets, drafting validation reports, inspecting project structures, improving code quality, and producing proposed notebooks or scripts.</p><p>Keeping Antigravity outside the standard routing path makes its use explicit and prevents it from bypassing the established responsibilities and tool boundaries of the specialist agents. It operates as a controlled extension of the architecture rather than as a default capability available throughout the system.</p><p>The Antigravity SDK integration is implemented in `src/visionops_crew/agents/visionops_orchestrator/tools.py. The tool first creates a local configuration using the workspace and artifact paths:</p><pre>from google.antigravity import LocalAgentConfig<br><br>return LocalAgentConfig(<br>   system_instructions=ANTIGRAVITY_EXPERT_INSTRUCTIONS,<br>   model=os.getenv(&quot;ANTIGRAVITY_MODEL&quot;, &quot;gemini-3.5-flash&quot;),<br>   workspaces=[str(paths[&quot;workspace&quot;])],<br>   api_key=os.getenv(&quot;GEMINI_API_KEY&quot;),<br>   save_dir=str(paths[&quot;sessions&quot;] / &quot;expert&quot;),<br>   app_data_dir=str(paths[&quot;app_data&quot;]),<br>   policies=_build_policies(<br>      allow_file_edits=allow_file_edits<br>   ),<br>   hooks=extra_hooks,<br>)</pre><p>The task is then executed asynchronously through run_antigravity_agent. The function validates the request, configures the workspace and artifact paths, starts the Antigravity agent, and sends the task using agent.chat(). It also tracks created or modified artifacts and returns them alongside the agent’s response and tool results.</p><p>Within the ADK application, this function applies strict execution policies. File creation and editing remain disabled unless the user confirms the specific write operation, and shell-command execution is blocked within the non-interactive tool path. Image generation is permitted, while created or modified artifacts are tracked only within explicitly configured artifact roots. These controls make Antigravity a governed extension of visionops_crew that operates within the system&#39;s established agent and too</p><pre>async def run_antigravity_agent(<br>        task: str,<br>        root_folder: str = &quot;&quot;,<br>        allow_file_edits: bool = False,<br>) -&gt; dict[str, Any]:<br>   &quot;&quot;&quot;Run Antigravity for an explicitly requested task.<br><br>   Args:<br>       task: Code, image, analysis, notebook, or artifact-generation request.<br>       root_folder: Absolute base folder for `.env`, `.antigravity/`, and<br>           `antigravity-workspace/`. If empty, `ANTIGRAVITY_ROOT_DIR` or the<br>           ADK process working directory is used.<br>       allow_file_edits: Whether to allow Antigravity create/edit file tools.<br>           Use only after the user confirms the exact file-writing action.<br><br>   Returns:<br>       Antigravity text output, resolved storage paths, detected artifacts, and<br>       captured tool results.<br><br>   Raises:<br>       ValueError: If `task` is blank.<br>       RuntimeError: If Antigravity configuration, connection, or execution<br>           fails.<br>   &quot;&quot;&quot;<br>   if not task.strip():<br>      raise ValueError(&quot;task is required.&quot;)<br><br>   try:<br>      paths = _configure_antigravity_paths(root_folder)<br>      artifact_hook = ArtifactTrackingHook()<br>      roots = _artifact_roots(paths=paths, include_workspace=allow_file_edits)<br>      before_files = _snapshot_files(roots)<br><br>      async with AntigravityAgent(<br>              _build_antigravity_config(<br>                 paths=paths,<br>                 allow_file_edits=allow_file_edits,<br>                 extra_hooks=[artifact_hook],<br>              )<br>      ) as agent:<br>         response = await agent.chat(task.strip())<br>         result = await response.text()<br><br>      after_files = _snapshot_files(roots)<br>      artifact_changes = _diff_snapshots(before_files, after_files)<br>      return {<br>         &quot;status&quot;: &quot;success&quot;,<br>         &quot;result&quot;: result,<br>         &quot;root_folder&quot;: str(paths[&quot;root&quot;]),<br>         &quot;workspace&quot;: str(paths[&quot;workspace&quot;]),<br>         &quot;artifact_root&quot;: str(paths[&quot;artifacts&quot;]),<br>         &quot;artifact_roots&quot;: [str(root) for root in roots],<br>         &quot;created_artifacts&quot;: artifact_changes[&quot;created&quot;],<br>         &quot;updated_artifacts&quot;: artifact_changes[&quot;updated&quot;],<br>         &quot;tool_results&quot;: artifact_hook.tool_results,<br>      }<br>   except AntigravityValidationError as exc:<br>      raise RuntimeError(<br>         &quot;Antigravity configuration is invalid. Check GEMINI_API_KEY, &quot;<br>         &quot;ANTIGRAVITY_MODEL, root_folder, and workspace settings.&quot;<br>      ) from exc<br>   except AntigravityConnectionError as exc:<br>      raise RuntimeError(<br>         &quot;Antigravity connection dropped. Retry the request or check the &quot;<br>         &quot;local network/session state.&quot;<br>      ) from exc<br>   except AntigravityExecutionError as exc:<br>      raise RuntimeError(f&quot;Antigravity execution failed: {exc}&quot;) from exc</pre><h3>End-to-End Walkthrough: An Audited Curation and Training Plan</h3><p>The architecture becomes most valuable when a request spans multiple systems. Consider a task that combines local dataset operations with hardware-aware implementation guidance:</p><blockquote><em>Load </em><em>Humayoun/SkinDisease into FiftyOne, inspect its label schema, and recommend a baseline image-classification training plan for my local hardware.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*atP-AKkcwADIpCzkvSAFjQ.png" /></figure><p>The workflow is intentionally sequential. The system first establishes the task, dataset, and runtime evidence, and then uses that evidence to produce implementation guidance:</p><ol><li><strong>Task framing:</strong> The orchestrator invokes vision_task_planner, which identifies the request as an image-classification task, records unresolved constraints, and recommends inspecting the dataset before generating training guidance.</li><li><strong>Data ingestion:</strong> The orchestrator delegates todata_curator, which uses the custom load_huggingface_dataset tool to retrieve a bounded sample from the Humayoun/SkinDisease repository. The agent materializes the media under the configured dataset directory, creates a persistent FiftyOne dataset, and can launch the FiftyOne App for interactive inspection.</li><li><strong>Schema inspection:</strong> Using FiftyOne MCP tools, the Data Curator performs local schema inspections and aggregation queries to identify the media field, semantic label field, class cardinality, label distribution, and any immediate missing-label or class-imbalance concerns before implementation begins.</li><li><strong>Hardware and framework audit:</strong> Once the dataset context has been established, the orchestrator invokes ml_engineer. The agent inspects the observable runtime and reports relevant platform, framework, and accelerator details, such as macOS, Apple Silicon, and PyTorch MPS support.</li><li><strong>Synthesis:</strong> The orchestrator combines the task brief, dataset evidence, and runtime observations into a coherent implementation plan. On Apple Silicon, for example, it can recommend a PyTorch transfer-learning baseline configured with device = &quot;mps&quot; rather than incorrectly assuming CUDA availability.</li></ol><h3>System Limitations and Safety Constraints</h3><p>Although the walkthrough demonstrates how the system preserves evidence across stages, the architecture still has important operational and scientific limitations:</p><ul><li><strong>Latency and cost:</strong> Delegating tasks across multiple agents increases token consumption and wall-clock latency. This architecture is most appropriate for requests that span several systems or require traceable evidence, rather than tasks that can be resolved through a single lookup.</li><li><strong>Local side effects:</strong> Dataset imports, notebook execution, file modifications, and command execution can alter local state. These operations should remain behind explicit confirmation boundaries and be recorded as part of the workflow.</li><li><strong>Runtime observability:</strong> Hardware profiling only describes the environment visible to the ADK runtime. It cannot infer the configuration of remote training or deployment infrastructure unless the user explicitly provides that information.</li><li><strong>Scientific validity:</strong> The system can organize evidence, identify potential issues, and propose baseline implementations, but it cannot guarantee dataset suitability, freedom from bias, adequate statistical power, clinical validity, or deployment readiness. These remain domain-specific research and validation responsibilities.</li><li><strong>Tool and schema drift:</strong> MCP servers, external APIs, model cards, and dataset schemas can evolve over time. Reproducible workflows should therefore record dataset versions, sample sizes, model revisions, tool configurations, and local package versions whenever results must be replicated or audited.</li></ul><h3>Where This Goes Next</h3><p>visionops_crew demonstrates a practical architectural pattern for agentic computer vision operations: centralize orchestration, constrain specialist tool access, preserve evidence across stages, and make local execution boundaries explicit. The system is not intended to replace experimental judgment. Instead, it provides a coordination layer that maintains context across model research, dataset inspection, runtime profiling, notebook prototyping, and artifact generation.</p><p>The next development priorities focus on reproducibility and evaluation: capturing structured provenance for dataset imports, preserving model and dataset revision metadata, integrating FiftyOne similarity search for anomaly discovery, and adding benchmark-specific evaluation templates. Integrating experiment-management platforms such as MLflow or Weights &amp; Biases would also enable structured tracking of configurations, metrics, artifacts, hardware metadata, and model versions across training runs. Together, these capabilities could support closed-loop training workflows in which the system compares experiments, diagnoses failures, and recommends subsequent runs based on recorded evidence without obscuring execution details or intermediate findings from the user.</p><p>If this direction is useful for your computer vision workflow, try the project on GitHub: <a href="https://github.com/OpenSciML/visionops_crew">OpenSciML/visionops_crew</a>. Issues, ideas, examples, dataset adapters, evaluation templates, and pull requests are welcome.</p><p><a href="https://github.com/OpenSciML/visionops_crew">GitHub - OpenSciML/visionops_crew</a></p><p><em>Originally published at </em><a href="https://haruiz.github.io/blog/visionops-crew-multi-agent-architecture-for-computer-vision-operations"><em>https://haruiz.github.io</em></a><em> on July 10, 2026.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=595987fd96cc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/google-cloud/visionops-crew-a-multi-agent-architecture-for-computer-vision-operations-using-google-adk-and-the-595987fd96cc">VisionOps Crew: A Multi-Agent Architecture for Computer Vision Operations Using Google ADK and the…</a> was originally published in <a href="https://medium.com/google-cloud">Google Cloud - Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Post-Training Gemma 3 for Earth Observation (EO) Understanding: A JAX Stack + TPU Pipeline for…]]></title>
            <link>https://medium.com/google-cloud/post-training-gemma-3-for-earth-observation-eo-understanding-a-jax-stack-tpu-pipeline-for-cc26da11e338?source=rss-4a509f6a939e------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc26da11e338</guid>
            <category><![CDATA[lora]]></category>
            <category><![CDATA[gemma]]></category>
            <category><![CDATA[tpu]]></category>
            <category><![CDATA[jax]]></category>
            <category><![CDATA[fine-tuning]]></category>
            <dc:creator><![CDATA[Henry Ruiz]]></dc:creator>
            <pubDate>Mon, 20 Apr 2026 17:12:30 GMT</pubDate>
            <atom:updated>2026-04-21T14:09:49.679Z</atom:updated>
            <content:encoded><![CDATA[<h3>Post-Training Gemma 3 for Earth Observation (EO) Understanding: A JAX Stack + TPU Pipeline for Multi-Label Sentinel Satellite Remote Sensing Scene Classification</h3><p>Earth observation has no shortage of data. What it still needs is broader, more practical adoption of scalable approaches to adapt modern multimodal models to geospatial tasks — without turning training into a months-long infrastructure project.</p><p>That was the motivation behind building GemmaEarth as part of the TPU Sprint.</p><p><a href="https://github.com/haruiz/gemma_earth">GitHub - haruiz/gemma_earth: The GemmaEarth project is a domain-focused Tunix post-training and benchmarking effort that fine-tunes Google&#39;s Gemma 3 4B IT model for Earth Observation (EO) understanding, beginning with satellite scene classification</a></p><p>GemmaEarth is a domain-focused post-training and benchmarking pipeline built with Tunix, designed to adapt Google’s Gemma 3 4B IT model for Earth Observation (EO) understanding using the <em>EarthDial: Turning Multi-sensory Earth Observations into Interactive Dialogues</em> (2025) dataset (<a href="https://arxiv.org/abs/2412.15190">https://arxiv.org/abs/2412.15190</a>). EarthDial provides a large-scale instruction-tuning dataset spanning diverse EO tasks, including classification, captioning, visual question answering (VQA), and reasoning.</p><p>While the long-term goal is to fine-tune the model across the full range of EarthDial tasks, TPU resource allocation constraints led this project to begin with a focused and practical use case: satellite remote-sensing scene classification. This initial stage leverages the BigEarthNet subset, a large-scale Sentinel benchmark for multi-label land-use and land-cover classification.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dwCUfIrnuqKne54T0QeJGQ.png" /><figcaption>EarthDial dataset</figcaption></figure><h3>Project Contributions</h3><p><em>GemmaEarth</em> provides a reproducible, end-to-end workflow for adapting Gemma 3 4B IT to Earth Observation tasks, with a primary focus on multi-label satellite scene classification. The pipeline is designed to be extensible to a broader set of EO tasks within the EarthDial dataset, leveraging a TPU-native JAX stack.</p><p>Rather than focusing on a single training run, the project emphasizes a reference workflow spanning data preparation, post-training, evaluation, and benchmarking.</p><p>The implementation leverages the full JAX ecosystem (<a href="https://jaxstack.ai/">https://jaxstack.ai/</a>):</p><ul><li><strong>Tunix</strong> orchestrates the PEFT-based training pipeline</li><li><strong>Grain</strong> enables scalable data processing</li><li><strong>Optax</strong> handles optimization and scheduling</li><li><strong>Orbax</strong> manages checkpointing</li><li><strong>Qwix</strong> injects LoRA adapters for efficient fine-tuning</li></ul><p>All experiments were executed on Google Cloud TPU <a href="https://tpu-visualizer.uc.r.appspot.com/">v5litepod-8</a>, with an emphasis on scalability and reproducibility.</p><p>Key contributions include:</p><ul><li>A <strong>reproducible JAX-based pipeline</strong> for end-to-end post-training and benchmarking</li><li><strong>Parameter-efficient adaptation</strong> of Gemma 3 using LoRA in a TPU-sharded setup</li><li><strong>Multimodal training support</strong> using image–text EO data</li><li><strong>TPU-native data and training pipelines</strong> for scalable experimentation</li><li>A <strong>practical evaluation framework</strong> with interpretable metrics for multi-label classification</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*mUBlz5KqSkvEcvHyMMstyg.png" /><figcaption>JAX AI stack</figcaption></figure><h3>The JAX Stack in Practice</h3><p><em>GemmaEarth</em> integrates multiple components from the JAX ecosystem into a cohesive, TPU-native training pipeline, structured across key layers: data processing, model adaptation, distributed training, optimization, and checkpointing.</p><h3>Data Loading and Preprocessing</h3><p>Efficient data handling is critical for TPU utilization. In <em>GemmaEarth</em>, Grain is used to construct a high-performance, composable input pipeline for multimodal data.</p><p>This pipeline handles shuffling, transformation, batching, and iteration, ensuring a steady stream of preprocessed data into the training loop.</p><p>Source: <a href="https://github.com/haruiz/gemma_earth/blob/5fd2e4c0b6cf3c65eac026bd5aecc136e81072b8/src/gemma_earth/dataset.py#L519">https://github.com/haruiz/gemma_earth/blob/5fd2e4c0b6cf3c65eac026bd5aecc136e81072b8/src/gemma_earth/dataset.py#L519</a></p><pre>def _build_train_pipeline(<br>        self,<br>        split: Any,<br>        image_processor: Any,<br>        tokenizer: tokenizer_lib.Tokenizer,<br>        num_epochs: int | None,<br>        split_name: str,<br>    ) -&gt; Any:<br>        &quot;&quot;&quot;Construct a shuffled, mapped, and batched Grain iterable pipeline.<br><br>        The pipeline applies the following operations in order: shuffle, map to<br>        training example, map to training input (tokenize + pad), batch, repeat,<br>        and convert to an iterable dataset.<br><br>        Args:<br>            split: HuggingFace Dataset split used as the Grain data source.<br>            image_processor: Tunix ImageProcessor forwarded to<br>                _to_training_example.<br>            tokenizer: Tunix tokenizer forwarded to _to_training_input.<br>            num_epochs: Number of times to repeat the dataset. Pass 1 (or<br>                None) for a single pass, typically used for validation.<br>            split_name: Human-readable label (&quot;train&quot; or &quot;validation&quot;)<br>                used in progress log messages.<br><br>        Returns:<br>            A Grain iterable dataset ready for use as train_ds or<br>            eval_ds in GemmaEarth.train.<br>        &quot;&quot;&quot;<br>        settings = self.settings<br>        logger.info(&quot;Building %s pipeline with %d rows...&quot;, split_name, len(split))<br>        return (<br>            grain.MapDataset.source(split)<br>            .shuffle(seed=settings.shuffle_seed)<br>            .map(lambda x: self._to_training_example(x, image_processor))<br>            .map(lambda x: self._to_training_input(x, tokenizer))<br>            .batch(settings.batch_size, drop_remainder=True)<br>            .repeat(num_epochs)<br>            .to_iter_dataset()<br>        )</pre><h3>Distributed Training (Tunix + Jax)</h3><p>In <em>GemmaEarth</em>, <strong>Tunix</strong> orchestrates the training loop, coordinating model updates, data flow, and optimization across the entire stack. It provides a unified interface for:</p><ul><li><strong>State-of-the-art TPU performance</strong> through JAX-native execution</li><li><strong>Supervised Fine-Tuning (SFT)</strong> for instruction-based adaptation</li><li><strong>Reinforcement Learning (RL)</strong> for policy optimization</li><li><strong>Agentic RL</strong>, enabling training loops where agents interact with dynamic environments</li></ul><p>Source: <a href="https://github.com/haruiz/gemma_earth/blob/5fd2e4c0b6cf3c65eac026bd5aecc136e81072b8/src/gemma_earth/trainers/base.py#L386">https://github.com/haruiz/gemma_earth/blob/5fd2e4c0b6cf3c65eac026bd5aecc136e81072b8/src/gemma_earth/trainers/base.py#L386</a></p><pre>def _build_trainer(<br>        self,<br>        lora_model: nnx.Module,<br>        optimizer: optax.GradientTransformation,<br>        max_steps: int,<br>        tokenizer: tokenizer_lib.Tokenizer,<br>    ) -&gt; peft_trainer.PeftTrainer:<br>        &quot;&quot;&quot;Build PeftTrainer (including training config) and attach input callback.<br><br>        Args:<br>            lora_model: LoRA-augmented model to optimize.<br>            optimizer: Optimizer instance used during training.<br>            max_steps: Maximum training steps used to shape training config.<br>            tokenizer: Tokenizer used when building model-input callback.<br><br>        Returns:<br>            Configured ``peft_trainer.PeftTrainer`` instance.<br>        &quot;&quot;&quot;<br>        settings = self.settings<br>        checkpointing_options = ocp.CheckpointManagerOptions(<br>            save_interval_steps=settings.save_interval_steps,<br>            max_to_keep=settings.max_to_keep,<br>        )<br>        metrics_logging_options = metrics_logger.MetricsLoggerOptions(<br>            log_dir=self._tensorboard_root(),<br>            flush_every_n_steps=20,<br>        )<br>        training_config = peft_trainer.TrainingConfig(<br>            eval_every_n_steps=settings.eval_every_n_steps,<br>            max_steps=max_steps,<br>            checkpoint_root_directory=self._checkpoint_root(),<br>            checkpointing_options=checkpointing_options,<br>            metrics_logging_options=metrics_logging_options,<br>        )<br>        trainer = peft_trainer.PeftTrainer(<br>            model=lora_model,<br>            optimizer=optimizer,<br>            training_config=training_config,<br>        )<br>        return trainer.with_gen_model_input_fn(self._gen_model_input_fn(tokenizer))</pre><p>On the other hand, <strong>JAX</strong> provides the low-level primitives that enable efficient and hardware-aware distributed training. In particular, this pipeline leverages the <strong>device mesh abstraction</strong>, which allows precise control over how computation is distributed across TPU cores.</p><p>This design enables <em>GemmaEarth</em> to scale from a small number of devices to large TPU configurations without changing the training logic.</p><p>Source: <a href="https://github.com/haruiz/gemma_earth/blob/5fd2e4c0b6cf3c65eac026bd5aecc136e81072b8/src/gemma_earth/trainers/base.py#L279">https://github.com/haruiz/gemma_earth/blob/5fd2e4c0b6cf3c65eac026bd5aecc136e81072b8/src/gemma_earth/trainers/base.py#L279</a></p><pre>def create_mesh(self) -&gt; jax.sharding.Mesh:<br>  num_devices = jax.local_device_count()<br>  logger.info(&quot;Detected %d local devices for JAX mesh creation.&quot;, num_devices)<br><br>  if num_devices &gt;= 8:<br>    return jax.make_mesh(<br>      (1, 4, 2),<br>      (&quot;data&quot;, &quot;fsdp&quot;, &quot;tp&quot;),<br>      axis_types=(jax.sharding.AxisType.Auto,) * 3,<br>    )<br><br>  if num_devices &gt;= 2:<br>    return jax.make_mesh(<br>      (num_devices, 1),<br>      (&quot;fsdp&quot;, &quot;tp&quot;),<br>      axis_types=(jax.sharding.AxisType.Auto,) * 2,<br>    )<br><br>  return jax.make_mesh(<br>    (1, 1),<br>    (&quot;fsdp&quot;, &quot;tp&quot;),<br>    axis_types=(jax.sharding.AxisType.Auto,) * 2,<br>  )</pre><h3>Model Adaptation (LoRA + Structured State)</h3><p>Model adaptation is handled through <strong>Qwix</strong> and <strong>Flax NNX</strong>, enabling parameter-efficient fine-tuning and structured state management.</p><ul><li><strong>Qwix</strong> injects LoRA adapters, enabling efficient adaptation without updating the full model</li><li><strong>Flax NNX + JAX</strong> manages model state and enforces sharding across the device mesh</li></ul><p>Result: a LoRA-augmented model with explicitly <strong>sharded state</strong>, ready for distributed TPU execution.</p><p>Source: <a href="https://github.com/haruiz/gemma_earth/blob/5fd2e4c0b6cf3c65eac026bd5aecc136e81072b8/src/gemma_earth/trainers/base.py#L328">https://github.com/haruiz/gemma_earth/blob/5fd2e4c0b6cf3c65eac026bd5aecc136e81072b8/src/gemma_earth/trainers/base.py#L328</a>v</p><pre>def build_lora_model(self, mesh: jax.sharding.Mesh) -&gt; nnx.Module:<br>  if self.base_model is None:<br>    raise RuntimeError(&quot;Base model was not initialized by load_base_model().&quot;)<br><br>  settings = self.settings<br>  lora_provider = qwix.LoraProvider(<br>    module_path=self.LORA_MODULE_PATH,<br>    rank=settings.lora_rank,<br>    alpha=settings.lora_alpha,<br>  )<br><br>  model_input = self.base_model.get_model_input()<br>  lora_model = qwix.apply_lora_to_model(self.base_model, lora_provider, **model_input)<br><br>  with mesh:<br>    state = nnx.state(lora_model)<br>    pspecs = nnx.get_partition_spec(state)<br>    sharded_state = jax.lax.with_sharding_constraint(state, pspecs)<br>    nnx.update(lora_model, sharded_state)<br><br>  return lora_model</pre><h3>Optimization</h3><p>Optimization is handled via Optax, a JAX-native gradient processing library.</p><p>The combination of warmup + cosine decay scheduling with AdamW ensures stable and efficient convergence during LoRA-based fine-tuning, particularly in large-scale TPU environments.</p><p>Source: <a href="https://github.com/haruiz/gemma_earth/blob/5fd2e4c0b6cf3c65eac026bd5aecc136e81072b8/src/gemma_earth/trainers/base.py#L361">https://github.com/haruiz/gemma_earth/blob/5fd2e4c0b6cf3c65eac026bd5aecc136e81072b8/src/gemma_earth/trainers/base.py#L361</a></p><pre>def _build_optimizer(self, max_steps: int) -&gt; optax.GradientTransformation:<br>  settings = self.settings<br>  warmup_steps = max(1, int(max_steps * settings.warmup_ratio))<br>  lr_schedule = optax.warmup_cosine_decay_schedule(<br>    init_value=0.0,<br>    peak_value=settings.learning_rate,<br>    warmup_steps=warmup_steps,<br>    decay_steps=max(1, max_steps),<br>    end_value=0.0,<br>  )<br><br>  return optax.adamw(<br>    learning_rate=lr_schedule,<br>    weight_decay=settings.weight_decay,<br>  )</pre><h3>Checkpointing and Experiment Management</h3><p>Checkpointing is managed using <strong>Orbax</strong>, which provides flexible and structured model persistence.</p><p>Orbax supports:</p><ul><li><strong>PyTree-based checkpoints</strong></li><li><strong>Partial restoration</strong>, allowing recovery even when model structures evolve</li></ul><p>This makes experimentation more robust and iterative.</p><p>Source: <a href="https://github.com/haruiz/gemma_earth/blob/5fd2e4c0b6cf3c65eac026bd5aecc136e81072b8/src/gemma_earth/trainers/base.py#L579">https://github.com/haruiz/gemma_earth/blob/5fd2e4c0b6cf3c65eac026bd5aecc136e81072b8/src/gemma_earth/trainers/base.py#L579</a></p><pre>manager = ocp.CheckpointManager(<br>  self._checkpoint_root(),<br>  item_handlers={&quot;model_params&quot;: ocp.PyTreeCheckpointHandler()},<br>)<br>try:<br>  resolved_step = step if step is not None else manager.latest_step()<br>  if resolved_step is None:<br>    raise RuntimeError(f&quot;No checkpoint found under {self._checkpoint_root()}&quot;)<br><br>  abstract_state = nnx.state(model)<br>  restore_args = ocp.checkpoint_utils.construct_restore_args(target=abstract_state)<br><br>  checkpoint = manager.restore(<br>    resolved_step,<br>    args=ocp.args.Composite(<br>      model_params=ocp.args.PyTreeRestore(<br>        item=abstract_state,<br>        restore_args=restore_args,<br>        partial_restore=True,<br>      )<br>    ),<br>  )<br><br>  nnx.update(model, checkpoint.model_params)<br>  return resolved_step<br>finally:<br>  manager.close()</pre><h3>Benchmark results (1.5k samples)</h3><p>After post-training, for the satellite scene classification task on a 1.5k-sample evaluation dataset, the fine-tuned model shows consistent and significant improvements over the baseline across all metrics, as illustrated in the figure below.</p><p>Performance gains are strongest in recall-oriented metrics, while improvements in F1 and Jaccard scores indicate better prediction quality and consistency.</p><p>The increase in macro_f1 confirms improvements across both frequent and less frequent classes, and higher exact match scores indicate better full-label-set predictions.</p><p>Training dynamics show stable convergence, with evaluation loss decreasing (~0.33 → ~0.22) and perplexity improving (~1.45 → ~1.25), without signs of overfitting. Performance plateaus around 25k–30k steps, suggesting convergence.</p><p>More detailed metrics and configurations are available in the GitHub repository.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lRPpUHL3VOoVyG9b9ha1xg.png" /></figure><h3>Future work</h3><p>The current implementation focuses on the classification subset of EarthDial (BigEarthNet). Future work will extend this pipeline to additional tasks, including captioning, VQA, and reasoning.</p><p>Given the modular design, adapting to these tasks primarily involves updating DATASET_RELATIVE_DIR and re-running the pipeline. Detailed instructions are available in the repository.</p><h3>Closing Thoughts</h3><p><em>GemmaEarth</em> demonstrates how the JAX ecosystem can be composed into a practical, production-oriented training stack for domain-specific multimodal models.</p><p>Beyond model performance, its key contribution is an extensible engineering blueprint — enabling the transition from experimentation to scalable, reproducible systems leveraging TPU acceleration.</p><p>Thanks for taking the time to explore <em>GemmaEarth</em>! If you found this useful, feel free to explore the repository, experiment with the pipeline, or share feedback — I’d love to see how others extend this work.</p><p>Happy building!!</p><h3>Acknowledgements</h3><p>Google Cloud credits for this project were provided through the <strong>#TPUSprint</strong></p><p>Although scripts are provided in the GitHub repository to provision GCP services — including TPU setup — you can refer to the official GCP documentation for more detailed guidance on creating and configuring a TPU VM:<br><a href="https://docs.cloud.google.com/tpu/docs/create-tpu-vm">https://docs.cloud.google.com/tpu/docs/create-tpu-vm</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc26da11e338" width="1" height="1" alt=""><hr><p><a href="https://medium.com/google-cloud/post-training-gemma-3-for-earth-observation-eo-understanding-a-jax-stack-tpu-pipeline-for-cc26da11e338">Post-Training Gemma 3 for Earth Observation (EO) Understanding: A JAX Stack + TPU Pipeline for…</a> was originally published in <a href="https://medium.com/google-cloud">Google Cloud - Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Single Agent to Production-Ready Multi Agent Architecture with ADK, MCP, A2A, and AG-UI]]></title>
            <link>https://medium.com/google-cloud/from-single-agent-to-production-ready-multi-agent-architecture-with-adk-mcp-a2a-and-ag-ui-1fe0c0378bef?source=rss-4a509f6a939e------2</link>
            <guid isPermaLink="false">https://medium.com/p/1fe0c0378bef</guid>
            <category><![CDATA[agent-development-kit]]></category>
            <category><![CDATA[multi-agent-systems]]></category>
            <category><![CDATA[ag-ui]]></category>
            <category><![CDATA[model-context-protocol]]></category>
            <category><![CDATA[agent-to-agent-protocol]]></category>
            <dc:creator><![CDATA[Henry Ruiz]]></dc:creator>
            <pubDate>Thu, 19 Feb 2026 21:39:20 GMT</pubDate>
            <atom:updated>2026-02-21T08:49:27.915Z</atom:updated>
            <content:encoded><![CDATA[<p>In the previous <a href="https://medium.com/google-cloud/building-interactive-agentic-applications-using-adk-and-ag-ui-protocol-3a49ae6d3dc9">post</a>, we built an end-to-end single-agent application using ADK and AG-UI. In this post, we evolve that design into a production-ready multi-agent architecture with three coordinated agents:</p><ul><li><strong>Weather Agent:</strong> retrieves and interprets real-time meteorological data.</li><li><strong>Maps Agent:</strong> performs geospatial reasoning, including location lookup, coordinate resolution, and map-aware contextual queries.</li><li><strong>Atlas Agent:</strong> supervises the workflow by delegating tasks to the right specialist, sequencing execution, and synthesizing results into a single, user-ready response.</li></ul><p>To power this collaboration, we leverage <strong>MCP (Model Context Protocol)</strong> to distribute tool-based function execution across agents and <strong>A2A (Agent-to-Agent Protocol)</strong> as a standardized inter-agent communication layer that ensures consistent, seamless coordination among peers. We further extend the <strong>AG-UI (Agent-User Interaction Protocol)</strong> integration introduced in the previous tutorial to support these capabilities end-to-end, enabling all three protocols to operate cohesively while preserving each agent’s ability to drive dynamic interface behavior through a unified interaction model. The following figure illustrates the overall architecture of this multi-agent system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/1*JjO4vaHDJ7xmrAXsworsww.png" /></figure><h4>Limitations of Single-Agent Architectures</h4><p>While single-agent architectures can effectively support many workflows, they encounter fundamental limitations as applications grow in complexity and scope. One of the most prominent challenges is context overload. As tasks become more interdependent and require longer, richer instruction sequences, the amount of information a single agent must process quickly exceeds what is practical or reliable. Recent studies (https://arxiv.org/abs/2307.03172, <a href="https://github.com/Arize-ai/LLMTest_NeedleInAHaystack)">https://github.com/Arize-ai/LLMTest_NeedleInAHaystack)</a> show that large language models often exhibit positional bias, placing disproportionate attention on the beginning and end of long prompts while overlooking information in the middle, where critical constraints and task dependencies are commonly specified. This limitation reduces reasoning consistency and degrades performance as task complexity increases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BYC3-MfvWlLAlBv6Zhm0xg.png" /><figcaption>Image taken from <a href="https://arize.com/blog-course/the-needle-in-a-haystack-test-evaluating-the-performance-of-llm-rag-systems/">https://arize.com/blog-course/the-needle-in-a-haystack-test-evaluating-the-performance-of-llm-rag-systems/</a></figcaption></figure><h4>Distributed Reasoning Through Multi-Agent Systems</h4><p>A multi-agent system helps address these shortcomings by distributing reasoning across specialized agents, each responsible for a well-defined subset of tasks. Rather than burdening a single agent with managing both the global application state and task handling logic, responsibilities are decomposed across agents with distinct roles, independent context windows, and dedicated toolsets. In doing so, multi-agent systems provide a principled design pattern for enforcing separation of concerns, where reasoning, decision-making, and tool interaction are explicitly isolated across agents rather than entangled within a monolithic control loop. This decomposition reduces cognitive load, improves reasoning reliability, and enables more scalable and maintainable system designs, particularly as task complexity and contextual requirements grow (https://arxiv.org/abs/2305.14325).</p><h4>When Multi-Agent Architectures Become Necessary</h4><p>These orchestration needs become especially pronounced in problem settings that exceed the limits of single-agent reasoning and are inherently multidisciplinary. In such scenarios, effective problem solving depends on integrating multiple forms of expertise, heterogeneous reasoning strategies, and specialized tools, each addressing a distinct aspect of the task. This makes coordinated interaction among specialized agents a core system requirement rather than an implementation choice.</p><p>Problems that motivate multi-agent architectures typically exhibit four defining characteristics: <strong><em>planning</em></strong>, where solutions require coordinated, multi-step reasoning with explicit dependency management; <strong><em>diverse expertise</em></strong>, where multiple forms of domain-specific reasoning must be applied in concert; <strong><em>extensive context</em></strong>, where relevant information spans large, heterogeneous inputs beyond the reliable capacity of a single agent; and<strong><em> adaptive solutions</em></strong>, where execution paths must evolve dynamically in response to intermediate results, partial failures, or changing constraints. (https://multiagentbook.com/).</p><p>Taken together, these properties make multi-agent systems a modular, interpretable, and scalable paradigm for building advanced AI applications. In the following sections, we demonstrate how to transition from a single-agent design to a coordinated multi-agent framework using ADK for agent definition, MCP for tool-based function calling, and A2A for structured agent-to-agent communication.</p><h4>Building the Multi-Agent System</h4><p>To evolve our application from a single-agent design into a fully collaborative system, we decompose the main agent’s reasoning into three coordinated specialist agents. The <strong><em>weather_agent</em></strong> is responsible for handling environmental and meteorological queries; the <strong><em>maps_agent</em></strong> focuses on geospatial reasoning and place-based information retrieval; and the <strong><em>atlas_agent</em></strong> integrates and synthesizes information across domains, enabling higher-level reasoning and informed decision-making through cross-agent coordination.</p><p><strong>Maps Agent</strong></p><p>The Maps Agent is responsible for all geospatial reasoning within the multi-agent architecture. It handles user queries related to location identification, geographic coordinate resolution, and the generation of contextual and semantic descriptions of places. To support these capabilities, we equip the agent with two MCP-integrated tools that combine the Google Maps API with the Gemini API, leveraging Google Maps grounding to (i) resolve precise geographic coordinates and (ii) generate semantically rich, map-aware descriptions of locations. This integration enables the agent to ground generative outputs in authoritative, up-to-date geospatial data while preserving semantic expressiveness.</p><p>The MCP server exposes the following tools to the Maps Agent:</p><ol><li><strong><em>get_place_location</em></strong></li></ol><p>Resolves the geographic coordinates (latitude and longitude) for a given place name using the Google Maps Geocoding API.</p><ul><li>The tool queries Google Maps directly.</li><li>If successful, it returns a structured JSON object containing the latitude and longitude.</li><li>If the place cannot be resolved, a descriptive error message is returned.</li></ul><p><strong><em>2. get_place_details</em></strong></p><p>Provides a semantically rich, Gemini-generated description of a place. —</p><ul><li>First, the get_place_location tool is invoked to obtain the location coordinates.</li><li>It then passes the user’s prompt and the resolved coordinates to the Gemini model, with Google Maps enabled, allowing Gemini to retrieve place-specific context, points of interest, and localized descriptions. —</li><li>The result is a high-level narrative or analytic summary generated by Gemini, grounded in the Maps tool’s retrieved information.</li></ul><p>Internally, these tools work together to bridge two modalities: Google Maps supplies precise geospatial data. Gemini interprets that data and produces natural-language, context-aware responses.</p><p>Here is the implementation of the maps agent and MCP server:</p><pre>git clone https://github.com/haruiz/atlas_app # clone repo <br>cd ./atlas_app # jump into the code folder <br>git checkout single_agent # switch to the single_agent branch <br>mkdir -p mcp/maps_server # create folder <br>touch mcp/maps_server/{server.py,tools.py,__init__.py} # create python files</pre><p><strong><em>mcp/maps_server/tools.py</em></strong></p><pre>import os<br>from typing import Any, Dict, Union<br><br>import googlemaps<br>from dotenv import load_dotenv, find_dotenv<br>from google import genai<br>from google.genai import types<br><br># Load environment variables<br>load_dotenv(find_dotenv())<br><br>gmaps_client = googlemaps.Client(key=os.getenv(&quot;GOOGLE_MAPS_API_KEY&quot;))<br>genai_client = genai.Client(http_options=types.HttpOptions(api_version=&quot;v1&quot;))<br><br><br># ---------------------------------------------------------------------------<br># Utility: Get Geolocation<br># ---------------------------------------------------------------------------<br>def get_place_location(place_name: str) -&gt; Dict[str, Union[str, Dict[str, float]]]:<br>    &quot;&quot;&quot;<br>    Get geographic coordinates from Google Maps API given a place name.<br>    &quot;&quot;&quot;<br>    try:<br>        geocode_result = gmaps_client.geocode(place_name)<br>        if not geocode_result:<br>            return {<br>                &quot;status&quot;: &quot;error&quot;,<br>                &quot;message&quot;: f&quot;Could not find coordinates for: {place_name}&quot;<br>            }<br>        location = geocode_result[0][&quot;geometry&quot;][&quot;location&quot;]<br>        return {<br>            &quot;status&quot;: &quot;success&quot;,<br>            &quot;result&quot;: {&quot;latitude&quot;: location[&quot;lat&quot;], &quot;longitude&quot;: location[&quot;lng&quot;]}<br>        }<br><br>    except Exception as e:<br>        return {&quot;status&quot;: &quot;error&quot;, &quot;message&quot;: str(e)}<br><br><br># ---------------------------------------------------------------------------<br># Utility: Get Place Details using Gemini + Maps Tool<br># ---------------------------------------------------------------------------<br>def get_place_details(place_name: str, query_prompt: str) -&gt; Dict[str, str]:<br>    &quot;&quot;&quot;<br>    Get place details using Gemini’s Google Maps Tool.<br>    &quot;&quot;&quot;<br>    try:<br>        # Get coordinates first<br>        location_result = get_place_location(place_name)<br><br>        if location_result[&quot;status&quot;] == &quot;error&quot;:<br>            raise Exception(location_result[&quot;message&quot;])<br><br>        coords = location_result[&quot;result&quot;]<br>        latitude = coords[&quot;latitude&quot;]<br>        longitude = coords[&quot;longitude&quot;]<br><br>        # Call Gemini with Maps tool<br>        response = genai_client.models.generate_content(<br>            model=&quot;gemini-2.5-flash&quot;,<br>            contents=query_prompt,<br>            config=types.GenerateContentConfig(<br>                tools=[<br>                    types.Tool(<br>                        google_maps=types.GoogleMaps(enable_widget=False)<br>                    )<br>                ],<br>                tool_config=types.ToolConfig(<br>                    retrieval_config=types.RetrievalConfig(<br>                        lat_lng=types.LatLng(<br>                            latitude=latitude,<br>                            longitude=longitude,<br>                        ),<br>                        language_code=&quot;en_US&quot;,<br>                    )<br>                ),<br>            ),<br>        )<br><br>        return {<br>            &quot;status&quot;: &quot;success&quot;,<br>            &quot;result&quot;: response.text<br>        }<br><br>    except Exception as e:<br>        return {<br>            &quot;status&quot;: &quot;error&quot;,<br>            &quot;message&quot;: f&quot;Failed to get place details: {str(e)}&quot;<br>        }</pre><p><strong><em>mcp/maps_server/server.py</em></strong></p><pre>from typing import Any<br><br>from mcp.server.fastmcp import FastMCP<br><br>from tools import get_place_location, get_place_details<br><br># Create an MCP server<br>mcp = FastMCP(&quot;geoloc_server&quot;, port=8080)<br><br>@mcp.tool(name=&quot;get_place_location&quot;, description=&quot;Get coordinates from an address using Google Maps API.&quot;)<br>async def get_place_location_tool(place_name: str) -&gt; dict[str, Any]:<br>    &quot;&quot;&quot;<br>    Get coordinates from an address using Google Maps API.<br>    :param place_name:<br>    :return:<br>    &quot;&quot;&quot;<br>    return get_place_location(place_name)<br><br>@mcp.tool(name=&quot;get_place_details&quot;, description=&quot;Get place details using Google Maps Tool in Gemini.&quot;)<br>async def get_place_details_tool(place_name: str, query_prompt: str) -&gt; dict[str, Any]:<br>    &quot;&quot;&quot;<br>    Get place details using Google Maps Tool in Gemini.<br>    :param query_prompt: User query prompt for place details<br>    :param  place_name: Name of the place to get details for<br>    :return:<br>    &quot;&quot;&quot;<br>    return get_place_details(place_name, query_prompt)<br><br><br>if __name__ == &quot;__main__&quot;:<br>    mcp.run(transport=&quot;streamable-http&quot;)</pre><p><strong>Weather Agent</strong></p><p>The Weather Agent is responsible for handling all user requests related to real-time atmospheric conditions and environmental insights. It provides structured meteorological information — such as temperature, humidity, wind speed, apparent temperature, and qualitative weather conditions — based on geospatial coordinates. To support these capabilities, the agent leverages MCP-accessible tools backed by the Open‑Meteo API for authoritative weather data retrieval and the Gemini API for reasoning, interpretation, and contextual synthesis. This combination enables the Weather Agent to deliver accurate, location-aware environmental insights while maintaining coherent, user-friendly responses.</p><p>The MCP server exposes the following tool to the Weather Agent:</p><ol><li><strong><em>get_weather</em></strong></li></ol><p>Retrieves current weather conditions for a specific latitude and longitude by querying the Open-Meteo API. The tool processes raw atmospheric measurements (temperature, humidity, wind speed, gust levels, and weather code) and maps weather codes to human-readable conditions using a predefined lookup table. The output is returned as a structured JSON object containing both the raw values and their semantic interpretation.</p><p>Internally, the tool workflow includes:</p><ul><li>Fetching meteorological variables via an asynchronous HTTP request.</li><li>Translating numerical weather codes into descriptive categories (e.g., Clear sky, Moderate rain, Fog).</li><li>Packaging the processed data into a standardized result format compatible with MCP.</li></ul><p>Below is the code for the weather agent and MCP server.</p><pre>mkdir -p mcp/weather_server # create folder <br>touch mcp/weather_server/{server.py,tools.py,__init__.py} # create python files</pre><p><strong><em>mcp/weather_server/tools.py</em></strong></p><pre>import httpx<br>from typing import Dict, Any, Optional<br><br><br># ---------------------------------------------------------------------------<br># Weather Code Mapping (constant)<br># ---------------------------------------------------------------------------<br>WEATHER_CODE_MAP: Dict[int, str] = {<br>    0: &quot;Clear sky&quot;,<br>    1: &quot;Mainly clear&quot;,<br>    2: &quot;Partly cloudy&quot;,<br>    3: &quot;Overcast&quot;,<br>    45: &quot;Fog&quot;,<br>    48: &quot;Depositing rime fog&quot;,<br>    51: &quot;Light drizzle&quot;,<br>    53: &quot;Moderate drizzle&quot;,<br>    55: &quot;Dense drizzle&quot;,<br>    61: &quot;Light rain&quot;,<br>    63: &quot;Moderate rain&quot;,<br>    65: &quot;Heavy rain&quot;,<br>    71: &quot;Light snow&quot;,<br>    73: &quot;Moderate snow&quot;,<br>    75: &quot;Heavy snow&quot;,<br>    80: &quot;Rain showers&quot;,<br>    95: &quot;Thunderstorm&quot;,<br>    99: &quot;Thunderstorm with hail&quot;,<br>}<br><br><br>def get_weather_condition(code: Optional[int]) -&gt; str:<br>    &quot;&quot;&quot;<br>    Convert a weather code into a human-readable description.<br><br>    Args:<br>        code: Weather condition code.<br><br>    Returns:<br>        A descriptive string representing the weather condition.<br>    &quot;&quot;&quot;<br>    return WEATHER_CODE_MAP.get(code, &quot;Unknown&quot;)<br><br><br># ---------------------------------------------------------------------------<br># Weather Fetching<br># ---------------------------------------------------------------------------<br>async def get_weather(latitude: float, longitude: float) -&gt; Dict[str, Any]:<br>    &quot;&quot;&quot;<br>    Fetch current weather conditions for a given latitude and longitude.<br><br>    Args:<br>        latitude: Latitude coordinate.<br>        longitude: Longitude coordinate.<br><br>    Returns:<br>        A dictionary containing:<br>            - status: &quot;success&quot; or &quot;error&quot;<br>            - result: weather fields (if success)<br>            - message: error message (if error)<br>    &quot;&quot;&quot;<br>    url = (<br>        &quot;https://api.open-meteo.com/v1/forecast?&quot;<br>        f&quot;latitude={latitude}&amp;longitude={longitude}&quot;<br>        &quot;&amp;current=temperature_2m,apparent_temperature,relative_humidity_2m,&quot;<br>        &quot;wind_speed_10m,wind_gusts_10m,weather_code&quot;<br>    )<br><br>    try:<br>        async with httpx.AsyncClient(timeout=10.0) as client:<br>            response = await client.get(url)<br>            response.raise_for_status()<br><br>            data = response.json()<br>            current = data.get(&quot;current&quot;)<br><br>            if not current:<br>                return {&quot;status&quot;: &quot;error&quot;, &quot;message&quot;: &quot;Weather API returned no &#39;current&#39; data.&quot;}<br><br>            result = {<br>                &quot;temperature&quot;: current.get(&quot;temperature_2m&quot;),<br>                &quot;feelsLike&quot;: current.get(&quot;apparent_temperature&quot;),<br>                &quot;humidity&quot;: current.get(&quot;relative_humidity_2m&quot;),<br>                &quot;windSpeed&quot;: current.get(&quot;wind_speed_10m&quot;),<br>                &quot;windGust&quot;: current.get(&quot;wind_gusts_10m&quot;),<br>                &quot;conditions&quot;: get_weather_condition(current.get(&quot;weather_code&quot;)),<br>            }<br><br>            return {&quot;status&quot;: &quot;success&quot;, &quot;result&quot;: result}<br><br>    except httpx.HTTPError as e:<br>        return {&quot;status&quot;: &quot;error&quot;, &quot;message&quot;: f&quot;HTTP error: {str(e)}&quot;}<br><br>    except Exception as e:<br>        return {&quot;status&quot;: &quot;error&quot;, &quot;message&quot;: str(e)}<br><br><br># ---------------------------------------------------------------------------<br># Example Execution<br># ---------------------------------------------------------------------------<br>if __name__ == &quot;__main__&quot;:<br>    import asyncio<br><br>    # Example: New York City coordinates<br>    nyc_lat, nyc_lon = 40.7128, -74.0060<br><br>    weather = asyncio.run(get_weather(nyc_lat, nyc_lon))<br>    print(&quot;Weather:&quot;, weather)</pre><p><strong><em>mcp/weather_server/server.py</em></strong></p><pre>from typing import Any<br><br>from mcp.server.fastmcp import FastMCP<br><br>from tools import get_weather<br><br># Create an MCP server<br>mcp = FastMCP(&quot;weather_server&quot;, port=8081, json_response=True)<br><br>@mcp.tool(name=&quot;get_weather&quot;, description=&quot;Get weather information for a given location.&quot;)<br>async def get_weather_tool(latitude: float, longitude: float) -&gt; dict:<br>    &quot;&quot;&quot;<br>    Get the weather for a given location.<br>    :param latitude: Latitude of the location.<br>    :param longitude: Longitude of the location.<br>    :return:<br>    &quot;&quot;&quot;<br>    return await get_weather(latitude, longitude)<br><br><br>if __name__ == &quot;__main__&quot;:<br>    mcp.run(transport=&quot;streamable-http&quot;)<br></pre><p>The instructions defining the behavior of both the maps and weather agents are available in the GitHub repository accompanying this blog post, in the multiple_agent branch.</p><p><a href="https://github.com/haruiz/atlas_app/tree/multiple_agent">GitHub - haruiz/atlas_app at multiple_agent</a></p><p><strong>Atlas Agent</strong></p><p>In the single-agent example, the Atlas Agent was responsible for managing all reasoning and decision-making within a single control loop. In this tutorial, however, the Atlas Agent transitions into a pure orchestration role, delegating domain-specific reasoning to specialized agents and focusing on coordination rather than execution. This section highlights the key changes required to evolve the Atlas Agent from a monolithic reasoning component into a multi-agent orchestrator.</p><p>Implemented using ADK(Agent Development Kit), the Atlas Agent supports A2A-based task delegation, optional debugging callbacks, and memory preloading. Its instruction set defines the end-to-end execution flow, including location resolution, weather data requests, sequencing of agent and tool calls, and the integration of multi-agent outputs into clear, user-friendly summaries.</p><p>Next, we implement this orchestration logic in code.</p><pre>pycharm ./agents/atlas_agent/agent.py</pre><p><strong><em>agents/atlas_agent/agent.py</em></strong></p><pre>from typing import Optional, Dict, Any<br><br>from a2a.utils import AGENT_CARD_WELL_KNOWN_PATH<br>from google.adk.agents.callback_context import CallbackContext<br>from google.adk.agents.llm_agent import Agent<br>from google.adk.agents.remote_a2a_agent import RemoteA2aAgent<br>from google.adk.models import LlmRequest, LlmResponse<br>from google.adk.tools import BaseTool, ToolContext, AgentTool<br>from google.adk.tools.preload_memory_tool import PreloadMemoryTool<br>from dotenv import load_dotenv, find_dotenv<br><br># Load environment variables<br>load_dotenv(find_dotenv())<br><br><br># ======================================================================<br># CALLBACKS<br># ======================================================================<br><br>def before_model(<br>    callback_context: CallbackContext,<br>    llm_request: LlmRequest,<br>) -&gt; Optional[LlmResponse]:<br>    &quot;&quot;&quot;<br>    Executes before the model handles a request.<br>    Allows inspection of inputs, debugging, or intercepting execution.<br><br>    Return:<br>        - LlmResponse to skip model execution<br>        - None to allow normal execution<br>    &quot;&quot;&quot;<br>    agent_name = callback_context.agent_name<br>    print(f&quot;[Orchestrator Callback] before_model for agent: {agent_name}&quot;)<br><br>    last_user_message = &quot;&quot;<br>    if llm_request.contents and llm_request.contents[-1].role == &quot;user&quot;:<br>        parts = llm_request.contents[-1].parts<br>        if parts:<br>            last_user_message = parts[0].text<br><br>    print(f&quot;[Orchestrator Callback] User message: {last_user_message}&quot;)<br><br>    print(&quot;[Orchestrator Callback] Tools available to model:&quot;)<br>    for tool in llm_request.config.tools or []:<br>        print(f&quot;  - {tool.name}&quot;)<br><br>    return None<br><br><br>def before_tool(<br>    tool: BaseTool, args: Dict[str, Any], tool_context: ToolContext<br>) -&gt; Optional[Dict]:<br>    &quot;&quot;&quot;<br>    Executes before any tool call.<br>    Allows modification of arguments or skipping execution.<br>    &quot;&quot;&quot;<br>    print(<br>        f&quot;[Orchestrator Callback] before_tool: &#39;{tool.name}&#39; &quot;<br>        f&quot;(agent: {tool_context.agent_name})&quot;<br>    )<br>    print(f&quot;[Orchestrator Callback] Tool arguments: {args}&quot;)<br>    return None<br><br><br># ======================================================================<br># REMOTE AGENTS (enable when servers are available to test a2a locally)<br># ======================================================================<br># maps_agent = RemoteA2aAgent(<br>#     name=&quot;maps_agent&quot;,<br>#     description=&quot;Provides geocoding, place lookup, and mapping utilities.&quot;,<br>#     agent_card=f&quot;http://127.0.0.1:8001{AGENT_CARD_WELL_KNOWN_PATH}&quot;,<br># )<br>#<br># weather_agent = RemoteA2aAgent(<br>#     name=&quot;weather_agent&quot;,<br>#     description=&quot;Retrieves real-time weather conditions for a given coordinate.&quot;,<br>#     agent_card=f&quot;http://127.0.0.1:8002{AGENT_CARD_WELL_KNOWN_PATH}&quot;,<br># )<br><br><br># ======================================================================<br># ORCHESTRATOR AGENT<br># ======================================================================<br><br>root_agent = Agent(<br>    name=&quot;atlas_agent&quot;,<br>    model=&quot;gemini-2.5-pro&quot;,<br><br>    # Uncomment for debugging<br>    # before_tool_callback=before_tool,<br>    # before_model_callback=before_model,<br><br>    tools=[<br>        PreloadMemoryTool(),<br><br>        # When remote agents are active:<br>        # AgentTool(agent=maps_agent),<br>        # AgentTool(agent=weather_agent),<br>    ],<br><br>    instruction=&quot;&quot;&quot;<br>    You are the Orchestrator Agent. Your role is to coordinate two specialized agents:<br>    <br>    - maps_agent: Resolves place names, coordinates, and map-related queries.<br>    - weather_agent: Retrieves weather information using geographic coordinates.<br>    <br>    Your responsibility is to determine when each agent should be called, how their outputs should be used, and how to produce a final integrated response for the user.<br>    <br>    ----------------------------------------------------------------------<br>    Workflow for Weather Queries<br>    ----------------------------------------------------------------------<br>    <br>    When the user requests weather information for a location:<br>    <br>    1. Call maps_agent  <br>       Input: the place name or location text.  <br>       Output: latitude and longitude.<br>    <br>    2. Call weather_agent  <br>       Input: coordinates returned by maps_agent.  <br>       Output: structured weather information.<br>    <br>    3. Combine both results into a clear, user-facing response.<br>    <br>    ----------------------------------------------------------------------<br>    Workflow for Location or Mapping Queries<br>    ----------------------------------------------------------------------<br>    <br>    If the user asks only for location information, directions, or coordinates:<br>    <br>    1. Call maps_agent directly.  <br>    2. Return the result to the user.<br>    <br>    ----------------------------------------------------------------------<br>    Execution Rules<br>    ----------------------------------------------------------------------<br>    <br>    - Execute agent calls in sequential order.  <br>    - Do not call multiple agents at the same time.  <br>    - Always wait for the response of the previous agent before making a new call.  <br>    - Pass intermediate outputs to the next agent when required.  <br>    - Do not fabricate or assume agent outputs; always rely on actual tool responses.  <br>    - Provide a final, coherent response after completing the workflow.<br>    <br>    ----------------------------------------------------------------------<br>    &quot;&quot;&quot;,<br>)</pre><h4><strong>MCP, A2A, and AG-UI Integration</strong></h4><p>Previously, we demonstrated how MCP standardizes interactions between models, agents, and tools, enabling a clear separation between the tools layer and agent implementations. This architectural decoupling improves scalability and maintainability while ensuring the tools layer remains fully language-agnostic, allowing tools to be implemented in any programming language and executed independently of the agent’s runtime environment.</p><p>Building on this foundation, we extend the architecture by transforming our ADK agents into remote agents using the Agent-to-Agent (A2A) protocol. A2A enables agents to communicate across network boundaries and operate as independently deployable services, significantly enhancing modularity, fault isolation, and scalability in distributed environments.</p><p>Beyond communication, A2A also brings structure. It standardizes how agent capabilities are defined and exposed, how requests are routed, and how messages and responses flow between agents. As a result, agents can collaborate as loosely coupled services that are easy to reason about, evolve, and operate.</p><p>The payoff is significant: agents can now be developed, scaled, updated, and even recovered independently, dramatically improving fault tolerance, system resilience, and long-term maintainability in real-world multi-agent systems.</p><h4>Exposing ADK Agents via A2A</h4><p>To begin, we need to convert our existing ADK agents into A2A-compliant endpoints so they can communicate with one another. This is the core step behind the question:</p><blockquote>I have an agent — how do I expose it so that other agents can use it via A2A?</blockquote><p>This capability is essential for building multi-agent systems where agents collaborate, delegate tasks, and exchange information programmatically. ADK offers two primary methods for exposing an agent through A2A:</p><ol><li>Using <strong>to_a2a(root_agent)</strong></li></ol><p>This is the simplest path when you want to convert an existing agent into an A2A endpoint. It gives you full control over deployment — e.g., exposing the agent via uvicorn rather than relying on adk deploy api_server. The to_a2a() function also auto-generates the agent card based on your code.</p><p>2. Creating and hosting your own <strong>agent.json</strong> card via <strong>adk api_server — a2a</strong></p><p>This approach integrates seamlessly with <strong>adk web </strong>for debugging and testing. It also allows you to host multiple agents from a single parent directory, each exposed automatically as long as an agent.json file is present. The tradeoff is that you must author the agent card manually (see the A2A Python tutorial for details).</p><p><a href="https://google.github.io/adk-docs/a2a/quickstart-exposing/">Agent Development Kit</a></p><p><strong>Approach Used in This Tutorial</strong></p><p>For this tutorial, we will use the <strong>to_a2a() </strong>function, as it provides the most direct and automated path for exposing an ADK agent as an A2A endpoint while generating the agent card behind the scenes. If you’re interested in the alternative adk api_server approach, refer to the full ADK documentation for additional guidance.</p><p>Let’s create and copy the following file to the <strong><em>weather_agent</em></strong> and <strong><em>maps_agent</em></strong> folders:</p><p><strong><em>agents/maps_agent/a2a_server.py</em></strong></p><pre>from google.adk.a2a.utils.agent_to_a2a import to_a2a<br>from agent import  root_agent<br><br># Make your agent A2A-compatible<br>a2a_app = to_a2a(root_agent, port=8001)<br><br>if __name__ == &#39;__main__&#39;:<br>    import uvicorn<br>    uvicorn.run(&quot;a2a_server:a2a_app&quot;,  host=&quot;127.0.0.1&quot;, port=8001, reload=True, workers=1)</pre><p><strong><em>agents/weather_agent/a2a_server.py</em></strong></p><pre>from google.adk.a2a.utils.agent_to_a2a import to_a2a<br>from agent import  root_agent<br><br># Make your agent A2A-compatible<br>a2a_app = to_a2a(root_agent, port=8002)<br><br>if __name__ == &#39;__main__&#39;:<br>    import uvicorn<br>    uvicorn.run(&quot;a2a_server:a2a_app&quot;, host=&quot;127.0.0.1&quot;,port=8002,  reload=True, workers=1)</pre><p>Now that we have our MCP servers in place and our A2A-compliant ADK agents running, the next step is to update the main application entry point. Specifically, we will modify the backend so the Atlas Agent is wrapped as an AG-UI–compatible agent, building directly on the previous example.</p><p>At this point, it is important to highlight an intentional design choice: during the implementation of the <a href="#"><strong><em>atlas_agent</em></strong></a>, <em>we deliberately did not enable the remote agents, nor did we register them as sub-agents within the orchestrator’s definition.</em> This is because, in this architecture, A2A task delegation and inter-agent messaging are managed at the frontend layer, within the Next.js application. The Next.js frontend acts as the coordination surface for user requests originating from the AG-UI interface, controlling how those requests are dispatched, tracked, and observed across the multi-agent system.</p><p>To support this flow, we need to update two key components:</p><ul><li>The backend main.py file, where the agent is exposed in an AG-UI–compatible form</li><li>The frontend route.ts file in our Next.js application, which handles incoming user requests and streams agent updates to the UI</li></ul><p>The core reason for these changes is that AG-UI must be able to intercept messages produced by the A2A-based multi-agent architecture. By doing so, AG-UI can observe agent interactions in real time and stream structured updates back to the React frontend, enabling a responsive and transparent user experience.</p><p>In the next sections, we’ll walk through the required updates on both the backend and frontend to make this integration work end-to-end.</p><p>First, let’s update the backend entry point: main.py. This is where we’ll wrap the Atlas Agent as an AG-UI–compatible agent and expose the endpoint that the frontend will connect to.</p><p><strong><em>main.py</em></strong></p><pre>&quot;&quot;&quot;<br>Orchestrator Agent - Coordinates between Weather and Maps agents.<br>Communicates using the AG-UI Protocol for UI integration, and delegates tasks<br>to specialized A2A agents through ADK middleware.<br>&quot;&quot;&quot;<br><br>from __future__ import annotations<br><br># Load environment variables (API keys, configs, etc.)<br>from dotenv import load_dotenv<br><br>load_dotenv()<br><br>import uvicorn<br>from fastapi import FastAPI<br><br># ADK wrapper that exposes agents through the AG-UI Protocol<br>from ag_ui_adk import ADKAgent, add_adk_fastapi_endpoint<br>from agents.atlas_agent.agent import root_agent as orchestrator_agent<br><br># -------------------------------------------------------------------<br># Wrap the LlmAgent using ADKAgent<br># This adds:<br># - session handling<br># - stateful memory<br># - tool routing<br># - AG-UI Protocol support<br># -------------------------------------------------------------------<br><br>adk_orchestrator_agent = ADKAgent(<br>    adk_agent=orchestrator_agent,  # The LLM agent defined above<br>    app_name=&quot;orchestrator_app&quot;,  # ID for the AG-UI front-end<br>    user_id=&quot;demo_user&quot;,  # Session tracking user ID<br>    session_timeout_seconds=3600,  # Auto-expire session after 1 hour<br>    use_in_memory_services=True  # Enables in-memory memory + tool services<br>)<br><br># -------------------------------------------------------------------<br># FastAPI application setup<br># Adds the ADK Orchestrator as an API endpoint using AG-UI Protocol<br># -------------------------------------------------------------------<br><br>app = FastAPI(title=&quot;A2A Orchestrator (ADK + AG-UI Protocol)&quot;)<br><br># Inject the orchestrator endpoint at &quot;/&quot;<br>add_adk_fastapi_endpoint(app, adk_orchestrator_agent, path=&quot;/&quot;)<br><br># -------------------------------------------------------------------<br># Run the development server (only when executing `python main.py`)<br># Uvicorn reloads on changes and ensures ADK&#39;s MCP tools run properly<br># -------------------------------------------------------------------<br><br>if __name__ == &#39;__main__&#39;:<br>    uvicorn.run(<br>        &quot;main:app&quot;,<br>        host=&quot;localhost&quot;,<br>        port=8000,<br>        reload=True,  # Auto-reload server on code changes (dev mode)<br>        workers=1  # ADK/MCP tools require single-worker execution<br>    )</pre><p>Next, we’ll move to the frontend and update <em>ui/app/api/copilotkit/route.ts.</em> This route will act as the bridge between the AG-UI interface and our remote multi-agent backend, handling requests and streaming agent updates back to the UI.</p><p><strong><em>ui/app/api/copilotkit/route.ts</em></strong></p><pre>import { A2AMiddlewareAgent } from &quot;@ag-ui/a2a-middleware&quot;<br>import {CopilotRuntime, copilotRuntimeNextJSAppRouterEndpoint, ExperimentalEmptyAdapter} from &quot;@copilotkit/runtime&quot;;<br>import {AbstractAgent, HttpAgent} from &quot;@ag-ui/client&quot;;<br>import {NextRequest} from &quot;next/server&quot;;<br><br><br><br>export async function POST(request: NextRequest) {<br>// These first two are the urls to the a2a agents<br>const weatherAgentUrl = process.env.WEATHER_AGENT_URL || &quot;http://localhost:8002&quot;;<br>const mapsAgentUrl = process.env.MAPS_AGENT_URL || &quot;http://localhost:8001&quot;;<br>const orchestratorUrl = process.env.ORCHESTRATOR_URL || &quot;http://localhost:8000&quot;;<br><br>// the orchestrator agent we pass to the middleware needs to be an instance of a derivative of an ag-ui `AbstractAgent`<br>// In this case, we have access to the agent via url, so we can gain an instance using the `HttpAgent` class<br>const orchestrationAgent: AbstractAgent = new HttpAgent({<br>  url: orchestratorUrl,<br>});<br><br>// A2A Middleware: Wraps orchestrator and injects send_message_to_a2a_agent tool<br>// This allows orchestrator to communicate with A2A agents transparently<br>const a2aMiddlewareAgent = new A2AMiddlewareAgent({<br>  description:<br>    &quot;An orchestrator agent that coordinates two specialized agents: Weather Agent and Maps Agent build on the ADK framework.&quot;,<br>  // We pass the urls to the a2a agents, the middleware will handle the connections<br>  agentUrls: [<br>    weatherAgentUrl,<br>    mapsAgentUrl,<br>  ],<br>  // Pass the agent instance<br>  orchestrationAgent<br>});<br><br>// CopilotKit runtime connects frontend to agent system<br>  // CopilotKit runtime connects frontend to agent system<br>  const runtime = new CopilotRuntime({<br>    agents: {<br>      a2a_chat: a2aMiddlewareAgent, // Must match agent prop in &lt;CopilotKit agent=&quot;a2a_chat&quot;&gt;<br>    },<br>  });<br><br>  const { handleRequest } = copilotRuntimeNextJSAppRouterEndpoint({<br>    runtime,<br>    serviceAdapter: new ExperimentalEmptyAdapter(),<br>    endpoint: &quot;/api/copilotkit&quot;,<br>  });<br><br>  return handleRequest(request);<br>}</pre><p>The most important piece of this frontend/Nextjs App integration is the A2A middleware layer, implemented via A2AMiddlewareAgent. Conceptually, it sits between your AG-UI/CopilotKit runtime and your remote A2A agents, turning a distributed set of services into a single, seamless “agent” the UI can talk to.</p><p>In this implementation, the middleware wraps the orchestrator, which is exposed as an AG UI AbstractAgent via HttpAgent, and registers the URLs of the specialized remote agents for Maps and Weather. From there, it injects a standardized tool interface, most notably a send_message_to_a2a_agent capability, allowing the orchestrator(atlas_agent) to delegate work to remote agents without having to manage low-level networking, request routing, or message formatting directly.</p><p>In other words, the orchestrator continues to focus on decision-making and sequencing, while the middleware handles the heavy lifting required for remote collaboration:</p><ul><li><strong>Agent connectivity:</strong> manages connections to multiple A2A agent endpoints via their URLs</li><li><strong>Request routing:</strong> forwards orchestrator calls to the appropriate specialized agent</li><li><strong>Message exchange + coordination:</strong> standardizes how messages are sent and responses are returned</li></ul><p>This is why, in the code, the UI only needs to register a single runtime agent:</p><pre>agents: {<br>  a2a_chat: a2aMiddlewareAgent,<br>}</pre><p>We finally need to update our page.tsx file so the UI can properly render A2A interactions. The complete implementations of the MessageToA2A and MessageFromA2A components are available in the GitHub repository under: <a href="https://github.com/haruiz/atlas_app">atlas_app</a>, multiple_agent branch:</p><p><a href="https://github.com/haruiz/atlas_app/tree/multiple_agent/ui/components/a2a">atlas_app/ui/components/a2a at multiple_agent · haruiz/atlas_app</a></p><p><strong><em>ui/app/page.tsx</em></strong></p><pre>&quot;use client&quot;;<br><br>import React, {useEffect} from &quot;react&quot;;<br>import &quot;@copilotkit/react-ui/styles.css&quot;;<br>// import &quot;./style.css&quot;;<br><br>// CopilotKit core<br>import {useCopilotAction, useCopilotChat,} from &quot;@copilotkit/react-core&quot;;<br>import {CopilotChat} from &quot;@copilotkit/react-ui&quot;;<br>import {MessageToA2A} from &quot;@/components/a2a/MessageToA2A&quot;;<br>import {MessageFromA2A} from &quot;@/components/a2a/MessageFromA2A&quot;;<br><br><br>const Chat = () =&gt; {<br>    const {visibleMessages} = useCopilotChat();<br><br>    useCopilotAction({<br>    name: &quot;send_message_to_a2a_agent&quot;,<br>    description: &quot;Sends a message to an A2A agent&quot;,<br>    available: &quot;frontend&quot;,<br>    parameters: [<br>      {<br>        name: &quot;agentName&quot;,<br>        type: &quot;string&quot;,<br>        description: &quot;The name of the A2A agent to send the message to&quot;,<br>      },<br>      {<br>        name: &quot;task&quot;,<br>        type: &quot;string&quot;,<br>        description: &quot;The message to send to the A2A agent&quot;,<br>      },<br>    ],<br>    render: (actionRenderProps) =&gt; {<br>        console.log(actionRenderProps);<br>      return (<br>        &lt;&gt;<br>          &lt;MessageToA2A {...actionRenderProps} /&gt;<br>          &lt;MessageFromA2A {...actionRenderProps} /&gt;<br>        &lt;/&gt;<br>      );<br>    },<br>  });<br><br>    useEffect(() =&gt; {<br>      const extractDataFromMessages = () =&gt; {<br>      for (const message of visibleMessages) {<br>        const msg = message;<br><br>        if (msg.type === &quot;ResultMessage&quot; &amp;&amp; msg.actionName === &quot;send_message_to_a2a_agent&quot;) {<br><br>          try {<br>            let parsed;<br>            const result = msg.result;<br>            if (typeof result === &quot;string&quot;) {<br>              try {<br>                  parsed = JSON.parse(result);<br>              }<br>            catch {<br>                continue;<br>            }<br>            } else if (typeof result === &quot;object&quot;) {<br>                parsed = result;<br>            }<br>            console.log(&quot;Sending message to A2A agent: &quot;, parsed);<br>          } catch (e) {<br>            console.error(&quot;Failed to extract data from message:&quot;, e);<br>          }<br>        }<br>      }<br>    };<br><br>    extractDataFromMessages();<br>    }, [visibleMessages]);<br><br>    /* --------------------------------------------------------------------------------------------<br>     * MAIN UI RENDERING<br>     * ------------------------------------------------------------------------------------------*/<br>    return (<br>        &lt;div<br>            className=&quot;flex justify-center items-center h-full w-full&quot;<br>            data-testid=&quot;background-container&quot;<br>        &gt;<br>            &lt;div className=&quot;h-full w-full md:w-8/10 md:h-8/10 rounded-lg&quot;&gt;<br>                &lt;CopilotChat<br>                    onSubmitMessage={(message) =&gt; {<br>                        console.log(&quot;User submitted message:&quot;, message);<br>                    }}<br>                    suggestions={[{<br>                        title: &quot;What is the weather in San Francisco?&quot;,<br>                        message: &quot;What is the weather in San Francisco?&quot;<br>                    }]}<br>                    className=&quot;h-full rounded-2xl max-w-6xl mx-auto&quot;<br>                    labels={{initial: &quot;Hi, I&#39;m an agent. Want to chat?&quot;}}<br>                /&gt;<br>            &lt;/div&gt;<br>            &lt;span className=&quot;absolute bottom-4 right-4 text-xs text-gray-400&quot;&gt;<br>                Num Messages: {visibleMessages.length}<br>            &lt;/span&gt;<br>        &lt;/div&gt;<br>    );<br>};<br><br>/* ------------------------------------------------------------------------------------------------<br> * HOME PAGE WRAPPER<br> * ----------------------------------------------------------------------------------------------*/<br><br>const HomePage = () =&gt; {<br>    return (<br>        &lt;main className=&quot;h-screen w-screen&quot;&gt;<br>            &lt;Chat/&gt;<br>        &lt;/main&gt;<br>    );<br>};<br><br>export default HomePage;</pre><p>Before wrapping up, here is a short video demo of the system in action, showing how user requests flow through the AG-UI frontend, are routed via the A2A middleware, and coordinated across the Maps, Weather, and Atlas agents in real time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*coaNujpPrlB-gT0tzLHctw.gif" /></figure><p>You now have a complete end-to-end multi-agent system that is modular, remotely deployable, and easy to extend. MCP keeps your tools cleanly separated and language-agnostic, A2A turns each ADK agent into a network-accessible service that can collaborate with peers, and AG-UI makes those interactions visible and interactive in the frontend. The result is an architecture where you can add new specialist agents, swap tool implementations, or scale components independently without rewriting your application.</p><p>From here, try adding a third agent, such as traffic, air quality, or travel planning, and update the A2A middleware instructions to route requests dynamically. As your agent ecosystem grows, you will start to see the real payoff of this approach: clearer separation of concerns, better reliability under complexity, and a user experience that remains transparent even as the system becomes increasingly distributed.</p><p>I hope this tutorial proves useful as you explore and build your own multi-agent systems. Whether you are experimenting with new agent interactions or designing production-ready architectures, I hope the patterns and examples shared here help accelerate your work. Thanks for following along, and I look forward to seeing you in the next post.</p><blockquote><strong>Note:</strong> The full, fully functional implementation of the application is available in the GitHub repository under the <strong>multiple_agent</strong> <a href="https://github.com/haruiz/atlas_app/blob/multiple_agent/run_app.sh">branch</a>. To run the complete app end-to-end, use the provided run_app.sh script. This script automatically dispatches all required components—including the MCP servers, the A2A agents, the backend API, and the frontend—so the entire system can be launched with a single command.</blockquote><p><strong>Acknowledgements</strong></p><p><em>This work was supported by </em><strong><em>Google ML Developer Programs</em></strong><em> and the </em><strong><em>Google Developers Program</em></strong><em>, which provided Google Cloud credits and high-quality technical resources #AISprint</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1fe0c0378bef" width="1" height="1" alt=""><hr><p><a href="https://medium.com/google-cloud/from-single-agent-to-production-ready-multi-agent-architecture-with-adk-mcp-a2a-and-ag-ui-1fe0c0378bef">From Single Agent to Production-Ready Multi Agent Architecture with ADK, MCP, A2A, and AG-UI</a> was originally published in <a href="https://medium.com/google-cloud">Google Cloud - Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building interactive agentic applications using ADK and AG-UI protocol]]></title>
            <link>https://medium.com/google-cloud/building-interactive-agentic-applications-using-adk-and-ag-ui-protocol-3a49ae6d3dc9?source=rss-4a509f6a939e------2</link>
            <guid isPermaLink="false">https://medium.com/p/3a49ae6d3dc9</guid>
            <category><![CDATA[ag-ui]]></category>
            <category><![CDATA[agent-development-kit]]></category>
            <category><![CDATA[google-adk]]></category>
            <category><![CDATA[agents]]></category>
            <dc:creator><![CDATA[Henry Ruiz]]></dc:creator>
            <pubDate>Sat, 20 Dec 2025 18:31:18 GMT</pubDate>
            <atom:updated>2026-03-05T20:33:06.894Z</atom:updated>
            <content:encoded><![CDATA[<p>The rise of multi-agent systems is reshaping how we design and deploy modern AI software. As LLMs become better at reasoning and planning, we are moving beyond “one prompt, one response” and toward applications where agents can take actions, call tools, and collaborate to automate complex, real-world workflows (see image below). However, as these systems grow in capability and complexity, a practical bottleneck quickly emerges: it is not only about making the model smarter, but about making the system usable and user-friendly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GEhUivFPkbEjexP9EEuNcw.png" /><figcaption>From standalone LLMs to agentic systems. A comparison between a single-prompt LLM interaction and a multi-agent system where agents combine reasoning, memory, tools, and retrieval to take actions in an environment, receive feedback, and collaborate with humans, APIs, and external tools.</figcaption></figure><p>In practice, many of these usability challenges arise at the interaction layer between backend agent execution and the frontend user interface. Multi-agent systems are inherently multi-turn, asynchronous, and stateful, and without a well-defined interface contract, both users and developers quickly lose visibility and control over what the system is doing. As a result, several recurring challenges consistently appear:</p><ul><li><strong>Complex conversation state</strong>: user intent, agent context, and partially completed tasks must be preserved and evolved across turns, rather than implicitly reconstructed from prompt history.</li><li><strong>Coordination overhead</strong>: multiple agents operate in parallel and respond asynchronously; naïve chat-based UIs collapse these interactions into an unreadable stream.</li><li><strong>Latency and user experience</strong>: multi-step reasoning and external tool calls introduce delays that must be communicated as progress, not experienced as silence.</li><li><strong>Conflict resolution</strong>: specialized agents may disagree, requiring clear mechanisms for comparison, arbitration, and guidance.</li><li><strong>Transparency and attribution</strong>: users need to know which agent produced which output in order to maintain trust.</li><li><strong>Human-in-the-loop control</strong>: real-world systems require intervention points to approve, reject, pause, or refine agent actions during execution.</li><li><strong>Scalability of interaction</strong>: as the number of agents and the depth of interaction grow, cognitive load becomes the dominant failure mode.</li></ul><p><strong>AG-UI</strong> is designed to address many of these challenges by standardizing the connection between agent execution and the user interface. It introduces an event-driven interaction protocol that allows agents to emit structured, typed events — such as messages, tool calls, tool results, state updates, and lifecycle signals — that the frontend can interpret deterministically and render consistently.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/822/0*3nf1cG0LSsG_0dea.gif" /><figcaption>Image source: <a href="https://www.copilotkit.ai/blog/introducing-ag-ui-the-protocol-where-agents-meet-users">https://www.copilotkit.ai/blog/introducing-ag-ui-the-protocol-where-agents-meet-users</a></figcaption></figure><p>By externalizing agent execution as observable, structured events, AG-UI makes conversation state explicit across turns. By attaching agent identity and role metadata to each event, it enables transparency and supports conflict resolution. By streaming execution status and intermediate signals, it mitigates latency through continuous, real-time feedback. Finally, by supporting UI-addressable actions, AG-UI enables human-in-the-loop control without coupling UI logic to agent prompts.</p><p>In this post, we will walk through how to integrate AG-UI with ADK to build engaging, agentic user experiences. As a concrete example, we will develop a system that provides users with both weather information and geographic context. To support real-time interactions, our agents will be equipped with tools that retrieve live weather data and interact with the Google Maps API.</p><p>Let’s get started.</p><ol><li><strong>Create ADK Agent</strong></li></ol><p>First, we’ll create our <em>uv</em> project and install the necessary dependencies. Let’s call our application &quot;atlas&quot;. To do so, run the following commands in the PyCharm terminal:</p><pre>uv init atlas --app # Create uv project<br>cd atlas # move into project folder<br>uv add ag-ui-adk google-adk google-genai googlemaps # install dependecies<br><br>pycharm ./ # Open project on code editor (pycharm)</pre><p>Next, we create our atlas_agent:</p><pre>mkdir agents # create agents folder<br>cd agents # move into agents folder<br>adk create atlas_agent # create an agent using adk<br>pycharm atlas_agent/agent.py # open agent file in the editor</pre><p>Create/update the content of the following files:</p><p><em>atlas_agent/agent.py</em></p><pre>from google.adk.agents.llm_agent import Agent<br>from google.adk.tools.preload_memory_tool import PreloadMemoryTool<br>from .tools import get_weather, get_place_location, get_place_details<br><br>agent_instructions = &quot;&quot;&quot;<br>You are a helpful assistant designed to answer user questions and provide useful information, <br>including weather updates and place details using Google Maps data.<br><br>Behavior Guidelines:<br>- If the user greets you, respond specifically with &quot;Hello&quot;.<br>- If the user greets you without making any request, reply with &quot;Hello&quot; and ask, &quot;How can I assist you?&quot;<br>- If the user asks a direct question, provide the most accurate and helpful answer possible.<br><br>Tool Usage:<br>- get_weather: Retrieve the current weather information for a specified location.<br>- get_place_location: Obtain the precise latitude and longitude of a specified place.<br>- get_place_details: Fetch detailed information about a place using its geographic coordinates.<br><br>Always choose the most appropriate tool to fulfill the user&#39;s request, and respond clearly and concisely.<br>&quot;&quot;&quot;<br>root_agent = Agent(<br>    name=&quot;assistant&quot;,                    # Internal agent name<br>    model=&quot;gemini-2.5-flash&quot;,            # LLM model to use<br>    instruction=agent_instructions,<br>    tools=[<br>        # Provides persistent memory during the session (non-long-term)<br>        PreloadMemoryTool(),<br><br>        # Direct tool integration example<br>        get_weather,<br>        get_place_location,<br>        get_place_details,<br><br>    ]<br>)</pre><p><em>atlas_agent/tools.py</em></p><pre>import os<br>from typing import Optional, Any<br><br>import googlemaps<br>import httpx<br>from google import genai<br>from google.genai import types<br>from dotenv import load_dotenv, find_dotenv<br><br>load_dotenv(find_dotenv())<br><br><br>gmaps_client = googlemaps.Client(key=os.getenv(&quot;GOOGLE_MAPS_API_KEY&quot;))<br>genai_client = genai.Client(http_options=types.HttpOptions(api_version=&quot;v1&quot;))<br><br>def get_weather_condition(code: int) -&gt; str:<br>    &quot;&quot;&quot;Map weather code to human-readable condition.<br><br>    Args:<br>        code: WMO weather code.<br><br>    Returns:<br>        Human-readable weather condition string.<br>    &quot;&quot;&quot;<br>    conditions = {<br>        0: &quot;Clear sky&quot;,<br>        1: &quot;Mainly clear&quot;,<br>        2: &quot;Partly cloudy&quot;,<br>        3: &quot;Overcast&quot;,<br>        45: &quot;Foggy&quot;,<br>        48: &quot;Depositing rime fog&quot;,<br>        51: &quot;Light drizzle&quot;,<br>        53: &quot;Moderate drizzle&quot;,<br>        55: &quot;Dense drizzle&quot;,<br>        56: &quot;Light freezing drizzle&quot;,<br>        57: &quot;Dense freezing drizzle&quot;,<br>        61: &quot;Slight rain&quot;,<br>        63: &quot;Moderate rain&quot;,<br>        65: &quot;Heavy rain&quot;,<br>        66: &quot;Light freezing rain&quot;,<br>        67: &quot;Heavy freezing rain&quot;,<br>        71: &quot;Slight snow fall&quot;,<br>        73: &quot;Moderate snow fall&quot;,<br>        75: &quot;Heavy snow fall&quot;,<br>        77: &quot;Snow grains&quot;,<br>        80: &quot;Slight rain showers&quot;,<br>        81: &quot;Moderate rain showers&quot;,<br>        82: &quot;Violent rain showers&quot;,<br>        85: &quot;Slight snow showers&quot;,<br>        86: &quot;Heavy snow showers&quot;,<br>        95: &quot;Thunderstorm&quot;,<br>        96: &quot;Thunderstorm with slight hail&quot;,<br>        99: &quot;Thunderstorm with heavy hail&quot;,<br>    }<br>    return conditions.get(code, &quot;Unknown&quot;)<br><br><br>async def get_weather(location: str) -&gt; dict:<br>    &quot;&quot;&quot;Get the weather for a given location.<br><br>    Args:<br>        location: City name.<br><br>    Returns:<br>        Dictionary with weather information including temperature, feels like,<br>        humidity, wind speed, wind gust, conditions, and location name.<br>    &quot;&quot;&quot;<br>    try:<br>        async with httpx.AsyncClient() as client:<br>            # Geocode the location<br>            geocoding_url = (<br>                f&quot;https://geocoding-api.open-meteo.com/v1/search?name={location}&amp;count=1&quot;<br>            )<br>            geocoding_response = await client.get(geocoding_url)<br>            geocoding_data = geocoding_response.json()<br>            print(geocoding_data)<br><br>            if not geocoding_data.get(&quot;results&quot;):<br>                raise ValueError(f&quot;Location &#39;{location}&#39; not found&quot;)<br><br>            result = geocoding_data[&quot;results&quot;][0]<br>            latitude = result[&quot;latitude&quot;]<br>            longitude = result[&quot;longitude&quot;]<br>            name = result[&quot;name&quot;]<br><br>            # Get weather data<br>            weather_url = (<br>                f&quot;https://api.open-meteo.com/v1/forecast?&quot;<br>                f&quot;latitude={latitude}&amp;longitude={longitude}&quot;<br>                f&quot;&amp;current=temperature_2m,apparent_temperature,relative_humidity_2m,&quot;<br>                f&quot;wind_speed_10m,wind_gusts_10m,weather_code&quot;<br>            )<br>            weather_response = await client.get(weather_url)<br>            weather_data = weather_response.json()<br><br><br>            current = weather_data[&quot;current&quot;]<br><br>            result =  {<br>                &quot;temperature&quot;: current[&quot;temperature_2m&quot;],<br>                &quot;feelsLike&quot;: current[&quot;apparent_temperature&quot;],<br>                &quot;humidity&quot;: current[&quot;relative_humidity_2m&quot;],<br>                &quot;windSpeed&quot;: current[&quot;wind_speed_10m&quot;],<br>                &quot;windGust&quot;: current[&quot;wind_gusts_10m&quot;],<br>                &quot;conditions&quot;: get_weather_condition(current[&quot;weather_code&quot;]),<br>                &quot;location&quot;: name,<br>            }<br>            return {<br>                &quot;status&quot;: &quot;success&quot;,<br>                &quot;result&quot;: result<br>            }<br>    except Exception as e:<br>        return {<br>            &quot;status&quot;: &quot;error&quot;,<br>            &quot;message&quot;: str(e)<br>        }<br><br><br>def get_place_location(place_name: str) -&gt; dict[str, str]:<br>    &quot;&quot;&quot;Get coordinates from an address using Google Maps API.<br><br>    Args:<br>        place_name: The name of the place to get coordinates for.<br><br>    Returns:<br>        A dictionary with the status of the operation and the result.<br>        If successful, the result contains the latitude and longitude.<br>    &quot;&quot;&quot;<br>    try:<br>        geocode_result = gmaps_client.geocode(place_name)<br>        if geocode_result is None:<br>            return {<br>                &quot;status&quot;: &quot;error&quot;,<br>                &quot;message&quot;: f&quot;Could not find coordinates for address: {place_name}&quot;<br>            }<br><br>        location = geocode_result[0][&quot;geometry&quot;][&quot;location&quot;]<br>        lat = location[&quot;lat&quot;]<br>        lng = location[&quot;lng&quot;]<br>        return {<br>            &quot;status&quot;: &quot;success&quot;,<br>            &quot;result&quot;: {&quot;latitude&quot;: lat, &quot;longitude&quot;: lng}<br>        }<br>    except Exception as e:<br>        return {<br>            &quot;status&quot;: &quot;error&quot;,<br>            &quot;message&quot;: str(e)<br>        }<br><br><br>def get_place_details(query_prompt: str, latitude: float, longitude: float, model_name: Optional[str]= &quot;gemini-2.5-flash&quot;) -&gt; dict[str, Any]:<br>    &quot;&quot;&quot;Get place details using Google Maps Tool in Gemini.<br><br>    Args:<br>        query_prompt: The prompt to search for.<br>        latitude: The latitude of the location.<br>        longitude: The longitude of the location.<br>        model_name: The name of the model to use.<br><br>    Returns:<br>        A dictionary with the status of the operation and the result.<br>        If successful, the result contains the place details.<br>    &quot;&quot;&quot;<br>    try:<br>        response = genai_client.models.generate_content(<br>            model=model_name,<br>            contents=query_prompt,<br>            config=types.GenerateContentConfig(<br>                tools=[<br>                    # Use Google Maps Tool<br>                    types.Tool(google_maps=types.GoogleMaps(<br>                        enable_widget=False  # Optional: return Maps widget token<br>                    ))<br>                ],<br>                tool_config=types.ToolConfig(<br>                    retrieval_config=types.RetrievalConfig(<br>                        lat_lng=types.LatLng(  # Pass geo coordinates for location-aware grounding<br>                            latitude=latitude,<br>                            longitude=longitude,<br>                        ),<br>                        language_code=&quot;en_US&quot;,  # Optional: localize Maps results<br>                    ),<br>                ),<br>            ),<br>        )<br>        return {<br>            &quot;status&quot;: &quot;success&quot;,<br>            &quot;result&quot;: response.text<br>        }<br>    except Exception as e:<br>        return {<br>            &quot;status&quot;: &quot;error&quot;,<br>            &quot;message&quot;: str(e)<br>        }</pre><p>To see the agent in action, you can use the ADK Web UI, which provides a clean, built-in environment for testing, debugging, and experimenting with your agent during development. The interface allows you to interact with the agent in real time, inspect responses, and verify that tools and external integrations are working as expected.</p><p>Before running the UI, make sure to configure access to the Google Maps API, as it is required by the agent’s get_place_location tool. This tool uses the Google Maps Geocoding service to convert the name of a place into its corresponding GPS coordinates (latitude and longitude). The agent relies on this functionality to translate a user-provided place name into geographic coordinates that can be used by other components of the system.</p><p>To enable this functionality, you need to create a Google Maps API key. Follow the instructions provided in the official documentation:<br> <a href="https://github.com/googlemaps/google-maps-services-python">https://github.com/googlemaps/google-maps-services-python</a></p><p>Once the API key is created, export it or add it to your .env file so the application can access it at runtime:</p><pre>GOOGLE_MAPS_API_KEY=your_api_key_here</pre><p>Setting this environment variable allows the agent to authenticate requests to the Google Maps API and successfully execute the geocoding tool.</p><p>To launch the interface, simply run the command below from your agents directory. This will start the ADK development server and automatically open the ADK Web UI in your browser, where you can interact with the agent, test prompts, and observe tool execution in real time.</p><pre>adk web</pre><p>Once the UI loads, you will see an interactive chat interface similar to the following<strong> </strong>image<strong>,</strong> where you can select your agent and begin sending queries. This environment is particularly useful for validating tool usage and iterating quickly on your agent’s capabilities before deploying it to a production environment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SYGET2BUHAqxg_SU2-1hDA.png" /><figcaption>ADK Web UI</figcaption></figure><p><strong>2. Building the AG-UI frontend</strong></p><p>Even though we can test our agent within the built-in ADK UI, real-world agentic applications often require a dedicated frontend capable of managing streaming outputs, coordinating asynchronous agent tasks, rendering custom UI components, preserving conversation state, and supporting human-in-the-loop control. AG-UI addresses these architectural needs by providing a standardized protocol for building frontends for multi-agent applications. It defines how agent state, UI intents, and user interactions flow between your model or agent runtime and your application’s frontend — allowing you to ship reliable, debuggable, and user-friendly agentic features quickly. In this section, we will learn how to build the frontend of our <em>atlas</em> application by leveraging AG-UI’s out-of-the-box integration with ADK to create a seamless, interactive agent experience.</p><p><strong><em>2.1. Create Next.js Application</em></strong></p><p>We start creating a Next.js App with the default settings, running the command:</p><pre>npx create-next-app@latest ui</pre><p>The command should have created a ui folder with the following structure:</p><pre>cd ./ui<br>tree -L 2<br><br>├── README.md<br>├── app<br>├── eslint.config.mjs<br>├── next-env.d.ts<br>├── next.config.ts<br>├── node_modules<br>├── package-lock.json<br>├── package.json<br>├── postcss.config.mjs<br>├── public<br>└── tsconfig.json</pre><p>Then, we check if our Next.js project was successfully created by running our application in the browser with the command:</p><pre>yarn dev</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rQHWvM7WRAFu2dUJt5nzDg.png" /><figcaption>Next js App running in the browser</figcaption></figure><p>If everything worked correctly in the previous step, and our application is open in the browser, we can now install the AG-UI dependencies and start building our frontend.</p><pre>yarn add  @copilotkit/react-ui @copilotkit/react-core @copilotkit/runtime @ag-ui/client  </pre><p><strong><em>2.2. Standardizing Backend-to-Frontend Communication with AG-UI</em></strong></p><p>As described earlier, AG-UI provides a standardized communication layer between the agent runtimes (such as ADK, LangGraph, or custom orchestrators) and the frontend. It defines:</p><ul><li>How the agent state is exchanged with the frontend</li><li>how UI actions are expressed as agent “intents.”</li><li>and how model outputs should be structured for dynamic UI rendering</li></ul><p>To make our ADK agent compatible with the AG-UI frontend, we need a way to intercept the agent’s internal events and convert them into AG-UI–compliant messages.</p><p>The AG-UI Python SDK provides a wrapper class that handles this translation for us. All we need to do is update our main application file to wrap the agent with this middleware and expose it through an AG-UI–compatible endpoint.</p><p>Below is the main.py file that initializes the agent runtime:</p><pre>cd ./../<br>touch main.py</pre><pre>from ag_ui_adk import ADKAgent, add_adk_fastapi_endpoint<br>from fastapi import FastAPI<br><br>from agents.atlas_agent.agent import root_agent as atlas_root_agent<br><br><br># -------------------------------------------------------------------<br># Wrap the agent inside an ADKAgent middleware<br># This provides sessions, user identity, in-memory services,<br># and the unified ADK API that frontend UI components expect.<br># -------------------------------------------------------------------<br>ag_atlas_agent = ADKAgent(<br>    adk_agent=atlas_root_agent,            # The core ADK agent<br>    app_name=&quot;atlas_app&quot;,                # App identifier<br>    user_id=&quot;demo_user&quot;,                # Mock user ID (replace in production)<br>    session_timeout_seconds=3600,       # Session expiration<br>    use_in_memory_services=True         # Enables in-memory RAG + storage<br>)<br><br># Create the FastAPI application<br>app = FastAPI(title=&quot;ADK Middleware Atlas Chat&quot;)<br><br># add custom routes<br>@app.get(&quot;/health&quot;)<br>async def health_check():<br>    return {&quot;status&quot;: &quot;ok&quot;}<br><br># -------------------------------------------------------------------<br># Register an ADK-compliant endpoint with FastAPI.<br># This exposes the chat API at &quot;/&quot;.<br># Your frontend (Next.js + CopilotKit) will call this endpoint.<br># -------------------------------------------------------------------<br>add_adk_fastapi_endpoint(app, ag_atlas_agent, path=&quot;/&quot;)<br><br># -------------------------------------------------------------------<br># Run the development server using Uvicorn<br># Only executes when running `python main.py`<br># -------------------------------------------------------------------<br>if __name__ == &#39;__main__&#39;:<br>    import uvicorn<br>    uvicorn.run(<br>        &quot;main:app&quot;,<br>        host=&quot;localhost&quot;,<br>        port=8000,<br>        reload=True,        # Auto-reload on code changes<br>        workers=1           # Single worker recommended for MCP tools<br>    )</pre><p><strong><em>2.3. Standardizing Frontend-to-Backend Communication with AG-UI</em></strong></p><p>With the backend wired up, the next step is to connect our Next.js frontend to the agent so it can send messages and receive responses. To do this, we create a Next.js route /api/copilotkit and initialize the Copilot Runtime inside its POST handler.</p><p>This route is responsible for:</p><ul><li>relaying requests from CopilotKit UI components</li><li>forwarding those requests to the ADK agent</li><li>returning streaming or structured responses back to the frontend</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/255/1*Zum_l4vZBLZy0iaOekUfEQ.png" /></figure><pre>import {<br>  CopilotRuntime,<br>  ExperimentalEmptyAdapter,<br>  copilotRuntimeNextJSAppRouterEndpoint,<br>} from &quot;@copilotkit/runtime&quot;;<br>import { HttpAgent } from &quot;@ag-ui/client&quot;;<br>import { NextRequest } from &quot;next/server&quot;;<br><br>// Create a service adapter for the CopilotKit runtime<br>const serviceAdapter = new ExperimentalEmptyAdapter();<br>// Create the main CopilotRuntime instance that manages communication between the frontend and backend agents<br>const runtime = new CopilotRuntime({<br>// Define the agents that will be available to the frontend<br>    agents: {<br>// Configure the ADK agent connection<br>    atlas_agent: new HttpAgent({<br>      // Specify the URL where the ADK agent is running<br>      url: &quot;http://localhost:8000/&quot;,<br>    })<br>},<br>});<br>// Export the POST handler for the API route<br>export const POST = async (req: NextRequest) =&gt; {<br>// Create the request handler using CopilotKit&#39;s Next.js helper<br>const { handleRequest } = copilotRuntimeNextJSAppRouterEndpoint({<br>    runtime, // The CopilotRuntime instance we configured<br>    serviceAdapter, // The service adapter for agent coordination<br>    endpoint: &quot;/api/copilotkit&quot;, // The endpoint path (matches this file&#39;s location)<br>});<br>return handleRequest(req);<br>};</pre><p><strong><em>2.4. Integrating CopilotKit</em></strong></p><p>Now that communication between frontend and backend is established, we must configure the CopilotKit provider so all UI components can access the runtime.</p><p>The &lt;CopilotKit&gt; Provider manages:</p><ul><li>agent sessions</li><li>streaming updates</li><li>contextual prompts</li><li>requests made by Copilot UI components</li></ul><p>Wrap your entire application with it inside layout.tsx:</p><pre>import type { Metadata } from &quot;next&quot;;<br>import { Geist, Geist_Mono } from &quot;next/font/google&quot;;<br>import &quot;./globals.css&quot;;<br><br>import { CopilotKit } from &quot;@copilotkit/react-core&quot;;<br>import &quot;@copilotkit/react-ui/styles.css&quot;;<br><br>const geistSans = Geist({<br>  variable: &quot;--font-geist-sans&quot;,<br>  subsets: [&quot;latin&quot;],<br>});<br><br>const geistMono = Geist_Mono({<br>  variable: &quot;--font-geist-mono&quot;,<br>  subsets: [&quot;latin&quot;],<br>});<br><br>export const metadata: Metadata = {<br>  title: &quot;Create Next App&quot;,<br>  description: &quot;Generated by create next app&quot;,<br>};<br><br>export default function RootLayout({<br>  children,<br>}: Readonly&lt;{<br>  children: React.ReactNode;<br>}&gt;) {<br>  return (<br>    &lt;html lang=&quot;en&quot;&gt;<br>      &lt;body<br>        className={`${geistSans.variable} ${geistMono.variable} antialiased`}<br>      &gt;<br>        &lt;CopilotKit runtimeUrl=&quot;/api/copilotkit&quot;<br>                    agent=&quot;atlas_agent&quot;<br>                    showDevConsole={false}&gt;<br>            {children}<br>        &lt;/CopilotKit&gt;<br>      &lt;/body&gt;<br>    &lt;/html&gt;<br>  );<br>}</pre><p>Once wrapped, any page can use CopilotKit’s built-in components.</p><p><strong><em>2.5. Adding Copilot UI Components</em></strong></p><p>CopilotKit includes prebuilt UI components for interacting with agents, such as:</p><ul><li>CopilotChat</li><li>CopilotPopup</li><li>CopilotSidebar</li></ul><p>Here’s an example using CopilotChat:</p><pre>&quot;use client&quot;;<br><br>import {CopilotChat} from &quot;@copilotkit/react-ui&quot;;<br><br><br>export default function HomePage() {<br>  return (<br>    &lt;main className=&quot;h-screen w-screen&quot;&gt;<br>        &lt;CopilotChat<br>            className=&quot;h-full rounded-2xl max-w-6xl mx-auto&quot;<br>            labels={{initial: &quot;Hi, I&#39;m an agent. Want to chat?&quot;}}<br>            suggestions={[{<br>                title: &quot;Weather in New York&quot;,<br>                message: &quot;What&#39;s the weather like in New York?&quot;<br>            }]}<br>        /&gt;<br>    &lt;/main&gt;<br>  );<br>}</pre><p><strong><em>2.6. Giving the Agent UI Control: Frontend Tools</em></strong></p><p>One of CopilotKit’s most powerful features is <strong>frontend tools</strong> — functions that let the LLM trigger actions directly in your UI. These tools enable the agent to do things like update component state, modify styles, or adjust the appearance of your app interface.</p><p>The useFrontendTool hook allows you to define actions that the Agents can invoke through a handler function. This is the main mechanism that gives your agent the ability to perform client-side operations, whether that means updating React state or triggering custom side effects.</p><p>Each frontend tool is defined using three core elements:</p><ol><li><strong>Name and description</strong> — tells the AI what the tool does and when to use it</li><li><strong>Parameters</strong> — a schema describing the inputs the tool accepts</li><li><strong>Handler function</strong> — executed on the client when the AI calls the tool</li></ol><p>Optionally, you can also include a render function to display custom UI inside the chat, such as tool results, status information, or visual feedback.</p><pre>&quot;use client&quot;;<br><br>import {CopilotChat} from &quot;@copilotkit/react-ui&quot;;<br>import {useState} from &quot;react&quot;;<br>import {useFrontendTool} from &quot;@copilotkit/react-core&quot;;<br><br><br>export default function HomePage() {<br>    const [background, setBackground] = useState&lt;string&gt;(<br>        &quot;--copilot-kit-background-color&quot;<br>    );<br><br>    /* --------------------------------------------------------------------------------------------<br>     * CHANGE BACKGROUND TOOL<br>     * This tool allows the LLM to set the chat background.<br>     * ------------------------------------------------------------------------------------------*/<br>    useFrontendTool({<br>        name: &quot;change_background&quot;,<br>        description:<br>            &quot;Change the chat&#39;s background using any CSS background value (color, gradient, etc.).&quot;,<br>        parameters: [<br>            {<br>                name: &quot;background&quot;,<br>                type: &quot;string&quot;,<br>                description: &quot;CSS background definition (colors, gradients, etc).&quot;,<br>            },<br>        ],<br><br>        // The tool handler executes when the LLM calls this tool.<br>        handler: ({background}) =&gt; {<br>            setBackground(background);<br><br>            return {<br>                status: &quot;success&quot;,<br>                message: `Background changed to ${background}`,<br>            };<br>        },<br>    });<br><br>  return (<br>    &lt;main className=&quot;h-screen w-screen&quot; style={{background}} &gt;<br>        &lt;CopilotChat<br>            className=&quot;h-full rounded-2xl max-w-6xl mx-auto&quot;<br>            labels={{initial: &quot;Hi, I&#39;m an agent. Want to chat?&quot;}}<br>            suggestions={[{<br>                title: &quot;Weather in New York&quot;,<br>                message: &quot;What&#39;s the weather like in New York?&quot;<br>            },{<br>                title: &quot;Change background&quot;,<br>                message: &quot;Change the background to a right-to-left gradient from blue to green.&quot;<br>            }]}<br>        /&gt;<br>    &lt;/main&gt;<br>  );<br>}</pre><p>Frontend tools turn your app from a simple chat interface into an active, UI-aware assistant capable of controlling and updating interface components in real time. For example, if you refresh the page and then type, <strong>“Can you change the background of the app to red?” </strong>(See animation below), that request is sent to your ADK-AG-UI–powered backend.</p><p>Because the frontend tool definitions are synchronized with the agent’s context, the agent understands exactly which UI capabilities are available and how to invoke them. It responds by emitting the appropriate function-call event through ADK.</p><p>This function call is then routed back to the client, where the useFrontendTool handler intercepts the ADK event and executes the corresponding UI action. In this case, the handler updates a state variable, triggering React to re-render the component HomePage with the new background color.</p><p>By following this same pattern, you can define as many frontend tools as needed, enabling increasingly rich, interactive behaviors driven directly by agent intent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fAoOqWW3dw6ihfHeNjzW3A.gif" /></figure><p>Frontend tools are great, but what about when we want to render a custom component based on the output of a function called in the backend? In the previous section, when we defined our agent, we equipped it with two tools: get_weather and get_location. The question now becomes: how can we intercept the output of those tool calls on the client side so we can render our own custom UI components?</p><p>This is exactly what we are going to implement next. Fortunately, AG-UI makes this process straightforward through the useRenderToolCall hook, which lets us capture tool-call responses and render fully customized React components based on the tool’s output.</p><pre>    /* --------------------------------------------------------------------------------------------<br>     * RENDER WEATHER TOOL CALL<br>     * This visually renders the result of the get_weather tool.<br>     * ------------------------------------------------------------------------------------------*/<br>    useRenderToolCall({<br>        name: &quot;get_weather&quot;,<br>        description: &quot;Get the current weather for a specified location.&quot;,<br>        available: &quot;disabled&quot;, // Using MCP or manually invoking elsewhere<br>        parameters: [{name: &quot;location&quot;, type: &quot;string&quot;, required: true}],<br>        render: ({args, status, result}) =&gt; {<br>           // The result variable is the function response<br>            /* STATUS: inProgress --------------------------------------------------*/<br>            if (status === &quot;inProgress&quot;) {<br>                return (<br>                    &lt;div className=&quot;bg-[#667eea] text-white p-4 rounded-lg max-w-md&quot;&gt;<br>                        &lt;span className=&quot;animate-spin&quot;&gt;⚙️ Retrieving weather...&lt;/span&gt;<br>                    &lt;/div&gt;<br>                );<br>            }<br><br>            /* STATUS: complete ----------------------------------------------------*/<br>            if (status === &quot;complete&quot; &amp;&amp; result) {<br>            // Her we can render our custom component<br>                return (<br>                    &lt;div className=&quot;bg-white p-4 rounded-lg shadow-md max-w-md&quot;&gt;<br>                        &lt;h2 className=&quot;text-xl font-bold mb-2&quot;&gt;<br>                            Weather in {args.location}<br>                        &lt;/h2&gt;<br>                        &lt;p className=&quot;text-gray-700&quot;&gt;<br>                            Temperature: {result.result.temperature}°C<br>                        &lt;/p&gt;<br>                        &lt;p className=&quot;text-gray-700&quot;&gt;<br>                            Condition: {result.result.condition}<br>                        &lt;/p&gt;<br>                    &lt;/div&gt;<br>                )<br>            }<br>            return null;<br>        },<br>    });</pre><p>We’ve included the complete source code for this tutorial — including the GoogleMap and WeatherCard components—to create a more engaging visualization for displaying the weather and location data, in the following GitHub repository: <a href="https://github.com/haruiz/atlas_app.git">https://github.com/haruiz/atlas_app.git</a></p><p>To use the GoogleMap component, make sure to create an .env file in your Next.js application and define the following environment variable:</p><pre>NEXT_PUBLIC_GOOGLE_MAPS_API_KEY=&lt;YOUR GOOGLE MAPS API KEY&gt;</pre><pre>/* --------------------------------------------------------------------------------------------<br>    * RENDER PLACE LOCATION TOOL CALL<br>    * This visually renders the result of the get_place_location tool.<br>    * ------------------------------------------------------------------------------------------<br>    */<br><br>    useRenderToolCall({<br>        name: &quot;get_place_location&quot;,<br>        description: &quot;get the latitude and longitude of a place given its name.&quot;,<br>        available: &quot;disabled&quot;,<br>        parameters: [{name: &quot;place_name&quot;, type: &quot;string&quot;, required: true}],<br>        render: ({args, status, result}) =&gt; {<br>            if (status === &quot;inProgress&quot;) {<br>                return (<br>                    &lt;div className=&quot;bg-[#667eea] text-white p-4 rounded-lg max-w-md&quot;&gt;<br>                        &lt;span className=&quot;animate-spin&quot;&gt;⚙️ Retrieving location...&lt;/span&gt;<br>                    &lt;/div&gt;<br>                );<br>            }<br>            if (status === &quot;complete&quot; &amp;&amp; result) {<br>                const {result: coords} = result;<br>                return &lt;GoogleMap lat={coords?.latitude} lng={coords?.longitude}/&gt;;<br>            }<br>            return null;<br>        }<br>    })<br><br>    /* --------------------------------------------------------------------------------------------<br>     * RENDER WEATHER TOOL CALL<br>     * This visually renders the result of the get_weather tool.<br>     * ------------------------------------------------------------------------------------------*/<br>    useRenderToolCall({<br>        name: &quot;get_weather&quot;,<br>        description: &quot;Get the current weather for a specified location.&quot;,<br>        available: &quot;disabled&quot;, // Using MCP or manually invoking elsewhere<br>        parameters: [{name: &quot;location&quot;, type: &quot;string&quot;, required: true}],<br>        render: ({args, status, result : toolResponse}) =&gt; {<br>            /* STATUS: inProgress --------------------------------------------------*/<br>            if (status === &quot;inProgress&quot;) {<br>                return (<br>                    &lt;div className=&quot;bg-[#667eea] text-white p-4 rounded-lg max-w-md&quot;&gt;<br>                        &lt;span className=&quot;animate-spin&quot;&gt;⚙️ Retrieving weather...&lt;/span&gt;<br>                    &lt;/div&gt;<br>                );<br>            }<br><br>            /* STATUS: complete ----------------------------------------------------*/<br>            if (status === &quot;complete&quot; &amp;&amp; toolResponse) {<br>                const weatherResult: WeatherToolResult | null = toolResponse?.result || null;<br>                console.log(&quot;Weather Result:&quot;, weatherResult);<br>                if (!weatherResult) {<br>                    return (<br>                        &lt;div className=&quot;bg-red-300 text-red-900 p-4 rounded-lg max-w-md&quot;&gt;<br>                            &lt;strong&gt;⚠️ Error:&lt;/strong&gt; Unable to retrieve weather data. Please try again.<br>                        &lt;/div&gt;<br>                    );<br>                }<br>                // Choose color based on weather conditions<br>                const themeColor = getThemeColor(weatherResult.conditions);<br>                return (<br>                    &lt;WeatherCard<br>                        location={args.location}<br>                        themeColor={themeColor}<br>                        result={weatherResult}<br>                        status={status || &quot;complete&quot;}<br>                    /&gt;<br>                );<br>            }<br><br>            return null;<br>        },<br>    });</pre><p>At this point, if we run our application, we should see the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O4vDP_vCfi6qQoFil186DA.gif" /></figure><p>By the end of this walkthrough, we have built a fully functional agentic application that goes beyond a simple chat interface. Using <a href="https://google.github.io/adk-docs/"><strong>ADK</strong></a> to define and orchestrate our agents, and <a href="https://docs.ag-ui.com/introduction"><strong>AG-UI</strong></a> to standardize how agent execution is surfaced in the frontend, we created an experience where agents can reason, call tools, stream progress, render custom UI components, and interact with users in real time.</p><p>We encourage you to explore ADK and AG-UI more deeply: experiment with additional agents, introduce new frontend tools, render richer UI components, and test human-in-the-loop workflows in your own applications. The real power of this stack emerges when agents stop being isolated responders and start becoming collaborative, UI-aware participants in your application.</p><p>In upcoming posts, we’ll dive deeper into advanced patterns such as multi-agent coordination, cross-agent routing, long-running tasks, and richer UI orchestration with AG-UI, such as Agent-to-Agent (A2A) integration. Stay tuned, and follow along as we continue exploring how to build robust, human-centered agentic systems.</p><p><strong>Acknowledgements</strong></p><p><em>This work was supported by </em><strong><em>Google ML Developer Programs</em></strong><em> and the </em><strong><em>Google Developers Program</em></strong><em>, which provided Google Cloud credits and high-quality technical resources #AISprint</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a49ae6d3dc9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/google-cloud/building-interactive-agentic-applications-using-adk-and-ag-ui-protocol-3a49ae6d3dc9">Building interactive agentic applications using ADK and AG-UI protocol</a> was originally published in <a href="https://medium.com/google-cloud">Google Cloud - Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Science Notes: Introducción a Colab]]></title>
            <link>https://medium.com/@haruiz/data-science-notes-introducci%C3%B3n-a-colab-14512f262c2d?source=rss-4a509f6a939e------2</link>
            <guid isPermaLink="false">https://medium.com/p/14512f262c2d</guid>
            <category><![CDATA[colab]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Henry Ruiz]]></dc:creator>
            <pubDate>Sat, 20 Jul 2019 19:49:47 GMT</pubDate>
            <atom:updated>2019-09-02T16:17:32.836Z</atom:updated>
            <content:encoded><![CDATA[<h3>Data Science Notes: Introducción a Google Colab</h3><p>Antes de empezar a mencionar las bondades y características más relevantes de Google colab, quisiera primero introducir el concepto de <em>notebook document</em>, citando la definición tomada de la documentación oficial de <a href="https://jupyter.org/">jupyter</a>:</p><blockquote>Notebook documents (or “notebooks”, all lower case) are documents produced by the <a href="https://jupyter-notebook-beginner-guide.readthedocs.io/en/latest/what_is_jupyter.html#notebook-app">Jupyter Notebook App</a>, which contain both computer code (e.g. python) and rich text elements (paragraph, equations, figures, links, etc…). Notebook documents are both human-readable documents containing the analysis description and the results (figures, tables, etc..) as well as executable documents which can be run to perform data analysis.</blockquote><p>En otras palabras podemos afirmar que un notebook es un documento ejecutable que permite insertar además de código (R, python..etc), texto en formato html, imágenes, videos, enlaces e incluso comandos que usualmente se ejecutan en una <a href="https://en.wikipedia.org/wiki/List_of_terminal_emulators">terminal</a>.</p><p>teniendo claro dicha definición, pasemos a describir que es Colab:</p><p>Google Colab es un entorno de creación y edición de python notebooks(basado en jupyter), el cual nos permite escribir, compartir, ejecutar y documentar nuestro código de una forma intuitiva. Estos pueden ser ejecutado sobre la G<a href="https://en.wikipedia.org/wiki/Graphics_processing_unit">PU</a>, C<a href="https://en.wikipedia.org/wiki/Central_processing_unit">PU </a>o <a href="https://en.wikipedia.org/wiki/Tensor_processing_unit">TPU</a> y son compatibles con otros runtimes cómo jupyter y jupyter-lab.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XY1uFM_olXEOxEZmWLRzyg.png" /></figure><p>Es conveniente para realizar pruebas de conceptos y experimentar con conceptos de machine learning , deep learning, visión por computadora etc.. sin incurrir en costos de procesamiento en la nube, o tratando de aprovisionar un entorno local para desarrollar este tipo de soluciones. Dicho ambiente de trabajo ya viene con ciertas librerías pre-instaladas listas para utilizar, como por ejemplo Tensorflow, opencv, numpy lo que adicionalmente representa una reducción en el tiempo de configuración de nuestro ambiente de desarrollo.</p><p>A continuación les comparto algunos “code snippets” que les serán de utilidad(el código debe ser ejecutado en una celda en el notebook):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q0ur0nMkElgKrbRblcSp6Q.png" /></figure><p><strong>Guardar archivos en Google Drive: </strong>El Api de google colab nos permite desde nuestros notebooks guardar archivos de forma permanente y acceder a estos.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6d5c0fa37a29b40b988b1b0b1d4a40d8/href">https://medium.com/media/6d5c0fa37a29b40b988b1b0b1d4a40d8/href</a></iframe><p><strong>Cargar archivos a Google Drive:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f57051fa400a623e8a68ead4be81bc8f/href">https://medium.com/media/f57051fa400a623e8a68ead4be81bc8f/href</a></iframe><p><strong>Listar Archivos de Google Drive: </strong>En ocasiones nos interesa saber que archivos tenemos almacenados en un folder en particular de nuestro drive, para ello podemos usar el siguiente código</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fadb7b8975cd07329e0a70250b33e3e5/href">https://medium.com/media/fadb7b8975cd07329e0a70250b33e3e5/href</a></iframe><p>Para más información les dejo este video que encontré en el canal de tensorflow en youtube que les podrá servir cómo complemento a la información subministrada en este post:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FinN8seMm7UI%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DinN8seMm7UI&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FinN8seMm7UI%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/372221b8074279245838247d98596ed0/href">https://medium.com/media/372221b8074279245838247d98596ed0/href</a></iframe><p><a href="https://colab.research.google.com/drive/16fcbPurht92ESKOitUKeidkkyOqRsnxG">link notebook</a></p><p>Muchas gracias y espero este contenido les pueda ser utíl,</p><p>Henry Ruiz</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=14512f262c2d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>