פיתוח סוכן נתונים באמצעות Python SDK

בדף הזה מוסבר איך משתמשים ב-Python SDK כדי לשלוח בקשות ל-Conversational Analytics API. בדוגמה לקוד Python אפשר לראות איך מבצעים את הפעולות הבאות:

אימות והגדרת הסביבה

כדי להשתמש ב-Python SDK ל-Conversational Analytics API, צריך לפעול לפי ההוראות ב-Conversational Analytics API SDK Colaboratory notebook כדי להוריד ולהתקין את ה-SDK. שימו לב: שיטת ההורדה והתוכן של SDK Colab עשויים להשתנות.

אחרי שמבצעים את הוראות ההגדרה במחברת, אפשר להשתמש בקוד הבא כדי לייבא את ספריות ה-SDK הנדרשות ולאמת את חשבון Google בסביבת Colaboratory:

from google.colab import auth
auth.authenticate_user()

from google.cloud import geminidataanalytics
from google.api_core import client_options

הגדרת ההגדרות והפעלת הלקוחות

בדוגמת הקוד הבאה ב-Python מוגדרים פרויקט החיוב, המיקום וההוראות למערכת שמשמשים לאורך הסקריפט, ומאותחלים לקוחות API עם הגדרות של נקודות קצה על סמך המיקום:

# Billing project
billing_project = "my_project_name"
location = "LOCATION"

# System instructions
system_instruction = "Help the user analyze their data."

# Set client options based on location.
if not location or location == "global":
  endpoint = "geminidataanalytics.googleapis.com"
elif "-" in location:
  # Regional endpoints
  endpoint = f"geminidataanalytics-{location}.googleapis.com"
else:
  # Multi-regional endpoints
  endpoint = f"geminidataanalytics.{location}.rep.googleapis.com"
opts = client_options.ClientOptions(api_endpoint=endpoint)

data_agent_client = geminidataanalytics.DataAgentServiceClient(client_options=opts)
data_chat_client = geminidataanalytics.DataChatServiceClient(client_options=opts)

מחליפים את הערכים לדוגמה באופן הבא:

  • my_project_name: המזהה של Google Cloud הפרויקט שבו הפעלתם את ממשקי ה-API הנדרשים.
  • LOCATION: המיקום שבו המשאבים מאוחסנים. כדי להשתמש בנקודת הקצה הגלובלית, מציינים global. כדי לעמוד בדרישות של מיקום אחסון הנתונים, צריך לציין אזור יחיד נתמך (למשל us-east4) או אזור שמכיל מספר אזורים (למשל eu או us). מידע נוסף זמין במאמר בנושא מיקום אחסון הנתונים.

  • Help the user analyze their data.: הוראות למערכת שמנחות את התנהגות הסוכן ומאפשרות להתאים אותה לצורכי הנתונים שלכם. לדוגמה, אתם יכולים להשתמש בהוראות מערכת כדי להגדיר מונחים עסקיים, לשלוט באורך התשובה או להגדיר את פורמט הנתונים. מומלץ להגדיר את ההוראות למערכת באמצעות פורמט ה-YAML המומלץ במאמר כתיבת הוראות יעילות למערכת כדי לספק הנחיות מפורטות ומובנות.

התחברות למקור נתונים

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

חיבור לנתונים ב-Looker

בדוגמאות הקוד הבאות אפשר לראות איך מגדירים את הפרטים של חיבור ל-Looker Explore באמצעות מפתחות API או אסימון גישה. אפשר לקשר עד חמישה דוחות Looker Explore בכל פעם באמצעות Conversational Analytics API.

כשמתחברים למקור נתונים של Looker, חשוב לשים לב לנקודות הבאות:

  • אתם יכולים לשאול שאלות על כל דוח Explore שכלול בשיחה.
  • סוכן יכול לשלוח שאילתה רק ל-Explore אחד בכל פעם. אי אפשר להריץ שאילתות בכמה ניתוחים בו-זמנית.
  • נציג יכול לשאול שאלות בכמה ניתוחים באותה שיחה.
  • סוכן יכול לשלוח שאילתות לכמה ניתוחים בשיחה שכוללת שאלות עם כמה חלקים, או בשיחות שכוללות שאלות המשך.

    לדוגמה: משתמש מקשר שני דוחות Explore, אחד בשם cat-explore ואחד בשם dog-explore. המשתמש מזין את השאלה 'מה גדול יותר: מספר החתולים או מספר הכלבים?' כך יישאלו שתי שאילתות: אחת לספירת מספר החתולים ב-cat-explore ואחת לספירת מספר הכלבים ב-dog-explore. הנציג משווה בין המספרים משתי השאילתות אחרי שהוא משלים את שתיהן.

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

מפתחות API

אתם יכולים ליצור חיבור למופע Looker באמצעות מפתחות Looker API שנוצרו, כמו שמתואר במאמר אימות וחיבור למקור נתונים.

looker_client_id = "my_looker_client_id"
looker_client_secret = "my_looker_client_secret"
looker_instance_uri = "https://my_company.looker.com"
lookml_model_1 = "my_model"
explore_1 = "my_explore"
lookml_model_2 = "my_model_2"
explore_2 = "my_explore_2"

looker_explore_reference = geminidataanalytics.LookerExploreReference()
looker_explore_reference.looker_instance_uri = looker_instance_uri
looker_explore_reference.lookml_model = "my_model"
looker_explore_reference.explore = "my_explore"

looker_explore_reference2 = geminidataanalytics.LookerExploreReference()
looker_explore_reference2.looker_instance_uri = looker_instance_uri
looker_explore_reference2.lookml_model = "my_model_2"
looker_explore_reference2.explore = "my_explore_2"

credentials = geminidataanalytics.Credentials()
credentials.oauth.secret.client_id = looker_client_id
credentials.oauth.secret.client_secret = looker_client_secret

datasource_references = geminidataanalytics.DatasourceReferences()
datasource_references.looker.explore_references = [looker_explore_reference, looker_explore_reference2]

מחליפים את הערכים לדוגמה באופן הבא:

  • my_looker_client_id: מזהה הלקוח של מפתח Looker API שנוצר.
  • my_looker_client_secret: ה-client secret של מפתח Looker API שנוצר.
  • https://my_company.looker.com: כתובת ה-URL המלאה של המכונה של Looker.
  • my_model: השם של מודל LookML שכולל את כלי הניתוח שרוצים להתחבר אליו.
  • my_explore: השם של Looker Explore שרוצים שהסוכן לגישה לנתונים ישלח אליו שאילתה.
  • my_model_2: השם של מודל LookML השני שכולל את התכונה Explore שאליה רוצים להתחבר. אפשר לחזור על המשתנה הזה עבור מודלים נוספים, עד חמישה ניתוחים.
  • my_explore_2: השם של Looker Explore נוסף שרוצים שהסוכן לגישה לנתונים ישלח אליו שאילתה. אפשר לחזור על המשתנה הזה כדי לכלול עד חמישה ניתוחים.

טוקן גישה

כדי ליצור קישור למופע Looker, אפשר להשתמש בטוקן גישה, כמו שמתואר במאמר אימות וקישור למקור נתונים באמצעות Conversational Analytics API.

looker_access_token = "my_access_token"
looker_instance_uri = "https://my_company.looker.com"
lookml_model = "my_model"
explore = "my_explore"
lookml_model_2 = "my_model_2"
explore_2 = "my_explore_2"

