วิเคราะห์การดำเนินการของ ADK Agent ด้วยปลั๊กอินการวิเคราะห์ Agent ของ BigQuery

1. บทนำ

ใน Codelab นี้ คุณจะได้สร้างระบบ Multi-Agent โดยใช้ Agent Development Kit (ADK) และเปิดใช้ความสามารถในการสังเกต Agent โดยใช้ปลั๊กอิน BigQuery Agent Analytics จากนั้นถามคำถามชุดหนึ่งกับ Agent แล้วใช้ BigQuery เพื่อวิเคราะห์การติดตามการสนทนาและการใช้งานเครื่องมือของ Agent

c8d3754ee87af43f.png

สิ่งที่คุณจะได้ทำ

  • สร้างผู้ช่วยด้านการค้าปลีกแบบ Multi-Agent โดยใช้ ADK
  • เริ่มต้นใช้งานปลั๊กอิน BigQuery Agent Analytics เพื่อบันทึกและจัดเก็บข้อมูลการติดตามเกี่ยวกับการดำเนินการของ Agent นี้ลงใน BigQuery
  • วิเคราะห์ข้อมูลบันทึกของ Agent ใน BigQuery

สิ่งที่คุณต้องมี

  • เว็บเบราว์เซอร์ เช่น Chrome
  • โปรเจ็กต์ Google Cloud ที่เปิดใช้การเรียกเก็บเงิน หรือ
  • บัญชี Gmail ส่วนถัดไปจะแสดงวิธีแลกรับเครดิตฟรี $5 สำหรับ Codelab นี้และตั้งค่าโปรเจ็กต์ใหม่

Codelab นี้เหมาะสำหรับนักพัฒนาซอฟต์แวร์ทุกระดับ รวมถึงผู้เริ่มต้น คุณจะได้ใช้อินเทอร์เฟซบรรทัดคำสั่งใน Google Cloud Shell และโค้ด Python สำหรับการพัฒนา ADK คุณไม่จำเป็นต้องเป็นผู้เชี่ยวชาญด้าน Python แต่ความเข้าใจพื้นฐานเกี่ยวกับวิธีอ่านโค้ดจะช่วยให้คุณเข้าใจแนวคิดต่างๆ ได้

2. ก่อนเริ่มต้น

สร้างโปรเจ็กต์ Google Cloud

  1. ใน คอนโซล Google Cloud ในหน้าตัวเลือกโปรเจ็กต์ ให้ เลือกหรือสร้างโปรเจ็กต์ Google Cloud

c745d833b0ed52b0.png

  1. ตรวจสอบว่าได้เปิดใช้การเรียกเก็บเงินสำหรับโปรเจ็กต์ที่อยู่ในระบบคลาวด์แล้ว ดูวิธี ตรวจสอบว่าได้เปิดใช้การเรียกเก็บเงินในโปรเจ็กต์แล้ว

เริ่มต้น Cloud Shell

Cloud Shell คือสภาพแวดล้อมบรรทัดคำสั่งที่ทำงานใน Google Cloud ซึ่งโหลดเครื่องมือที่จำเป็นไว้ล่วงหน้า

  1. คลิกเปิดใช้งาน Cloud Shell ที่ด้านบนของคอนโซล Google Cloud

404e4cce0f23e5c5.png

  1. เมื่อเชื่อมต่อกับ Cloud Shell แล้ว ให้เรียกใช้คำสั่งนี้เพื่อยืนยันการตรวจสอบสิทธิ์ใน Cloud Shell
gcloud auth list
  1. เรียกใช้คำสั่งต่อไปนี้เพื่อยืนยันว่าได้กำหนดค่าโปรเจ็กต์ให้ใช้กับ gcloud แล้ว
gcloud config get project
  1. หากไม่ได้กำหนดค่าโปรเจ็กต์ตามที่คาดไว้ ให้ใช้คำสั่งต่อไปนี้เพื่อตั้งค่าโปรเจ็กต์
export PROJECT_ID=<YOUR_PROJECT_ID>
gcloud config set project $PROJECT_ID

เปิดใช้ API

  1. เรียกใช้คำสั่งนี้เพื่อเปิดใช้ API และบริการที่จำเป็นทั้งหมด
gcloud services enable bigquery.googleapis.com \
cloudresourcemanager.googleapis.com \
aiplatform.googleapis.com
  1. เมื่อเรียกใช้คำสั่งสำเร็จ คุณควรเห็นข้อความที่คล้ายกับข้อความที่แสดงด้านล่าง

Operation "operations/..." finished successfully.

3. การติดตั้งและการตั้งค่า

กลับไปที่ Cloud Shell และตรวจสอบว่าคุณอยู่ในไดเรกทอรีหลัก

เรียกใช้คำสั่งต่อไปนี้ใน Cloud Shell เพื่อสร้างชุดข้อมูลใหม่ชื่อ adk_logs ใน BigQuery

bq mk --dataset --location=US adk_logs

ตอนนี้เรามาสร้างสภาพแวดล้อมเสมือนของ Python และติดตั้งแพ็กเกจที่จำเป็นกัน

  1. เปิดแท็บเทอร์มินัลใหม่ใน Cloud Shell แล้วเรียกใช้คำสั่งนี้เพื่อสร้างและไปยังโฟลเดอร์ชื่อ adk-agent-observability
mkdir adk-agent-observability
cd adk-agent-observability
  1. สร้างสภาพแวดล้อมเสมือนของ Python
python -m venv .venv
  1. เปิดใช้งานสภาพแวดล้อมเสมือน
source .venv/bin/activate
  1. ติดตั้ง ADK
pip install --upgrade google-adk

4. สร้างแอปพลิเคชัน ADK

ตอนนี้เรามาสร้าง Agent ผู้ช่วยด้านการค้าปลีกกัน Agent นี้จะได้รับการออกแบบมาเพื่อ ...

  1. เรียกใช้คำสั่งยูทิลิตี adk create เพื่อสร้างโครงสร้างแอปพลิเคชัน Agent ใหม่ด้วยโฟลเดอร์และไฟล์ที่จำเป็น
adk create retail_assistant_app

ทำตามคำแนะนำ

  1. เลือก gemini-2.5-flash สำหรับโมเดล
  2. เลือก Vertex AI สำหรับแบ็กเอนด์
  3. ยืนยันรหัสโปรเจ็กต์ Google Cloud และภูมิภาคเริ่มต้น

ตัวอย่างการโต้ตอบแสดงไว้ด้านล่าง

acc9c6bb436f7025.png

  1. คลิกปุ่ม Open Editor ใน Cloud Shell เพื่อเปิด Cloud Shell Editor และดูโฟลเดอร์และไฟล์ที่สร้างขึ้นใหม่

a940b7eaf3c9f4b3.png

โปรดทราบไฟล์ที่สร้างขึ้น

retail_assistant_app/
├── .venv/
└── retail_assistant_app/
    ├── __init__.py
    ├── agent.py
    └── .env
  • init.py: ทำเครื่องหมายโฟลเดอร์เป็นโมดูล Python
  • agent.py: มีคำจำกัดความเริ่มต้นของ Agent
  • .env: คุณอาจต้องคลิก View > Toggle Hidden Files เพื่อดูไฟล์นี้

16a1a92b33f78e6b.png

  • ไฟล์ .env มีตัวแปรสภาพแวดล้อมสำหรับโปรเจ็กต์ของคุณ โปรดอัปเดตตัวแปรที่ตั้งค่าไม่ถูกต้องจากข้อความแจ้ง
GOOGLE_GENAI_USE_VERTEXAI=1
GOOGLE_CLOUD_PROJECT=<YOUR_GOOGLE_PROJECT_ID>
GOOGLE_CLOUD_LOCATION=<YOUR_GOOGLE_CLOUD_REGION>

5. กำหนด Agent

ตอนนี้เรามากำหนดระบบ Multi-Agent แบบลำดับชั้นกัน

  1. Real Time Trend Agent: ใช้ Google Search เพื่อค้นหาเทรนด์แฟชั่นปัจจุบัน
  2. Inventory Data Agent: ใช้ชุดเครื่องมือ BigQuery เพื่อค้นหาชุดข้อมูลสาธารณะ thelook_ecommerce สำหรับผลิตภัณฑ์ที่มี
  3. Retail assistant (Root) Agent: จัดการเวิร์กโฟลว์โดยขอคำแนะนำจาก Trend Agent และขอผลิตภัณฑ์ที่ตรงกันจาก Inventory Agent

แทนที่เนื้อหาทั้งหมดของ retail_assistant_app/agent.py ด้วยโค้ดต่อไปนี้

import os
import uuid
import asyncio
import google.auth
import dotenv
from google.genai import types
from google.adk.agents import Agent
from google.adk.apps import App
from google.adk.runners import InMemoryRunner
from google.adk.tools import AgentTool, google_search
from google.adk.tools.bigquery import BigQueryCredentialsConfig, BigQueryToolset
from google.adk.plugins.bigquery_agent_analytics_plugin import BigQueryAgentAnalyticsPlugin

dotenv.load_dotenv()

# --- Configuration ---

PROJECT_ID = os.getenv('GOOGLE_CLOUD_PROJECT', 'project_not_set')
DATASET_ID = "adk_logs"
TABLE_ID = "retail_assistant_agent_logs"
APP_NAME = "retail_assistant_agent"
USER_ID = "test_user"

# --- Toolsets ---

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

# --- Agents ---

# 1. Trend Spotter
real_time_agent = Agent(
   name="real_time_agent",
   model="gemini-2.5-flash",
    description="Researches external factors like weather, local events, and current fashion trends.",
   instruction="""
       You are a real-time research agent.
       Use Google Search to find real-time information relevant to the user's request,
       such as the current weather in their location or trending styles.
   """,
   tools=[google_search]
)

# 2. Inventory Manager
inventory_data_agent = Agent(
   name="inventory_data_agent",
   model="gemini-2.5-flash",
   description="Oversees product inventory in the BigQuery `thelook_ecommerce` dataset to find available items and prices.",
   instruction=f"""
   You manage the inventory. You have access to the `bigquery-public-data.thelook_ecommerce` dataset via the BigQuery toolset.
   Run all BigQuery queries the project id of: '{PROJECT_ID}'
  
   Your workflow:
   1. Look at the products table.
   2. Find items that match the requirements, factor in the results from the trend_setter agent if there are any.
   3. Return with a user friendly response, including the list of specific products and prices.
   """,
   tools=[bigquery_toolset]
)

# 3. Root Orchestrator
root_agent = Agent(
   name="retail_assistant",
   model="gemini-2.5-flash",   
   description="The primary orchestrator, responsible for handling user input, delegating to sub-agents, and synthesizing the final product recommendation.",
   instruction="""
   You are a Retail Assistant.   
   You can ask the 'real_time_agent' agent for any realtime information needed, or style advice, include any information provided by the user.
   You should ask the 'inventory_data_agent' agent to find a maximum of 3 available items matching that style.
   Combine the results into a recommendation.
   """,
   tools=[AgentTool(agent=real_time_agent)],
   sub_agents=[inventory_data_agent]
)

6. สร้างบันทึกด้วยปลั๊กอิน BigQuery Agent Analytics

ตอนนี้เรามากำหนดค่าปลั๊กอิน BigQuery Agent Analytics เพื่อบันทึกข้อมูลการดำเนินการกัน

ในการดำเนินการนี้ คุณจะต้องสร้างอินสแตนซ์ของคลาส App คลาสนี้ทำหน้าที่เป็นคอนเทนเนอร์รันไทม์สำหรับ Agent โดยจะจัดการลูปการสนทนา จัดการสถานะของผู้ใช้ และจัดการปลั๊กอินที่แนบมา (เช่น ตัวบันทึกข้อมูลวิเคราะห์ Agent ของเรา)

โค้ดด้านล่างจะทำสิ่งต่อไปนี้

  • เริ่มต้นปลั๊กอินการบันทึก: สร้าง BigQueryAgentAnalyticsPlugin พร้อมรายละเอียดการเชื่อมต่อที่จำเป็น
  • ผสานรวมปลั๊กอิน: ส่งปลั๊กอิน BigQuery ที่เริ่มต้นแล้วไปยังตัวสร้าง App เพื่อให้มั่นใจว่าระบบจะบันทึกและติดตามเหตุการณ์การดำเนินการของ Agent โดยอัตโนมัติ
  • เรียกใช้และบันทึกการดำเนินการของ Agent: เรียกใช้โฟลว์การสนทนาผ่าน runner.run_async โดยที่ปลั๊กอินจะรวบรวมและส่งลำดับเหตุการณ์ทั้งหมดไปยัง BigQuery พร้อมกันก่อนที่จะปิดทรัพยากร

