הערכת סוכני AI גנרטיבי באמצעות GenAI Client ב-Agent Platform SDK

אחרי שיוצרים מודל AI גנרטיבי ומעריכים אותו, אפשר להשתמש במודל כדי ליצור סוכן, כמו צ'אטבוט. באמצעות Gen AI evals אפשר למדוד את היכולת של הסוכן להשלים משימות ולהשיג יעדים לתרחיש השימוש שלכם.

בדף הזה מוסבר איך ליצור ולפרוס סוכן בסיסי ולהשתמש בהערכות של AI גנרטיבי כדי להעריך את הסוכן:

לפני שמתחילים

  1. נכנסים לחשבון Google Cloud . אם אתם משתמשים חדשים ב- Google Cloud, צרו חשבון כדי שתוכלו להעריך את הביצועים של המוצרים שלנו בתרחישים מהעולם האמיתי. לקוחות חדשים מקבלים בחינם גם קרדיט בשווי 300$ להרצה, לבדיקה ולפריסה של עומסי העבודה.

    In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

    Verify that billing is enabled for your Google Cloud project.

    In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

    Verify that billing is enabled for your Google Cloud project.

  2. מתקינים את Agent Platform SDK ל-Python:

    %pip install google-cloud-aiplatform[adk,agent_engines]
    %pip install --upgrade --force-reinstall -q google-cloud-aiplatform[evaluation]
    
  3. מגדירים את פרטי הכניסה. אם אתם מריצים את המדריך הזה ב-Colaboratory, מריצים את הפקודה הבאה:

    from google.colab import auth
    auth.authenticate_user()
    

    בסביבות אחרות, אפשר לעיין במאמר בנושא אימות ב-Agent Platform.

  4. אתחול לקוח ה-AI הגנרטיבי ב-Agent Platform SDK:

    import vertexai
    from vertexai import Client
    from google.genai import types as genai_types
    
    GCS_DEST = "gs://BUCKET_NAME/output-path"
    vertexai.init(
        project=PROJECT_ID,
        location=LOCATION,
    )
    
    client = Client(
        project=PROJECT_ID,
        location=LOCATION,
        http_options=genai_types.HttpOptions(api_version="v1beta1"),
      )
    

    מחליפים את מה שכתוב בשדות הבאים:

    • BUCKET_NAME: שם הקטגוריה של Cloud Storage. במאמר יצירת קטגוריה יש מידע נוסף על יצירת קטגוריות.

    • PROJECT_ID: מזהה הפרויקט.

    • LOCATION: האזור שבחרתם.

פיתוח סוכן

פיתוח סוכן באמצעות ערכה לפיתוח סוכנים (ADK) על ידי הגדרת המודל, ההוראה וערכת הכלים. מידע נוסף על פיתוח סוכנים זמין במאמר פיתוח סוכנים באמצעות ערכה לפיתוח סוכנים (ADK).

from google.adk import Agent

# Define Agent Tools
def search_products(query: str):
    """Searches for products based on a query."""
    # Mock response for demonstration
    if "headphones" in query.lower():
        return {"products": [{"name": "Wireless Headphones", "id": "B08H8H8H8H"}]}
    else:
        return {"products": []}

def get_product_details(product_id: str):
    """Gets the details for a given product ID."""
    if product_id == "B08H8H8H8H":
        return {"details": "Noise-cancelling, 20-hour battery life."}
    else:
        return {"error": "Product not found."}

def add_to_cart(product_id: str, quantity: int):
    """Adds a specified quantity of a product to the cart."""
    return {"status": f"Added {quantity} of {product_id} to cart."}

# Define Agent
my_agent = Agent(
    model="gemini-2.5-flash",
    name='ecommerce_agent',
    instruction='You are an ecommerce expert',
    tools=[search_products, get_product_details, add_to_cart],
)

פריסת הסוכן

פורסים את הסוכן ב-Agent Platform Runtime. הפעולה עשויה להימשך עד 10 דקות. מאחזרים את שם המשאב מהסוכן שנפרס.