looker_explore_reference = geminidataanalytics.LookerExploreReference()
looker_explore_reference.looker_instance_uri = looker_instance_uri
looker_explore_reference.lookml_model = "my_model"
looker_explore_reference.explore = "my_explore"

looker_explore_reference2 = geminidataanalytics.LookerExploreReference()
looker_explore_reference2.looker_instance_uri = looker_instance_uri
looker_explore_reference2.lookml_model = "my_model_2"
looker_explore_reference2.explore = "my_explore_2"

credentials = geminidataanalytics.Credentials()
credentials.oauth.secret.client_id = looker_client_id
credentials.oauth.secret.client_secret = looker_client_secret

datasource_references = geminidataanalytics.DatasourceReferences()
datasource_references.looker.explore_references = [looker_explore_reference, looker_explore_reference2]

מחליפים את הערכים לדוגמה באופן הבא:

  • my_access_token: ערך access_token שיוצרים כדי לבצע אימות ל-Looker.
  • https://my_company.looker.com: כתובת ה-URL המלאה של המכונה של Looker.
  • my_model: השם של מודל LookML שכולל את כלי הניתוח שרוצים להתחבר אליו.
  • my_explore: השם של Looker Explore שרוצים שהסוכן לגישה לנתונים ישלח אליו שאילתה.
  • my_model_2: השם של מודל LookML השני שכולל את התכונה Explore שאליה רוצים להתחבר. אפשר לחזור על המשתנה הזה עבור מודלים נוספים, עד חמישה ניתוחים.
  • my_explore_2: השם של Looker Explore נוסף שרוצים שהסוכן לגישה לנתונים ישלח אליו שאילתה. אפשר לחזור על המשתנה הזה כדי לכלול עד חמישה ניתוחים.

התחברות לנתוני BigQuery

ב-Conversational Analytics API, אין מגבלות קשיחות על מספר הטבלאות ב-BigQuery שאפשר להתחבר אליהן. עם זאת, חיבור למספר גדול של טבלאות עלול להפחית את רמת הדיוק או לגרום לחריגה ממגבלת הטוקנים של הקלט במודל.

בקטעים הבאים מוסבר איך להתחבר לנתונים ב-BigQuery באמצעות הפניות לטבלאות או הפניות לגרפים.

התחברות לטבלאות BigQuery

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

bigquery_table_reference_1 = geminidataanalytics.BigQueryTableReference()
bigquery_table_reference_1.project_id = "PROJECT_ID_1"
bigquery_table_reference_1.dataset_id = "DATASET_ID_1"
bigquery_table_reference_1.table_id = "TABLE_ID_1"
bigquery_table_reference_1.schema = geminidataanalytics.Schema()
bigquery_table_reference_1.schema.description = "TABLE_DESCRIPTION"
bigquery_table_reference_1.schema.fields = [
  geminidataanalytics.Field(
    name="COLUMN_NAME",
    description="COLUMN_DESCRIPTION"
  )
]

bigquery_table_reference_2 = geminidataanalytics.BigQueryTableReference()
bigquery_table_reference_2.project_id = "PROJECT_ID_2"
bigquery_table_reference_2.dataset_id = "DATASET_ID_2"
bigquery_table_reference_2.table_id = "TABLE_ID_2"

bigquery_table_reference_3 = geminidataanalytics.BigQueryTableReference()
bigquery_table_reference_3.project_id = "PROJECT_ID_3"
bigquery_table_reference_3.dataset_id = "DATASET_ID_3"
bigquery_table_reference_3.table_id = "TABLE_ID_3"

bigquery_table_reference_3.dataset_id = "DATASET_ID_3"
bigquery_table_reference_3.table_id = "TABLE_ID_3"

# Connect to your data source
datasource_references = geminidataanalytics.DatasourceReferences()
datasource_references.bq.table_references = [bigquery_table_reference_1, bigquery_table_reference_2, bigquery_table_reference_3]

מחליפים את הערכים לדוגמה באופן הבא:

  • PROJECT_ID_1: המזהה של הפרויקט Google Cloud שמכיל את מערך הנתונים והטבלה ב-BigQuery שאליהם רוצים להתחבר. כדי להתחבר למערך נתונים ציבורי, מציינים את bigquery-public-data.
  • DATASET_ID_1: המזהה של מערך הנתונים ב-BigQuery. לדוגמה, san_francisco.
  • TABLE_ID_1: המזהה של הטבלה ב-BigQuery. לדוגמה, street_trees.
  • TABLE_DESCRIPTION: תיאור אופציונלי של תוכן הטבלה והמטרה שלה.
  • COLUMN_NAME: שם העמודה בטבלה שרוצים לספק לה תיאור אופציונלי.
  • COLUMN_DESCRIPTION: תיאור אופציונלי של התוכן והמטרה של העמודה.

התחברות ל-BigQuery Graph

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

# BigQuery graph reference
bigquery_pg_reference = geminidataanalytics.BigQueryPropertyGraphReference()
bigquery_pg_reference.project_id = "GRAPH_PROJECT_ID"
bigquery_pg_reference.dataset_id = "GRAPH_DATASET_ID"
bigquery_pg_reference.property_graph_id = "GRAPH_ID"

# Connect to your data source
datasource_references = geminidataanalytics.DatasourceReferences()
datasource_references.bq.property_graph_references = [bigquery_pg_reference]

מחליפים את הערכים לדוגמה באופן הבא:

  • GRAPH_PROJECT_ID: המזהה של הפרויקט שמכיל את הגרף ב-BigQuery. Google Cloud
  • GRAPH_DATASET_ID: המזהה של מערך הנתונים ב-BigQuery שמכיל את הגרף.
  • GRAPH_ID: המזהה של הגרף ב-BigQuery.

התחברות לנתונים ב-Data Studio

בדוגמת הקוד הבאה מוגדר חיבור למקור נתונים ב-Data Studio.

studio_datasource_id = "my_datasource_id"

studio_references = geminidataanalytics.StudioDatasourceReference()
studio_references.datasource_id = studio_datasource_id

## Connect to your data source
datasource_references.studio.studio_references = [studio_references]

בדוגמה הקודמת, מחליפים את my_datasource_id במזהה של מקור הנתונים.

חיבור לנתוני AlloyDB

בדוגמת הקוד הבאה מוגדר חיבור למסד נתונים של AlloyDB באמצעות Python SDK.

# Define the AlloyDB database reference
alloydb_database_reference = geminidataanalytics.AlloyDbDatabaseReference()
alloydb_database_reference.project_id = "PROJECT_ID"
alloydb_database_reference.region = "REGION"
alloydb_database_reference.cluster_id = "CLUSTER_ID"
alloydb_database_reference.instance_id = "INSTANCE_ID"
alloydb_database_reference.database_id = "DATABASE"
alloydb_database_reference.table_ids = ["TABLE_1_ID", "TABLE_2_ID"]

# Optional: Include this if you have created advanced context for the agent
agent_context_reference = geminidataanalytics.AgentContextReference()
agent_context_reference.context_set_id = f"projects/{billing_project}/locations/{location}/contextSets/your_context_set_id"

