Integration Management
======================

The Integration module provides functionality to create, manage, and interact with integrations (tool plugins) in the Globant Enterprise AI Lab. Integrations are containers that group related tools with shared configurations and parameters, defined using OpenAPI 3.0 specifications.

This section covers:

* Creating integrations from OpenAPI manifests
* Retrieving integration information and manifests
* Updating integration configurations
* Publishing integration tools
* Managing shared parameters
* Listing integrations
* Deleting integrations
* Migrating integrations between environments

For each operation, you have two implementation options:

* `Command Line`_ (where available)
* `Python API`_ (using managers)


Create Integration
~~~~~~~~~~~~~~~~~~

Creates a new integration from an OpenAPI 3.0 manifest. The manifest defines all tools, their parameters, and shared configurations for the integration.

Command Line
^^^^^^^^^^^^

Currently, integration creation is available via Python API only. CLI support coming soon.

Python API
^^^^^^^^^^^^^^^^^^^^^^^^

.. code-block:: python

    from pygeai.lab.integrations import IntegrationClient
    import json
    
    client = IntegrationClient()
    
    # Define OpenAPI manifest
    manifest = {
        "openapi": "3.0.0",
        "info": {
            "title": "Weather API",
            "description": "Get weather information",
            "version": "1.0.0"
        },
        "servers": [
            {"url": "https://api.weather.com"}
        ],
        "paths": {
            "/current": {
                "get": {
                    "summary": "Get current weather",
                    "operationId": "getCurrentWeather",
                    "parameters": [
                        {
                            "name": "location",
                            "in": "query",
                            "required": true,
                            "schema": {"type": "string"}
                        }
                    ],
                    "responses": {
                        "200": {
                            "description": "Success",
                            "content": {
                                "application/json": {
                                    "schema": {
                                        "type": "object",
                                        "properties": {
                                            "temperature": {"type": "number"},
                                            "conditions": {"type": "string"}
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    
    integration = client.create_integration(
        name="weather_api",
        description="Weather information API integration",
        manifest=json.dumps(manifest),
        access_scope="private",
        automatic_publish=True
    )
    
    print(f"Created integration: {integration.id}")

Python API (Alternative)
^^^^^^^^^^^^^^^^^^^^^^^^^

.. code-block:: python

    from pygeai.lab.managers import AILabManager
    import json
    
    manager = AILabManager()
    
    # Same manifest as above
    manifest = {...}
    
    integration = manager.create_integration(
        name="weather_api",
        description="Weather information API integration",
        manifest=json.dumps(manifest),
        access_scope="private",
        automatic_publish=True
    )
    
    print(f"Integration ID: {integration.id}")
    print(f"Integration name: {integration.name}")


Get Integration
~~~~~~~~~~~~~~~

Retrieves an integration by ID or name. The response includes the complete OpenAPI manifest.

Command Line
^^^^^^^^^^^^

.. code-block:: shell

    geai lab get-tool-plugin --id <integration-id>
    
    # Or by name
    geai lab get-tool-plugin --name weather_api

Python API
^^^^^^^^^^^^^^^^^^^^^^^^

.. code-block:: python

    from pygeai.lab.integrations import IntegrationClient
    
    client = IntegrationClient()
    
    # Get by ID
    integration = client.get_integration("integration-id-here")
    
    # Or by name
    integration = client.get_integration("weather_api")
    
    print(f"Name: {integration.name}")
    print(f"Description: {integration.description}")
    print(f"Manifest: {integration.manifest}")

Python API (Alternative)
^^^^^^^^^^^^^^^^^^^^^^^^^

.. code-block:: python

    from pygeai.lab.managers import AILabManager
    
    manager = AILabManager()
    
    integration = manager.get_integration("weather_api")
    
    print(f"Integration: {integration.name}")
    print(f"Tools defined: {len(integration.manifest)}")


Update Integration
~~~~~~~~~~~~~~~~~~

Updates an existing integration by re-importing with a new manifest or modified configuration.

Python API
^^^^^^^^^^^^^^^^^^^^^^^^

.. code-block:: python

    from pygeai.lab.integrations import IntegrationClient
    import json
    
    client = IntegrationClient()
    
    # Get existing integration
    existing = client.get_integration("weather_api")
    
    # Modify manifest (add new endpoint, etc.)
    updated_manifest = json.loads(existing.manifest)
    # ... make changes to manifest ...
    
    updated = client.update_integration(
        integration_id_or_name="weather_api",
        name="weather_api",
        description="Updated weather API with more features",
        manifest=json.dumps(updated_manifest),
        access_scope="private",
        automatic_publish=False
    )
    
    print(f"Updated integration: {updated.name}")

Python API (Alternative)
^^^^^^^^^^^^^^^^^^^^^^^^^

.. code-block:: python

    from pygeai.lab.managers import AILabManager
    import json
    
    manager = AILabManager()
    
    existing = manager.get_integration("weather_api")
    updated_manifest = json.loads(existing.manifest)
    # ... modify manifest ...
    
    updated = manager.update_integration(
        integration_id_or_name="weather_api",
        name="weather_api",
        description="Updated description",
        manifest=json.dumps(updated_manifest),
        access_scope="private",
        automatic_publish=False
    )


Publish Integration Tools
~~~~~~~~~~~~~~~~~~~~~~~~~~

Publishes all tools defined in the integration's manifest. Required after creating or updating an integration if automatic_publish was False.

Python API
^^^^^^^^^^^^^^^^^^^^^^^^

.. code-block:: python

    from pygeai.lab.integrations import IntegrationClient
    
    client = IntegrationClient()
    
    result = client.publish_tools("weather_api")
    print("Tools published successfully")

Python API (Alternative)
^^^^^^^^^^^^^^^^^^^^^^^^^

.. code-block:: python

    from pygeai.lab.managers import AILabManager
    
    manager = AILabManager()
    
    manager.publish_integration_tools("weather_api")
    print("Integration tools published")


List Integrations
~~~~~~~~~~~~~~~~~

Lists integrations with optional filtering by name, ID, access scope, and other criteria.

Command Line
^^^^^^^^^^^^

.. code-block:: shell

    # List all integrations
    geai lab list-tool-plugins
    
    # Filter by access scope
    geai lab list-tool-plugins --access-scope private

Python API
^^^^^^^^^^^^^^^^^^^^^^^^

.. code-block:: python

    from pygeai.lab.integrations import IntegrationClient
    
    client = IntegrationClient()
    
    # List all private integrations
    integrations = client.list_integrations(
        access_scope="private",
        count=100
    )
    
    for plugin in integrations.plugins:
        print(f"{plugin.name}: {plugin.description}")

Python API (Alternative)
^^^^^^^^^^^^^^^^^^^^^^^^^

.. code-block:: python

    from pygeai.lab.managers import AILabManager
    from pygeai.lab.models import FilterSettings
    
    manager = AILabManager()
    
    filters = FilterSettings(
        access_scope="private",
        count=100
    )
    
    integrations = manager.list_integrations(filters)
    
    for plugin in integrations.plugins:
        print(f"{plugin.name} (ID: {plugin.id})")


Get Integration Configuration
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Retrieves the shared parameters configured for an integration.

Command Line
^^^^^^^^^^^^

.. code-block:: shell

    geai lab get-tool-plugin-config --id <integration-id>

Python API
^^^^^^^^^^^^^^^^^^^^^^^^

.. code-block:: python

    from pygeai.lab.integrations import IntegrationClient
    
    client = IntegrationClient()
    
    params = client.get_config("weather_api")
    
    for param in params:
        print(f"{param.key}: {param.value}")

Python API (Alternative)
^^^^^^^^^^^^^^^^^^^^^^^^^

.. code-block:: python

    from pygeai.lab.managers import AILabManager
    
    manager = AILabManager()
    
    config = manager.get_integration_config("weather_api")
    
    for param in config:
        print(f"Parameter: {param.key}, Required: {param.is_required}")


Set Integration Configuration
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Sets or updates shared parameters for an integration. These parameters are inherited by all tools in the integration.

Command Line
^^^^^^^^^^^^

.. code-block:: shell

    geai lab set-tool-plugin-config \
      --id <integration-id> \
      --parameters '[{"key":"api_key","dataType":"String","isRequired":true}]'

Python API
^^^^^^^^^^^^^^^^^^^^^^^^

.. code-block:: python

    from pygeai.lab.integrations import IntegrationClient
    
    client = IntegrationClient()
    
    parameters = [
        {
            "key": "api_key",
            "dataType": "String",
            "description": "API key for authentication",
            "isRequired": True
        },
        {
            "key": "base_url",
            "dataType": "String",
            "description": "API base URL",
            "isRequired": False,
            "value": "https://api.weather.com"
        }
    ]
    
    client.set_config("weather_api", parameters)

Python API (Alternative)
^^^^^^^^^^^^^^^^^^^^^^^^^

.. code-block:: python

    from pygeai.lab.managers import AILabManager
    
    manager = AILabManager()
    
    parameters = [
        {
            "key": "api_key",
            "dataType": "String",
            "description": "API authentication key",
            "isRequired": True
        }
    ]
    
    manager.set_integration_config("weather_api", parameters)


Delete Integration
~~~~~~~~~~~~~~~~~~

Deletes an integration and all its associated tools.

Python API
^^^^^^^^^^^^^^^^^^^^^^^^

.. code-block:: python

    from pygeai.lab.integrations import IntegrationClient
    
    client = IntegrationClient()
    
    client.delete_integration("weather_api")
    print("Integration deleted")

Python API (Alternative)
^^^^^^^^^^^^^^^^^^^^^^^^^

.. code-block:: python

    from pygeai.lab.managers import AILabManager
    
    manager = AILabManager()
    
    manager.delete_integration("weather_api")


Migrate Integration
~~~~~~~~~~~~~~~~~~~

Migrates an integration from one environment to another using the manifest-based approach. This ensures atomic migration of all tools and configurations.

Using Migration Strategy
^^^^^^^^^^^^^^^^^^^^^^^^^

.. code-block:: python

    from pygeai.migration.strategies import IntegrationMigrationStrategy
    
    strategy = IntegrationMigrationStrategy(
        from_api_key="source-api-key",
        from_instance="https://api.source.com",
        integration_id_or_name="weather_api",
        to_api_key="dest-api-key",
        to_instance="https://api.destination.com"
    )
    
    result = strategy.migrate()
    print(f"Migrated integration: {result.name}")

Using CLI
^^^^^^^^^

.. code-block:: shell

    # Migrate specific integration
    geai migrate clone-project \
      --integrations weather_api \
      --from-api-key <source-key> \
      --from-instance https://api.source.com \
      --from-project-id <source-project-id> \
      --to-api-key <dest-key> \
      --to-instance https://api.destination.com \
      --to-project-id <dest-project-id>
    
    # Migrate all integrations
    geai migrate clone-project \
      --integrations all \
      --from-api-key <source-key> \
      --from-instance https://api.source.com \
      --from-project-id <source-project-id> \
      --to-api-key <dest-key> \
      --to-instance https://api.destination.com \
      --to-project-id <dest-project-id>


Export and Import Integration
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Note: The export endpoint is not yet available on the server. Use get_integration() to retrieve the manifest instead.

Get Manifest for Manual Export
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

.. code-block:: python

    from pygeai.lab.managers import AILabManager
    import json
    
    manager = AILabManager()
    
    integration = manager.get_integration("weather_api")
    
    # Save manifest to file
    with open("weather_api_manifest.json", "w") as f:
        json.dump(json.loads(integration.manifest), f, indent=2)
    
    print(f"Exported manifest for {integration.name}")

Import from Saved Manifest
^^^^^^^^^^^^^^^^^^^^^^^^^^^

.. code-block:: python

    from pygeai.lab.managers import AILabManager
    import json
    
    manager = AILabManager()
    
    # Load manifest from file
    with open("weather_api_manifest.json", "r") as f:
        manifest = json.load(f)
    
    # Create new integration from manifest
    new_integration = manager.create_integration(
        name="weather_api_imported",
        description="Imported weather API",
        manifest=json.dumps(manifest),
        access_scope="private"
    )


Integration Model Fields
~~~~~~~~~~~~~~~~~~~~~~~~~

The ToolPlugin model includes the following fields:

* ``id`` (str): Unique identifier for the integration
* ``name`` (str): Integration name
* ``description`` (str): Integration description
* ``manifest`` (str): OpenAPI 3.0 specification (JSON string)
* ``access_scope`` (str): Access level (private/public)
* ``public_name`` (str): Public identifier if public
* ``status`` (str): Current status
* ``type`` (str): Integration type
* ``is_read_only`` (bool): Whether integration is read-only
* ``parameters`` (List[ToolParameter]): Shared parameters


Best Practices
~~~~~~~~~~~~~~

**OpenAPI Manifest Design**
    Design your OpenAPI manifest with clear operation IDs and comprehensive parameter definitions. Each operation becomes a tool in the integration.

**Shared Parameters**
    Use shared parameters for credentials and base URLs that all tools in the integration need. This avoids duplication and simplifies configuration.

**Access Scope**
    Use ``private`` for organization-specific integrations and ``public`` for integrations shared across the platform.

**Automatic Publishing**
    Set ``automatic_publish=True`` when creating or updating if you want tools immediately available. Set to ``False`` if you need to review before publishing.

**Manifest Versioning**
    Include version information in your OpenAPI manifest's ``info.version`` field to track integration changes.

**Migration Strategy**
    Use IntegrationMigrationStrategy for environment migrations. It ensures atomic migration of the entire integration with all tools and configurations.

**Error Handling**
    Always wrap integration operations in try-except blocks and handle APIResponseError appropriately.


Complete Example
~~~~~~~~~~~~~~~~

Here's a complete example creating, configuring, and using an integration:

.. code-block:: python

    from pygeai.lab.managers import AILabManager
    import json
    
    manager = AILabManager()
    
    # Define OpenAPI manifest
    manifest = {
        "openapi": "3.0.0",
        "info": {
            "title": "Customer API",
            "description": "Customer management API",
            "version": "1.0.0"
        },
        "servers": [
            {"url": "https://api.example.com"}
        ],
        "paths": {
            "/customers": {
                "get": {
                    "summary": "List customers",
                    "operationId": "listCustomers",
                    "responses": {
                        "200": {
                            "description": "Customer list",
                            "content": {
                                "application/json": {
                                    "schema": {
                                        "type": "array",
                                        "items": {
                                            "type": "object",
                                            "properties": {
                                                "id": {"type": "string"},
                                                "name": {"type": "string"}
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    
    # Create integration
    integration = manager.create_integration(
        name="customer_api",
        description="Customer management integration",
        manifest=json.dumps(manifest),
        access_scope="private",
        automatic_publish=False
    )
    
    print(f"Created: {integration.id}")
    
    # Configure shared parameters
    manager.set_integration_config(integration.id, [
        {
            "key": "api_key",
            "dataType": "String",
            "description": "API authentication key",
            "isRequired": True
        }
    ])
    
    # Publish tools
    manager.publish_integration_tools(integration.id)
    
    print("Integration ready to use!")
    
    # List all integrations
    from pygeai.lab.models import FilterSettings
    integrations = manager.list_integrations(
        FilterSettings(access_scope="private")
    )
    
    for plugin in integrations.plugins:
        print(f"- {plugin.name}")


API Reference
~~~~~~~~~~~~~

For detailed API documentation, see:

* :class:`pygeai.lab.integrations.IntegrationClient`
* :class:`pygeai.lab.integrations.IntegrationManager`
* :class:`pygeai.lab.models.ToolPlugin`
* :class:`pygeai.migration.strategies.IntegrationMigrationStrategy`

For additional examples, see:

* ``snippets/lab/integrations/list_integrations.py``
* ``snippets/lab/integrations/manage_config.py``
* ``snippets/lab/integrations/export_import_integration.py``
* ``snippets/lab/integrations/migrate_integration.py``
