קל לארגן דפים בעזרת אוספים
אפשר לשמור ולסווג תוכן על סמך ההעדפות שלך.
בדף הזה מוסבר איך להשתמש ב-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 כדי להציג אותו.
כדי להשתמש בקוד לדוגמה הבא, מחליפים את הפרטים הבאים:
Create a bar graph that shows the top five states by the total number of airports: ההנחיה שרוצים לשלוח ל-Conversational Analytics API.
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.")
[[["התוכן קל להבנה","easyToUnderstand","thumb-up"],["התוכן עזר לי לפתור בעיה","solvedMyProblem","thumb-up"],["סיבה אחרת","otherUp","thumb-up"]],[["התוכן קשה להבנה","hardToUnderstand","thumb-down"],["שגיאות בקוד לדוגמה או במידע","incorrectInformationOrSampleCode","thumb-down"],["חסרים לי פרטים או דוגמאות","missingTheInformationSamplesINeed","thumb-down"],["בעיה בתרגום","translationIssue","thumb-down"],["סיבה אחרת","otherDown","thumb-down"]],["עדכון אחרון: 2025-06-11 (שעון 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\")"]]