# Add the AlloyDB reference to the DatasourceReferences object
datasource_references = geminidataanalytics.DatasourceReferences()
datasource_references.alloydb.database_reference = alloydb_database_reference
# Optional:
# datasource_references.alloydb.agent_context_reference = agent_context_reference

מחליפים את הערכים לדוגמה באופן הבא:

  • PROJECT_ID: מזהה Google Cloud הפרויקט שמכיל את אשכול AlloyDB.
  • REGION: האזור שבו נמצא אשכול AlloyDB, לדוגמה us-central1.
  • CLUSTER_ID: המזהה של אשכול AlloyDB.
  • INSTANCE_ID: המזהה של מופע AlloyDB.
  • DATABASE: השם של מסד הנתונים של היעד – לדוגמה, financial.
  • TABLE_1_ID, TABLE_2_ID: רשימה של הטבלאות במסד הנתונים שהסוכן לגישה לנתונים מציע להשתמש בהן – לדוגמה, "loan", "client", "disp".
  • your_context_set_id: אם יצרתם הקשר מתקדם לסוכן, המזהה של קבוצת ההקשר.

חיבור לנתוני Cloud SQL ל-MySQL

כדי להתחבר למכונה של Cloud SQL ל-MySQL, משתמשים במחלקה CloudSqlReference מה-SDK של geminidataanalytics. כדי לעשות את זה, צריך לציין את הפרויקט, את המופע, את מסד הנתונים ואת הטבלאות הספציפיות שרוצים שהסוכן יתייחס אליהן (אופציונלי).

לפני שמתחברים לנתונים ב-Cloud SQL ל-MySQL, צריך לוודא שמתבצע אימות ל-Cloud SQL ל-MySQL באמצעות ניהול זהויות והרשאות גישה (IAM). למידע נוסף, אפשר לעיין במאמר בנושא אימות ב-Cloud SQL ל-MySQL וב-Cloud SQL ל-PostgreSQL.

בדוגמה הבאה מוגדר חיבור למסד נתונים של Cloud SQL ל-MySQL באמצעות Python SDK.

# Import the necessary library
from google.cloud import geminidataanalytics

# Define the Cloud SQL database reference
cloud_sql_database_reference = geminidataanalytics.CloudSqlDatabaseReference(
    project_id="PROJECT_ID",
    instance_id="INSTANCE_ID",
    database_id="DATABASE_ID",
    # Optional: Specify table IDs to guide the agent
    table_ids=["TABLE_1_ID", "TABLE_2_ID"]
)

# Create a CloudSqlReference object
cloud_sql_reference = geminidataanalytics.CloudSqlReference(
    database_reference=cloud_sql_database_reference
    # Optional: Include this if you have created advanced context for the agent
    # agent_context_reference=geminidataanalytics.AgentContextReference(
    # context_set_id=f"projects/{billing_project}/locations/{location}/contextSets/your_context_set_id"
    # )
)

# Add the Cloud SQL reference to the DatasourceReferences object
datasource_references = geminidataanalytics.DatasourceReferences()
datasource_references.cloud_sql = cloud_sql_reference

מחליפים את הערכים לדוגמה באופן הבא:

  • PROJECT_ID: המזהה של Google Cloud הפרויקט שמכיל את מופע Cloud SQL ל-MySQL.
  • INSTANCE_ID: המזהה של מופע Cloud SQL ל-MySQL.
  • DATABASE_ID: השם של מסד הנתונים היעד בתוך המופע – לדוגמה, financial.
  • TABLE_1_ID, TABLE_2_ID: (אופציונלי) רשימה של שמות טבלאות ספציפיים במסד הנתונים שהסוכן לנתונים מוצע להשתמש בהם – לדוגמה, "orders" ו-"customers".
  • your_context_set_id: אם יצרתם הקשר מתקדם לסוכן, המזהה של קבוצת ההקשר.

אפשר להשתמש באובייקט datasource_references כשיוצרים סוכן נתונים או כשמבצעים אינטראקציה איתו.

חיבור לנתוני Cloud SQL ל-PostgreSQL

כדי להתחבר למופע Cloud SQL ל-PostgreSQL, משתמשים במחלקה CloudSqlReference מה-SDK של geminidataanalytics. כדי לעשות את זה, צריך לציין את הפרויקט, את המופע, את מסד הנתונים ואת הטבלאות הספציפיות שרוצים שהסוכן יתייחס אליהן (אופציונלי).

לפני שמתחברים לנתונים ב-Cloud SQL ל-PostgreSQL, צריך לוודא שמאמתים את הזהות ב-Cloud SQL ל-PostgreSQL באמצעות IAM. למידע נוסף, אפשר לקרוא את המאמר בנושא אימות ב-Cloud SQL ל-MySQL וב-Cloud SQL ל-PostgreSQL.

בדוגמה הבאה מוגדר חיבור למסד נתונים של Cloud SQL ל-PostgreSQL באמצעות Python SDK.

# Import the necessary library
from google.cloud import geminidataanalytics

# Define the Cloud SQL database reference
cloud_sql_database_reference = geminidataanalytics.CloudSqlDatabaseReference(
    project_id="PROJECT_ID",
    instance_id="INSTANCE_ID",
    database_id="DATABASE_ID",
    # Optional: Specify table IDs to guide the agent
    table_ids=["TABLE_1_ID", "TABLE_2_ID"]
)

# Create a CloudSqlReference object
cloud_sql_reference = geminidataanalytics.CloudSqlReference(
    database_reference=cloud_sql_database_reference
    # Optional: Include this if you have created advanced context for the agent
    # agent_context_reference=geminidataanalytics.AgentContextReference(
    # context_set_id=f"projects/{billing_project}/locations/{location}/contextSets/your_context_set_id"
    # )
)

# Add the Cloud SQL reference to the DatasourceReferences object
datasource_references = geminidataanalytics.DatasourceReferences()
datasource_references.cloud_sql = cloud_sql_reference

מחליפים את הערכים לדוגמה באופן הבא:

  • PROJECT_ID: המזהה של Google Cloud הפרויקט שמכיל את מופע Cloud SQL ל-PostgreSQL.
  • INSTANCE_ID: המזהה של מופע Cloud SQL ל-PostgreSQL.
  • DATABASE_ID: השם של מסד הנתונים היעד בתוך המופע – לדוגמה, postgres.
  • TABLE_1_ID, TABLE_2_ID: (אופציונלי) רשימה של שמות טבלאות ספציפיים במסד הנתונים שהסוכן לנתונים מוצע להשתמש בהם – לדוגמה, "users" ו-"products".
  • your_context_set_id: אם יצרתם הקשר מתקדם לסוכן, המזהה של קבוצת ההקשר.

אפשר להשתמש באובייקט datasource_references כשיוצרים סוכן נתונים או כשמבצעים אינטראקציה איתו.

חיבור לנתוני Spanner

כדי להתחבר למופע Spanner, משתמשים במחלקה SpannerReference מ-geminidataanalytics SDK. כדי לעשות את זה, צריך לציין את הפרויקט, את המופע, את מסד הנתונים ואת הטבלאות הספציפיות שרוצים שהסוכן יתייחס אליהן (אופציונלי).

לפני שמתחברים לנתונים ב-Spanner, מוודאים שלמשתמש או לחשבון השירות יש את תפקיד ה-IAM‏ spanner.databaseReader. מידע נוסף זמין במאמר הקצאת תפקידי IAM.

