Agent Development Kit (ADK)

repository·main·Indexed 12 days ago

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

An open-source, code-first Python framework for building, evaluating, and deploying AI agents. ADK 2.0 features a graph-based workflow runtime, a structured Task API, and specialized components like LlmAgent, ManagedAgent, and the Agent Builder Assistant. It supports complex agentic orchestration with features for memory management, self-healing plugins, and integrations for Slack, GCP IAM, and Model Context Protocol (MCP) servers.

Tokens
40.3K
Snippets
102
Records
153
Agent score
98%

What's inside ADK

  1. Explore ADK Developer Guides

    main

    The ADK Python implementation provides several specialized guides for building complex agentic systems. Key areas of focus include:

    • Agents: Configuring LlmAgent for single-turn or task-based modes, and using ManagedAgent with server-side tools.
    • Events: Managing Event and NodeInfo within workflows, and using RequestInput for human-in-the-loop patterns.
    • Memory: Utilizing BaseMemoryService to store and recall finished sessions.
    • Plugins: Implementing self-healing error recovery using ReflectAndRetryModelPlugin (for model failures) and ReflectAndRetryToolPlugin (for tool failures).
    • Sessions: Managing the session lifecycle and state scoping via Session and BaseSessionService.
    • Tools: Exposing an ADK agent as a Model Context Protocol (MCP) server using to_mcp_server.
    • Workflows: Orchestrating multi-step interactions using graph-based structures, including Function Nodes, JoinNode for synchronization, ParallelWorker for concurrency, and Dynamic Nodes for runtime scheduling.
  2. Prioritize Measures over Standard SQL Aggregations

    main

    To maintain the integrity of business logic defined within the semantic graph, you must prioritize using pre-defined measures (columns with is_measure=TRUE) over writing manual SQL aggregations (like COUNT(DISTINCT ...) or SUM()).

    Why this matters: Semantic graphs embed specific business logic within measures to prevent errors like overcounting. Bypassing these measures with standard SQL aggregations ignores that logic and can lead to incorrect results.

    -- Scenario: User asks for "total number of entities"
    -- Schema provides: Entity_id (STRING) and Entity_count (INT64 OPTIONS(is_measure=TRUE))
    
    -- INCORRECT (Standard SQL):
    SELECT COUNT(DISTINCT Entity_id) AS total_entities FROM GRAPH_EXPAND("...");
    
    -- CORRECT (Using Measure):
    SELECT AGG(Entity_count) AS total_entities FROM GRAPH_EXPAND("...");
  3. How session continuity works in MCP servers

    main

    The to_mcp_server implementation maintains session continuity based on the transport type:

    • stdio transport: There is one connection per process. All tool calls made through that process share a single ADK session, forming a single multi-turn conversation.
    • streamable-http transport: Each unique client connection is assigned its own ADK session.

    Sessions are mapped using a weakref.WeakKeyDictionary, meaning a session is automatically dropped when its connection is garbage-collected. For long-lived networked servers, it is recommended to provide a custom Runner with a persistent session service to prevent session accumulation and data loss on restarts.

  4. Follow ADK project structure and naming conventions

    main

    To ensure compatibility with the Agent Builder Assistant's validation and analysis tools, follow these organizational patterns:

    Directory Structure

    my_adk_project/
    └── src/
        └── my_app/
            ├── root_agent.yaml
            ├── sub_agent_1.yaml
            ├── sub_agent_2.yaml
            ├── tools/
            │   ├── process_email.py    # Note: No '_tool' suffix
            │   └── analyze_sentiment.py
            └── callbacks/
                ├── logging.py          # Note: No '_callback' suffix
                └── security.py

    Naming Rules

    • Agent directories: Use snake_case.
    • Tool files: Use descriptive_action.py (do not append _tool).
    • Callback files: Use descriptive_name.py (do not append _callback).
    • Tool paths: Format as project_name.tools.module.function_name.
    • Callback paths: Format as project_name.callbacks.module.function_name.
  5. Define Measures in Semantic Graphs

    main

    Measures represent predefined calculations or aggregations (e.g., business metrics) defined within a PROPERTIES block.

    Syntax: MEASURE(AGG_FUNC(column)) AS measure_name

    Supported Aggregations: SUM, COUNT, AVG, MIN, MAX, COUNT(DISTINCT ...).

    Critical Requirement (Dimension Property): Any source column used inside a MEASURE aggregate expression MUST also be explicitly declared as a standard dimension property in the same PROPERTIES(...) block. If you aggregate a column that is not exposed as a dimension, the query will fail.

    Example:

    PROPERTIES (
      amount, -- Dimension property (MANDATORY)
      MEASURE(SUM(amount)) AS total_order_amount
    )
    PROPERTIES (
      amount, -- Expose 'amount' as a dimension property (MANDATORY)
      MEASURE(SUM(amount)) AS total_order_amount -- Aggregate the dimension property
    )
  6. How session resumption works in AntigravityAgent

    main

    For standalone agents (not in single_turn mode), AntigravityAgent uses the save_dir in the LocalAgentConfig to persist conversation state.

    Mechanism:

    1. Conversation ID: The wrapper derives a conversation_id by taking the sha256 hex digest of <session_id>/<agent_name>.
    2. Persistence: The SDK saves state to a traj-<derived_conversation_id> file.
    3. Resumption: On subsequent turns within the same ADK session, the wrapper passes the derived ID. If the file exists, the SDK rehydrates the conversation.
    4. Step Management: To prevent re-emitting old turns into the ADK session, the wrapper uses a .resume file (e.g., traj-<...>.resume) to track the highest step_index already emitted. Steps at or below this index are skipped during rehydration.

    Note: This mechanism does not apply to mode='single_turn' agents, as they are designed to be isolated and stateless.

  7. Validate user input against response_schema

    main
    While the ADK handles parsing the response upon resumption, it is highly recommended that the client application performs client-side validation using the provided response_schema. This ensures that the data sent back to the workflow is correct, providing a better user experience and preventing errors during the workflow's resumption phase.
  8. Use the Event class to represent interactions

    main

    In ADK, the Event class is the fundamental data structure used to model conversations and workflow executions as a sequence of events. An Event captures:

    • Content: Messages (text, function calls, function responses).
    • Actions: Side-effects like state updates, routing decisions, agent transfers, or UI rendering requests.
    • Metadata: Information about the author, timestamp, and the workflow node that generated the event.

    Key classes that depend on Event include Session (for event history) and Workflow / NodeRunner (for execution flow and state management).

    from google.adk.events.event import Event
    
    # Create a simple event
    event = Event(author="user", message="Hello!")
  9. Construct GQL Queries using Sequential Statements and NEXT

    main

    BigQuery GQL queries execute clauses sequentially, where the output of one clause serves as the input for the next.

    Common Sequential Statements

    • MATCH: Identifies topological patterns.
    • WITH: Projects variables into the next scope (supports ORDER BY, LIMIT, GROUP BY).
    • LET: Defines new variables or aliases.
    • FILTER: Filters intermediate graph mappings.
    • RETURN: Ends the query and projects final variables.

    Chaining with NEXT

    You can compose multiple linear statements into a compound query using the NEXT keyword. The results of the first statement are piped into the statement following NEXT.

    GRAPH <project>.<dataset>.<graph>
    MATCH (blocked:Account WHERE blocked.is_frozen = true)
    RETURN blocked.id AS frozen_id
    NEXT
    MATCH (a:Account)-[t:Transfers]->(b:Account)
    FILTER a.id = frozen_id
    RETURN a.id AS source, b.id AS destination, t.amount AS amount
  10. Use the bigquery-ai-ml skill for BigQuery AI/ML tasks

    main

    The bigquery-ai-ml skill is designed for performing BigQuery AI and Machine Learning operations using standard SQL and AI.* functions.

    Best Practice: Agents should prefer using this Skill (via execute_sql()) over dedicated BigQuery tools for tasks such as Forecasting and Anomaly Detection. Instead of using high-level tools, use execute_sql() with the appropriate BigQuery AI.* functions.