คัดลอกและวางโค้ดนี้ไว้ใต้คำจำกัดความของ Agent ในไฟล์ agent.py

async def main(prompt: str):
    """Runs a conversation with the BigQuery agent using the ADK Runner."""
    bq_logger_plugin = BigQueryAgentAnalyticsPlugin(
        project_id=PROJECT_ID, dataset_id=DATASET_ID, table_id=TABLE_ID
    )
    app = App(name=APP_NAME, root_agent=root_agent, plugins=[bq_logger_plugin])
    runner = InMemoryRunner(app=app)

    try:
        session_id = f"{USER_ID}_{uuid.uuid4().hex[:8]}"

        my_session = await runner.session_service.create_session(
            app_name=APP_NAME, user_id=USER_ID, session_id=session_id
        )

        async for event in runner.run_async(
            user_id=USER_ID,
            new_message=types.Content(
                role="user", parts=[types.Part.from_text(text=prompt)]
            ),
            session_id=my_session.id,
        ):
            if event.content.parts and event.content.parts[0].text:
                print(f"** {event.author}: {event.content.parts[0].text}")

    except Exception as e:
        print(f"Error in main: {e}")
    finally:
        print("Closing BQ Plugin...")
        await bq_logger_plugin.close()
        print("BQ Plugin closed.")

async def run_all_prompts():
    """Runs all prompts in a single event loop."""
    prompts = [
        "what outfits do you have available that are suitable for the weather in london this week?",
        "You are such a cool agent! I need a gift idea for my friend who likes yoga.",
        "I'd like to complain - the products sold here are not very good quality!"
    ]
    for prompt in prompts:
        await main(prompt)

if __name__ == "__main__":
    asyncio.run(run_all_prompts())

เมื่อมีการวัดและบันทึกข้อมูลแล้ว ก็ถึงเวลาดู Agent ในการทำงานจริง เรียกใช้สคริปต์เพื่อทริกเกอร์เวิร์กโฟลว์การสนทนา

python retail_assistant_app/agent.py

คุณควรเห็นผู้ช่วยด้านการค้าปลีกจัดการเวิร์กโฟลว์ดังนี้

  1. ขอให้ Real Time Trend Agent (real_time_agent) ระบุสภาพอากาศในลอนดอนและค้นหาเทรนด์แฟชั่นที่เหมาะสม
  2. จากนั้นมอบหมายให้ Inventory Data Agent (inventory_data_agent) ค้นหาชุดข้อมูล thelook_ecommerce BigQuery สำหรับสินค้าที่เฉพาะเจาะจงซึ่งตรงกับเทรนด์เหล่านั้น
  3. สุดท้าย Root Orchestrator จะสังเคราะห์ผลลัพธ์เป็นคำแนะนำสุดท้าย

ในขณะเดียวกัน ปลั๊กอินจะสตรีมการติดตามการดำเนินการของ Agent ไปยัง BigQuery

7. วิเคราะห์บันทึกของ Agent

การใช้งานเครื่องมือ

ตอนนี้เราสามารถดูสิ่งที่ Agent ของเราทำอยู่เบื้องหลังได้แล้ว ระบบได้สตรีมข้อมูลไปยัง BigQuery และพร้อมสำหรับการวิเคราะห์แล้ว

  1. ในคอนโซล Google Cloud ให้ค้นหา BigQuery
  2. ในบานหน้าต่าง Explorer ให้ค้นหาโปรเจ็กต์
  3. ขยายชุดข้อมูล adk_logs
  4. เปิดตาราง retail_assitant_agent_logs แล้วคลิก Query

a2de3b52da21855f.png

หากต้องการดูการเรียกใช้เครื่องมือที่ Agent ของคุณทำและบันทึกข้อผิดพลาดของเครื่องมือ ให้เรียกใช้การค้นหาต่อไปนี้ใน BigQuery Editor

SELECT
  -- Extract