এজেন্ট ডেভেলপমেন্ট কিট (ADK) এবং GenAI ইভাল পরিষেবা ব্যবহার করে BigQuery এজেন্ট তৈরি ও মূল্যায়ন করুন

1. ভূমিকা

এই কোডল্যাবে আপনি শিখবেন কীভাবে এজেন্ট তৈরি করতে হয় যেগুলি এজেন্ট ডেভেলপমেন্ট কিট (ADK ) ব্যবহার করে BigQuery- এ সংরক্ষিত ডেটা সম্পর্কে প্রশ্নের উত্তর দিতে পারে। আপনি Vertex AI এর GenAI মূল্যায়ন পরিষেবা ব্যবহার করে এই এজেন্টদের মূল্যায়ন করবেন:

dff1b6eccdd36160.png

আপনি কি করবেন

  • ADK- এ একটি কথোপকথন বিশ্লেষণী এজেন্ট তৈরি করুন
  • BigQuery-এর জন্য এই এজেন্টকে ADK-এর প্রথম পক্ষের টুলসেট দিয়ে সজ্জিত করুন যাতে এটি BigQuery-এ সঞ্চিত ডেটার সাথে ইন্টারঅ্যাক্ট করতে পারে
  • Vertex AI GenAI মূল্যায়ন পরিষেবা ব্যবহার করে আপনার এজেন্টের জন্য একটি মূল্যায়ন কাঠামো তৈরি করুন
  • সুবর্ণ প্রতিক্রিয়াগুলির একটি সেটের বিরুদ্ধে এই এজেন্টের মূল্যায়ন চালান

আপনি কি প্রয়োজন হবে

  • একটি ওয়েব ব্রাউজার যেমন ক্রোম
  • বিলিং সক্ষম সহ একটি Google ক্লাউড প্রকল্প, বা৷
  • একটি জিমেইল অ্যাকাউন্ট। এই কোডল্যাবের জন্য কীভাবে বিনামূল্যে $5 ক্রেডিট রিডিম করবেন এবং একটি নতুন প্রকল্প সেট আপ করবেন তা পরবর্তী বিভাগটি আপনাকে দেখাবে

এই কোডল্যাবটি নতুনদের সহ সকল স্তরের বিকাশকারীদের জন্য। আপনি ADK ডেভেলপমেন্টের জন্য Google ক্লাউড শেল এবং পাইথন কোডে কমান্ড-লাইন ইন্টারফেস ব্যবহার করবেন। আপনাকে পাইথন বিশেষজ্ঞ হতে হবে না, তবে কোড কীভাবে পড়তে হয় তার একটি প্রাথমিক ধারণা আপনাকে ধারণাগুলি বুঝতে সাহায্য করবে।

2. আপনি শুরু করার আগে

একটি Google ক্লাউড প্রকল্প তৈরি করুন

  1. Google ক্লাউড কনসোলে , প্রকল্প নির্বাচক পৃষ্ঠায়, একটি Google ক্লাউড প্রকল্প নির্বাচন করুন বা তৈরি করুন

a6e0191f0ee7bf4a.png

  1. নিশ্চিত করুন যে আপনার ক্লাউড প্রকল্পের জন্য বিলিং সক্ষম করা আছে৷ একটি প্রকল্পে বিলিং সক্ষম কিনা তা পরীক্ষা করতে শিখুন।

ক্লাউড শেল শুরু করুন

ক্লাউড শেল হল Google ক্লাউডে চলমান একটি কমান্ড-লাইন পরিবেশ যা প্রয়োজনীয় সরঞ্জামগুলির সাথে আগে থেকে লোড করা হয়।

  1. Google ক্লাউড কনসোলের শীর্ষে সক্রিয় ক্লাউড শেল ক্লিক করুন:

cc25e6aa09f99271.png

  1. একবার ক্লাউড শেলের সাথে সংযুক্ত হয়ে গেলে, ক্লাউড শেলে আপনার প্রমাণীকরণ যাচাই করতে এই কমান্ডটি চালান:
gcloud auth list
  1. আপনার প্রকল্পটি gcloud-এর সাথে ব্যবহারের জন্য কনফিগার করা হয়েছে তা নিশ্চিত করতে নিম্নলিখিত কমান্ডটি চালান:
gcloud config list project
  1. আপনার প্রকল্প সেট করতে নিম্নলিখিত কমান্ড ব্যবহার করুন:
export PROJECT_ID=<YOUR_PROJECT_ID>
gcloud config set project $PROJECT_ID

এপিআই সক্ষম করুন

  1. সমস্ত প্রয়োজনীয় API এবং পরিষেবাগুলি সক্ষম করতে এই কমান্ডটি চালান:
gcloud services enable bigquery.googleapis.com \
                       aiplatform.googleapis.com \
                       cloudresourcemanager.googleapis.com
  1. কমান্ডের সফল সঞ্চালন হলে, আপনি নীচের দেখানো একটি অনুরূপ একটি বার্তা দেখতে হবে:
Operation "operations/..." finished successfully.

3. একটি BigQuery ডেটাসেট তৈরি করুন৷

  1. BigQuery-এ ইকমার্স নামে একটি নতুন ডেটাসেট তৈরি করতে ক্লাউড শেল-এ নিম্নলিখিত কমান্ডটি চালান:
bq mk --dataset --location=US ecommerce

BigQuery পাবলিক ডেটাসেটের একটি স্ট্যাটিক সাবসেট thelook_ecommerce একটি সর্বজনীন Google ক্লাউড স্টোরেজ বাকেটের মধ্যে AVRO ফাইল হিসাবে সংরক্ষণ করা হয়।

  1. এই Avro ফাইলগুলিকে টেবিল হিসাবে BigQuery-এ লোড করতে ক্লাউড শেল-এ এই কমান্ডটি চালান (ইভেন্ট, অর্ডার_আইটেম, পণ্য, ব্যবহারকারী, অর্ডার):
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 ক্লাউড প্রজেক্টে BigQuery কনসোলে গিয়ে ডেটাসেট এবং টেবিল তৈরি করা হয়েছে তা যাচাই করুন:

f8ba5156d27b73d0.png

4. ADK এজেন্টদের জন্য পরিবেশ প্রস্তুত করুন

ক্লাউড শেল এ ফিরে যান এবং নিশ্চিত করুন যে আপনি আপনার হোম ডিরেক্টরিতে আছেন। আমরা একটি ভার্চুয়াল পাইথন পরিবেশ তৈরি করব এবং প্রয়োজনীয় প্যাকেজগুলি ইনস্টল করব।

  1. ক্লাউড শেলে একটি নতুন টার্মিনাল ট্যাব খুলুন এবং bigquery-adk-codelab নামে একটি ফোল্ডার তৈরি করতে এবং নেভিগেট করতে এই কমান্ডটি চালান:
mkdir bigquery-adk-codelab
cd bigquery-adk-codelab
  1. একটি ভার্চুয়াল পাইথন পরিবেশ তৈরি করুন:
python -m venv .venv
  1. ভার্চুয়াল পরিবেশ সক্রিয় করুন:
source .venv/bin/activate
  1. Google এর ADK এবং AI-প্ল্যাটফর্ম পাইথন প্যাকেজ ইনস্টল করুন। বিগকুয়েরি এজেন্ট মূল্যায়ন করার জন্য এআই প্ল্যাটফর্ম এবং পান্ডাস প্যাকেজ প্রয়োজন:
pip install google-adk google-cloud-aiplatform[evaluation] pandas

5. একটি ADK অ্যাপ্লিকেশন তৈরি করুন৷

এখন, আমাদের BigQuery এজেন্ট তৈরি করা যাক। এই এজেন্টটিকে BigQuery-এ সঞ্চিত ডেটা সম্পর্কে স্বাভাবিক ভাষার প্রশ্নের উত্তর দেওয়ার জন্য ডিজাইন করা হবে।

  1. প্রয়োজনীয় ফোল্ডার এবং ফাইল সহ একটি নতুন এজেন্ট অ্যাপ্লিকেশন স্ক্যাফোল্ড করতে adk create utility কমান্ডটি চালান:
adk create data_agent_app

প্রম্পটগুলি অনুসরণ করুন:

  1. মডেলের জন্য মিথুন-2.5-ফ্ল্যাশ বেছে নিন।
  2. ব্যাকএন্ডের জন্য ভার্টেক্স এআই বেছে নিন।
  3. আপনার ডিফল্ট Google ক্লাউড প্রকল্প আইডি এবং অঞ্চল নিশ্চিত করুন৷

একটি নমুনা মিথস্ক্রিয়া নীচে দেখানো হয়েছে:

c833d29f517f0a0f.png

  1. ক্লাউড শেল এডিটর খুলতে এবং নতুন তৈরি ফোল্ডার এবং ফাইল দেখতে ক্লাউড শেল-এ ওপেন এডিটর বোতামে ক্লিক করুন :

16ed263528e6cc1f.png

উত্পন্ন ফাইল নোট করুন:

bigquery-adk-codelab/
├── .venv/
└── data_agent_app/
    ├── __init__.py
    ├── agent.py
    └── .env
  • init.py: ফোল্ডারটিকে পাইথন মডিউল হিসেবে চিহ্নিত করে।
  • 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 ডেটাতে SQL কোয়েরি চালানোর ক্ষমতা প্রদান করে। টুলসেট ব্যবহার করার জন্য, আপনাকে অবশ্যই প্রমাণীকরণ করতে হবে, বিকাশের জন্য অ্যাপ্লিকেশন ডিফল্ট শংসাপত্র (ADC), যখন এজেন্টকে একটি নির্দিষ্ট ব্যবহারকারীর পক্ষে কাজ করতে হবে তার জন্য ইন্টারেক্টিভ OAuth, বা নিরাপদ, উৎপাদন-স্তরের প্রমাণীকরণের জন্য পরিষেবা অ্যাকাউন্টের শংসাপত্রগুলি হচ্ছে।

এখান থেকে, আপনি ক্লাউড শেলে ফিরে এসে এই কমান্ডটি চালিয়ে আপনার এজেন্টের সাথে চ্যাট করতে পারেন:

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 ওয়েব চালু করতে দেওয়া url-এ ক্লিক করুন - আপনি আপনার এজেন্টকে ডেটাসেট সম্পর্কে কিছু প্রশ্ন করতে পারেন:

c0ceac4d3a3cc321.gif

adk ওয়েব বন্ধ করুন এবং ওয়েব সার্ভার বন্ধ করতে টার্মিনালে Ctrl + C টিপুন।

7. মূল্যায়নের জন্য আপনার এজেন্টকে প্রস্তুত করুন

এখন আপনি আপনার BigQuery এজেন্টকে সংজ্ঞায়িত করেছেন, আপনাকে এটিকে মূল্যায়নের জন্য চালাতে হবে।

নীচের কোডটি একটি ফাংশন সংজ্ঞায়িত করে, run_conversation , যা একটি এজেন্ট তৈরি করে, একটি সেশন চালানোর মাধ্যমে এবং চূড়ান্ত প্রতিক্রিয়া পুনরুদ্ধার করার জন্য ইভেন্টগুলি প্রক্রিয়া করার মাধ্যমে কথোপকথন প্রবাহ পরিচালনা করে।

  1. ক্লাউড এডিটরে ফিরে যান এবং 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 ​​মূল্যায়ন ডেটাসেট এবং কাস্টম মেট্রিক্স নেয় এবং একটি নতুন মূল্যায়ন পরীক্ষা সেট আপ করে।

এই ফাংশন, রান_ইভাল, মূল্যায়নের প্রধান ইঞ্জিন। এটি একটি 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. আপনার মূল্যায়ন চালান

এখন যেহেতু আপনার এজেন্ট, মূল্যায়ন মেট্রিক্স এবং মূল্যায়ন ডেটাসেট প্রস্তুত, আপনি মূল্যায়ন চালাতে পারেন।

ক্লাউড শেল-এ ফিরে যান, নিশ্চিত করুন যে আপনি 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 ক্লাউড অ্যাকাউন্টে চলমান চার্জ এড়াতে, এই কর্মশালার সময় আমরা যে সংস্থানগুলি তৈরি করেছি তা মুছে ফেলা গুরুত্বপূর্ণ৷

আপনি যদি এই কোডল্যাবের জন্য কোনো নির্দিষ্ট 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. অভিনন্দন

অভিনন্দন! আপনি সফলভাবে এজেন্ট ডেভেলপমেন্ট কিট (ADK) ব্যবহার করে একটি BigQuery এজেন্ট তৈরি ও মূল্যায়ন করেছেন। আপনি এখন বুঝতে পারছেন কিভাবে BigQuery টুল দিয়ে একটি ADK এজেন্ট সেট আপ করতে হয় এবং কাস্টম মূল্যায়ন মেট্রিক্স ব্যবহার করে এর কার্যক্ষমতা পরিমাপ করতে হয়।

রেফারেন্স ডক্স