Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Amazon Bedrock - Knowledge Bases and Data Sources #39245

Merged
merged 27 commits into from May 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
a34a85b
Amazon Bedrock Agent hook and unit tests
ferruzzi Apr 10, 2024
7a2e21a
AOSS hook implemented
ferruzzi Apr 18, 2024
0d183e9
AOSS collection_available waiter/sensor/trigger with tests
ferruzzi Apr 18, 2024
e98d37d
create_kb - operator, trigger, sensor, and waiter (with unit tests)
ferruzzi Apr 24, 2024
4ae8c61
create_data_source - operator and tests - takes under a second, no wa…
ferruzzi Apr 23, 2024
b19e0ee
Update previous sensor unit tests to match new pattern
ferruzzi Apr 23, 2024
78df56c
ingest_data - operator, trigger, sensor, and waiter (with unit tests)
ferruzzi Apr 23, 2024
687086a
Amazon Bedrock Knowledge Base system test
ferruzzi Apr 24, 2024
461a513
Doc pages - OpenSearch Serverless
ferruzzi Apr 25, 2024
7db6a87
Doc Page - Bedrock Agent
ferruzzi Apr 25, 2024
be0f339
static check doc fixes
ferruzzi Apr 25, 2024
e40d975
fix missing docstrings
ferruzzi Apr 25, 2024
1988a7c
add reference to opensearchserverless.rst
ferruzzi Apr 25, 2024
ee3e4e3
implement ingestion job deferrable
ferruzzi Apr 25, 2024
9069a0b
Fix a new trigger bug and improve new trigger test coverage
ferruzzi Apr 25, 2024
fa7dc78
more reasonable defaults for knowledge_base_active waiter
ferruzzi Apr 26, 2024
d1fbda2
fix create knowledge base deferrable mode returning the wrong value
ferruzzi Apr 26, 2024
7138c0b
Implement deferrable in OpenSearchServerlessCollectionActiveSensor
ferruzzi Apr 26, 2024
5029167
account_id is no longer used, should have been cleaned up earlier
ferruzzi Apr 29, 2024
68f762a
Move some hooks into tasks
ferruzzi Apr 29, 2024
d2fba72
fix opensearch unit test
ferruzzi Apr 29, 2024
73ab4a9
Add BedrockAgentBaseSensor to BASE_CLASSES
ferruzzi Apr 29, 2024
6d5cdd2
Standardize system test dag declaration
ferruzzi Apr 30, 2024
8135c57
aws_conn_id=None
ferruzzi Apr 30, 2024
f4d2d00
Fix templating
ferruzzi Apr 30, 2024
4700305
more generic BedrockBaseSensor
ferruzzi May 1, 2024
bf0d9d4
remove now-non-existant base sensor
ferruzzi May 1, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
20 changes: 20 additions & 0 deletions airflow/providers/amazon/aws/hooks/bedrock.py
Expand Up @@ -57,3 +57,23 @@ class BedrockRuntimeHook(AwsBaseHook):
def __init__(self, *args, **kwargs) -> None:
kwargs["client_type"] = self.client_type
super().__init__(*args, **kwargs)


class BedrockAgentHook(AwsBaseHook):
"""
Interact with the Amazon Agents for Bedrock API.

Provide thin wrapper around :external+boto3:py:class:`boto3.client("bedrock-agent") <AgentsforBedrock.Client>`.

Additional arguments (such as ``aws_conn_id``) may be specified and
are passed down to the underlying AwsBaseHook.

.. seealso::
- :class:`airflow.providers.amazon.aws.hooks.base_aws.AwsBaseHook`
"""

client_type = "bedrock-agent"

def __init__(self, *args, **kwargs) -> None:
kwargs["client_type"] = self.client_type
super().__init__(*args, **kwargs)
39 changes: 39 additions & 0 deletions airflow/providers/amazon/aws/hooks/opensearch_serverless.py
@@ -0,0 +1,39 @@
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from __future__ import annotations

from airflow.providers.amazon.aws.hooks.base_aws import AwsBaseHook


class OpenSearchServerlessHook(AwsBaseHook):
"""
Interact with the Amazon OpenSearch Serverless API.

Provide thin wrapper around :external+boto3:py:class:`boto3.client("opensearchserverless") <OpenSearchServiceServerless.Client>`.

Additional arguments (such as ``aws_conn_id``) may be specified and
are passed down to the underlying AwsBaseHook.

.. seealso::
- :class:`airflow.providers.amazon.aws.hooks.base_aws.AwsBaseHook`
"""

client_type = "opensearchserverless"

def __init__(self, *args, **kwargs) -> None:
kwargs["client_type"] = self.client_type
super().__init__(*args, **kwargs)
315 changes: 314 additions & 1 deletion airflow/providers/amazon/aws/operators/bedrock.py

Large diffs are not rendered by default.

173 changes: 166 additions & 7 deletions airflow/providers/amazon/aws/sensors/bedrock.py
Expand Up @@ -18,14 +18,16 @@
from __future__ import annotations

import abc
from typing import TYPE_CHECKING, Any, Sequence
from typing import TYPE_CHECKING, Any, Sequence, TypeVar

from airflow.configuration import conf
from airflow.exceptions import AirflowException, AirflowSkipException
from airflow.providers.amazon.aws.hooks.bedrock import BedrockHook
from airflow.providers.amazon.aws.hooks.bedrock import BedrockAgentHook, BedrockHook
from airflow.providers.amazon.aws.sensors.base_aws import AwsBaseSensor
from airflow.providers.amazon.aws.triggers.bedrock import (
BedrockCustomizeModelCompletedTrigger,
BedrockIngestionJobTrigger,
BedrockKnowledgeBaseActiveTrigger,
BedrockProvisionModelThroughputCompletedTrigger,
)
from airflow.providers.amazon.aws.utils.mixins import aws_template_fields
Expand All @@ -34,7 +36,10 @@
from airflow.utils.context import Context


class BedrockBaseSensor(AwsBaseSensor[BedrockHook]):
_GenericBedrockHook = TypeVar("_GenericBedrockHook", BedrockAgentHook, BedrockHook)


ferruzzi marked this conversation as resolved.
Show resolved Hide resolved
class BedrockBaseSensor(AwsBaseSensor[_GenericBedrockHook]):
"""
General sensor behavior for Amazon Bedrock.

Expand All @@ -57,7 +62,7 @@ class BedrockBaseSensor(AwsBaseSensor[BedrockHook]):
SUCCESS_STATES: tuple[str, ...] = ()
FAILURE_MESSAGE = ""

aws_hook_class = BedrockHook
aws_hook_class: type[_GenericBedrockHook]
ui_color = "#66c3ff"

def __init__(
Expand All @@ -68,7 +73,7 @@ def __init__(
super().__init__(**kwargs)
self.deferrable = deferrable

def poke(self, context: Context) -> bool:
def poke(self, context: Context, **kwargs) -> bool:
state = self.get_state()
if state in self.FAILURE_STATES:
# TODO: remove this if block when min_airflow_version is set to higher than 2.7.1
Expand All @@ -83,7 +88,7 @@ def get_state(self) -> str:
"""Implement in subclasses."""


class BedrockCustomizeModelCompletedSensor(BedrockBaseSensor):
class BedrockCustomizeModelCompletedSensor(BedrockBaseSensor[BedrockHook]):
"""
Poll the state of the model customization job until it reaches a terminal state; fails if the job fails.

Expand Down Expand Up @@ -115,6 +120,8 @@ class BedrockCustomizeModelCompletedSensor(BedrockBaseSensor):
SUCCESS_STATES: tuple[str, ...] = ("Completed",)
FAILURE_MESSAGE = "Bedrock model customization job sensor failed."

aws_hook_class = BedrockHook

template_fields: Sequence[str] = aws_template_fields("job_name")

