Configura el entorno

Antes de trabajar con LangChain en IA Vertex, debes asegurarte de que tu entorno esté configurado. Debes tener un proyecto de Google Cloud con la facturación habilitada, tener los permisos necesarios, configurar un bucket de Cloud Storage e instalar el SDK de Vertex AI para Python. Usa los siguientes temas para asegurarte de que estés listo para comenzar a trabajar con LangChain en IA Vertex.

Configura el proyecto de Google Cloud

  1. Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  3. Verify that billing is enabled for your Google Cloud project.

  4. Enable the Vertex AI and Cloud Storage APIs.

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains the serviceusage.services.enable permission. Learn how to grant roles.

    Enable the APIs

  5. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  6. Verify that billing is enabled for your Google Cloud project.

  7. Enable the Vertex AI and Cloud Storage APIs.

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains the serviceusage.services.enable permission. Learn how to grant roles.

    Enable the APIs

Obtén los roles necesarios

A fin de obtener los permisos que necesitas para usar el motor de razonamiento, pídele a tu administrador que te otorgue los siguientes roles de IAM en tu proyecto:

Para obtener más información sobre cómo otorgar roles, consulta Administra el acceso a proyectos, carpetas y organizaciones.

También puedes obtener los permisos necesarios mediante roles personalizados o cualquier otro rol predefinido.

Configura los permisos del agente de servicio

Las aplicaciones que implementas en el motor de razonamiento se ejecutan como una cuenta de servicio del agente de servicio de AI Platform Reasoning Engine. Esta cuenta tiene un rol de agente de servicio de Vertex AI Reasoning Engine que otorga los permisos básicos que requiere tu aplicación de motor de razonamiento. Puedes ver la lista completa de permisos básicos en la documentación de IAM.

Si necesitas permisos adicionales, puedes otorgar roles adicionales a este agente de servicio mediante los siguientes pasos:

  1. Ve a la página IAM y marca la casilla de verificación “Incluir asignaciones de roles proporcionados por Google”.

    Ir a IAM

  2. Busca el principal que coincide con service-PROJECT_NUMBER@gcp-sa-aiplatform-re.iam.gserviceaccount.com.

  3. Para agregar los roles necesarios a la principal, haz clic en el botón Editar y, luego, en el botón Guardar.

Genera manualmente un agente de servicio de Reasoning Engine

Si bien el agente de servicio del motor de razonamiento se aprovisiona automáticamente durante la implementación del motor de razonamiento, es posible que haya situaciones en las que debas generarlo manualmente de antemano. Esto es muy importante cuando necesitas otorgar roles específicos al agente de servicio de Reasoning Engine para garantizar que el proceso de implementación tenga los permisos necesarios y evite posibles fallas de implementación.

Estos son los pasos para generar manualmente un agente de servicio de Reasoning Engine:

  1. Genera el agente de servicio de Reasoning Engine con Google Cloud CLI.

    gcloud beta services identity create --service=aiplatform.googleapis.com --project=PROJECT-ID-OR-PROJECT-NUMBER
  2. Ve a la página IAM y haz clic en Otorgar acceso.

    Ir a IAM

  3. En la sección Agregar principales, en el campo Principales nuevas, ingresa service-PROJECT_NUMBER@gcp-sa-aiplatform-re.iam.gserviceaccount.com.

  4. En la sección Asignar roles, busca y selecciona los roles que necesitas.

  5. Haz clic en el botón Save.

Cree un bucket de Cloud Storage

El motor de razonamiento almacena en etapa intermedia los artefactos de tus aplicaciones en un bucket de Cloud Storage como parte del proceso de implementación. Asegúrate de que la principal que esté autenticada para usar Vertex AI (ya sea tú o una cuenta de servicio) tenga acceso Storage Admin a este bucket. Esto es necesario porque el SDK de Vertex AI para Python empaqueta y escribe tu código en este bucket.

Google Cloud consola

  1. In the Google Cloud console, go to the Cloud Storage Buckets page.

    Go to Buckets

  2. Click Create.
  3. On the Create a bucket page, enter your bucket information. To go to the next step, click Continue.
    1. In the Get started section, do the following:
      • Enter a globally unique name that meets the bucket naming requirements.
      • To add a bucket label, expand the Labels section (), click Add label, and specify a key and a value for your label.
    2. In the Choose where to store your data section, do the following:
      1. Select a Location type.
      2. Choose a location where your bucket's data is permanently stored from the Location type drop-down menu.
      3. To set up cross-bucket replication, select Add cross-bucket replication via Storage Transfer Service and follow these steps:

        Set up cross-bucket replication

        1. In the Bucket menu, select a bucket.
        2. In the Replication settings section, click Configure to configure settings for the replication job.

          The Configure cross-bucket replication pane appears.

          • To filter objects to replicate by object name prefix, enter a prefix that you want to include or exclude objects from, then click Add a prefix.
          • To set a storage class for the replicated objects, select a storage class from the Storage class menu. If you skip this step, the replicated objects will use the destination bucket's storage class by default.
          • Click Done.
    3. In the Choose how to store your data section, do the following:
      1. Select a default storage class for the bucket or Autoclass for automatic storage class management of your bucket's data.
      2. To enable hierarchical namespace, in the Optimize storage for data-intensive workloads section, select Enable hierarchical namespace on this bucket.
    4. In the Choose how to control access to objects section, select whether or not your bucket enforces public access prevention, and select an access control method for your bucket's objects.
    5. In the Choose how to protect object data section, do the following:
      • Select any of the options under Data protection that you want to set for your bucket.
        • To enable soft delete, click the Soft delete policy (For data recovery) checkbox, and specify the number of days you want to retain objects after deletion.
        • To set Object Versioning, click the Object versioning (For version control) checkbox, and specify the maximum number of versions per object and the number of days after which the noncurrent versions expire.
        • To enable the retention policy on objects and buckets, click the Retention (For compliance) checkbox, and then do the following:
          • To enable Object Retention Lock, click the Enable object retention checkbox.
          • To enable Bucket Lock, click the Set bucket retention policy checkbox, and choose a unit of time and a length of time for your retention period.
      • To choose how your object data will be encrypted, expand the Data encryption section (), and select a Data encryption method.
  4. Click Create.

Línea de comandos

    Create a Cloud Storage bucket and configure it as follows:
    • Sustituye STORAGE_CLASS por la clase de almacenamiento que prefieras.
    • Sustituye LOCATION por la ubicación que prefieras (ASIA, EU o US)
    • Sustituye BUCKET_NAME por un nombre de segmento que cumpla los requisitos de nombres de segmentos.
    • gcloud storage buckets create gs://BUCKET_NAME --default-storage-class STORAGE_CLASS --location LOCATION

Instala e inicializa el SDK de Vertex AI para Python

Ejecuta el siguiente comando a fin de instalar el paquete de motor de razonamiento SDK de Vertex AI para Python:

pip install google-cloud-aiplatform[reasoningengine,langchain]

Ejecuta el siguiente código para importar y, luego, inicializar el SDK para Reasoning Engine:

import vertexai
from vertexai.preview import reasoning_engines

vertexai.init(
    project="PROJECT_ID",
    location="LOCATION",
    staging_bucket="gs://BUCKET_NAME",
)
  • PROJECT_ID: ID del proyecto
  • LOCATION: Tu región. En este momento, solo se admite us-central1.
  • BUCKET_NAME: Tu Google Cloud bucket.

¿Qué sigue?