בדוגמת הקוד הבאה ב-Python מוגדר חיבור למסד נתונים של Spanner באמצעות Python SDK.

# Import the necessary library
from google.cloud import geminidataanalytics

# Define the Spanner database reference
spanner_database_reference = geminidataanalytics.SpannerDatabaseReference(
    project_id="PROJECT_ID",
    instance_id="INSTANCE_ID",
    database_id="DATABASE_ID",
    # Optional: Specify table IDs to guide the agent
    table_ids=["TABLE_1_ID", "TABLE_2_ID"]
)

# Create a SpannerReference object
spanner_reference = geminidataanalytics.SpannerReference(
    database_reference=spanner_database_reference
    # Optional: Include this if you have created advanced context for the agent
    # agent_context_reference=geminidataanalytics.AgentContextReference(
    # context_set_id=f"projects/{billing_project}/locations/{location}/contextSets/your_context_set_id"
    # )
)

# Add the Spanner reference to the DatasourceReferences object
datasource_references = geminidataanalytics.DatasourceReferences()
datasource_references.spanner = spanner_reference

מחליפים את הערכים לדוגמה באופן הבא:

  • PROJECT_ID: מזהה הפרויקט של Google Cloud שמכיל את מכונת Spanner.
  • INSTANCE_ID: המזהה של מכונת Spanner.
  • DATABASE_ID: השם של מסד נתוני היעד במופע.
  • TABLE_1_ID, TABLE_2_ID: (אופציונלי) רשימה של שמות טבלאות ספציפיים במסד הנתונים שהסוכן לנתונים מוצע להשתמש בהם – לדוגמה, "Singers" ו-"Albums".
  • your_context_set_id: אם יצרתם הקשר מתקדם לסוכן, המזהה של קבוצת ההקשר.

אפשר להשתמש באובייקט datasource_references כשיוצרים סוכן נתונים או כשמבצעים אינטראקציה איתו.

הגדרת הקשר לשיחה עם שמירת מצב או לשיחה ללא שמירת מצב

ה-API של ניתוח נתונים בממשק שיחה תומך בשיחות רב-שלביות, שמאפשרות למשתמשים לשאול שאלות המשך שמבוססות על ההקשר הקודם. בדוגמה הבאה של קוד Python אפשר לראות איך מגדירים הקשר לשיחה עם שמירת מצב או ללא שמירת מצב:

  • צ'אט עם שמירת מצב: Google Cloud שומר ומנהל את היסטוריית השיחות. צ'אט עם שמירת מצב הוא מטבעו רב-שלבי, כי ה-API שומר את ההקשר מההודעות הקודמות. צריך לשלוח רק את ההודעה הנוכחית בכל תור.
  • צ'אט ללא שמירת מצב: האפליקציה שלכם מנהלת את היסטוריית השיחות. צריך לכלול את כל היסטוריית השיחות בכל הודעה חדשה. דוגמאות מפורטות לניהול שיחות רב-שלביות במצב בלי שמירת מצב זמינות במאמר יצירת שיחה רב-שלבית בלי שמירת מצב.

צ'אט עם שמירת מצב

בדוגמת הקוד הבאה מוגדר הקשר לשיחה עם שמירת מצב, שבה Google Cloud מאחסן את היסטוריית השיחה ומנהל אותה. אפשר גם להפעיל ניתוח מתקדם באמצעות Python על ידי הוספת השורה published_context.options.analysis.python.enabled = True לקוד לדוגמה הבא.

# Set up context for stateful chat
published_context = geminidataanalytics.Context()
published_context.system_instruction = system_instruction
published_context.datasource_references = datasource_references
# Optional: To enable advanced analysis with Python, include the following line:
published_context.options.analysis.python.enabled = True
# Optional: To limit query costs to 100 MiB, include the following line:
published_context.options.datasource.big_query_max_billed_bytes.value = 104857600

צ'אט ללא שמירת מצב

קוד לדוגמה שבו מוגדר הקשר לשיחה חסרת מצב, שבה צריך לשלוח את כל היסטוריית השיחות עם כל הודעה. אפשר גם להפעיל ניתוח מתקדם באמצעות Python על ידי הוספת השורה inline_context.options.analysis.python.enabled = True לקוד לדוגמה הבא.

# Set up context for stateless chat
inline_context = geminidataanalytics.Context()
inline_context.system_instruction = system_instruction
inline_context.datasource_references = datasource_references
# Optional: To enable advanced analysis with Python, include the following line:
inline_context.options.analysis.python.enabled = True
# Optional: To limit query costs to 100 MiB, include the following line:
inline_context.options.datasource.big_query_max_billed_bytes = 104857600

יצירת סוכן נתונים

דוגמת הקוד הבאה ב-Python יוצרת בקשת API ליצירת סוכן נתונים, שאחר כך אפשר להשתמש בו כדי לנהל שיחה על הנתונים שלכם. אפשר ליצור סוכן באופן סינכרוני או אסינכרוני. סוכן הנתונים מוגדר עם מקור הנתונים, הוראות המערכת וההקשר שצוינו.

אפשר גם להגן על סוכן הנתונים באמצעות CMEK על ידי מתן kms_key במהלך היצירה. הצפנה באמצעות מפתח משל לקוח נתמכת רק במקורות נתונים של Looker. מידע נוסף מופיע במאמר בנושא מפתחות הצפנה בניהול הלקוח (CMEK).

סינכרוני

  data_agent_id = "data_agent_1"

  # Optional: If using CMEK, replace the empty strings with your KMS key details.
  key_ring = ""    # KEY_RING_NAME
  key_name = ""    # KEY_NAME
  key_project = "" # KMS_PROJECT_ID (Defaults to billing_project if empty)

  data_agent = geminidataanalytics.DataAgent()
  data_agent.data_analytics_agent.published_context = published_context
  data_agent.name = f"projects/{billing_project}/locations/{location}/dataAgents/{data_agent_id}" # Optional

  # Optional: Add CMEK key if details are provided
  if key_ring and key_name:
    if not key_project:
      key_project = billing_project
    kms_key_data_agent = f"projects/{key_project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{key_name}"
    data_agent.kms_key = kms_key_data_agent # Add for CMEK

  request = geminidataanalytics.CreateDataAgentRequest(
    parent=f"projects/{billing_project}/locations/{location}",
    data_agent_id=data_agent_id, # Optional
    data_agent=data_agent,
  )

  try:
    response = data_agent_client.create_data_agent_sync(request=request)
    print("Data Agent created")
    print(response)
  except Exception as e:
    print(f"Error creating Data Agent: {e}")

אסינכרוני

  data_agent_id = "data_agent_1"

  # Optional: If using CMEK, replace the empty strings with your KMS key details.
  key_ring = ""    # KEY_RING_NAME
  key_name = ""    # KEY_NAME
  key_project = "" # KMS_PROJECT_ID (Defaults to billing_project if empty)

  data_agent = geminidataanalytics.DataAgent()
  data_agent.data_analytics_agent.published_context = published_context
  data_agent.name = f"projects/{billing_project}/locations/{location}/dataAgents/{data_agent_id}" # Optional

  # Optional: Add CMEK key if details are provided
  if key_ring and key_name:
    if not key_project:
      key_project = billing_project
    kms_key_data_agent = f"projects/{key_project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{key_name}"
    data_agent.kms_key = kms_key_data_agent # Add for CMEK

  request = geminidataanalytics.CreateDataAgentRequest(
    parent=f"projects/{billing_project}/locations/{location}",
    data_agent_id=data_agent_id, # Optional
    data_agent=data_agent,
  )

  try:
    data_agent_client.create_data_agent(request=request)
    print("Data Agent created")
  except Exception as e:
    print(f"Error creating Data Agent: {e}")

בדוגמה הקודמת, מחליפים את הערכים באופן הבא:

  • data_agent_1: מזהה ייחודי של סוכן הנתונים.
  • KEY_RING_NAME: אם משתמשים ב-CMEK, השם של אוסף המפתחות ב-Cloud KMS.
  • KEY_NAME: אם משתמשים ב-CMEK, השם של מפתח Cloud KMS.
  • KMS_PROJECT_ID: אם משתמשים במפתח הצפנה שבניהול הלקוח (CMEK), מזהה הפרויקט שבו מתארח המפתח.

יצירת שיחה

בדוגמה הבאה של קוד Python מבוצעת בקשת API ליצירת שיחה.

אפשר גם להגן על השיחה באמצעות CMEK על ידי ציון kms_key במהלך היצירה. הצפנה באמצעות מפתח משל לקוח נתמכת רק במקורות נתונים של Looker. מידע נוסף מופיע במאמר בנושא מפתחות הצפנה בניהול הלקוח (CMEK).

# Initialize request arguments
data_agent_id = "data_agent_1"
conversation_id = "conversation_1"


# Optional: If using CMEK, replace the empty strings with your KMS key details.
key_ring = ""    # KEY_RING_NAME
key_name = ""    # KEY_NAME
key_project = "" # KMS_PROJECT_ID (Defaults to billing_project if empty)

if key_project == "":
  key_project = billing_project
kms_key_conversation = f"projects/{key_project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{key_name}"

conversation = geminidataanalytics.Conversation()
conversation.agents = [f'projects/{billing_project}/locations/{location}/dataAgents/{data_agent_id}']
conversation.name = f"projects/{billing_project}/locations/{location}/conversations/{conversation_id}"

# Optional: Add CMEK key if details are provided
if key_ring and key_name:
  if not key_project:
    key_project = billing_project
  kms_key_conversation = f"projects/{key_project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{key_name}"
  conversation.kms_key = kms_key_conversation # Add for CMEK

request = geminidataanalytics.CreateConversationRequest(
  parent=f"projects/{billing_project}/locations/{location}",
  conversation_id=conversation_id,
  conversation=conversation,
)

# Make the request
response = data_chat_client.create_conversation(request=request)

# Handle the response
print(response)

מחליפים את הערכים לדוגמה באופן הבא:

  • data_agent_1: המזהה של סוכן הנתונים, כפי שמוגדר בבלוק הקוד לדוגמה במאמר יצירת סוכן נתונים.
  • conversation_1: מזהה ייחודי של השיחה.
  • KEY_RING_NAME: אם משתמשים ב-CMEK, השם של אוסף המפתחות ב-Cloud KMS.
  • KEY_NAME: אם משתמשים ב-CMEK, השם של מפתח Cloud KMS.
  • KMS_PROJECT_ID: אם משתמשים במפתח הצפנה שבניהול הלקוח (CMEK), מזהה הפרויקט שבו מתארח המפתח.

ניהול סוכני נתונים ושיחות

בדוגמאות הקוד הבאות אפשר לראות איך לנהל את סוכני הנתונים והשיחות באמצעות Conversational Analytics API. אפשר לבצע את המשימות הבאות:

קבלת סוכן נתונים

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

# Initialize request arguments
data_agent_id = "data_agent_1"
request = geminidataanalytics.GetDataAgentRequest(
  name=f"projects/{billing_project}/locations/{location}/dataAgents/{data_agent_id}",
)

# Make the request
response = data_agent_client.get_data_agent(request=request)

# Handle the response
print(response)

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

הצגת רשימה של סוכני נתונים

בדוגמה הבאה מוצג קוד שמראה איך אפשר להציג רשימה של כל סוכני הנתונים של פרויקט מסוים באמצעות קריאה לשיטה list_data_agents. כדי לראות את רשימת כל הסוכנים, צריכה להיות לכם הרשאה geminidataanalytics.dataAgents.list בפרויקט. למידע נוסף על תפקידי IAM שכוללים את ההרשאה הזו, אפשר לעיין ברשימת התפקידים המוגדרים מראש.

billing_project = "YOUR-BILLING-PROJECT"
location = "global"
request = geminidataanalytics.ListDataAgentsRequest(
  parent=f"projects/{billing_project}/locations/{location}",
)

# Make the request
page_result = data_agent_client.list_data_agents(request=request)

# Handle the response
for response in page_result:
  print(response)

מחליפים את YOUR-BILLING-PROJECT במזהה פרויקט החיוב.

הצגת רשימה של סוכני נתונים שאפשר לגשת אליהם

בדוגמה הבאה אפשר לראות איך מציגים רשימה של כל סוכני הנתונים שאפשר לגשת אליהם בפרויקט מסוים באמצעות קריאה לשיטה list_accessible_data_agents.

billing_project = "YOUR-BILLING-PROJECT"
creator_filter = "YOUR-CREATOR-FILTER"
location = "global"
request = geminidataanalytics.ListAccessibleDataAgentsRequest(
  parent=f"projects/{billing_project}/locations/{location}",
  creator_filter=creator_filter
)

# Make the request
page_result = data_agent_client.list_accessible_data_agents(request=request)

# Handle the response
for response in page_result:
  print(response)

מחליפים את הערכים לדוגמה באופן הבא:

  • YOUR-BILLING-PROJECT: מזהה הפרויקט לחיוב.
  • YOUR-CREATOR-FILTER: המסנן להחלה על סמך יוצר סוכן הנתונים. הערכים האפשריים כוללים NONE (ברירת מחדל), CREATOR_ONLY ו-NOT_CREATOR_ONLY.

עדכון סוכן נתונים

בדוגמת הקוד הבאה אפשר לראות איך מעדכנים סוכן נתונים באופן סינכרוני או אסינכרוני על ידי הפעלת השיטה update_data_agent_sync או update_data_agent במשאב של סוכן הנתונים. הבקשה צריכה לכלול אובייקט DataAgent עם הערכים החדשים של השדות שרוצים לשנות, ופרמטר update_mask שמקבל אובייקט FieldMask כדי לציין אילו שדות לעדכן.

כדי לעדכן סוכן נתונים, צריך את הרשאת ה-IAM‏ geminidataanalytics.dataAgents.update בסוכן. למידע נוסף על תפקידי IAM שכוללים את ההרשאה הזו, אפשר לעיין ברשימת התפקידים המוגדרים מראש.

סינכרוני

data_agent_id = "data_agent_1"
billing_project = "YOUR-BILLING-PROJECT"
data_agent = geminidataanalytics.DataAgent()
data_agent.data_analytics_agent.published_context = published_context
data_agent.name = f"projects/{billing_project}/locations/{location}/dataAgents/{data_agent_id}"
data_agent.description = "Updated description of the data agent."

update_mask = field_mask_pb2.FieldMask(paths=['description', 'data_analytics_agent.published_context'])

