Agent Development Kit (ADK) JS

repository·main·Indexed 23 days ago

https://github.com/google/adk-js

An open-source, code-first TypeScript toolkit for building, evaluating, and deploying AI agents in Node.js and browser runtimes. It features multi-agent orchestration, Zod schema validation, and a rich tool ecosystem including Google Search and Vertex AI Search. The toolkit includes the @google/adk core SDK, @google/adk-devtools for CLI and Web UI testing, and @google/adk-integrations for external service connectivity. It supports deployment to Google Cloud Run and provides A2A (Agent-to-Agent) protocol support for inter-agent communication via REST and JSON-RPC.

Tokens
21.5K
Snippets
30
Records
126
Agent score
80%

What's inside adk-js

  1. Overview of Agent Development Kit (ADK)

    main

    Agent Development Kit (ADK) is an open-source, code-first TypeScript toolkit for building, evaluating, and deploying sophisticated AI agents. It is designed for both Node.js and browser environments, offering full type safety and Zod schema validation.

    Key Capabilities:

    • Multi-Agent Orchestration: Compose agents into sequential, parallel, loop, and routed workflows, or delegate to remote agents via the A2A protocol.
    • Rich Tool Ecosystem: Includes built-in tools (Google Search, Google Maps, Vertex AI Search) and supports connecting MCP servers or wrapping any function as a tool.
    • Deployment: Supports deployment to various environments, including Google Cloud Run via adk deploy cloud_run.
  2. Overview of ADK Integrations

    main
    The @google/adk-integrations package provides ready-to-use integrations designed for the Google Agent Development Kit (ADK). These integrations allow you to extend the capabilities of your agents by connecting them to various external services and platforms supported by the ADK ecosystem.
  3. Manage agent sessions with runEphemeral and session isolation

    main

    ADK TS provides mechanisms to manage agent state and prevent history leakage between runs:

    • runEphemeral: Use this helper for temporary session creation. It ensures a clean slate for each run while allowing you to pass an initial stateDelta.
    • Resumable Invocations: You can hydrate agent state from persisted sessions to support multi-turn conversations across separate execution instances (e.g., across different CLI calls).
  4. Implement Human-in-the-Loop (HITL) tool approval

    main

    To implement safety mechanisms where sensitive tool operations require user consent, use the Runner's confirmation callback mechanism:

    1. Configure a Confirmation Callback: Provide a callback to the Runner to handle tool approval requests.
    2. Handle Tool Confirmation Events: When a tool requires confirmation, the Runner yields a tool confirmation request event.
    3. Suspend Execution: CRITICAL: The host application must explicitly suspend or exit the agent loop after yielding the confirmation event to return control to the user.
    4. Resume Execution: Once the user provides approval, the host application resumes the agent execution with the result.
  5. Run and test agents with the ADK CLI and Web UI

    main

    Once your agent is defined, you can test and debug it using the provided CLI commands from your agent project directory.

    • Interactive CLI: Use npx adk run <file> to run an agent file interactively.
    • Web UI: Use npx adk web to launch a development UI designed for testing and debugging agent workflows and function calls.
    # Interactive CLI
    npx adk run agent.ts
    
    # Web UI
    npx adk web
  6. Install the Agent Development Kit (ADK)

    main

    To use ADK in your TypeScript project, install the core SDK and the dev tools (CLI and dev UI) as a development dependency.

    Prerequisite: Requires a current Node.js LTS release.

    Using npm:

    npm install @google/adk
    npm install -D @google/adk-devtools

    Using yarn:

    yarn add @google/adk
    yarn add -D @google/adk-devtools
  7. Format of an ADK Input File for automated testing

    main

    To use the inputFile option in runAgent, provide a JSON file that follows this structure. This allows you to automate a sequence of queries and pre-set the agent's state.

    {
      "state": {
        "key": "value"
      },
      "queries": [
        "Hello, agent!",
        "What is the current state?"
      ]
    }
    interface InputFile {
      state: Record<string, unknown>;
      queries: string[];
    }
  8. How session resumption works in ADK

    main

    Session resumption allows an agent workflow to continue across tool boundaries or Long Running Operations (LROs). The Runner uses determineAgentForResumption to decide which agent should handle the next step in a session.

    Resumption Logic:

    1. Function Response Resumption: If the last event in a session is a function response and resumabilityConfig.isResumable is enabled, the Runner attempts to find the agent that originally made the function call.
    2. Transferable Agent Scan: If Case 1 doesn't apply, the Runner scans the session events in reverse order to find the last agent that emitted a message. An agent is considered "routable" (transferable) if:
      • It is an instance of LlmAgent.
      • All its ancestors have disallowTransferToParent set to false.
    3. Fallback: If no suitable agent is found, it defaults to the rootAgent.
  9. Define and register FunctionTools

    main

    A FunctionTool is used to provide agents with executable capabilities. You define a tool by providing a name, description, and a parameters schema (using zod). The execute function contains the logic to run when the tool is called.

    Example of a FunctionTool for searching flights:

    import { FunctionTool } from '@google/adk';
    import { z } from 'zod';
    
    export const searchFlights = new FunctionTool({
      name: 'search_flights',
      description: 'Search for flights based on trip details and preferences.',
      parameters: z.object({
        trip: z.object({
          origin: z.string().describe('Departure city or airport code'),
          destination: z.string().describe('Arrival city or airport code'),
          departureDate: z.string().describe('Departure date in YYYY-MM-DD format'),
          returnDate: z.string().optional().nullable().describe('Return date in YYYY-MM-DD format, or None for one-way trip'),
        }),
        preferences: z.object({
          cabinClass: z.string().default('economy'),
          maxStops: z.number().default(1),
          preferredAirline: z.string().optional().nullable(),
          flexibleDates: z.boolean().default(false),
        }).optional(),
      }),
      execute: (input) => {
        // Implementation logic
        return { search_status: 'completed', /* ... */ };
      },
    });
  10. Define and register LongRunningFunctionTools

    main

    A LongRunningFunctionTool is used for tasks that do not complete immediately (e.g., requiring human approval). Unlike a standard FunctionTool, its execute method can return a pending status.

    Example of an approval tool:

    import { LongRunningFunctionTool } from '@google/adk';
    import { z } from 'zod';
    
    export const askForApproval = new LongRunningFunctionTool({
      name: 'ask_for_approval',
      description: 'Ask for approval for the reimbursement.',
      parameters: z.object({
        purpose: z.string(),
        amount: z.number(),
      }),
      execute: ({purpose, amount}, context) => {
        return {
          status: 'pending',
          amount: amount,
          ticketId: 'reimbursement-ticket-001',
        };
      },
    });
  11. Use Agent Callbacks (Before and After)

    main

    Callbacks allow you to intercept agent execution to modify state or inject content.

    • Before Agent Callbacks: Executed before the agent processes a request. They can modify the Context.state or return Content to provide a direct response to the user, effectively short-circuiting the agent.
    • After Agent Callbacks: Executed after the agent has finished its turn. These are useful for post-processing or logging.

    Callbacks follow the SingleAgentCallback signature and receive a Context object. Returning Content (from @google/genai) allows you to provide a model-like response immediately.

  12. Understand the StructuredEvent types

    main

    The ADK uses StructuredEvent to represent the various types of output an agent can produce during a turn. When consuming an event stream, you can use the EventType enum to distinguish between different categories of information.

    Common event types include:

    • THOUGHT: A reasoning trace emitted by the model.
    • CONTENT: Text deltas intended for the end user.
    • TOOL_CALL: A request to execute a tool (function call).
    • TOOL_RESULT: The result returned by a tool execution.
    • CALL_CODE: A request to execute code.
    • CODE_RESULT: The result of code execution.
    • ERROR: A runtime error signaled via event.errorCode.
    • ACTIVITY: A generic status update.
    • TOOL_CONFIRMATION: A request for the user to confirm tool calls.
    • FINISHED: Indicates the agent has completed its task for the current turn.