Algunos productos y funciones están en proceso de cambiar de nombre. Las funciones de flujo y de la guía generativa también se migrarán a una sola consola consolidada. Consulta los detalles.
Organiza tus páginas con colecciones
Guarda y categoriza el contenido según tus preferencias.
Actualmente, tu webhook usa datos codificados en la función cruisePlanCoverage.
En este paso del instructivo,
crearás una
base de datos de
Spanner, la propagarás con destinos cubiertos
y actualizarás tu función para consultar la base de datos.
Configuración de proyectos
Es importante que el agente de Dialogflow y la base de datos
estén en el mismo proyecto.
Esta es la forma más fácil para que tu función tenga acceso seguro a tu base de datos.
Además, debes habilitar la API de Spanner.
Antes de crear la base de datos,
selecciona tu proyecto en la consola de Google Cloud .
Cuando uses Spanner por primera vez, deberás crear una instancia, que es una asignación de recursos que usan las bases de datos de Spanner en esa instancia.
En la consola de Google Cloud , ve a la página Instancias de Spanner.
Haz clic en Enviar.
La Google Cloud consola regresa a la página Descripción general de la base de datos y muestra que se están realizando actualizaciones de esquemas.
Espera a que se complete la actualización.
Cómo insertar datos en tu tabla
Ahora que tu base de datos tiene una tabla, debes agregarle datos.
Para agregar datos, sigue estos pasos:
En la lista de tablas de la página Descripción general de la base de datos, haz clic en la tabla Destinos.
La Google Cloud consola muestra la página Esquema de la tabla Destinos.
En el menú de navegación de la izquierda, haz clic en Datos para mostrar la página Datos de la tabla Destinos.
Haga clic en Insert.
La Google Cloud consola muestra la página Consulta de la tabla Destinos con una
pestaña de consulta nueva que contiene sentencias INSERT y SELECT.
Reemplaza esas sentencias con lo siguiente:
En el menú de navegación de la izquierda, vuelve a hacer clic en Datos para mostrar los datos de la tabla de destino.
Confirma que la tabla contenga los datos deseados.
Actualiza la Cloud Function para consultar la base de datos
La función cruisePlanCoverage en el código del webhook verifica si se configuraron variables de entorno específicas con información para conectarse a la base de datos.
Si no se establecen estas variables de entorno, la función usa una lista de destinos codificados.
Ahora que tienes una base de datos configurada,
actualiza tu Cloud Function para establecer las variables de entorno necesarias:
Abre la página Descripción general de Cloud Functions:
Haz clic en la función tutorial-telecommunications-webhook para ir a su página de detalles.
Haz clic en Editar.
Abre la sección Configuración de entorno de ejecución, compilación y conexiones.
Selecciona la pestaña Entorno de ejecución.
Agrega las siguientes variables en la sección Variables de entorno de ejecución:
PROJECT_ID: El ID de tu proyecto
SPANNER_INSTANCE_ID: El ID de tu instancia de Spanner (probablemente tutorial-instance)
SPANNER_DATABASE_ID: El ID de tu base de datos de Spanner (probablemente, tutorial-database)
Haz clic en Siguiente.
Haz clic en Implementar.
Espera hasta que el indicador de estado muestre que la función se implementó correctamente.
Prueba tu agente
Ya puedes probar el agente.
Haz clic en el botón Test Agent de la consola de Dialogflow para abrir el simulador.
Intenta tener la siguiente conversación con el agente:
Turno de conversación
Tú
Agente
1
Hola
¡Hola! Soy el agente virtual de telecomunicaciones. Puedo ayudarte a resolver preguntas sobre la facturación y la planificación, solucionar problemas y agregar planes de viajes y cruceros. ¿En qué puedo ayudarte hoy?
2
Quiero agregar un plan de crucero
Déjame revisarlo por ti. ¿Cuál es tu número de teléfono registrado con nosotros?
3
123-123-1234
¿Cuántos días dura el crucero?
4
7
La opción 1 incluye llamadas y mensajes de texto. Cuesta USD [XX] por día. Obtén más información aquí [URL]. La opción 2 incluye llamadas, mensajes de texto y datos. Cuesta USD [XX] por día. Obtén más información aquí [URL]. ¿Qué plan de crucero te gustaría agregar?
5
Opción 1
Entendido. Agregué ese plan a tu cuenta. Es posible que también necesites cobertura en tierra durante el crucero. ¿En qué puerto te detendrás?
6
Italia
¿Cuántos días pasarás allí?
7
3
¡Excelentes noticias! Italia tiene cobertura terrestre gratuita. ¡Listo! ¿Hay algo más con lo que pueda ayudarte?
Si examinas el código, Italia no está en la lista hard-coded de destinos cubiertos.
Esto significa que tuwebhook se conectó correctamente a la base de datos, que sí incluye a Italia.
Soluciona problemas
El código del webhook incluye instrucciones de registro.
Si tienes problemas, intenta ver los registros de tu Cloud Function.
Si tu función no se conecta a la base de datos y ves un error de permiso en los registros, es posible que debas corregir el rol de la cuenta de servicio predeterminada que usa tu función.
Esta cuenta de servicio tiene el formato PROJECT_ID@appspot.gserviceaccount.com.
Puedes solucionar este problema de una de las siguientes maneras:
Si la cuenta de servicio predeterminada se muestra en la página principal de IAM, cambia los permisos de la cuenta de servicio.
El rol de editor funcionará,
pero es posible que desees un rol más detallado en una situación de producción.
Si no se muestra una cuenta de servicio predeterminada en la página principal de IAM, otorga el rol requerido agregando la cuenta de servicio como un principal nuevo.
[[["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-09-04 (UTC)"],[[["\u003cp\u003eThis tutorial guides you through setting up a Spanner database to replace hardcoded data in your webhook's \u003ccode\u003ecruisePlanCoverage\u003c/code\u003e function, improving its functionality and data management.\u003c/p\u003e\n"],["\u003cp\u003eYou will create a Spanner instance and database, define a table named "Destinations" with "Destination" and "Covered" columns, and then populate it with data representing covered travel destinations.\u003c/p\u003e\n"],["\u003cp\u003eThe process involves enabling the Spanner API, selecting the project in the Google Cloud console, creating the Spanner instance and database, and defining a table schema.\u003c/p\u003e\n"],["\u003cp\u003eYou'll update your Cloud Function's runtime environment variables with your \u003ccode\u003ePROJECT_ID\u003c/code\u003e, \u003ccode\u003eSPANNER_INSTANCE_ID\u003c/code\u003e, and \u003ccode\u003eSPANNER_DATABASE_ID\u003c/code\u003e to enable it to connect to the newly created database.\u003c/p\u003e\n"],["\u003cp\u003eFinally, you can test the updated agent by having a conversation to verify that it successfully queries the Spanner database instead of using hardcoded data to determine coverage, as demonstrated with Italy.\u003c/p\u003e\n"]]],[],null,["# Query a database\n\nYour webhook currently uses hardcoded data in the `cruisePlanCoverage` function.\nIn this step of the tutorial,\nyou will create a\n[Spanner](/spanner/docs)\ndatabase, populate it with covered destinations,\nand update your function to query the database.\n\nProject configuration\n---------------------\n\nIt is important that your Dialogflow agent and the database\nare both in the same project.\nThis is the easiest way for your function to have\nsecure access to your database.\nAlso, you must enable the Spanner API.\n\n1. Before creating the database,\n select your project from the Google Cloud console.\n\n [Go to project selector](https://console.cloud.google.com/projectselector2/home/dashboard)\n2. Enable the Spanner API for the project.\n\n [Enable the Spanner API](https://console.cloud.google.com/flows/enableapi?apiid=spanner.googleapis.com)\n\nCreate a Spanner instance\n-------------------------\n\nWhen you first use Spanner,\nyou must create an instance,\nwhich is an allocation of resources\nthat are used by Spanner databases in that instance.\n\n1. In the Google Cloud console, go to the **Spanner Instances** page.\n\n [Go to Spanner instances](https://console.cloud.google.com/spanner/instances)\n2. Click **Create instance**.\n\n3. For the instance name, enter **Tutorial Instance**.\n\n4. The instance ID is automatically entered based on the instance name.\n\n5. In **Choose your configuration** ,\n retain the default option **Regional** and select the same region\n [location](/dialogflow/cx/docs/concept/region#avail)\n that you chose when creating the function.\n\n6. In **Allocate compute capacity**,\n enter 100 processing units.\n This provides a minimal capacity for the tutorial.\n\n7. Click **Create** .\n The Google Cloud console displays the **Overview** page for the instance\n you created.\n\nCreate a Spanner database\n-------------------------\n\nNow that you have an instance,\nyou need to create a database.\nTo create a database:\n\n1. In the instance **Overview** page, click **Create database**.\n2. For the database name, enter **tutorial-database**.\n3. Select the **Google Standard SQL** database dialect.\n4. Click **Create** . The Google Cloud console displays the **Overview** page for the database you created.\n\nCreate a table for your database\n--------------------------------\n\nNow that you have a database,\nyou need to create a table for the database.\nTo create a table:\n\n1. In the Tables section of the database **Overview** page, click **Create table**.\n2. In the **Write DDL statements** page, enter:\n\n CREATE TABLE Destinations (\n Destination STRING(1024),\n Covered BOOL,\n ) PRIMARY KEY(Destination);\n\n3. Click **Submit** .\n The Google Cloud console returns to the database **Overview** page and\n shows that **Schema updates** are underway.\n Wait until the update is complete.\n\nInsert data into your table\n---------------------------\n\nNow that your database has a table,\nyou need to add data to the table.\nTo add data:\n\n1. In the list of tables on the database **Overview** page, click the Destinations table. The Google Cloud console displays the Destinations table's **Schema** page.\n2. In the left navigation menu, click **Data** to display the Destinations table's **Data** page.\n3. Click **Insert** .\n The Google Cloud console displays the Destinations table's **Query** page with a\n new query tab that contains `INSERT` and `SELECT` statements.\n Overwrite those statements with the following:\n\n INSERT INTO Destinations (Destination, Covered)\n VALUES('anguilla', TRUE),\n ('canada', TRUE),\n ('china', TRUE),\n ('italy', TRUE),\n ('mexico', TRUE),\n ('spain', FALSE);\n\n4. Click **Run**.\n\n5. In the left navigation menu,\n click **Data** again to display the Destination table's data.\n Confirm that the table contains the desired data.\n\nUpdate the Cloud Function to query the database\n-----------------------------------------------\n\nThe `cruisePlanCoverage` function in the webhook code\nchecks whether specific environment variables are set\nwith information for connecting to the database.\nIf these environment variables are not set,\nthe function uses a hardcoded list of destinations.\n\nNow that you have a database set up,\nupdate your Cloud Function to set required environment variables:\n\n1. Open the Cloud Functions overview page.\n\n [Go to Cloud Functions overview](https://console.cloud.google.com/functions/list)\n2. Click the tutorial-telecommunications-webhook function to go to its details page.\n\n3. Click **Edit**.\n\n4. Open the **Runtime, build and connections settings** section.\n\n5. Select the **Runtime** tab.\n\n6. Add the following variables in the Runtime environment variables section:\n\n - `PROJECT_ID`: your project ID\n - `SPANNER_INSTANCE_ID`: your Spanner instance ID (probably `tutorial-instance`)\n - `SPANNER_DATABASE_ID`: your spanner database ID (probably `tutorial-database`)\n7. Click **Next**.\n\n8. Click **Deploy**.\n\n9. Wait until the status indicator shows that the function\n has successfully deployed.\n\nTest your agent\n---------------\n\nYour agent is now ready to try.\nClick the **Test Agent** button from the Dialogflow console\nto open the simulator.\nAttempt to have the following conversation with the agent:\n\nIf you examine the code,\nItaly is not in the hardcoded list of covered destinations.\nThis means that your webhook has successfully connected to the database,\nwhich does include Italy.\n\nTroubleshooting\n---------------\n\nThe webhook code includes logging statements.\nIf you are having issues, try viewing the logs for your Cloud Function.\n\nIf your function is not connecting to the database,\nand you see a permission error in the logs,\nyou may need to fix the role for the default service account\nused by your function.\nThis service account is of the form\n\u003cvar translate=\"no\"\u003ePROJECT_ID\u003c/var\u003e`@appspot.gserviceaccount.com`.\nYou can fix this in one of the following ways:\n\n- If the default service account is shown on the IAM main page,\n [change permissions for the service account](/functions/docs/securing/function-identity#default).\n The *Editor* role will work,\n but you may want a more granular role in a production scenario.\n\n [Go to the IAM main page](https://console.cloud.google.com/iam-admin/iam)\n- If the a default service account is not shown on the IAM main page,\n [grant the required role](/iam/docs/grant-role-console#grant_an_iam_role)\n by adding the service account as a new principal.\n\n- Alternatively, you can\n [use a service account that you create](/functions/docs/securing/function-identity#individual).\n\nMore information\n----------------\n\nFor more information about the steps above, see:\n\n- [Using Cloud Spanner with Cloud Functions](/functions/docs/tutorials/use-cloud-spanner)\n- [Create and query a database by using the Google Cloud console](/spanner/docs/create-query-database-console)\n- [Google Standard SQL data definition language](/spanner/docs/reference/standard-sql/data-definition-language)\n- [Google Standard SQL data manipulation language](/spanner/docs/reference/standard-sql/dml-syntax)"]]