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

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

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

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

אחרי שתסיימו את הוראות ההגדרה ב-notebook, תוכלו להשתמש בקוד הבא כדי לייבא את ספריות ה-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 עם הגדרות של נקודות קצה (endpoints) על סמך המיקום:

# 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 בכל פעם באמצעות Conversational Analytics API.

מפתחות 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: סוד הלקוח של מפתח ה-API שנוצר ב-Looker.
  • ‫https://my_company.looker.com: כתובת ה-URL המלאה של המכונה ב-Looker.
  • ‫my_model: השם של מודל LookML שכולל את ה-Explore שאליו רוצים להתחבר.
  • ‫my_explore: השם של חקירת Looker שרוצים שהסוכן לאינטראקציה עם נתונים ישלח אליה שאילתה.
  • ‫my_model_2: השם של המודל השני ב-LookML שכולל את ה-Explore שאליו רוצים להתחבר. אפשר לחזור על המשתנה הזה במודלים נוספים, עד חמישה ניתוחים.
  • ‫my_explore_2: השם של חקירת Looker הנוספת שרוצים שהסוכן לאינטראקציה עם נתונים ישלח אליה שאילתות. אפשר לחזור על המשתנה הזה כדי לכלול עד חמישה ניתוחים.

טוקן גישה

אתם יכולים לקשר למכונה של 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 שכולל את ה-Explore שאליו רוצים להתחבר.
  • ‫my_explore: השם של חקירת Looker שרוצים שהסוכן לאינטראקציה עם נתונים ישלח אליה שאילתה.
  • ‫my_model_2: השם של המודל השני ב-LookML שכולל את ה-Explore שאליו רוצים להתחבר. אפשר לחזור על המשתנה הזה במודלים נוספים, עד חמישה ניתוחים.
  • ‫my_explore_2: השם של חקירת Looker הנוספת שרוצים שהסוכן לאינטראקציה עם נתונים ישלח אליה שאילתות. אפשר לחזור על המשתנה הזה כדי לכלול עד חמישה ניתוחים.

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

חיבור לנתונים ב-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"

# 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 ועל המגבלות של שאילתות גרפים, ראו התחברות ל-BigQuery Graph.

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

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

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

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

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

חיבור לנתונים ב-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 מ-SDK של geminidataanalytics. כדי לעשות את זה, צריך לציין את הפרויקט, המכונה, מסד הנתונים, ואם רוצים, גם את הטבלאות הספציפיות שהסוכן צריך להביא בחשבון.

לפני שמתחברים לנתונים ב-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 כשאתם יוצרים את הסוכן לאינטראקציה עם נתונים או משתמשים בו.

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

‫Conversational Analytics 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

צ'אט ללא שמירת מצב (stateless)

הקוד לדוגמה הבא מגדיר הקשר לצ'אט בלי שמירת מצב, שבו צריך לשלוח את כל היסטוריית השיחות עם כל הודעה. אפשר גם להפעיל ניתוח מתקדם באמצעות 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 כשיוצרים את הסוכן. מידע נוסף מופיע במאמר מפתחות הצפנה בניהול הלקוח (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)
  key_location = "" # KEY_LOCATION (Defaults to location if empty; except eu)

  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
    if not key_location:
      key_location = location
    kms_key_data_agent = f"projects/{key_project}/locations/{key_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)
  key_location = "" # KEY_LOCATION (Defaults to location if empty; except eu)

  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
    if not key_location:
      key_location = location
    kms_key_data_agent = f"projects/{key_project}/locations/{key_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, מזהה הפרויקט שבו המפתח מתארח.
  • ‫KEY_LOCATION: אם משתמשים ב-CMEK, המיקום של אוסף המפתחות. בשביל eu במספר אזורים, משתמשים ב-europe. בכל המיקומים האחרים, צריך להשתמש באותו מיקום כמו של הסוכן לאינטראקציה עם נתונים. אם לא מציינים מיקום, כברירת מחדל נבחר המיקום של הסוכן לאינטראקציה עם נתונים, שמתאים לכל המיקומים חוץ מהמיקום eu במספר אזורים. מידע נוסף זמין במאמר דרישות לגבי מיקום המפתח.

יצירת שיחה

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

כדי להגן על השיחה באמצעות CMEK, אתם יכולים להגדיר את השדה kms_key כשאתם יוצרים את השיחה. מידע נוסף מופיע במאמר מפתחות הצפנה בניהול הלקוח (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)
key_location = "" # KEY_LOCATION (Defaults to location if empty; single regions only)

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
  if not key_location:
    key_location = location
  kms_key_conversation = f"projects/{key_project}/locations/{key_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, מזהה הפרויקט שבו המפתח מתארח.
  • ‫KEY_LOCATION: אם משתמשים ב-CMEK, המיקום של אוסף המפתחות. בשביל us במספר אזורים, משתמשים ב-us-central1. בשביל eu במספר אזורים, משתמשים ב-europe-west1. אם אתם בוחרים אזור אחד, בחרו את האזור שבו מתנהלת השיחה. אם לא מציינים מיקום, ברירת המחדל היא המיקום של השיחה, וזה עובד רק באזורים בודדים. מידע נוסף זמין במאמר דרישות לגבי מיקום המפתח.

ניהול סוכנים לאינטראקציה עם נתונים ושיחות

דוגמאות הקוד הבאות מראות איך לנהל את הסוכנים לאינטראקציה עם נתונים ואת השיחות באמצעות 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 במזהה הייחודי של הסוכן לאינטראקציה עם נתונים שרוצים לאחזר.

הצגת רשימה של סוכנים לאינטראקציה עם נתונים

הקוד הבא מראה איך להציג את כל הסוכנים לאינטראקציה עם נתונים בפרויקט מסוים באמצעות קריאה ל-method‏ 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 במזהה של הפרויקט לחיוב.

רשימת הסוכנים לאינטראקציה עם נתונים שיש אליהם גישה

הקוד הבא מראה איך להציג את כל הסוכנים לאינטראקציה עם נתונים שאפשר לגשת אליהם בפרויקט נתון, באמצעות קריאה ל-method‏ 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.

עדכון סוכן לאינטראקציה עם נתונים

הקוד לדוגמה הבא מראה איך לעדכן סוכן לאינטראקציה עם נתונים באופן סינכרוני או אסינכרוני, על ידי קריאה ל-method‏ 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: רשימה מופרדת בפסיקים של כתובות אימייל של משתמשים שרוצים לתת להם את התפקיד שצוין.

מחיקת סוכן לאינטראקציה עם נתונים

הקוד לדוגמה הבא ממחיש איך להשתמש ב-method‏ 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: המזהה של הסוכן לאינטראקציה עם נתונים שרוצים למחוק.

איך מקבלים שיחה

הקוד לדוגמה הבא ממחיש איך להשתמש ב-method‏ 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: המזהה של השיחה שרוצים לאחזר.

הצגת רשימת השיחות

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

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

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 הנדרשים.

הצגת רשימת ההודעות בשיחה

הקוד לדוגמה הבא ממחיש איך להשתמש ב-method‏ 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. הסטרימינג הזה יכול להכיל סוגים שונים של הודעות, כולל טקסט, טבלאות נתונים ותרשימים. הודעות SMS יכולות לספק תובנות לגבי תהליך החשיבה של הסוכן, לדווח על ההתקדמות שלו או לתת את התשובה הסופית. המטרה של כל הודעת טקסט מצוינת בערך 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')