בדף הזה מוסבר איך להשתמש ב-Python SDK כדי לעבד ויזואליזציה ממפרטי התרשים שמופיעים בתגובה של Conversational Analytics API. קוד לדוגמה שולף את מפרט התרשים (בפורמט Vega-Lite) מהשדה chart בתשובה, ומשתמש בספרייה Vega-Altair כדי לעבד את התרשים, לשמור אותו כתמונה ולהציג אותו.
דוגמה: יצירת תרשים עמודות מ-API
בדוגמה הזו מוסבר איך להציג תרשים עמודות מתוך תשובה של סוכן Conversational Analytics API. בדוגמה הבאה נשלחת בקשה עם ההנחיה הבאה:
"Create a bar graph that shows the top five states by the total number of airports."
קוד הדוגמה מגדיר את פונקציות העזר הבאות:
-
render_chart_response: מחלץ את ההגדרה של Vega-Lite מההודעהchart, ממיר אותה לפורמט שאפשר להשתמש בו בספריית Vega-Altair, מעבד את התרשים, שומר אותו ב-chart.pngומציג אותו. -
chat: שולח בקשה אל Conversational Analytics API באמצעות המשתנהinline_contextוהרשימה הנוכחיתmessages, מעבד את התגובה של הסטרימינג, ואם מוחזר תרשים, קורא ל-render_chart_responseכדי להציג אותו.
כדי להשתמש בקוד לדוגמה הבא, צריך להחליף את הערכים הבאים:
- sqlgen-testing: המזהה של פרויקט החיוב שבו מופעלים ממשקי ה-API הנדרשים.
- Create a bar graph that shows the top five states by the total number of airports: ההנחיה שרוצים לשלוח אל Conversational Analytics API.
from google.cloud import geminidataanalytics
from google.protobuf.json_format import MessageToDict
import altair as alt
import proto
# Helper function for rendering chart response
def render_chart_response(resp):
def _convert(v):
if isinstance(v, proto.marshal.collections.maps.MapComposite):
return {k: _convert(v) for k, v in v.items()}
elif isinstance(v, proto.marshal.collections.RepeatedComposite):
return [_convert(el) for el in v]
elif isinstance(v, (int, float, str, bool)):
return v
else:
return MessageToDict(v)
vega_config = _convert(resp.result.vega_config)
chart = alt.Chart.from_dict(vega_config)
chart.save('chart.png')
chart.display()
# Helper function for calling the API
def chat(q: str):
billing_project = "sqlgen-testing"
input_message = geminidataanalytics.Message(
user_message=geminidataanalytics.UserMessage(text=q)
)
client = geminidataanalytics.DataChatServiceClient()
request = geminidataanalytics.ChatRequest(
inline_context=inline_context,
parent=f"projects/{billing_project}/locations/global",
messages=messages,
)
# Make the request
stream = client.chat(request=request)
for reply in stream:
if "chart" in reply.system_message:
# ChartMessage includes `query` for generating a chart and `result` with the generated chart.
if "result" in reply.system_message.chart:
render_chart_response(reply.system_message.chart)
# Send the prompt to make a bar graph
chat("Create a bar graph that shows the top five states by the total number of airports.")