request = geminidataanalytics.UpdateDataAgentRequest(
  data_agent=data_agent,
  update_mask=update_mask,
)

try:
  # Make the request
  response = data_agent_client.update_data_agent_sync(request=request)
  print("Data Agent Updated")
  print(response)
except Exception as e:
  print(f"Error updating Data Agent: {e}")

אסינכרוני

data_agent_id = "data_agent_1"
billing_project = "YOUR-BILLING-PROJECT"
data_agent = geminidataanalytics.DataAgent()
data_agent.data_analytics_agent.published_context = published_context
data_agent.name = f"projects/{billing_project}/locations/{location}/dataAgents/{data_agent_id}"
data_agent.description = "Updated description of the data agent."

update_mask = field_mask_pb2.FieldMask(paths=['description', 'data_analytics_agent.published_context'])

request = geminidataanalytics.UpdateDataAgentRequest(
  data_agent=data_agent,
  update_mask=update_mask,
)

try:
  # Make the request
  data_agent_client.update_data_agent(request=request)
  print("Data Agent Updated")
except Exception as e:
  print(f"Error updating Data Agent: {e}")

מחליפים את הערכים לדוגמה באופן הבא:

  • data_agent_1: המזהה של סוכן הנתונים שרוצים לעדכן.
  • YOUR-BILLING-PROJECT: מזהה הפרויקט לחיוב.
  • Updated description of the data agent.: תיאור של סוכן הנתונים המעודכן.

קבלת מדיניות IAM לסוכן נתונים

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

billing_project = "YOUR-BILLING-PROJECT"
location = "global"
data_agent_id = "data_agent_1"

resource = f"projects/{billing_project}/locations/{location}/dataAgents/{data_agent_id}"
request = iam_policy_pb2.GetIamPolicyRequest(
      resource=resource,
    )
try:
  response = data_agent_client.get_iam_policy(request=request)
  print("IAM Policy fetched successfully!")
  print(f"Response: {response}")
except Exception as e:
  print(f"Error setting IAM policy: {e}")

מחליפים את הערכים לדוגמה באופן הבא:

  • YOUR-BILLING-PROJECT: מזהה הפרויקט לחיוב.
  • data_agent_1: המזהה של סוכן הנתונים שעבורו רוצים לקבל את מדיניות ה-IAM.

הגדרת מדיניות IAM לסוכן נתונים

כדי לשתף סוכן, אפשר להשתמש בשיטה set_iam_policy כדי להקצות תפקידי IAM למשתמשים בסוכן ספציפי. הבקשה כוללת קישורים שמציינים אילו תפקידים צריך להקצות לאילו משתמשים.

billing_project = "YOUR-BILLING-PROJECT"
location = "global"
data_agent_id = "data_agent_1"
role = "roles/geminidataanalytics.dataAgentEditor"
users = "EMAIL_ADDRESS"

resource = f"projects/{billing_project}/locations/{location}/dataAgents/{data_agent_id}"

# Construct the IAM policy
binding = policy_pb2.Binding(
  role=role,
  members= [f"user:{i.strip()}" for i in users.split(",")]
)

policy = policy_pb2.Policy(bindings=[binding])

# Create the request
request = iam_policy_pb2.SetIamPolicyRequest(
  resource=resource,
  policy=policy
)

# Send the request
try:
  response = data_agent_client.set_iam_policy(request=request)
  print("IAM Policy set successfully!")
  print(f"Response: {response}")
except Exception as e:
  print(f"Error setting IAM policy: {e}")

מחליפים את הערכים לדוגמה באופן הבא:

  • YOUR-BILLING-PROJECT: מזהה הפרויקט לחיוב.
  • data_agent_1: המזהה של סוכן הנתונים שעבורו רוצים להגדיר את מדיניות ה-IAM.
  • EMAIL_ADDRESSES: רשימה מופרדת בפסיקים של כתובות אימייל של משתמשים שרוצים להקצות להם את התפקיד שצוין.

מחיקה של סוכן נתונים

בדוגמת קוד לדוגמה הבאה אפשר לראות איך להשתמש בשיטה delete_data_agent_sync או delete_data_agent כדי למחוק סוכן נתונים באופן סינכרוני או אסינכרוני. כשמוחקים סוכן נתונים, הוא נכנס לתקופת מחיקה רכה של 30 יום שבמהלכה אי אפשר לשחזר אותו. מידע נוסף זמין במאמר בנושא שמירת נתונים ומחיקת נתונים. בבקשה מצוינת כתובת ה-URL של משאב סוכן הנתונים.

סינכרוני

billing_project = "YOUR-BILLING-PROJECT"
location = "global"
data_agent_id = "data_agent_1"

request = geminidataanalytics.DeleteDataAgentRequest(
  name=f"projects/{billing_project}/locations/{location}/dataAgents/{data_agent_id}",
)

try:
  # Make the request
  data_agent_client.delete_data_agent_sync(request=request)
  print("Data Agent Deleted")
except Exception as e:
  print(f"Error deleting Data Agent: {e}")

אסינכרוני

billing_project = "YOUR-BILLING-PROJECT"
location = "global"
data_agent_id = "data_agent_1"

request = geminidataanalytics.DeleteDataAgentRequest(
  name=f"projects/{billing_project}/locations/{location}/dataAgents/{data_agent_id}",
)

try:
  # Make the request
  data_agent_client.delete_data_agent(request=request)
  print("Data Agent Deleted")
except Exception as e:
  print(f"Error deleting Data Agent: {e}")

מחליפים את הערכים לדוגמה באופן הבא:

  • YOUR-BILLING-PROJECT: מזהה הפרויקט לחיוב.
  • data_agent_1: המזהה של סוכן הנתונים שרוצים למחוק.

קבלת שיחה

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

billing_project = "YOUR-BILLING-PROJECT"
location = "global"
conversation_id = "conversation_1"

request = geminidataanalytics.GetConversationRequest(
  name = f"projects/{billing_project}/locations/{location}/conversations/{conversation_id}"
)

# Make the request
response = data_chat_client.get_conversation(request=request)

# Handle the response
print(response)

מחליפים את הערכים לדוגמה באופן הבא:

  • YOUR-BILLING-PROJECT: מזהה הפרויקט לחיוב.
  • conversation_1: המזהה של השיחה שרוצים לאחזר.

רשימת השיחות

בדוגמת הקוד הבאה מוצג איך מפעילים את השיטה list_conversations כדי להציג רשימה של שיחות בפרויקט נתון. בבקשה מצוינת כתובת ה-URL של משאב האב, שהיא הפרויקט והמיקום (לדוגמה, projects/my-project/locations/global).

כברירת מחדל, השיטה הזו מחזירה את השיחות שיצרתם. אדמינים (משתמשים עם cloudaicompanion.topicAdmin תפקיד IAM) יכולים לראות את כל השיחות בפרויקט.

billing_project = "YOUR-BILLING-PROJECT"
location = "global"
request = geminidataanalytics.ListConversationsRequest(
  parent=f"projects/{billing_project}/locations/{location}",
)

# Make the request
response = data_chat_client.list_conversations(request=request)

# Handle the response
print(response)

מחליפים את YOUR-BILLING-PROJECT במזהה של פרויקט החיוב שבו הפעלתם את ממשקי ה-API הנדרשים.

איך רואים את רשימת ההודעות בשיחה

