Integrate a context set with an application

This tutorial describes how to set up and use context sets in Cloud SQL for PostgreSQL using the Google Cloud console and integrate it with your application. Learn how to build the context set file, create a context set that uses the context set file, use MCP Toolbox to call the QueryData API to generate SQL queries for natural language questions, and integrate it with your application.

For more information, see Context sets overview.

Objectives

  • Create database tables and populate them with data.
  • Build a context set file with Gemini CLI and MCP toolbox.
  • Create a context set and upload context set file.
  • Test the context set and generate SQL queries in Studio.
  • Integrate the context set with your application using Gemini Data Analytics QueryData tool in MCP Toolbox.
  • Add grounding to LLM responses using value search queries.

Costs

In this document, you use the following billable components of Google Cloud:

To generate a cost estimate based on your projected usage, use the pricing calculator.

New Google Cloud users might be eligible for a free trial.

To avoid continued billing, delete the resources you created when you finish the tasks in this document. For more information, see Clean up.

Before you begin

Complete the following prerequisites before creating a context set.

Enable required services

Enable the following services for your project:

Prepare a Cloud SQL instance

Make sure that you have access to an existing Cloud SQL instance or create a new one. For more information, see Create instances for Cloud SQL.

This tutorial requires you to have a database in your Cloud SQL instance. For more information, see Create a database on the Cloud SQL instance

Required roles and permissions

Grant executesql permission to Cloud SQL instance

To grant the executesql permission to Cloud SQL instance and enable the Cloud SQL Data API, run the following command:
gcloud config set project PROJECT_ID
gcloud components update
gcloud beta sql instances patch INSTANCE_ID --data-api-access=ALLOW_DATA_API
Replace the following:
  • PROJECT_ID: The ID of your Google Cloud project.
  • INSTANCE_ID: The ID of your Cloud SQL instance.
To perform steps in this tutorial, sign in to Google Cloud, and then authenticate to the database using IAM authentication.

Create the flights and airports schema and tables

In this section, you create the flights and airports database tables for this tutorial.

  1. In the Google Cloud console, go to the Cloud SQL page.

    Go to Cloud SQL

  2. Select an instance from the list.

  3. In the navigation menu, click Cloud SQL Studio.

  4. Sign in to Studio using Identity and Access Management authentication.

  5. Click Authenticate. The Explorer pane displays a list of the objects in your database.

  6. Click New SQL editor tab or New tab to open a new tab.

  7. To create the airports table and schema, execute the following SQL statement:

    CREATE TABLE IF NOT EXISTS airports (
      id INT PRIMARY KEY,
      iata TEXT,
      name TEXT,
      city TEXT,
      country TEXT
      );
    
  8. Create the flights table and schema:

    CREATE TABLE IF NOT EXISTS flights (
      id INT PRIMARY KEY,
      airline VARCHAR(10),
      flight_number INT,
      departure_airport VARCHAR(5),
      arrival_airport VARCHAR(5),
      departure_time TIMESTAMP,
      arrival_time TIMESTAMP,
      departure_gate VARCHAR(10),
      arrival_gate VARCHAR(10)
    );
    

Populate the flights and airports tables

In this section, you populate the flights and airports tables using the provided SQL scripts.

  1. Populate the airports table.

  2. Populate the flights table.

  3. Run the following query to verify that the tables are populated:

    SELECT * FROM "public"."flights" LIMIT 10;
    SELECT * FROM "public"."airports" LIMIT 10;
    

Create a context set in Studio

In this section, create a context set named flights-assistant. This context set doesn't include any context set file uploaded to it.

  1. In the Google Cloud console, go to the Cloud SQL page.

    Go to Cloud SQL

  2. Select an instance from the list.

  3. In the navigation menu, click Cloud SQL Studio.

  4. Sign in to Studio using IAM authentication.

  5. In the Explorer pane, next to Context sets, click View actions.

  6. Click Create context set.

  7. In Context set name, enter flights-assistant.

  8. Click Create.

Test the context set in Studio

In this section, ask the flights-assistant context set a natural language question to generate a SQL query. Since the context set doesn't have any context set file uploaded to it, even after asking a question with context such as nighttime traffic, QueryData generates a sub-optimal query.

  1. In the Explorer pane, next to your context set, click View actions.
  2. Click Test context set.
  3. In the query editor, click Generate SQL using QueryData with: flights-assistant.
  4. Enter the following natural language question to generate a SQL query, and click Generate.

    Find flights from SFO to JFK.
    

    Review the SQL query. Notice that QueryData generates the correct SQL for this unambiguous question.

      SELECT
        *
      FROM
        "flights"
      WHERE
        "departure_airport" = 'SFO' AND "arrival_airport" = 'JFK';
    
  5. In the Generate SQL using QueryData with: flights-assistant window, click Edit.

  6. Enter the following natural language question to generate a SQL query, and click Update.

    Tell me flights that can help me beat nighttime traffic if traveling from New York
    

    The database fails to understand the term nighttime traffic. This might prevent it from generating a SQL query or cause it to generate a query that ignores the term, as the following query shows.

    -- The database schema does not contain information about traffic.
    -- Returning all flights departing from New York airports.
    SELECT
      f.airline,
      f.flight_number,
      a.name AS departure_airport_name,
      f.departure_time,
      b.name AS arrival_airport_name,
      f.arrival_time
    FROM
      flights AS f
    JOIN
      airports AS a
      ON f.departure_airport = a.iata
    JOIN
      airports AS b
      ON f.arrival_airport = b.iata
    WHERE
      a.city = 'New York'
    ORDER BY
      f.departure_time;
    
  7. In the Generate SQL using QueryData with: flights-assistant window, click Edit.

  8. Enter the following natural language question to generate a SQL query, and click Update.

    flight to disney world
    

    The context set logic generates a query to find an airport with "disney world" in its name. Since no such airport or city exists in the database, the query won't return any rows.

    SELECT
      "flights"."id",
      "flights"."airline",
      "flights"."flight_number",
      "flights"."departure_airport",
      "flights"."arrival_airport",
      "flights"."departure_time",
      "flights"."arrival_time",
      "flights"."departure_gate",
      "flights"."arrival_gate"
    FROM
      "flights"
    INNER JOIN
      "airports" ON "flights"."arrival_airport" = "airports"."iata"
    WHERE
      "airports"."name" ILIKE '%Disney World%';
    

Generate context for the context set

In this section, you create a context file that helps improve the context set's querying capabilities.

Set up your environment

Before you can start generating context, you must prepare your environment.

To set up your environment, perform the following steps:

  1. Install Gemini CLI. For more information, see Gemini CLI quickstart.
  2. Install the gcloud CLI.
  3. Set up Application Default Credentials (ADC). Run the following commands in your terminal to authenticate and select your project:

    gcloud auth application-default login
  4. Install the DB Context Enrichment extension, which includes workflows for context generation.

    gemini extensions install https://github.com/GoogleCloudPlatform/db-context-enrichment

    Ensure that the version is 0.4.2 or higher. To update the DB Context Enrichment extension, run the following command:

    gemini extensions update mcp-db-context-enrichment
  5. To update the DB Context Enrichment extension or to replace the GEMINI_API_KEY, run the following command:

    gemini extensions config mcp-db-context-enrichment GEMINI_API_KEY

    Replace GEMINI_API_KEY with your Gemini API key.

  6. In your terminal, start Gemini CLI.

    gemini
  7. Complete the Gemini CLI Authentication Setup.

  8. Set up Database Connection. The extension requires a database connection for context generation, which is supported by the MCP Toolbox and defined within the tools.yaml configuration file.

    To create the tools.yaml configuration file in your current directory, enter a prompt such as Help me set up the database connection and follow the instructions provided by the skill. For more information about the tools.yaml file, see MCP Toolbox documentation.

  9. To reload the configuration after creating the tools.yaml file is created, run the following command in the Gemini CLI:

    /mcp reload
  10. Verify that the MCP toolbox and the database enrichment extension are connected and ready to use.

    /mcp list

Generate template context

In this section, to address the issue from the previous section where QueryData didn't recognize the term nighttime traffic, define the term in the context set file as traffic occurring between 5:00 PM and 7:00 PM.

