Skip to content

Commit

Permalink
Amazon Bedrock - Knowledge Bases and Data Sources (#39245)
Browse files Browse the repository at this point in the history
  • Loading branch information
ferruzzi committed May 2, 2024
1 parent ee584f4 commit 598398a
Show file tree
Hide file tree
Showing 24 changed files with 2,409 additions and 40 deletions.
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)


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",
)
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)

0 comments on commit 598398a

Please sign in to comment.