בדוגמת הקוד הבאה אפשר לראות איך משתמשים במתודה list_messages כדי לאחזר את כל ההודעות בשיחה. הבקשה מציינת את נתיב המשאב של השיחה.

כדי להציג את רשימת ההודעות, צריכה להיות לכם הרשאה של cloudaicompanion.topics.get בשיחה.

billing_project = "YOUR-BILLING-PROJECT"
location = "global"

conversation_id = "conversation_1"

request = geminidataanalytics.ListMessagesRequest(
  parent=f"projects/{billing_project}/locations/{location}/conversations/{conversation_id}",
)

# Make the request
response = data_chat_client.list_messages(request=request)

# Handle the response
print(response)

מחליפים את הערכים לדוגמה באופן הבא:

  • YOUR-BILLING-PROJECT: מזהה הפרויקט לחיוב.
  • conversation_1: המזהה של השיחה שרוצים להציג את ההודעות שלה.

למחוק שיחה

הקוד לדוגמה הבא מדגים איך למחוק שיחה. אדמינים (משתמשים עם התפקיד cloudaicompanion.topicAdmin בניהול הזהויות והרשאות הגישה) או משתמשים עם הרשאת cloudaicompanion.topics.delete בניהול הזהויות והרשאות הגישה יכולים למחוק שיחות בפרויקט.

billing_project = "YOUR-BILLING-PROJECT"
location = "global"
conversation_id = "conversation_1"

request = geminidataanalytics.DeleteConversationRequest(
  name = f"projects/{billing_project}/locations/{location}/conversations/{conversation_id}"
)

# Make the request
response = data_chat_client.delete_conversation(request=request)

# Handle the response
print(response)

מחליפים את הערכים לדוגמה באופן הבא:

  • YOUR-BILLING-PROJECT: מזהה הפרויקט לחיוב.
  • conversation_1: המזהה של השיחה שרוצים להציג את ההודעות שלה.

איך לשאול שאלות באמצעות ה-API