To generate template context, perform the following steps:

  1. Run the /generate_targeted_templates command and follow the workflow:

    /generate_targeted_templates
  2. Provide the natural language query that you want to add to the query template in the terminal.

    Tell me flights that can help me beat nighttime traffic if traveling from New York
  3. Provide a corresponding SQL query that you want to add to the query template. This query template defines the term nighttime as occurring between 5:00 PM and 7:00 PM.

    SELECT
      f.airline,
      f.flight_number,
      a.name AS airport_name,
      f.departure_time
    FROM
      flights f
    JOIN
      airports a
      ON f.departure_airport = a.iata
    WHERE
      a.city = 'New York'
      AND (
        EXTRACT(HOUR FROM f.departure_time) < 17
        OR EXTRACT(HOUR FROM f.departure_time) >= 19
      )
    ORDER BY
      f.departure_time;
    
  4. Press Enter. Gemini converts your input into a specific format that refines the context set's performance across a wide range of user queries. For more information, see Context sets overview.

    Optionally, run the /generate_bulk_templates workflow to let Gemini CLI generate more context by scanning your database schema and suggesting related context.

  5. Review the generated query template. You can either save the query template as a new agent context file or append it to an existing agent context file.

  6. Select the option to create a new agent context file. Gemini creates a filename INSTANCE_ID_DATABASE_ID_context_set_TIMESTAMP.json in the same directory, with the following content:

    {
      "templates": [
        {
          "nl_query": "Tell me flights that can help me beat nighttime traffic if traveling from New York",
          "sql": "SELECT f.airline, f.flight_number, a.name AS airport_name, f.departure_time FROM flights f JOIN airports a ON f.departure_airport = a.iata WHERE a.city = 'New York' AND (EXTRACT(HOUR FROM f.departure_time) < 17 OR EXTRACT(HOUR FROM f.departure_time) >= 19) ORDER BY f.departure_time;",
          "intent": "Tell me flights that can help me beat nighttime traffic if traveling from New York",
          "manifest": "Tell me flights that can help me beat nighttime traffic if traveling from a given city",
          "parameterized": {
            "parameterized_sql": "SELECT f.airline, f.flight_number, a.name AS airport_name, f.departure_time FROM flights f JOIN airports a ON f.departure_airport = a.iata WHERE a.city = ? AND (EXTRACT(HOUR FROM f.departure_time) < 17 OR EXTRACT(HOUR FROM f.departure_time) >= 19) ORDER BY f.departure_time;",
            "parameterized_intent": "Tell me flights that can help me beat nighttime traffic if traveling from ?"
          }
        }
      ]
    }
    

Generate value search context

In this section, you generate value search context to help context set logic map value phrases to specific values stored in your database columns. For example, if a user asks for "Flights to Disney World", value search can map this to Disney World in "Orlando" city based on the concept type that correlates to the airports.city column in your database.

To generate value search context, perform the following steps:

  1. Run the /generate_targeted_value_searches command:

    /generate_targeted_value_searches
  2. Enter postgresql to select Cloud SQL as the database engine.

  3. Enter the value search configuration as follows:

    Table: airports
    Column: city
    Concept: Airport City
    Match Function: SEMANTIC_SIMILARITY_MATCH
  4. Confirm if you want to generate the value search definition.

  5. Review the generated value search definition. You can either save the value search definition as a new context set file or append it to an existing context set file.

  6. Select the option to append to an existing context set file. This adds the value search definition to the context file created in the earlier section.

  7. Enter the database instance and database name for which the context set file was generated.

    The existing context file is updated with the value search definition. Gemini creates a filename INSTANCE_ID_DATABASE_ID_context_set_TIMESTAMP.json in the same directory, with the following content:

      {
        "templates": [
          {
            "nl_query": "Tell me flights that can help me beat nighttime traffic if traveling from New York",
            "sql": "SELECT f.airline, f.flight_number, a.name AS airport_name, f.departure_time FROM flights f JOIN airports a ON f.departure_airport = a.iata WHERE a.city = 'New York' AND (EXTRACT(HOUR FROM f.departure_time) < 17 OR EXTRACT(HOUR FROM f.departure_time) >= 19) ORDER BY f.departure_time;",
            "intent": "Tell me flights that can help me beat nighttime traffic if traveling from New York",
            "manifest": "Tell me flights that can help me beat nighttime traffic if traveling from a given city",
            "parameterized": {
              "parameterized_sql": "SELECT f.airline, f.flight_number, a.name AS airport_name, f.departure_time FROM flights f JOIN airports a ON f.departure_airport = a.iata WHERE a.city = $1 AND (EXTRACT(HOUR FROM f.departure_time) < 17 OR EXTRACT(HOUR FROM f.departure_time) >= 19) ORDER BY f.departure_time;",
              "parameterized_intent": "Tell me flights that can help me beat nighttime traffic if traveling from $1"
            }
          }
        ],
        "value_searches": [
          {
              "query": "/* Requires extensions: vector, google_ml_integration */ WITH SemanticMetrics AS (    SELECT T.city AS original_value, (        (google_ml.embedding('gemini-embedding-001', $value)::vector <=>          google_ml.embedding('gemini-embedding-001', T.city)::vector) / 2.0    ) AS normalized_dist     FROM airports T     WHERE T.city IS NOT NULL) SELECT original_value AS value, 'airports.city' AS columns, 'Airport City' AS concept_type, normalized_dist AS distance, ''::text AS context FROM SemanticMetrics",
              "concept_type": "Airport City",
              "description": "Semantic search for airport city name"
          }
      ]
      }
    

Upload context set file to the QueryData

In this section, you upload the context set file to QueryData, so that it improves the QueryData's SQL generation capabilities on your database.

To upload the context, perform the following steps:

  1. In the Google Cloud console, go to the Cloud SQL page.

    Go to Cloud SQL

  2. Select an instance from the list.

  3. In the navigation menu, click Cloud SQL Studio.

  4. Sign in to Studio using Identity and Access Management authentication.

  5. In the Explorer pane, next to Context sets, click the Actions () icon.

  6. Click Edit context set.

  7. Optional: Edit Context set description.

  8. Click Browse in the Upload context set file section, and select the context set file generated earlier.

  9. Click Save.

Generate SQL query using context set

In this section, you use the context set file you uploaded to ask natural language questions. This lets you verify that QueryData correctly understands and applies definitions for terms like nighttime traffic and other related phrases, and that value search maps value phrases to specific values stored in your database columns (for example, mapping "Disney World" to "Orlando")

To generate SQL queries, perform the following steps:

  1. In the Explorer pane, next to your context set, click View actions.
  2. Click Test context set.
  3. In the query editor, click Generate SQL using QueryData with: flights assistant.
  4. Enter the following natural language question to generate a SQL query, and click Generate.

    Tell me flights that can help me beat nighttime traffic if traveling from New York

    The generated SQL query looks similar to the following:

    SELECT
      f.airline,
      f.flight_number,
      a.name AS airport_name,
      f.departure_time
    FROM
      flights f
    JOIN
      airports a ON f.departure_airport = a.iata
    WHERE
      a.city = 'New York'
      AND (
        EXTRACT(HOUR FROM f.departure_time) < 17
        OR EXTRACT(HOUR FROM f.departure_time) >= 19
      )
    ORDER BY
      f.departure_time;
    

    This is the same question you added to QueryData's context. Observe that QueryData can now accurately interpret the term nighttime traffic.

    Although the context originates from one particular question, QueryData uses it to enhance SQL generation for a wide range of similar questions.

  5. In the Generate SQL using QueryData with: flights-assistant window, click Edit.

  6. Enter the following similar question to generate a SQL query, and click Update.

    What are the flights that can help me avoid evening traffic if departing from Boston

    Since the question replaces the term nighttime traffic with a similar term, evening traffic, QueryData provides a consistent answer to this question by applying the same interpretation.

    The generated SQL query looks similar to the following:

    -- What are the flights that can help me avoid evening traffic if departing from Boston
    SELECT
      f.airline,
      f.flight_number,
      a.name AS airport_name,
      f.departure_time
    FROM
      flights f
    JOIN
      airports a
    ON
      f.departure_airport = a.iata
    WHERE
      a.city = 'Boston'
      AND (
        EXTRACT(HOUR FROM f.departure_time) < 17
        OR EXTRACT(HOUR FROM f.departure_time) >= 19
      )
    ORDER BY
      f.departure_time;
    
  7. In the Generate SQL using QueryData with: flights-assistant window, click Edit.

  8. Enter the following question to generate a SQL query, and click Update.

    flights to disney world

    The generated SQL query looks similar to the following:

    SELECT
      "flights"."id",
      "flights"."airline",
      "flights"."flight_number",
      "flights"."departure_airport",
      "flights"."arrival_airport",
      "flights"."departure_time",
      "flights"."arrival_time",
      "flights"."departure_gate",
      "flights"."arrival_gate"
    FROM
      "flights"
    JOIN
      "airports" ON "flights"."arrival_airport" = "airports"."iata"
    WHERE
      "airports"."city" = 'Orlando';
    

    Observe that QueryData can now accurately interpret that "disney world" relates to the city of "Orlando".

Integrate the context set with your application

In this section, you create a QueryData agent for a flight-finding application. This QueryData agent provides a conversational interface to the flights and airports table you created earlier. It also explains how to create and integrate this QueryData agent into your application using Agent Development Kit (ADK), the Gemini Data Analytics QueryData MCP tool, and context set to improve quality of the responses.

  1. Download MCP Toolbox version 0.31.0 or later. MCP toolbox exposes the QueryData agent as a tool for applications to connect with. The MCP toolbox differs from the MCP Toolbox Gemini CLI extension you installed earlier, which generates context.

  2. Set up Application Default Credentials (ADC).

    gcloud auth application-default login
  3. Find the context set ID. For more information about how to find the context set ID, see Find the context set ID.

  4. Create the tools.yaml configuration to connect to the QueryData agent using the MCP toolbox. For more information, see Gemini Data Analytics Source and Gemini Data Analytics QueryData Tool.

    kind: source
    name: gda-api-source
    type: cloud-gemini-data-analytics
    projectId: "PROJECT_ID"
    ---
    kind: tool
    name: cloud_gda_query_tool
    type: cloud-gemini-data-analytics-query
    source: gda-api-source
    description: Use this tool to send natural language queries to the Gemini Data Analytics API and receive SQL, natural language answers, and explanations.
    location: "REGION_ID"
    context:
      datasourceReferences:
        cloudSqlReference:
          databaseReference:
            engine: "POSTGRESQL"
            projectId: "PROJECT_ID"
            region: "REGION_ID"
            instanceId: "INSTANCE_ID"
            databaseId: "DATABASE_ID"
          agentContextReference:
            contextSetId: "CONTEXT_SET_ID"
    generationOptions:
      generateQueryResult: true
      generateNaturalLanguageAnswer: true
      generateExplanation: true
      generateDisambiguationQuestion: true
    

    Replace the following:

    • PROJECT_ID: Your Google Cloud project ID.
    • REGION_ID: The region of your Cloud SQL instance (e.g., us-central1).
    • INSTANCE_ID: The ID of your Cloud SQL instance.
    • DATABASE_ID: The name of the database to connect to.
    • CONTEXT_SET_ID: The context set ID. For more information about how to find the context set ID, see Find the context set ID.
  5. Run the MCP Toolbox server with the tools.yaml file.

    ./toolbox --config "tools.yaml"
  6. Create an ADK application that invokes Gemini Data Analytics QueryData tool using the MCP Toolbox's Python SDK. For more information about how to use the MCP Toolbox's Python SDK, see the quickstart for Toolbox and for Python ADK, see the quickstart for ADK.

    1. Create a directory to store the application, for example flight-assistant-app.
    2. Change directory to the flight-assistant-app directory.

      mkdir flight-assistant-app
      cd flight-assistant-app
    3. Run the following commands under the flight-assistant-app directory to create a virtual environment and install required components.

      python3 -m venv .venv
      source .venv/bin/activate
      pip install toolbox-core
      pip install google-genai
      pip install google-adk
    4. Set up an ADK agent.

      1. Create an ADK agent.

        adk create my_agent
      2. Select the gemini-2.5-flash model.

      3. Select Google AI, and enter your Gemini API key. For more information about how to find your API key, see Using Gemini API keys.

    5. Replace the contents of the agent.py file with the following Flight Data Assistant sample application code.

      from typing import cast
      
      from google.adk.agents.llm_agent import Agent
      from google.adk.agents.llm_agent import ToolUnion
      
      from toolbox_core import ToolboxSyncClient
      
      TOOLBOX_URL = "http://127.0.0.1:5000"
      
      INSTRUCTION = """
      # ROLE
      You are a friendly and factual flight data assistant. Your goal is to help users find the best flights for their needs by providing accurate information with a helpful, professional tone.
      - use the Query Data Tool to answer the user's question, if the tool fails to generate a valid query, ask the user to clarify their question.
      
      # OPERATIONAL CONSTRAINTS
      - TOOL LIMITATION: You only have access to the Query Data Tool. Do not claim to have capabilities beyond what this tool provides.
      - TRANSPARENCY POLICY: Maintain a seamless user experience. Never mention that you are using a tool, querying a database, or generating SQL. Frame all responses as your own direct assistance.
      - SCOPE MANAGEMENT: If a user asks for something beyond your capabilities, politely state that you cannot perform that specific task. Guide the user towards what you can help with.
      
      # COMMUNICATION STYLE
      - Be concise and scannable when listing answers.
      - Maintain a helpful, professional persona.
      
      =====
      
      # QUERY DATA TOOL
      
      Inputs:
      1. query: A natural language formulation of a database query.
      
      Outputs: (all optional)
      1. disambiguation_question: Clarification questions or comments where the tool needs the users' input.
      2. generated_query: The generated query for the user query.
      3. intent_explanation: An explanation for why the tool produced `generated_query`.
      4. query_result: The result of executing `generated_query`.
      5. natural_language_answer: The natural language answer that summarizes the `query` and `query_result`.
      
      Usage guidance:
      1. If `disambiguation_question` is produced, then solicit the needed inputs from the user and try the tool with a new `query` that has the needed clarification.
      2. If `natural_language_answer` is produced, use `intent_explanation` and `generated_query` to see if you need to clarify any assumptions for the user.
      3. If the tool output indicates failure or empty results, explain that clearly using the provided reasoning.
      """
      
      client = ToolboxSyncClient(TOOLBOX_URL)
      
      mcp_tool = client.load_tool("cloud_gda_query_tool")
      
      root_agent = Agent(
          model="gemini-2.5-flash",
          name="root_agent",
          instruction=INSTRUCTION,
          tools=cast(list[ToolUnion], [mcp_tool]),
      )
      
  7. Run the following commands under the flight-assistant-app directory to start the application and access the ADK web server at http://127.0.0.1:8000.

    adk web --port 8000
  8. Enter any text, such as hello, to start interacting with the agent.

    The ADK agent answers general questions and calls the required MCP tools.

  9. Enter the following flight-related question.

    How many flights depart from the west side?
    

    The MCP tool is called to answer this question. However, since the term the west is ambiguous and doesn't specify any airports, the MCP tool returns a disambiguation question which the agent uses to construct a response.

    I cannot determine how many flights depart from the 'west side' as the database does not contain information about which airports are considered to be on the 'west side'. However, I can help you with questions like:
    
    1. How many flights depart from a specific airport?
    
    2. What are the departure airports for all flights?
    
    3. How many flights depart from each airport? Would you like to rephrase your question based on these options?
    
  10. Enter a question similar to that in the query template generated for the agent.

    Help me find flights from San Francisco that avoid the evening rush hour.
    

    Based on the QueryData context added earlier, the MCP tool understands that evening traffic occurs between 5 PM and 7 PM. The MCP tool returns the associated data for the agent to use in constructing its response.

    Here are the flights departing from San Francisco that avoid the evening rush hour (defined as 5 PM to 7 PM):
    
    * UA 1532 departing at 05:50:00
    * UA 1158 departing at 05:57:00
    * CY 922 departing at 06:38:00
    * OO 5441 departing at 07:08:00
    * UA 616 departing at 07:14:00
    * AA 24 departing at 07:14:00
    * B6 434 departing at 08:00:00
    * AA 242 departing at 08:18:00
    * UA 1739 departing at 08:22:00
    * OO 6336 departing at 08:32:00
    * US 1784 departing at 08:47:00
    * DL 1631 departing at 09:00:00
    * DL 1106 departing at 09:06:00
    * OO 5427 departing at 09:06:00
    * CY 352 departing at 09:25:00
    
  11. Enter a question based on the concept type that you added in the QueryData agent context.

    Get me flights to disney world
    

    Based on the value search context added earlier, the QueryData agent understands that disney world relates to the city Orlando and returns the associated data for the QueryData agent to use in constructing its response.

    Here are the flights heading to Orlando, which is the location of Disney World:
    
    * Flight UA 1249 departs from SFO and arrives at MCO on 2025-01-02 at 18:15:00Z.
    * Flight UA 698 departs from SFO and arrives at MCO on 2025-01-02 at 22:33:00Z.
    * Flight UA 292 departs from SFO and arrives at MCO on 2025-01-03 at 06:37:00Z.
    

