Afficher une réponse d'agent sous forme de visualisation
Restez organisé à l'aide des collections
Enregistrez et classez les contenus selon vos préférences.
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 message chart, la convertit dans un format utilisable par la bibliothèque Vega-Altair, affiche le graphique, l'enregistre dans chart.png et l'affiche.
chat : envoie une requête à l'API Conversational Analytics à l'aide de la variable inline_context et de la liste messages actuelle, traite la réponse affichée et, si un graphique est renvoyé, appelle render_chart_response pour l'afficher.
Pour utiliser cet exemple de code, remplacez les éléments suivants :
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.
fromgoogle.cloudimportgeminidataanalyticsfromgoogle.protobuf.json_formatimportMessageToDictimportaltairasaltimportproto# Helper function for rendering chart responsedefrender_chart_response(resp):def_convert(v):ifisinstance(v,proto.marshal.collections.maps.MapComposite):return{k:_convert(v)fork,vinv.items()}elifisinstance(v,proto.marshal.collections.RepeatedComposite):return[_convert(el)forelinv]elifisinstance(v,(int,float,str,bool)):returnvelse:returnMessageToDict(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 APIdefchat(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 requeststream=client.chat(request=request)forreplyinstream:if"chart"inreply.system_message:# ChartMessage includes `query` for generating a chart and `result` with the generated chart.if"result"inreply.system_message.chart:render_chart_response(reply.system_message.chart)# Send the prompt to make a bar graphchat("Create a bar graph that shows the top five states by the total number of airports.")
Sauf indication contraire, le contenu de cette page est régi par une licence Creative Commons Attribution 4.0, et les échantillons de code sont régis par une licence Apache 2.0. Pour en savoir plus, consultez les Règles du site Google Developers. Java est une marque déposée d'Oracle et/ou de ses sociétés affiliées.
Dernière mise à jour le 2025/09/04 (UTC).
[[["Facile à comprendre","easyToUnderstand","thumb-up"],["J'ai pu résoudre mon problème","solvedMyProblem","thumb-up"],["Autre","otherUp","thumb-up"]],[["Difficile à comprendre","hardToUnderstand","thumb-down"],["Informations ou exemple de code incorrects","incorrectInformationOrSampleCode","thumb-down"],["Il n'y a pas l'information/les exemples dont j'ai besoin","missingTheInformationSamplesINeed","thumb-down"],["Problème de traduction","translationIssue","thumb-down"],["Autre","otherDown","thumb-down"]],["Dernière mise à jour le 2025/09/04 (UTC)."],[],[],null,["# Render an agent response as a visualization\n\n| This product or feature is subject to the \"Pre-GA Offerings Terms\" in the General Service Terms section\n| of the [Service Specific Terms](/terms/service-terms#1).\n|\n| Pre-GA products and features are available \"as is\" and might have limited support.\n|\n| For more information, see the\n| [launch stage descriptions](/products#product-launch-stages).\n\nThis page shows how to use the Python SDK to render a visualization from the chart specifications that are provided within a [Conversational Analytics API](/gemini/docs/conversational-analytics-api/overview) response. The [sample code](#example-render-bar-chart) extracts the chart specification (in the [Vega-Lite format](https://vega.github.io/vega-lite/)) from the response's `chart` field and uses the [Vega-Altair](https://altair-viz.github.io/) library to render the chart, save it as an image, and display it.\n| **Note:** This guide assumes that you're working in an environment like Colaboratory. This guide also builds on the setup in [Build a data agent using the Python SDK](/gemini/docs/conversational-analytics-api/build-agent-sdk), which shows how to authenticate and initialize the required `client`, `inline_context`, and `messages` variables.\n\nExample: Render a bar chart from an API\n---------------------------------------\n\nThis example shows how to render a bar chart from a Conversational Analytics API agent response. The example sends a request with the following prompt: \n\n```\n\"Create a bar graph that shows the top five states by the total number of airports.\"\n```\n\nThe sample code defines the following helper functions:\n\n- `render_chart_response`: Extracts the Vega-Lite configuration from the `chart` message, converts it to a format that can be used by the Vega-Altair library, renders the chart, saves it to `chart.png`, and displays it.\n- `chat`: Sends a request to the Conversational Analytics API using the `inline_context` variable and the current `messages` list, processes the streaming response, and if a chart is returned, calls `render_chart_response` to display it.\n\nTo use the following sample code, replace the following:\n\n- \u003cvar class=\"readonly\" translate=\"no\"\u003esqlgen-testing\u003c/var\u003e: The ID of your billing project that has the [required APIs enabled](/gemini/docs/conversational-analytics-api/enable-the-api).\n- \u003cvar class=\"readonly\" translate=\"no\"\u003eCreate a bar graph that shows the top five states by the total number of airports\u003c/var\u003e: The prompt that you want to send to the Conversational Analytics API.\n\n from google.cloud import geminidataanalytics\n from google.protobuf.json_format import MessageToDict\n import altair as alt\n import proto\n\n # Helper function for rendering chart response\n def render_chart_response(resp):\n def _convert(v):\n if isinstance(v, proto.marshal.collections.maps.MapComposite):\n return {k: _convert(v) for k, v in v.items()}\n elif isinstance(v, proto.marshal.collections.RepeatedComposite):\n return [_convert(el) for el in v]\n elif isinstance(v, (int, float, str, bool)):\n return v\n else:\n return MessageToDict(v)\n\n vega_config = _convert(resp.result.vega_config)\n chart = alt.Chart.from_dict(vega_config)\n chart.save('chart.png')\n chart.display()\n\n # Helper function for calling the API\n def chat(q: str):\n billing_project = \"\u003cvar class=\"edit\" translate=\"no\"\u003esqlgen-testing\u003c/var\u003e\"\n\n input_message = geminidataanalytics.Message(\n user_message=geminidataanalytics.UserMessage(text=q)\n )\n\n client = geminidataanalytics.DataChatServiceClient()\n request = geminidataanalytics.ChatRequest(\n inline_context=inline_context,\n parent=f\"projects/{billing_project}/locations/global\",\n messages=messages,\n )\n\n # Make the request\n stream = client.https://cloud.google.com/python/docs/reference/google-cloud-geminidataanalytics/latest/google.cloud.geminidataanalytics_v1alpha.services.data_chat_service.DataChatServiceClient.html(request=request)\n\n for reply in stream:\n if \"chart\" in reply.system_message:\n # ChartMessage includes `query` for generating a chart and `result` with the generated chart.\n if \"result\" in reply.system_message.chart:\n render_chart_response(reply.system_message.chart)\n\n # Send the prompt to make a bar graph\n chat(\"\u003cvar class=\"edit\" translate=\"no\"\u003eCreate a bar graph that shows the top five states by the total number of airports.\u003c/var\u003e\")"]]