def __init__(
Expand Down Expand Up @@ -148,7 +155,7 @@ def get_state(self) -> str:
return self.hook.conn.get_model_customization_job(jobIdentifier=self.job_name)["status"]


class BedrockProvisionModelThroughputCompletedSensor(BedrockBaseSensor):
class BedrockProvisionModelThroughputCompletedSensor(BedrockBaseSensor[BedrockHook]):
"""
Poll the provisioned model throughput job until it reaches a terminal state; fails if the job fails.

Expand Down Expand Up @@ -180,6 +187,8 @@ class BedrockProvisionModelThroughputCompletedSensor(BedrockBaseSensor):
SUCCESS_STATES: tuple[str, ...] = ("InService",)
FAILURE_MESSAGE = "Bedrock provision model throughput sensor failed."

aws_hook_class = BedrockHook

template_fields: Sequence[str] = aws_template_fields("model_id")

def __init__(
Expand Down Expand Up @@ -211,3 +220,153 @@ def execute(self, context: Context) -> Any:
)
else:
super().execute(context=context)


class BedrockKnowledgeBaseActiveSensor(BedrockBaseSensor[BedrockAgentHook]):
"""
Poll the Knowledge Base status until it reaches a terminal state; fails if creation fails.

.. seealso::
For more information on how to use this sensor, take a look at the guide:
:ref:`howto/sensor:BedrockKnowledgeBaseActiveSensor`

:param knowledge_base_id: The unique identifier of the knowledge base for which to get information. (templated)

:param deferrable: If True, the sensor will operate in deferrable more. This mode requires aiobotocore
module to be installed.
(default: False, but can be overridden in config file by setting default_deferrable to True)
:param poke_interval: Polling period in seconds to check for the status of the job. (default: 5)
:param max_retries: Number of times before returning the current state (default: 24)
:param aws_conn_id: The Airflow connection used for AWS credentials.
If this is ``None`` or empty then the default boto3 behaviour is used. If
running Airflow in a distributed manner and aws_conn_id is None or
empty, then default boto3 configuration would be used (and must be
maintained on each worker node).
:param region_name: AWS region_name. If not specified then the default boto3 behaviour is used.
:param verify: Whether or not to verify SSL certificates. See:
https://boto3.amazonaws.com/v1/documentation/api/latest/reference/core/session.html
:param botocore_config: Configuration dictionary (key-values) for botocore client. See:
https://botocore.amazonaws.com/v1/documentation/api/latest/reference/config.html
"""

INTERMEDIATE_STATES: tuple[str, ...] = ("CREATING", "UPDATING")
FAILURE_STATES: tuple[str, ...] = ("DELETING", "FAILED")
SUCCESS_STATES: tuple[str, ...] = ("ACTIVE",)
FAILURE_MESSAGE = "Bedrock Knowledge Base Active sensor failed."

aws_hook_class = BedrockAgentHook

template_fields: Sequence[str] = aws_template_fields("knowledge_base_id")

def __init__(
self,
*,
knowledge_base_id: str,
poke_interval: int = 5,
max_retries: int = 24,
**kwargs,
) -> None:
super().__init__(**kwargs)
self.poke_interval = poke_interval
self.max_retries = max_retries
self.knowledge_base_id = knowledge_base_id

def get_state(self) -> str:
return self.hook.conn.get_knowledge_base(knowledgeBaseId=self.knowledge_base_id)["knowledgeBase"][
"status"
]

def execute(self, context: Context) -> Any:
if self.deferrable:
self.defer(
trigger=BedrockKnowledgeBaseActiveTrigger(
knowledge_base_id=self.knowledge_base_id,
waiter_delay=int(self.poke_interval),
waiter_max_attempts=self.max_retries,
aws_conn_id=self.aws_conn_id,
),
method_name="poke",
ferruzzi marked this conversation as resolved.
Show resolved Hide resolved
)
else:
super().execute(context=context)


class BedrockIngestionJobSensor(BedrockBaseSensor[BedrockAgentHook]):
"""
Poll the ingestion job status until it reaches a terminal state; fails if creation fails.

.. seealso::
For more information on how to use this sensor, take a look at the guide:
:ref:`howto/sensor:BedrockIngestionJobSensor`

:param knowledge_base_id: The unique identifier of the knowledge base for which to get information. (templated)
:param data_source_id: The unique identifier of the data source in the ingestion job. (templated)
:param ingestion_job_id: The unique identifier of the ingestion job. (templated)

:param deferrable: If True, the sensor will operate in deferrable more. This mode requires aiobotocore
module to be installed.
(default: False, but can be overridden in config file by setting default_deferrable to True)
:param poke_interval: Polling period in seconds to check for the status of the job. (default: 60)
:param max_retries: Number of times before returning the current state (default: 10)
:param aws_conn_id: The Airflow connection used for AWS credentials.
If this is ``None`` or empty then the default boto3 behaviour is used. If
running Airflow in a distributed manner and aws_conn_id is None or
empty, then default boto3 configuration would be used (and must be
maintained on each worker node).
:param region_name: AWS region_name. If not specified then the default boto3 behaviour is used.
:param verify: Whether or not to verify SSL certificates. See:
https://boto3.amazonaws.com/v1/documentation/api/latest/reference/core/session.html
:param botocore_config: Configuration dictionary (key-values) for botocore client. See:
https://botocore.amazonaws.com/v1/documentation/api/latest/reference/config.html
"""

INTERMEDIATE_STATES: tuple[str, ...] = ("STARTING", "IN_PROGRESS")
FAILURE_STATES: tuple[str, ...] = ("FAILED",)
SUCCESS_STATES: tuple[str, ...] = ("COMPLETE",)
FAILURE_MESSAGE = "Bedrock ingestion job sensor failed."

aws_hook_class = BedrockAgentHook

template_fields: Sequence[str] = aws_template_fields(
"knowledge_base_id", "data_source_id", "ingestion_job_id"
)

def __init__(
self,
*,
knowledge_base_id: str,
data_source_id: str,
ingestion_job_id: str,
poke_interval: int = 60,
max_retries: int = 10,
**kwargs,
) -> None:
super().__init__(**kwargs)
self.poke_interval = poke_interval
self.max_retries = max_retries
self.knowledge_base_id = knowledge_base_id
self.data_source_id = data_source_id
self.ingestion_job_id = ingestion_job_id

def get_state(self) -> str:
return self.hook.conn.get_ingestion_job(
knowledgeBaseId=self.knowledge_base_id,
ingestionJobId=self.ingestion_job_id,
dataSourceId=self.data_source_id,
)["ingestionJob"]["status"]

def execute(self, context: Context) -> Any:
if self.deferrable:
self.defer(
trigger=BedrockIngestionJobTrigger(
knowledge_base_id=self.knowledge_base_id,
ingestion_job_id=self.ingestion_job_id,
data_source_id=self.data_source_id,
waiter_delay=int(self.poke_interval),
waiter_max_attempts=self.max_retries,
aws_conn_id=self.aws_conn_id,
),
method_name="poke",
)
else:
super().execute(context=context)