Renderiza una respuesta del agente como una visualización
Organiza tus páginas con colecciones
Guarda y categoriza el contenido según tus preferencias.
En esta página, se muestra cómo usar el SDK de Python para renderizar una visualización a partir de las especificaciones del gráfico que se proporcionan en una respuesta de la API de Conversational Analytics. El código de muestra extrae la especificación del gráfico (en el formato de Vega-Lite) del campo chart de la respuesta y usa la biblioteca Vega-Altair para renderizar el gráfico, guardarlo como una imagen y mostrarlo.
Ejemplo: Renderiza un gráfico de barras a partir de una API
En este ejemplo, se muestra cómo renderizar un gráfico de barras a partir de una respuesta del agente de la API de Conversational Analytics. En el ejemplo, se envía una solicitud con la siguiente instrucción:
"Create a bar graph that shows the top five states by the total number of airports."
El código de muestra define las siguientes funciones auxiliares:
render_chart_response: Extrae la configuración de Vega-Lite del mensaje chart, la convierte en un formato que pueda usar la biblioteca de Vega-Altair, renderiza el gráfico, lo guarda en chart.png y, luego, lo muestra.
chat: Envía una solicitud a la API de Conversational Analytics con la variable inline_context y la lista messages actual, procesa la respuesta de transmisión y, si se muestra un gráfico, llama a render_chart_response para mostrarlo.
Para usar el siguiente código de muestra, reemplaza lo siguiente:
Create a bar graph that shows the top five states by the total number of airports: Es la instrucción que deseas enviar a la API de 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.")
[[["Fácil de comprender","easyToUnderstand","thumb-up"],["Resolvió mi problema","solvedMyProblem","thumb-up"],["Otro","otherUp","thumb-up"]],[["Difícil de entender","hardToUnderstand","thumb-down"],["Información o código de muestra incorrectos","incorrectInformationOrSampleCode","thumb-down"],["Faltan la información o los ejemplos que necesito","missingTheInformationSamplesINeed","thumb-down"],["Problema de traducción","translationIssue","thumb-down"],["Otro","otherDown","thumb-down"]],["Última actualización: 2025-08-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\")"]]