def deploy_adk_agent(root_agent):
  """Deploy agent to agent engine.
  Args:
    root_agent: The ADK agent to deploy.
  """
  app = vertexai.agent_engines.AdkApp(
      agent=root_agent,
  )
  remote_app = client.agent_engines.create(
      agent=app,
      config = {
          "staging_bucket": gs://BUCKET_NAME,
          "requirements": ['google-cloud-aiplatform[adk,agent_engines]'],
          "env_vars": {"GOOGLE_CLOUD_AGENT_ENGINE_ENABLE_TELEMETRY": "true"}
      }
  )
  return remote_app

agent_engine = deploy_adk_agent(my_agent)
agent_engine_resource_name = agent_engine.api_resource.name

כדי לראות את רשימת הסוכנים שנפרסו ב-Agent Platform, אפשר לעיין במאמר בנושא ניהול סוכנים שנפרסו.

יצירת תשובות

  1. יצירת תשובות של המודל למערך הנתונים באמצעות run_inference():

    מכינים את מערך הנתונים כ-DataFrame של Pandas. ההנחיות צריכות להיות ספציפיות לסוכן. כדי לעקוב אחרי שיחות, צריך להזין את נתוני הסשן. מידע נוסף זמין במאמר סשן: מעקב אחרי שיחות ספציפיות.

    import pandas as pd
    from vertexai import types
    
    session_inputs = types.evals.SessionInput(
        user_id="user_123",
        state={},
    )
    agent_prompts = [
        "Search for 'noise-cancelling headphones'.",
        "Show me the details for product 'B08H8H8H8H'.",
        "Add one pair of 'B08H8H8H8H' to my shopping cart.",
        "Find 'wireless earbuds' and then add the first result to my cart.",
        "I need a new laptop for work, can you find one with at least 16GB of RAM?",
    ]
    agent_dataset = pd.DataFrame({
        "prompt": agent_prompts,
        "session_inputs": [session_inputs] * len(agent_prompts),
    })
    
  2. יצירת תשובות של מודל באמצעות run_inference():

    agent_dataset_with_inference = client.evals.run_inference(
        agent=agent_engine_resource_name,
        src=agent_dataset,
    )
    
  3. כדי להציג את תוצאות ההיסק, קוראים לפונקציה .show() באובייקט EvaluationDataset כדי לבדוק את הפלט של המודל לצד ההנחיות וההפניות המקוריות:

    agent_dataset_with_inference.show()
    

הרצת הערכה של הסוכן

מריצים את create_evaluation_run() כדי להעריך את התשובות של הסוכן.

  1. אפשר לאחזר את agent_info באמצעות פונקציית העזר המובנית:

    agent_info = types.evals.AgentInfo.load_from_agent(
        my_agent,
        agent_engine_resource_name
    )
    
  2. הערכת התשובות של המודל באמצעות מדדים מותאמים אישית שמבוססים על קריטריונים (FINAL_RESPONSE_QUALITY,‏ TOOL_USE_QUALITY ו-HALLUCINATION) שספציפיים לסוכן:

    evaluation_run = client.evals.create_evaluation_run(
        dataset=agent_dataset_with_inference,
        agent_info=agent_info,
        metrics=[
            types.RubricMetric.FINAL_RESPONSE_QUALITY,
            types.RubricMetric.TOOL_USE_QUALITY,
            types.RubricMetric.HALLUCINATION,
            types.RubricMetric.SAFETY,
        ],
        dest=GCS_DEST,
    )
    

צפייה בתוצאות ההערכה של הנציג

אפשר לראות את תוצאות ההערכה באמצעות Agent Platform SDK.

כדי לאחזר את הרצת ההערכה ולהציג את תוצאות ההערכה, קוראים ל-.show() כדי להציג מדדי סיכום ותוצאות מפורטות:

evaluation_run = client.evals.get_evaluation_run(
    name=evaluation_run.name,
    include_evaluation_items=True
)

evaluation_run.show()

התוצאות המפורטות כוללות גם עקבות שמראות את האינטראקציות עם הסוכן. מידע נוסף על עקבות זמין במאמר מעקב אחר סוכן.

המאמרים הבאים

אפשר לנסות את מחברות ההערכה הבאות של סוכנים: