एजेंट डेवलपमेंट किट (एडीके) और जेन एआई इवैल सेवा का इस्तेमाल करके, BigQuery एजेंट बनाना और उनका आकलन करना

1. परिचय

इस कोडलैब में, आपको ऐसे एजेंट बनाने का तरीका बताया जाएगा जो एजेंट डेवलपमेंट किट (एडीके) का इस्तेमाल करके, BigQuery में सेव किए गए डेटा के बारे में सवालों के जवाब दे सकते हैं. आपको Vertex AI की GenAI Evaluation सेवा का इस्तेमाल करके, इन एजेंट का आकलन भी करना होगा:

dff1b6eccdd36160.png

आपको क्या करना होगा

  • ADK में Conversational Analytics एजेंट बनाना
  • इस एजेंट को ADK के BigQuery के लिए पहले पक्ष के टूलसेट से लैस करें, ताकि यह BigQuery में सेव किए गए डेटा के साथ इंटरैक्ट कर सके
  • Vertex AI GenAI Evaluation service का इस्तेमाल करके, अपने एजेंट के लिए आकलन का फ़्रेमवर्क बनाएं
  • आकलन चलाएं: इस एजेंट के लिए, सबसे सही जवाबों के सेट के आधार पर आकलन चलाएं

आपको इन चीज़ों की ज़रूरत होगी

  • कोई वेब ब्राउज़र, जैसे कि Chrome
  • बिलिंग की सुविधा वाला Google Cloud प्रोजेक्ट या
  • Gmail खाता. अगले सेक्शन में, इस कोडलैब के लिए 5 डॉलर का मुफ़्त क्रेडिट रिडीम करने और नया प्रोजेक्ट सेट अप करने का तरीका बताया गया है

यह कोडलैब, सभी लेवल के डेवलपर के लिए है. इसमें शुरुआती डेवलपर भी शामिल हैं. ADK डेवलपमेंट के लिए, Google Cloud Shell में कमांड-लाइन इंटरफ़ेस और Python कोड का इस्तेमाल किया जाएगा. इसके लिए, आपको Python का एक्सपर्ट होने की ज़रूरत नहीं है. हालांकि, कोड को पढ़ने की बुनियादी जानकारी होने से, आपको कॉन्सेप्ट समझने में मदद मिलेगी.

2. शुरू करने से पहले

Google Cloud प्रोजेक्ट बनाना

  1. Google Cloud Console में, प्रोजेक्ट चुनने वाले पेज पर जाकर, Google Cloud प्रोजेक्ट चुनें या बनाएं.

a6e0191f0ee7bf4a.png

  1. पक्का करें कि आपके Cloud प्रोजेक्ट के लिए बिलिंग चालू हो. किसी प्रोजेक्ट के लिए बिलिंग चालू है या नहीं, यह देखने का तरीका जानें.

Cloud Shell शुरू करें

Cloud Shell, Google Cloud में चलने वाला एक कमांड-लाइन एनवायरमेंट है. इसमें ज़रूरी टूल पहले से लोड होते हैं.

  1. Google Cloud Console में सबसे ऊपर मौजूद, Cloud Shell चालू करें पर क्लिक करें:

cc25e6aa09f99271.png

  1. Cloud Shell से कनेक्ट होने के बाद, Cloud Shell में पुष्टि करने के लिए यह कमांड चलाएं:
gcloud auth list
  1. यह पुष्टि करने के लिए कि आपका प्रोजेक्ट gcloud के साथ इस्तेमाल करने के लिए कॉन्फ़िगर किया गया है, यह निर्देश चलाएं:
gcloud config list project
  1. अपना प्रोजेक्ट सेट करने के लिए, इस निर्देश का इस्तेमाल करें:
export PROJECT_ID=<YOUR_PROJECT_ID>
gcloud config set project $PROJECT_ID

एपीआई चालू करें

  1. सभी ज़रूरी एपीआई और सेवाओं को चालू करने के लिए, यह निर्देश चलाएं:
gcloud services enable bigquery.googleapis.com \
                       aiplatform.googleapis.com \
                       cloudresourcemanager.googleapis.com
  1. कमांड के सही तरीके से लागू होने पर, आपको यहां दिखाए गए मैसेज जैसा कोई मैसेज दिखेगा:
Operation "operations/..." finished successfully.

3. BigQuery डेटासेट बनाना

  1. BigQuery में ecommerce नाम का नया डेटासेट बनाने के लिए, Cloud Shell में यह कमांड चलाएं:
bq mk --dataset --location=US ecommerce

BigQuery के सार्वजनिक डेटासेट thelook_ecommerce का स्टैटिक सबसेट, Google Cloud Storage के सार्वजनिक बकेट में AVRO फ़ाइलों के तौर पर सेव किया जाता है.

  1. इन Avro फ़ाइलों को BigQuery में टेबल (इवेंट, order_items, प्रॉडक्ट, उपयोगकर्ता, ऑर्डर) के तौर पर लोड करने के लिए, Cloud Shell में यह कमांड चलाएं:
bq load --source_format=AVRO --autodetect \
    ecommerce.events \
  gs://sample-data-and-media/thelook_dataset_snapshot/events/*.avro.gz

bq load --source_format=AVRO --autodetect \
    ecommerce.order_items \
    gs://sample-data-and-media/thelook_dataset_snapshot/order_items/*.avro.gz

bq load --source_format=AVRO --autodetect \
    ecommerce.products \
    gs://sample-data-and-media/thelook_dataset_snapshot/products/*.avro.gz

bq load --source_format=AVRO --autodetect \
    ecommerce.users \
    gs://sample-data-and-media/thelook_dataset_snapshot/users/*.avro.gz

bq load --source_format=AVRO --autodetect \
    ecommerce.orders \
gs://sample-data-and-media/thelook_dataset_snapshot/orders/*.avro.gz
bq load --source_format=AVRO --autodetect \
    ecommerce.inventory_items \
    gs://sample-data-and-media/thelook_dataset_snapshot/inventory_items/*.avro.gz
bq load --source_format=AVRO --autodetect \
    ecommerce.distribution_centers \
    gs://sample-data-and-media/thelook_dataset_snapshot/distribution_centers/*.avro.gz

इस प्रोसेस में कुछ मिनट लग सकते हैं.

  1. यह पुष्टि करें कि डेटासेट और टेबल बन गई हैं. इसके लिए, अपने Google Cloud प्रोजेक्ट में BigQuery कंसोल पर जाएं:

f8ba5156d27b73d0.png

4. ADK एजेंट के लिए एनवायरमेंट तैयार करना

Cloud Shell पर वापस जाएं और पक्का करें कि आप अपनी होम डायरेक्ट्री में हों. हम एक वर्चुअल Python एनवायरमेंट बनाएंगे और ज़रूरी पैकेज इंस्टॉल करेंगे.

  1. Cloud Shell में एक नया टर्मिनल टैब खोलें. इसके बाद, bigquery-adk-codelab नाम का फ़ोल्डर बनाने और उस पर जाने के लिए, यह निर्देश चलाएं:
mkdir bigquery-adk-codelab
cd bigquery-adk-codelab
  1. वर्चुअल Python एनवायरमेंट बनाएं:
python -m venv .venv
  1. वर्चुअल एनवायरमेंट चालू करें:
source .venv/bin/activate
  1. Google का ADK और AI-Platform Python पैकेज इंस्टॉल करें. bigquery एजेंट का आकलन करने के लिए, एआई प्लैटफ़ॉर्म और pandas पैकेज की ज़रूरत होती है:
pip install google-adk google-cloud-aiplatform[evaluation] pandas

5. ADK ऐप्लिकेशन बनाना

अब हम अपना BigQuery एजेंट बनाएंगे. इस एजेंट को BigQuery में सेव किए गए डेटा के बारे में, नैचुरल लैंग्वेज में पूछे गए सवालों के जवाब देने के लिए डिज़ाइन किया जाएगा.

  1. ज़रूरी फ़ोल्डर और फ़ाइलों के साथ नया एजेंट ऐप्लिकेशन बनाने के लिए, adk create utility command चलाएं:
adk create data_agent_app

दिए गए निर्देशों का पालन करें:

  1. मॉडल के लिए, gemini-2.5-flash चुनें.
  2. बैकएंड के लिए Vertex AI को चुनें.
  3. अपने डिफ़ॉल्ट Google Cloud प्रोजेक्ट आईडी और क्षेत्र की पुष्टि करें.

यहां इंटरैक्शन का एक उदाहरण दिया गया है:

c833d29f517f0a0f.png

  1. Cloud Shell Editor खोलने और नए बनाए गए फ़ोल्डर और फ़ाइलें देखने के लिए, Cloud Shell में Open Editor बटन पर क्लिक करें:

16ed263528e6cc1f.png

जनरेट की गई फ़ाइलों को नोट करें:

bigquery-adk-codelab/
├── .venv/
└── data_agent_app/
    ├── __init__.py
    ├── agent.py
    └── .env
  • init.py: यह फ़ोल्डर को Python मॉड्यूल के तौर पर मार्क करता है.
  • agent.py: इसमें एजेंट की शुरुआती परिभाषा शामिल होती है.
  • .env: इसमें आपके प्रोजेक्ट के लिए एनवायरमेंट वैरिएबल होते हैं (इस फ़ाइल को देखने के लिए, आपको शायद देखें > छिपी हुई फ़ाइलें टॉगल करें पर क्लिक करना पड़े)

उन वैरिएबल को अपडेट करें जिन्हें प्रॉम्प्ट से सही तरीके से सेट नहीं किया गया था:

GOOGLE_GENAI_USE_VERTEXAI=1
GOOGLE_CLOUD_PROJECT=<YOUR_GOOGLE_PROJECT_ID>
GOOGLE_CLOUD_LOCATION=<YOUR_GOOGLE_CLOUD_REGION>

6. अपने एजेंट को तय करें और उसे BigQuery टूलसेट असाइन करें

BigQuery टूलसेट का इस्तेमाल करके BigQuery के साथ इंटरैक्ट करने वाले ADK एजेंट को तय करने के लिए, agent.py फ़ाइल के मौजूदा कॉन्टेंट को इस कोड से बदलें.

आपको एजेंट के निर्देशों में मौजूद प्रोजेक्ट आईडी को अपने असली प्रोजेक्ट आईडी से अपडेट करना होगा:

from google.adk.agents import Agent
from google.adk.tools.bigquery import BigQueryCredentialsConfig, BigQueryToolset
import google.auth
import dotenv

dotenv.load_dotenv()

credentials, _ = google.auth.default()
credentials_config = BigQueryCredentialsConfig(credentials=credentials)
bigquery_toolset = BigQueryToolset(
  credentials_config=credentials_config
)

root_agent = Agent(
 model="gemini-2.5-flash",
 name="bigquery_agent",
 description="Agent that answers questions about BigQuery data by executing SQL queries.",
 instruction=(
     """
       You are a BigQuery data analysis agent.
       You are able to answer questions on data stored in project-id: '<YOUR_PROJECT_ID>' on the `ecommerce` dataset.
     """
 ),
 tools=[bigquery_toolset]
)

def get_bigquery_agent():
 return root_agent

BigQuery टूलसेट, एजेंट को BigQuery डेटा पर मेटाडेटा फ़ेच करने और एसक्यूएल क्वेरी चलाने की सुविधाएं देता है. टूलसेट का इस्तेमाल करने के लिए, आपको पुष्टि करनी होगी. इसके लिए, सबसे ज़्यादा इस्तेमाल किए जाने वाले विकल्प ये हैं: डेवलपमेंट के लिए ऐप्लिकेशन के डिफ़ॉल्ट क्रेडेंशियल (एडीसी), इंटरैक्टिव OAuth (जब एजेंट को किसी उपयोगकर्ता की ओर से कार्रवाई करनी हो), या सुरक्षित, प्रोडक्शन-लेवल की पुष्टि के लिए सेवा खाते के क्रेडेंशियल.

यहां से, Cloud Shell पर वापस जाकर और यह कमांड चलाकर, अपने एजेंट से चैट की जा सकती है:

adk web

आपको एक सूचना दिखेगी, जिसमें लिखा होगा कि वेबसर्वर शुरू हो गया है:

...
INFO:     Started server process [2735]
INFO:     Waiting for application startup.

+-----------------------------------------------------------------------------+
| ADK Web Server started                                                      |                                                      |
| For local testing, access at http://127.0.0.1:8000.                         |
+-----------------------------------------------------------------------------+

INFO:     Application startup complete.
INFO:     Uvicorn running on http://127.0.0.1:8000 

adk web लॉन्च करने के लिए, दिए गए यूआरएल पर क्लिक करें. अपने एजेंट से डेटासेट के बारे में कुछ सवाल पूछे जा सकते हैं:

c0ceac4d3a3cc321.gif

adk वेब को बंद करें और वेब सर्वर को बंद करने के लिए, टर्मिनल में Ctrl + C दबाएं.

7. अपने एजेंट को आकलन के लिए तैयार करना

BigQuery एजेंट को तय करने के बाद, आपको उसे आकलन के लिए चालू करना होगा.

यहां दिए गए कोड में, run_conversation फ़ंक्शन के बारे में बताया गया है. यह फ़ंक्शन, बातचीत के फ़्लो को मैनेज करता है. इसके लिए, यह एजेंट बनाता है, सेशन चलाता है, और इवेंट प्रोसेस करता है, ताकि फ़ाइनल जवाब मिल सके.

  1. Cloud Editor पर वापस जाएं. इसके बाद, bigquery-adk-codelab डायरेक्ट्री में run_agent.py नाम की नई फ़ाइल बनाएं . इसके बाद, यहां दिए गए कोड को कॉपी करके चिपकाएं:
from data_agent_app.agent import get_bigquery_agent
from google.adk.sessions import InMemorySessionService
from google.adk.runners import Runner
from google.genai import types
import uuid

APP_NAME = "data_agent_app"
USER_ID = "biquery_user_101"

async def run_conversation(prompt: str):
  session_service = InMemorySessionService()
  session_id = f"{APP_NAME}-{uuid.uuid4().hex[:8]}"
  root_agent = get_bigquery_agent()
 
  runner = Runner(
      agent=root_agent,
      app_name=APP_NAME,
      session_service=session_service
  )
 
  session = await session_service.create_session(
       app_name=APP_NAME,
       user_id=USER_ID,
       session_id=session_id
  )   
  final_response_text = "Unable to retrieve final response."
 
  try:
      # Run the agent and process the events as they are generated
      async for event in runner.run_async(
          user_id=USER_ID,
          session_id=session_id,
          new_message=types.Content(role='user', parts=[types.Part(text=prompt)])
      ):
          if event.is_final_response():
              if event.content and event.content.parts:
                  final_response_text = event.content.parts[0].text
              break
  except Exception as e:
      print(f"Error in run_conversation: {e}")
      final_response_text = f"An error occurred: {e}"
    
  return final_response_text

नीचे दिए गए कोड में, इस रन किए जा सकने वाले फ़ंक्शन को कॉल करने और नतीजे को वापस लाने के लिए, यूटिलिटी फ़ंक्शन तय किए गए हैं. इसमें हेल्पर फ़ंक्शन भी शामिल हैं, जो आकलन के नतीजों को प्रिंट और सेव करते हैं:

  1. bigquery-adk-codelab डायरेक्ट्री में utils.py नाम की एक नई फ़ाइल बनाएं. इसके बाद, इस कोड को utils.py फ़ाइल में कॉपी/चिपकाएं:
import json
import os
import asyncio
import run_agent

def get_agent_response(prompt: str) -> dict:
  try:
      response = asyncio.run(run_agent.run_conversation(prompt)) # Invoke the agent
      return {"response": response}
  except Exception as e:
      return {"response": "Error: Agent failed to produce a response."}

def save_evaluation_results(eval_result, experiment_run):
  """Processes, saves, and prints the evaluation results for a single run."""
  os.makedirs("eval_results", exist_ok=True)
  output_file_path = os.path.join("eval_results", f"bq_agent_eval_results_{experiment_run}.json")

  # Prepare data for JSON serialization
  eval_result_dict = {
      'summary_metrics': eval_result.summary_metrics,
      'pointwise_metrics': eval_result.metrics_table.to_dict('records')
  }
   # --- Save the results as a JSON file ---
  with open(output_file_path, "w") as f:
      json.dump(eval_result_dict, f, indent=4)
  print(f"Results for run '{experiment_run}' saved to {output_file_path}")

def print_evaluation_summary(eval_result):
  pointwise_metrics = eval_result.metrics_table
  # Print summary metrics for the current run
  summary_metrics = eval_result.summary_metrics
  if summary_metrics:
    for key, value in summary_metrics.items():
        metric_name = key.replace('/mean', '').replace('_', ' ').title()
        print(f"- {metric_name}: {key}: {value:.2f}")
  else:
    print("No summary metrics found for this run.")
  print("\n" + "="*50 + "\n")

  if not pointwise_metrics.empty:
    total_questions = len(pointwise_metrics)
    avg_completeness_score = pointwise_metrics['completeness_metric/score'].mean()
    avg_factual_accuracy_score = pointwise_metrics['factual_accuracy_metric/score'].mean()
    print("\n" + "="*50 + "\n")
    print("--- Aggregated Evaluation Summary ---")
    print(f"Total questions in evaluation dataset: {total_questions}")
    print(f"Average Completeness Score: {avg_completeness_score:.2f}")
    print(f"Average Factual Accuracy Score: {avg_factual_accuracy_score:.2f}")
    print("\n" + "="*50 + "\n")
  else:
     print("\nNo successful evaluation runs were completed.")

8. आकलन के लिए डेटासेट बनाना

अपने एजेंट का आकलन करने के लिए, आपको आकलन के लिए डेटासेट बनाना, आकलन की मेट्रिक तय करना, और आकलन का टास्क पूरा करना होगा.

इवैल्यूएशन डेटासेट में, सवालों (प्रॉम्प्ट) और उनके सही जवाबों (रेफ़रंस) की सूची होती है. जवाबों का आकलन करने वाली सेवा, इन पेयर का इस्तेमाल करके आपके एजेंट के जवाबों की तुलना करेगी. इससे यह पता चलेगा कि जवाब सटीक हैं या नहीं.

  1. bigquery-adk-codelab डायरेक्ट्री में evaluation_dataset.json नाम की एक नई फ़ाइल बनाएं. इसके बाद, नीचे दिए गए आकलन डेटासेट को कॉपी करके चिपकाएं:
[
   {
       "prompt": "What tables are available in the dataset `ecommerce_data`?",
       "reference": "The tables available in the dataset `ecommerce_data` are: `distribution_centers`, `events`, `inventory_items`, `order_items`, `orders`, `products`, and `users`."
   },
   {
       "prompt": "How many users are there in total?",
       "reference": "There are 100,000 users in total."
   },
   {
       "prompt": "Find the email and age of the user with id 72685.",
       "reference": "The email address of user 72685 is lindseybrennan@example.org and their age is 59."
   },
   {
       "prompt": "How many orders have a status of Complete?",
       "reference": "There are 31,077 orders with a status of 'complete'."
   },
   {
       "prompt": "Which distribution center has the highest latitude, and what is it's latitude?",
       "reference": "Chicago IL is the distribution center with the highest latitude, with a latitude of 41.84."
   },
   {
       "prompt": "Retrieve the order id for all orders with a status of cancelled placed on the 1st June 2023 before 6am.",
       "reference": "The order IDs for all orders with a status of 'cancelled' placed on the 1st June 2023 before 6am are: 26622, 49223"
   },
   {
       "prompt": "What id the full name and user ids of the top 5 users with the most orders.",
       "reference": "The top 5 users with the most orders are: Kristine Pennington (user ID 77359), Anthony Bright (user ID 4137), David Bean (user ID 30740), Michelle Wright (user ID 54563), and Matthew Reynolds (user ID 41136), each with 4 total orders."
   },
   {
       "prompt": "Which distribution center is associated with the highest average retail price of its products, and what is the average retail price?",
       "reference": "The distribution center associated with the highest average retail price of its products is Houston TX, with an average retail price of $69.74."
   },
   {
       "prompt": "How many events were of type 'purchase' in Seoul during May 2024?",
       "reference": "In May 2024, there were 57 'purchase' events recorded in Seoul."
   },
   {
       "prompt": "For orders placed in June 2023, how many took three days or longer to be delivered after they were shipped?",
       "reference": "In June 2023, there were 260 orders with a time difference of of 3 days or more between when they were shipped and delivered."
   },
   {
       "prompt": "What are the names of the products and their respective retail price that have never been sold, but have a retail price greater than $210?",
       "reference": "The products that have never been sold but have a retail price greater than $210 are:\n- Tommy Hilfiger Men's 2 Button Side Vent Windowpane Trim Fit Sport Coat, with a retail price of $249.9\n- MICHAEL Michael Kors Women's Hooded Leather Jacket: $211.11"
   },
   {
       "prompt": "List the id and first name of users between the ages of 70 and 75 who have Facebook were sourced from Facebook and are located in California.",
       "reference": "The users between the ages of 70 and 75 from California with 'Facebook' as their traffic source are:\n- Julie (ID: 25379)\n- Sherry (ID: 85196)\n- Kenneth (ID: 82238)\n- Linsday (ID: 64079)\n- Matthew (ID: 99612)"
   },
   {
       "prompt": "Identify the full name and user id of users over the age of 67 who live within 3.5 kilometers of any distribution_center.",
       "reference": "The users over the age of 67 who live within 3.5 kilometers of any distribution center are:\n- William Campbell (user ID: 26082)\n- Becky Cantrell (user ID: 39008)"
   },
   {
       "prompt": "What is the median age of users for each gender?",
       "reference": "The median age for female users is 41, and the median age for male users is 41."
   },
   {
       "prompt": "What is the average sale price of complete orders compared to returned orders, and what is the percentage difference (to two decimal places) between them?",
       "reference": "The average sale price for 'Complete' orders was $59.56, while for 'Returned' orders it was $59.76. This represents a percentage difference of 0.34%."
   }
]

9. आकलन की मेट्रिक तय करना

अब हम दो कस्टम मेट्रिक का इस्तेमाल करेंगे. इनसे यह पता चलेगा कि एजेंट, आपके BigQuery डेटा से जुड़े सवालों के जवाब दे सकता है या नहीं. दोनों मेट्रिक के लिए, 1 से 5 तक का स्कोर दिया जाएगा:

  • तथ्यों के सटीक होने की मेट्रिक: इससे यह पता चलता है कि जवाब में दिए गए सभी तथ्य और डेटा, भरोसेमंद सोर्स से मिले तथ्यों और डेटा से मेल खाते हैं या नहीं.
  • जवाब में पूरी जानकारी मौजूद होने का आकलन करने वाली मेट्रिक: इससे यह पता चलता है कि जवाब में, उपयोगकर्ता की ओर से मांगी गई सभी अहम जानकारी शामिल है या नहीं. साथ ही, यह भी पता चलता है कि जवाब में सही जानकारी मौजूद है या नहीं और कोई भी ज़रूरी जानकारी छूटी तो नहीं है.
  1. आखिर में, bigquery-adk-codelab डायरेक्ट्री में evaluate_agent.py नाम की नई फ़ाइल बनाएं. इसके बाद, मेट्रिक की परिभाषा वाले कोड को evaluate_agent.py फ़ाइल में कॉपी/चिपकाएं:
import uuid
import pandas as pd
from datetime import datetime
from vertexai.preview.evaluation import EvalTask
from vertexai.preview.evaluation.metrics import (
  PointwiseMetricPromptTemplate,
  PointwiseMetric,
  MetricPromptTemplateExamples
)
from utils import (
   save_evaluation_results,
   print_evaluation_summary,
   get_agent_response
)

factual_accuracy_metric = PointwiseMetric(
   metric="factual_accuracy_metric",
   metric_prompt_template=PointwiseMetricPromptTemplate(
       instruction="""You are an expert evaluator assessing the factual accuracy of an AI's answer to a user's question, given a natural language prompt and a 'reference' (ground truth) answer. Your task is to determine if all factual information in the AI's answer is precise and correct when compared to the reference.""",
       criteria={
           "Accuracy": """The AI's answer must present factual information (numerical values, names, dates, specific values) that are **identical** to or an exact logical derivation from the reference.
           - **Wording may vary, but the core factual information must be the same.**
           - No numerical discrepancies.
           - No incorrect names or identifiers.
           - No fabricated or misleading details.
           - Note: Minor rounding of numerical values that doesn't alter the core meaning or lead to significant misrepresentation is generally acceptable, assuming the prompt doesn't ask for exact precision."""
       },
       rating_rubric={
           "5": "Excellent: The response is entirely factually correct. **All factual information precisely matches the reference.** There are absolutely no inaccuracies or misleading details.",
           "3": "Good: The response is generally accurate, but contains minor, non-critical factual inaccuracies (e.g., a negligible rounding difference or slightly wrong detail) that do not impact the core understanding.",
           "1": "Poor: The response contains significant factual errors, major numerical discrepancies, or fabricated information that makes the answer incorrect or unreliable."
       },
       input_variables=["prompt", "reference", "response"],
   ),
)

completeness_metric = PointwiseMetric(
   metric="completeness_metric",
   metric_prompt_template=PointwiseMetricPromptTemplate(
       instruction="""You are an expert evaluator assessing the completeness of an AI's answer to a user's question, given a natural language prompt and a 'reference' (ground truth) answer. Your task is to determine if the AI's answer provides all the essential information requested by the user and present in the reference.""",
       criteria={
           "Completeness": """The AI's answer must include **all** key pieces of information explicitly or implicitly requested by the prompt and present in the reference.
           - No omissions of critical facts.
           - All requested attributes (e.g., age AND email, not just one) must be present.
           - If the reference provides a multi-part answer, all parts must be covered."""
       },
       rating_rubric={
           "5": "Excellent: The response is perfectly complete. **All key information requested by the prompt and present in the reference is included.** There are absolutely no omissions.",
           "3": "Good: The response is mostly complete. It has only a slight, non-critical omission that does not impact the core understanding or utility of the answer.",
           "1": "Poor: The response is critically incomplete. Essential parts of the requested information are missing, making the answer less useful or unusable for the user's purpose."
       },
       input_variables=["prompt", "reference", "response"],
   ),
)

10. इवैलुएशन टास्क बनाना

EvalTask, मूल्यांकन वाले डेटासेट और कस्टम मेट्रिक का इस्तेमाल करता है. साथ ही, एक नया मूल्यांकन एक्सपेरिमेंट सेट अप करता है.

run_eval फ़ंक्शन, आकलन करने वाला मुख्य इंजन है. यह EvalTask के ज़रिए लूप करता है. साथ ही, डेटासेट में मौजूद हर सवाल पर आपके एजेंट को चलाता है. यह हर सवाल के लिए, एजेंट के जवाब को रिकॉर्ड करता है. इसके बाद, पहले से तय की गई मेट्रिक का इस्तेमाल करके, जवाब को ग्रेड देता है.

यहां दिए गए कोड को कॉपी करके, evaluate_agent.py फ़ाइल में सबसे नीचे चिपकाएं:

def run_eval():
   eval_dataset = pd.read_json("evaluation_dataset.json")

   # Generate a unique run name
   current_time = datetime.now().strftime('%Y%m%d-%H%M%S')
   experiment_run_id = f"{current_time}-{uuid.uuid4().hex[:8]}"
      
   print(f"--- Starting evaluation: ({experiment_run_id}) ---")

   # Define the evaluation task with your dataset and metrics
   eval_task = EvalTask(
       dataset=eval_dataset,
       metrics=[
          factual_accuracy_metric,
          completeness_metric
       ],
       experiment="evaluate-bq-data-agent"
   )

   try:
       eval_result = eval_task.evaluate(
           runnable=get_agent_response, experiment_run_name=experiment_run_id
       )
       save_evaluation_results(eval_result, experiment_run_id)
       print_evaluation_summary(eval_result)

   except Exception as e:
       print(f"An error occurred during evaluation run: {e}")

if __name__ == "__main__":
   run_eval()

नतीजों की खास जानकारी दी जाती है और उन्हें JSON फ़ाइल में सेव किया जाता है.

11. आकलन करना

अब आपके पास एजेंट, आकलन की मेट्रिक, और आकलन का डेटासेट तैयार है. इसलिए, आकलन किया जा सकता है.

Cloud Shell पर वापस जाएं. पक्का करें कि आप bigquery-adk-codelab डायरेक्ट्री में हों. इसके बाद, इस कमांड का इस्तेमाल करके, आकलन स्क्रिप्ट चलाएं:

python evaluate_agent.py

जैसे-जैसे आकलन आगे बढ़ेगा, आपको इस तरह का आउटपुट दिखेगा:

All 30 metric requests are successfully computed.
Evaluation Took:29.00278048400105 seconds
Results for run '20250919-181822-6a13dd42' saved to eval_results/bq_agent_eval_results_20250919-181822-6a13dd42.json
- Row Count: row_count: 15.00
- Factual Accuracy Metric: factual_accuracy_metric/mean: 2.60
- Factual Accuracy Metric/Std: factual_accuracy_metric/std: 1.72
- Completeness Metric: completeness_metric/mean: 3.27
- Completeness Metric/Std: completeness_metric/std: 1.98
- Latency In Seconds: latency_in_seconds/mean: 12.17
- Latency In Seconds/Std: latency_in_seconds/std: 6.06
- Failure: failure/mean: 0.00
- Failure/Std: failure/std: 0.00

नतीजों को समझना:

data_agent_app डायरेक्ट्री में मौजूद eval_results फ़ोल्डर पर जाएं और bq_agent_eval_results_*.json नाम की फ़ाइल खोलें:

3738abd0c9bff89d.png

  • खास जानकारी देने वाली मेट्रिक: इससे आपको डेटासेट में, एजेंट की परफ़ॉर्मेंस की खास जानकारी मिलती है.
  • तथ्यों के सही होने और जानकारी के पूरी होने के आधार पर तय की गई मेट्रिक: 5 के आस-पास का स्कोर, तथ्यों के सही होने और जानकारी के पूरी होने की ज़्यादा संभावना दिखाता है. हर सवाल के लिए एक स्कोर होगा. साथ ही, यह भी बताया जाएगा कि उस सवाल को वह स्कोर क्यों मिला.

हम देख सकते हैं कि जवाब में मौजूद जानकारी के पूरी तरह से मौजूद होने और तथ्यों के सही होने का औसत स्कोर क्रमशः 3.27 और 1.72 है.

नतीजे बहुत अच्छे नहीं हैं! आइए, हम अपने एजेंट की सवालों के जवाब देने की क्षमता को बेहतर बनाने की कोशिश करते हैं.

12. अपने एजेंट के परफ़ॉर्मेंस के आकलन के नतीजों को बेहतर बनाना

bigquery-adk-codelab डायरेक्ट्री में मौजूद agent.py पर जाएं. इसके बाद, एजेंट के मॉडल और सिस्टम के निर्देशों को अपडेट करें. <YOUR_PROJECT_ID> की जगह अपना प्रोजेक्ट आईडी डालना न भूलें:

root_agent = Agent(
 model="gemini-2.5-flash",
 name="bigquery_agent",
 description="Agent that answers questions about BigQuery data by executing SQL queries.",
 instruction=(
     """
     You are a data analysis agent with access to several BigQuery tools.
     Use the appropriate tools to fetch relevant BigQuery metadata and execute SQL queries.
     You must use these tools to answer the user's questions.
     Run these queries in the project-id: '<YOUR_PROJECT_ID>' on the `ecommerce` dataset.
    """
 ),
 tools=[bigquery_toolset]
)

अब टर्मिनल पर वापस जाएं और फिर से आकलन करें:

python evaluate_agent.py

आपको दिखना चाहिए कि अब नतीजे पहले से ज़्यादा बेहतर हैं:

==================================================

--- Aggregated Evaluation Summary ---
Total questions in evaluation dataset: 15
Average Completeness Score: 4.73
Average Factual Accuracy Score: 4.20

==================================================

अपने एजेंट का आकलन करना, लगातार की जाने वाली प्रोसेस है. जवाबों के आकलन के नतीजों को और बेहतर बनाने के लिए, सिस्टम के निर्देशों, मॉडल के पैरामीटर या BigQuery में मौजूद मेटाडेटा में बदलाव किया जा सकता है. ज़्यादा आइडिया पाने के लिए, ये सलाह और तरकीबें देखें.

13. क्लीन अप करें

अपने Google Cloud खाते से शुल्क लिए जाने से बचने के लिए, इस वर्कशॉप के दौरान बनाई गई संसाधनों को मिटाना ज़रूरी है.

अगर आपने इस कोडलैब के लिए कोई खास BigQuery डेटासेट या टेबल बनाई हैं (जैसे, ई-कॉमर्स डेटासेट), तो हो सकता है कि आपको उन्हें मिटाना हो:

bq rm -r $PROJECT_ID:ecommerce

bigquery-adk-codelab डायरेक्ट्री और उसके कॉन्टेंट को हटाने के लिए:

cd .. # Go back to your home directory if you are still in bigquery-adk-codelab
rm -rf bigquery-adk-codelab

14. बधाई हो

बधाई हो! आपने Agent Development Kit (ADK) का इस्तेमाल करके, BigQuery एजेंट को बना लिया है और उसका आकलन कर लिया है. अब आपको पता चल गया है कि BigQuery टूल के साथ ADK एजेंट को कैसे सेट अप किया जाता है. साथ ही, कस्टम आकलन मेट्रिक का इस्तेमाल करके, उसकी परफ़ॉर्मेंस का आकलन कैसे किया जाता है.

रेफ़रंस दस्तावेज़