Iterate agent performance

The ADK web UI lets you inspect the request and response from the Gemini Data Analytics QueryData MCP tool. You can use this response to observe the tool responses such as generated SQL query, result set, intent explanation, disambiguation question, and natural language answer, to help you confirm the correctness of your agent's responses.

For example, for the input text How many flights depart from the west side? you entered earlier, click the agent bubble. In the Event tab in the left navigation, expand the functionResponse to see the following response.

"{"disambiguationQuestion": ["[NOT_ENOUGH_INFO] The database schema does not
contain information about which airports are on the 'west side'. Therefore, I
cannot determine how many flights depart from the west side.Possible alternative
questions: 1. How many flights depart from a specific airport? 2. What are the
departure airports for all flights? 3. How many flights depart from each
airport?"]}"

Refine response accuracy

You can continuously refine the accuracy of responses from the Gemini Data Analytics QueryData tool by adding additional context. Use the Gemini CLI to generate context, and then upload the updated context set file to the existing flights-assistant QueryData agent. For more information, see Build contexts using Gemini CLI. The console immediately ingests new context after you upload it, enabling you to enhance the agent's accuracy without any application downtime.

Multiple agents

In your development environment, you can perform A/B testing on multiple QueryData agent contexts by assigning distinct names to tools in your tools.yaml file. For example, you can create unique tools.yaml configurations by defining two cloud-gemini-data-analytics-query tools with different names, such as cloud_gda_query_tool_v1 and cloud_gda_query_tool_v2. This setup lets you implement application logic that programmatically selects the required context version by choosing the corresponding tool name.

