Eseguire il rendering di una risposta dell'agente come visualizzazione
Mantieni tutto organizzato con le raccolte
Salva e classifica i contenuti in base alle tue preferenze.
Questa pagina mostra come utilizzare l'SDK Python per eseguire il rendering di una visualizzazione dalle specifiche del grafico fornite all'interno di una risposta dell'API Conversational Analytics. Il codice di esempio estrae la specifica del grafico (in formato Vega-Lite) dal campo chart della risposta e utilizza la libreria Vega-Altair per eseguire il rendering del grafico, salvarlo come immagine e visualizzarlo.
Esempio: visualizzare un grafico a barre da un'API
Questo esempio mostra come eseguire il rendering di un grafico a barre da una risposta dell'agente dell'API Conversational Analytics. L'esempio invia una richiesta con il seguente prompt:
"Create a bar graph that shows the top five states by the total number of airports."
Il codice campione definisce le seguenti funzioni di assistenza:
render_chart_response: estrae la configurazione Vega-Lite dal messaggio chart, la converte in un formato utilizzabile dalla libreria Vega-Altair, esegue il rendering del grafico, lo salva in chart.png e lo visualizza.
chat: invia una richiesta all'API Conversational Analytics utilizzando la variabile inline_context e l'elenco messages corrente, elabora la risposta di streaming e, se viene restituito un grafico, chiama render_chart_response per visualizzarlo.
Per utilizzare il seguente codice campione, sostituisci quanto segue:
Create a bar graph that shows the top five states by the total number of airports: il prompt che vuoi inviare all'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.")
[[["Facile da capire","easyToUnderstand","thumb-up"],["Il problema è stato risolto","solvedMyProblem","thumb-up"],["Altra","otherUp","thumb-up"]],[["Difficile da capire","hardToUnderstand","thumb-down"],["Informazioni o codice di esempio errati","incorrectInformationOrSampleCode","thumb-down"],["Mancano le informazioni o gli esempi di cui ho bisogno","missingTheInformationSamplesINeed","thumb-down"],["Problema di traduzione","translationIssue","thumb-down"],["Altra","otherDown","thumb-down"]],["Ultimo aggiornamento 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\")"]]