אחרי שיוצרים סוכן נתונים ושיחה (במקרה של צ'אט עם שמירת מצב), אפשר לשלוח שאילתות לסוכן. בדוגמאות הקוד הבאות אפשר לראות איך מפעילים את השיטה data_chat_client.chat. בדוגמאות האלה נעשה שימוש במשתני ההקשר (כמו מקור נתונים והוראות מערכת) שהגדרתם במאמר הגדרת הקשר לשיחה עם שמירת מצב או בלי שמירת מצב.

כששולחים שאילתה, ה-API מחזיר זרם של אובייקטים מסוג Message. הזרם הזה יכול להכיל סוגים שונים של הודעות, כולל טקסט, טבלאות נתונים ותרשימים. הודעות טקסט יכולות לספק תובנות לגבי ההיגיון של הסוכן, לדווח על ההתקדמות שלו או לתת את התשובה הסופית. הערך של TextType מציין את המטרה של כל הודעת טקסט:

  • THOUGHT: הצגת תהליך החשיבה הפנימי של הסוכן בזמן שהוא מתכנן איך לענות על השאילתה. הודעות THOUGHT מספקות תובנות שלב אחר שלב לגבי תהליך החשיבה וההחלטות של הנציג, והן כוללות שני חלקים: parts[0] הוא סיכום החשיבה, שכולל סיכום קצר של הטקסט המלא של החשיבה, וparts[1] הוא הטקסט המלא של החשיבה.
  • PROGRESS: דיווח על התקדמות הסוכן בפעולה, כמו אחזור נתונים או כלי שמופעל. הערך הזה מוחזר רק למקורות נתונים של Looker והוא מכיל שני חלקים: parts[0] הוא הסיכום, ו-parts[1] הוא הטקסט המלא של ההתקדמות.
  • FINAL_RESPONSE: מספק את התשובה הסופית לשאילתה.

בדוגמאות הקוד הבאות נעשה שימוש בפונקציית העזר show_message, שמוגדרת במאמר הגדרת פונקציות עזר, כדי לעבד ולהציג כל הודעה בזרם. הוראות להצגת ההודעות האלה בממשק משתמש כשמשתמשים במקורות נתונים של Looker מופיעות במאמר הצגת תשובות של סוכנים למקורות נתונים של Looker.

צ'אט עם שמירת מצב

שליחת בקשה לצ'אט עם שמירת מצב עם הפניה Conversation

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

# Create a request that contains a single user message (your question)
question = "Which species of tree is most prevalent?"
messages = [geminidataanalytics.Message()]
messages[0].user_message.text = question

data_agent_id = "data_agent_1"
conversation_id = "conversation_1"

# Create a conversation_reference
conversation_reference = geminidataanalytics.ConversationReference()
conversation_reference.conversation = f"projects/{billing_project}/locations/{location}/conversations/{conversation_id}"
conversation_reference.data_agent_context.data_agent = f"projects/{billing_project}/locations/{location}/dataAgents/{data_agent_id}"

# Form the request
request = geminidataanalytics.ChatRequest(
    parent = f"projects/{billing_project}/locations/{location}",
    # credentials = credentials,
    messages = messages,
    conversation_reference = conversation_reference
)

# Make the request
stream = data_chat_client.chat(request=request, timeout=300 #custom timeout up to 600s)

# Handle the response
for response in stream:
    show_message(response)

מחליפים את הערכים לדוגמה באופן הבא:

  • Which species of tree is most prevalent?: שאלה בשפה טבעית לשליחה לסוכן הנתונים.
  • data_agent_1: המזהה הייחודי של סוכן הנתונים, כפי שמוגדר במאמר יצירת סוכן נתונים.
  • conversation_1: המזהה הייחודי של השיחה, כפי שמוגדר במאמר יצירת שיחה.

צ'אט ללא שמירת מצב

בדוגמאות הקוד הבאות אפשר לראות איך לשלוח שאילתה לסוכן הנתונים כשמגדירים הקשר לצ'אט חסר מצב. אפשר לשלוח שאילתות ללא מצב (stateless) על ידי הפניה למשאב DataAgent שהוגדר קודם לכן או על ידי שימוש בהקשר מוטבע בבקשה.

שליחת בקשה לצ'אט ללא שמירת מצב עם הפניה DataAgent

אפשר לשלוח שאילתה לסוכן הנתונים על ידי הפניה לDataAgent משאב שיצרתם בעבר.

# Create a request that contains a single user message (your question)
question = "Which species of tree is most prevalent?"
messages = [geminidataanalytics.Message()]
messages[0].user_message.text = question

data_agent_id = "data_agent_1"

data_agent_context = geminidataanalytics.DataAgentContext()
data_agent_context.data_agent = f"projects/{billing_project}/locations/{location}/dataAgents/{data_agent_id}"

# Form the request
request = geminidataanalytics.ChatRequest(
    parent=f"projects/{billing_project}/locations/{location}",
    # credentials=credentials,
    messages=messages,
    data_agent_context = data_agent_context
)

# Make the request
stream = data_chat_client.chat(request=request, timeout=300 #custom timeout up to 600s)

# Handle the response
for response in stream:
    show_message(response)

מחליפים את הערכים לדוגמה באופן הבא:

  • Which species of tree is most prevalent?: שאלה בשפה טבעית לשליחה לסוכן הנתונים.
  • data_agent_1: המזהה הייחודי של סוכן הנתונים, כפי שמוגדר במאמר יצירת סוכן נתונים.

שליחת בקשה לצ'אט ללא שמירת מצב עם הקשר מוטבע

בדוגמת הקוד הבאה אפשר לראות איך משתמשים בפרמטר inline_context כדי לספק הקשר ישירות בבקשת הצ'אט חסרת המצב.

# Create a request that contains a single user message (your question)
question = "Which species of tree is most prevalent?"
messages = [geminidataanalytics.Message()]
messages[0].user_message.text = question

request = geminidataanalytics.ChatRequest(
    inline_context=inline_context,
    parent=f"projects/{billing_project}/locations/{location}",
    # credentials=credentials,
    messages=messages,
)

# Make the request
stream = data_chat_client.chat(request=request, timeout=300 #custom timeout up to 600s)

# Handle the response
for response in stream:
    show_message(response)

בדוגמה הקודמת, מחליפים את Which species of tree is most prevalent? בשאלה בשפה טבעית כדי לשלוח אותה לסוכן הנתונים.

יצירת שיחה רב-שלבית בלי שמירת מצב

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

# List that is used to track previous turns and is reused across requests
conversation_messages = []

data_agent_id = "data_agent_1"

# Use data agent context
data_agent_context = geminidataanalytics.DataAgentContext()
data_agent_context.data_agent = f"projects/{billing_project}/locations/{location}/dataAgents/{data_agent_id}"

# Helper function for calling the API
def multi_turn_Conversation(msg):

  message = geminidataanalytics.Message()
  message.user_message.text = msg

  # Send a multi-turn request by including previous turns and the new message
  conversation_messages.append(message)

  request = geminidataanalytics.ChatRequest(
    parent=f"projects/{billing_project}/locations/{location}",
    # credentials=credentials,
    messages=conversation_messages,
    # Use data agent context
    data_agent_context=data_agent_context,
    # Use inline context
    # inline_context=inline_context,
  )

  # Make the request
  stream = data_chat_client.chat(request=request, timeout=300 #custom timeout up to 600s)

  # Handle the response
  for response in stream:
    show_message(response)
    conversation_messages.append(response)

# Send the first turn request
multi_turn_Conversation("Which species of tree is most prevalent?")

# Send follow-up turn request
multi_turn_Conversation("Can you show me the results as a bar chart?")

בדוגמה הקודמת, מחליפים את הערכים לדוגמה באופן הבא:

  • data_agent_1: המזהה הייחודי של סוכן הנתונים, כפי שמוגדר בבלוק הקוד לדוגמה במאמר יצירת סוכן נתונים.
  • Which species of tree is most prevalent?: שאלה בשפה טבעית לשליחה לסוכן הנתונים.
  • Can you show me the results as a bar chart?: שאלה המשך שמבוססת על השאלה הקודמת או משפרת אותה.

הגדרת פונקציות עזר

קוד לדוגמה הבא מכיל הגדרות של פונקציות עזר שמשמשות בדוגמאות הקוד הקודמות. הפונקציות האלה עוזרות לנתח את התגובה מממשק ה-API ולהציג את התוצאות.

import json as json_lib
import textwrap
import time

import altair as alt
import IPython
import pandas as pd
import proto
import requests

from google.protobuf.json_format import MessageToDict, MessageToJson
from IPython.display import display, HTML
from pygments import highlight, lexers, formatters
from google.protobuf import field_mask_pb2
from google.iam.v1 import policy_pb2
from google.iam.v1 import iam_policy_pb2

def handle_text_response(resp):
  parts = resp.parts
  full_text = "".join(parts)
  if "\n" not in full_text and len(full_text) > 80:
    wrapped_text = textwrap.fill(full_text, width=80)
    print(wrapped_text)
  else:
    print(full_text)

def display_schema(data):
  fields = getattr(data, "fields")
  df = pd.DataFrame({
    "Column": map(lambda field: getattr(field, 'name'), fields),
    "Type": map(lambda field: getattr(field, 'type'), fields),
    "Description": map(lambda field: getattr(field, 'description', '-'), fields),
    "Mode": map(lambda field: getattr(field, 'mode'), fields)
  })
  display(df)

def display_section_title(text):
  display(HTML('<h2>{}</h2>'.format(text)))

def format_looker_table_ref(table_ref):
  return 'lookmlModel: {}, explore: {}, lookerInstanceUri: {}'.format(table_ref.lookml_model, table_ref.explore, table_ref.looker_instance_uri)

def format_bq_table_ref(table_ref):
  return '{}.{}.{}'.format(table_ref.project_id, table_ref.dataset_id, table_ref.table_id)

def display_datasource(datasource):
  source_name = ''
  if 'studio_datasource_id' in datasource:
    source_name = getattr(datasource, 'studio_datasource_id')
  elif 'looker_explore_reference' in datasource:
    source_name = format_looker_table_ref(getattr(datasource, 'looker_explore_reference'))
  else:
    source_name = format_bq_table_ref(getattr(datasource, 'bigquery_table_reference'))

  print(source_name)
  display_schema(datasource.schema)

def handle_schema_response(resp):
  if 'query' in resp:
    print(resp.query.question)
  elif 'result' in resp:
    display_section_title('Schema resolved')
    print('Data sources:')
    for datasource in resp.result.datasources:
      display_datasource(datasource)

def handle_data_response(resp):
  if "query" in resp:
    query = resp.query
    display_section_title("Retrieval query")
    print(f"Query name: {query.name}")
    if "question" in query:
      print(f"Question: {query.question}")
    if "datasources" in query:
      print("Data sources:")
      for datasource in query.datasources:
        display_datasource(datasource)
  elif "generated_sql" in resp:
    display_section_title("SQL generated")
    print(resp.generated_sql)
  elif "result" in resp:
    display_section_title("Data retrieved")

    fields = [field.name for field in resp.result.schema.fields]
    d = {}
    for el in resp.result.data:
      for field in fields:
        if field in d:
          d[field].append(el[field])
        else:
          d[field] = [el[field]]

    display(pd.DataFrame(d))

def handle_chart_response(resp):
  def _value_to_dict(v):
    if isinstance(v, proto.marshal.collections.maps.MapComposite):
      return _map_to_dict(v)
    elif isinstance(v, proto.marshal.collections.RepeatedComposite):
      return [_value_to_dict(el) for el in v]
    elif isinstance(v, (int, float, str, bool)):
      return v
    else:
      return MessageToDict(v)

  def _map_to_dict(d):
    out = {}
    for k in d:
      if isinstance(d[k], proto.marshal.collections.maps.MapComposite):
        out[k] = _map_to_dict(d[k])
      else:
        out[k] = _value_to_dict(d[k])
    return out

  if 'query' in resp:
    print(resp.query.instructions)
  elif 'result' in resp:
    vegaConfig = resp.result.vega_config
    vegaConfig_dict = _map_to_dict(vegaConfig)
    alt.Chart.from_json(json_lib.dumps(vegaConfig_dict)).display();

def show_message(msg):
  m = msg.system_message
  if 'text' in m:
    handle_text_response(getattr(m, 'text'))
  elif 'schema' in m:
    handle_schema_response(getattr(m, 'schema'))
  elif 'data' in m:
    handle_data_response(getattr(m, 'data'))
  elif 'chart' in m:
    handle_chart_response(getattr(m, 'chart'))
  print('\n')