Cette page explique comment utiliser le SDK Python pour afficher une visualisation à partir des spécifications de graphique fournies dans une réponse de l'API Conversational Analytics. L'exemple de code extrait la spécification du graphique (au format Vega-Lite) du champ chart
de la réponse et utilise la bibliothèque Vega-Altair pour afficher le graphique, l'enregistrer en tant qu'image et l'afficher.
Exemple : Afficher un graphique à barres à partir d'une API
Cet exemple montre comment afficher un graphique à barres à partir d'une réponse d'agent de l'API Conversational Analytics. L'exemple envoie une requête avec le prompt suivant :
"Create a bar graph that shows the top five states by the total number of airports."
L'exemple de code définit les fonctions d'assistance suivantes :
render_chart_response
: extrait la configuration Vega-Lite du messagechart
, la convertit dans un format utilisable par la bibliothèque Vega-Altair, affiche le graphique, l'enregistre danschart.png
et l'affiche.chat
: envoie une requête à l'API Conversational Analytics à l'aide de la variableinline_context
et de la listemessages
actuelle, traite la réponse affichée et, si un graphique est renvoyé, appellerender_chart_response
pour l'afficher.
Pour utiliser cet exemple de code, remplacez les éléments suivants :
- sqlgen-testing : ID de votre projet de facturation pour lequel les API requises sont activées.
- Create a bar graph that shows the top five states by the total number of airports : prompt que vous souhaitez envoyer à l'API Conversational Analytics.
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.")