The following example tools.yaml shows how to set up multiple QueryData agents for a database source:

kind: source
name: gda-api-source
type: cloud-gemini-data-analytics
projectId: <var>PROJECT_ID</var>
---
kind: tool
name: cloud_gda_query_tool_v1
type: cloud-gemini-data-analytics-query
source: gda-api-source
context:
  datasourceReferences:
    <var>DB_SOURCE</var>:
      databaseReference: ...
      agentContextReference:
        contextSetId: "V1_YOUR_CONTEXT_SET_ID"
generationOptions: ...
---
kind: tool
name: cloud_gda_query_tool_v2
type: cloud-gemini-data-analytics-query
source: gda-api-source
context:
  datasourceReferences:
    <var>DB_SOURCE</var>:
      databaseReference: ...
      agentContextReference:
        contextSetId: "V2_YOUR_CONTEXT_SET_ID"
generationOptions: ...

Replace the following:

  • PROJECT_ID: Your Google Cloud project ID.
  • V1_YOUR_CONTEXT_SET_ID: The context set ID for version 1.
  • V2_YOUR_CONTEXT_SET_ID: The context set ID for version 2

Clean up

The following sections describe how to delete these resources and objects.

Delete the context set

Before you delete the instance, delete the context set that you created.

  1. In the Google Cloud console, go to the Cloud SQL page.

    Go to Cloud SQL

  2. Select an instance from the list.

  3. In the navigation menu, click Cloud SQL Studio.

  4. Sign in to Studio using Identity and Access Management authentication.

  5. In the Explorer pane, next to your context set, click View actions.

  6. In the Delete context set window, enter flight-assistant in the confirmation box.

  7. Click Confirm.

Delete the instance

When you delete the instance that you created in the before you begin section, you also delete all of the objects you created.

  1. In the Google Cloud console, go to the Cloud SQL page.

    Go to Cloud SQL

  2. Select an instance from the list.

  3. Click Delete.

  4. Confirm that you want to delete the instance by entering the instance name and clicking Delete.

What's next