You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@airflow.apache.org by "ferruzzi (via GitHub)" <gi...@apache.org> on 2024/04/25 03:10:38 UTC
[PR] Amazon Bedrock - Knowledge Bases and Data Sources [airflow]
ferruzzi opened a new pull request, #39245:
URL: https://github.com/apache/airflow/pull/39245
Adds hooks, operators, sensors, triggers, and waiters to enable support for Amazon Bedrock Knowledge Bases. This includes Bedrock Data Sources and Ingestion Jobs, and some light additions (a thin hook, and a waiter/sensor/trigger set) for Amazon OpenSearch Serverless which are needed to make the system test work end-to-end.
System test and unit tests are included, as well as docs. Static checks, unit tests, and build-docs all pass locally.
<!--
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.
-->
<!--
Thank you for contributing! Please make sure that your code changes
are covered with tests. And in case of new features or big changes
remember to adjust the documentation.
Feel free to ping committers for the review!
In case of an existing issue, reference it using one of the following:
closes: #ISSUE
related: #ISSUE
How to write a good git commit message:
http://chris.beams.io/posts/git-commit/
-->
<!-- Please keep an empty line above the dashes. -->
---
**^ Add meaningful description above**
Read the **[Pull Request Guidelines](https://github.com/apache/airflow/blob/main/contributing-docs/05_pull_requests.rst#pull-request-guidelines)** for more information.
In case of fundamental code changes, an Airflow Improvement Proposal ([AIP](https://cwiki.apache.org/confluence/display/AIRFLOW/Airflow+Improvement+Proposals)) is needed.
In case of a new dependency, check compliance with the [ASF 3rd Party License Policy](https://www.apache.org/legal/resolved.html#category-x).
In case of backwards incompatible changes please leave a note in a newsfragment file, named `{pr_number}.significant.rst` or `{issue_number}.significant.rst`, in [newsfragments](https://github.com/apache/airflow/tree/main/newsfragments).
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Amazon Bedrock - Knowledge Bases and Data Sources [airflow]
Posted by "ferruzzi (via GitHub)" <gi...@apache.org>.
ferruzzi merged PR #39245:
URL: https://github.com/apache/airflow/pull/39245
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Amazon Bedrock - Knowledge Bases and Data Sources [airflow]
Posted by "vincbeck (via GitHub)" <gi...@apache.org>.
vincbeck commented on PR #39245:
URL: https://github.com/apache/airflow/pull/39245#issuecomment-2077854596
> I'm really not sure what that failing static check is trying to tell me. Wouldn't mind a hand on that if someone knows what it means.
I think, it tries to tell you that you created a doc (`opensearchserverless.rst`) that you do not reference anywhere. Adding a `how-to-guide` section in `provider.yaml` which references the new doc should solve it
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Amazon Bedrock - Knowledge Bases and Data Sources [airflow]
Posted by "ferruzzi (via GitHub)" <gi...@apache.org>.
ferruzzi commented on code in PR #39245:
URL: https://github.com/apache/airflow/pull/39245#discussion_r1579829206
##########
airflow/providers/amazon/aws/operators/bedrock.py:
##########
@@ -351,3 +353,288 @@ def execute_complete(self, context: Context, event: dict[str, Any] | None = None
self.log.info("Bedrock provisioned throughput job `%s` complete.", event["provisioned_model_id"])
return event["provisioned_model_id"]
+
+
+class BedrockCreateKnowledgeBaseOperator(AwsBaseOperator[BedrockAgentHook]):
+ """
+ Create a knowledge base that contains data sources used by Amazon Bedrock LLMs and Agents.
+
+ To create a knowledge base, you must first set up your data sources and configure a supported vector store.
+
+ .. seealso::
+ For more information on how to use this operator, take a look at the guide:
+ :ref:`howto/operator:BedrockCreateKnowledgeBaseOperator`
+
+ :param name: The name of the knowledge base. (templated)
+ :param embedding_model_arn: ARN of the model used to create vector embeddings for the knowledge base. (templated)
+ :param role_arn: The ARN of the IAM role with permissions to create the knowledge base. (templated)
+ :param storage_config: Configuration details of the vector database used for the knowledge base. (templated)
+ :param wait_for_indexing: Vector indexing can take some time and there is no apparent way to check the state
+ before trying to create the Knowledge Base. If this is True, and creation fails due to the index not
+ being available, the operator will wait and retry. (default: True) (templated)
+ :param indexing_error_retry_delay: Seconds between retries if an index error is encountered. (default 5) (templated)
+ :param indexing_error_max_attempts: Maximum number of times to retry when encountering an index error. (default 20) (templated)
+
+ :param wait_for_completion: Whether to wait for cluster to stop. (default: True)
+ :param waiter_delay: Time in seconds to wait between status checks. (default: 60)
+ :param waiter_max_attempts: Maximum number of attempts to check for job completion. (default: 20)
+ :param deferrable: If True, the operator will wait asynchronously for the cluster to stop.
+ This implies waiting for completion. This mode requires aiobotocore module to be installed.
+ (default: False)
+ :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
+ """
+
+ aws_hook_class = BedrockAgentHook
+ template_fields: Sequence[str] = aws_template_fields(
+ "name",
+ "embedding_model_arn",
+ "role_arn",
+ "storage_config",
+ "wait_for_indexing",
+ "indexing_error_retry_delay",
+ "indexing_error_max_attempts",
+ )
+
+ def __init__(
+ self,
+ name: str,
+ embedding_model_arn: str,
+ role_arn: str,
+ storage_config: dict[str, Any],
+ create_knowledge_base_kwargs: dict[str, Any] | None = None,
+ wait_for_indexing: bool = True,
+ indexing_error_retry_delay: int = 5, # seconds
+ indexing_error_max_attempts: int = 20,
+ wait_for_completion: bool = True,
+ waiter_delay: int = 60,
+ waiter_max_attempts: int = 20,
+ deferrable: bool = conf.getboolean("operators", "default_deferrable", fallback=False),
+ **kwargs,
+ ):
+ super().__init__(**kwargs)
+ self.name = name
+ self.role_arn = role_arn
+ self.storage_config = storage_config
+ self.create_knowledge_base_kwargs = create_knowledge_base_kwargs or {}
+ self.embedding_model_arn = embedding_model_arn
+ self.knowledge_base_config = {
+ "type": "VECTOR",
+ "vectorKnowledgeBaseConfiguration": {"embeddingModelArn": self.embedding_model_arn},
+ }
+ self.wait_for_indexing = wait_for_indexing
+ self.indexing_error_retry_delay = indexing_error_retry_delay
+ self.indexing_error_max_attempts = indexing_error_max_attempts
+
+ self.wait_for_completion = wait_for_completion
+ self.waiter_delay = waiter_delay
+ self.waiter_max_attempts = waiter_max_attempts
+ self.deferrable = deferrable
+
+ def execute_complete(self, context: Context, event: dict[str, Any] | None = None) -> str:
+ event = validate_execute_complete_event(event)
+
+ if event["status"] != "success":
+ raise AirflowException(f"Error while running job: {event}")
+
+ self.log.info("Bedrock knowledge base creation job `%s` complete.", self.name)
+ return self.hook.conn.get_knowledge_base(knowledgeBaseId=event["knowledge_base_id"])["knowledgeBase"][
+ "status"
+ ]
+
+ def execute(self, context: Context) -> str:
+ def _create_kb():
+ # This API call will return the following if the index has not completed, but there is no apparent
+ # way to check the state of the index beforehand, so retry on index failure if set to do so.
+ # botocore.errorfactory.ValidationException: An error occurred (ValidationException)
+ # when calling the CreateKnowledgeBase operation: The knowledge base storage configuration
+ # provided is invalid... no such index [bedrock-sample-rag-index-abc108]
+ try:
+ return self.hook.conn.create_knowledge_base(
+ name=self.name,
+ roleArn=self.role_arn,
+ knowledgeBaseConfiguration=self.knowledge_base_config,
+ storageConfiguration=self.storage_config,
+ **self.create_knowledge_base_kwargs,
+ )["knowledgeBase"]["knowledgeBaseId"]
+ except ClientError as error:
+ if all(
+ [
+ error.response["Error"]["Code"] == "ValidationException",
+ "no such index" in error.response["Error"]["Message"],
+ self.wait_for_indexing,
+ self.indexing_error_max_attempts > 0,
+ ]
+ ):
+ self.indexing_error_max_attempts -= 1
+ self.log.warning(
+ "Vector index not ready, retrying in %s seconds.", self.indexing_error_retry_delay
+ )
+ self.log.debug("%s retries remaining.", self.indexing_error_max_attempts)
+ sleep(self.indexing_error_retry_delay)
+ return _create_kb()
+ raise
+
+ self.log.info("Creating Amazon Bedrock Knowledge Base %s", self.name)
+ knowledge_base_id = _create_kb()
+
+ if self.deferrable:
+ self.log.info("Deferring for Knowledge base creation.")
+ self.defer(
+ trigger=BedrockKnowledgeBaseActiveTrigger(
+ knowledge_base_id=knowledge_base_id,
+ waiter_delay=self.waiter_delay,
+ waiter_max_attempts=self.waiter_max_attempts,
+ aws_conn_id=self.aws_conn_id,
+ ),
+ method_name="execute_complete",
+ )
+ if self.wait_for_completion:
+ self.log.info("Waiting for Knowledge Base creation.")
+ self.hook.get_waiter("knowledge_base_active").wait(
+ knowledgeBaseId=knowledge_base_id,
+ WaiterConfig={"Delay": self.waiter_delay, "MaxAttempts": self.waiter_max_attempts},
+ )
+
+ return knowledge_base_id
+
+
+class BedrockCreateDataSourceOperator(AwsBaseOperator[BedrockAgentHook]):
+ """
+ Set up an Amazon Bedrock Data Source to be added to an Amazon Bedrock Knowledge Base.
+
+ .. seealso::
+ For more information on how to use this operator, take a look at the guide:
+ :ref:`howto/operator:BedrockCreateDataSourceOperator`
+
+ :param name: name for the Amazon Bedrock Data Source being created. (templated).
+ :param bucket_name: The name of the Amazon S3 bucket to use for data source storage. (templated)
+ :param knowledge_base_id: The unique identifier of the knowledge base to which to add the data source. (templated)
+
+ :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
+ """
+
+ aws_hook_class = BedrockAgentHook
+
+ def __init__(
+ self,
+ name: str,
+ knowledge_base_id: str,
+ bucket_name: str | None = None,
+ create_data_source_kwargs: dict[str, Any] | None = None,
+ **kwargs,
+ ):
+ super().__init__(**kwargs)
+ self.name = name
+ self.knowledge_base_id = knowledge_base_id
+ self.bucket_name = bucket_name
+ self.create_data_source_kwargs = create_data_source_kwargs or {}
+
+ template_fields: Sequence[str] = aws_template_fields(
+ "name",
+ "bucket_name",
+ "knowledge_base_id",
+ )
+
+ def execute(self, context: Context) -> str:
+ create_ds_response = self.hook.conn.create_data_source(
+ name=self.name,
+ knowledgeBaseId=self.knowledge_base_id,
+ dataSourceConfiguration={
+ "type": "S3",
+ "s3Configuration": {"bucketArn": f"arn:aws:s3:::{self.bucket_name}"},
+ },
+ **self.create_data_source_kwargs,
+ )
+
+ return create_ds_response["dataSource"]["dataSourceId"]
+
+
+class BedrockIngestDataOperator(AwsBaseOperator[BedrockAgentHook]):
+ """
+ Begin an ingestion job, in which an Amazon Bedrock data source is added to an Amazon Bedrock knowledge base.
+
+ .. seealso::
+ For more information on how to use this operator, take a look at the guide:
+ :ref:`howto/operator:BedrockIngestDataOperator`
+
+ :param knowledge_base_id: The unique identifier of the knowledge base to which to add the data source. (templated)
+ :param data_source_id: The unique identifier of the data source to ingest. (templated)
+
+ :param wait_for_completion: Whether to wait for cluster to stop. (default: True)
+ :param waiter_delay: Time in seconds to wait between status checks. (default: 60)
+ :param waiter_max_attempts: Maximum number of attempts to check for job completion. (default: 10)
+ :param deferrable: If True, the operator will wait asynchronously for the cluster to stop.
+ This implies waiting for completion. This mode requires aiobotocore module to be installed.
+ (default: False)
+ :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
+ """
+
+ aws_hook_class = BedrockAgentHook
+
+ def __init__(
+ self,
+ knowledge_base_id: str,
+ data_source_id: str,
+ ingest_data_kwargs: dict[str, Any] | None = None,
+ wait_for_completion: bool = True,
+ waiter_delay: int = 60,
+ waiter_max_attempts: int = 10,
+ deferrable: bool = conf.getboolean("operators", "default_deferrable", fallback=False),
+ **kwargs,
+ ):
+ super().__init__(**kwargs)
+ self.knowledge_base_id = knowledge_base_id
+ self.data_source_id = data_source_id
+ self.ingest_data_kwargs = ingest_data_kwargs or {}
+
+ self.wait_for_completion = wait_for_completion
+ self.waiter_delay = waiter_delay
+ self.waiter_max_attempts = waiter_max_attempts
+ self.deferrable = deferrable
+
+ template_fields: Sequence[str] = aws_template_fields(
+ "knowledge_base_id",
+ "data_source_id",
+ )
+
+ def execute(self, context: Context) -> str:
+ ingestion_job_id = self.hook.conn.start_ingestion_job(
+ knowledgeBaseId=self.knowledge_base_id, dataSourceId=self.data_source_id
+ )["ingestionJob"]["ingestionJobId"]
+
+ if self.wait_for_completion:
Review Comment:
Good catch, I made the Trigger and forgot to implement it there. Fix coming.
##########
airflow/providers/amazon/aws/sensors/opensearch_serverless.py:
##########
@@ -0,0 +1,110 @@
+# 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 typing import TYPE_CHECKING, Any, Sequence
+
+from airflow.exceptions import AirflowException, AirflowSkipException
+from airflow.providers.amazon.aws.hooks.opensearch_serverless import OpenSearchServerlessHook
+from airflow.providers.amazon.aws.sensors.base_aws import AwsBaseSensor
+from airflow.providers.amazon.aws.utils.mixins import aws_template_fields
+from airflow.utils.helpers import exactly_one
+
+if TYPE_CHECKING:
+ from airflow.utils.context import Context
+
+
+class OpenSearchServerlessCollectionActiveSensor(AwsBaseSensor[OpenSearchServerlessHook]):
+ """
+ Poll the state of the Collection until it reaches a terminal state; fails if the query fails.
+
+ .. seealso::
+ For more information on how to use this sensor, take a look at the guide:
+ :ref:`howto/sensor:OpenSearchServerlessCollectionAvailableSensor`
+
+ :param collection_id: A collection ID. You can't provide a name and an ID in the same request.
+ :param collection_name: A collection name. You can't provide a name and an ID in the same request.
+
+ :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)
Review Comment:
Ah, no, I made the trigger for that and forgot to implement it there. Good catch, I'll add it now.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Amazon Bedrock - Knowledge Bases and Data Sources [airflow]
Posted by "ferruzzi (via GitHub)" <gi...@apache.org>.
ferruzzi commented on code in PR #39245:
URL: https://github.com/apache/airflow/pull/39245#discussion_r1585192344
##########
tests/system/providers/amazon/aws/example_bedrock_knowledge_base.py:
##########
@@ -0,0 +1,519 @@
+# 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
+
+import json
+import logging
+import os.path
+import tempfile
+from datetime import datetime
+from time import sleep
+from urllib.request import urlretrieve
+
+import boto3
+from botocore.exceptions import ClientError
+from opensearchpy import (
+ AuthorizationException,
+ AWSV4SignerAuth,
+ OpenSearch,
+ RequestsHttpConnection,
+)
+
+from airflow import DAG
+from airflow.decorators import task
+from airflow.providers.amazon.aws.hooks.bedrock import BedrockAgentHook
+from airflow.providers.amazon.aws.hooks.opensearch_serverless import OpenSearchServerlessHook
+from airflow.providers.amazon.aws.hooks.s3 import S3Hook
+from airflow.providers.amazon.aws.hooks.sts import StsHook
+from airflow.providers.amazon.aws.operators.bedrock import (
+ BedrockCreateDataSourceOperator,
+ BedrockCreateKnowledgeBaseOperator,
+ BedrockIngestDataOperator,
+)
+from airflow.providers.amazon.aws.operators.s3 import S3CreateBucketOperator, S3DeleteBucketOperator
+from airflow.providers.amazon.aws.sensors.bedrock import (
+ BedrockIngestionJobSensor,
+ BedrockKnowledgeBaseActiveSensor,
+)
+from airflow.providers.amazon.aws.sensors.opensearch_serverless import (
+ OpenSearchServerlessCollectionActiveSensor,
+)
+from airflow.utils.helpers import chain
+from airflow.utils.trigger_rule import TriggerRule
+from tests.system.providers.amazon.aws.utils import SystemTestContextBuilder
+
+###############################################################################
+# NOTE: The account running this test must first manually request access to
+# the `Titan Embeddings G1 - Text` foundation model via the Bedrock console.
+# Gaining access to the model can take 24 hours from the time of request.
+###############################################################################
+
+# Externally fetched variables:
+ROLE_ARN_KEY = "ROLE_ARN"
+sys_test_context_task = SystemTestContextBuilder().add_variable(ROLE_ARN_KEY).build()
+
+DAG_ID = "example_bedrock_knowledge_base"
+
+log = logging.getLogger(__name__)
+
+
+@task
+def create_opensearch_policies(bedrock_role_arn: str, collection_name: str):
+ """
+ Create security, network and data access policies within Amazon OpenSearch Serverless.
+
+ :param bedrock_role_arn: Arn of the Bedrock Knowledge Base Execution Role.
+ :param collection_name: Name of the OpenSearch collection to apply the policies to.
+ """
+
+ encryption_policy_name = f"{naming_prefix}rag-sp-{env_id}"
+ network_policy_name = f"{naming_prefix}rag-np-{env_id}"
+ access_policy_name = f"{naming_prefix}rag-ap-{env_id}"
+
+ def _create_security_policy(name, policy_type, policy):
+ try:
+ aoss_client.create_security_policy(name=name, policy=json.dumps(policy), type=policy_type)
+ except ClientError as e:
+ if e.response["Error"]["Code"] == "ConflictException":
+ log.info("OpenSearch security policy %s already exists.", name)
+ raise
+
+ def _create_access_policy(name, policy_type, policy):
+ try:
+ aoss_client.create_access_policy(name=name, policy=json.dumps(policy), type=policy_type)
+ except ClientError as e:
+ if e.response["Error"]["Code"] == "ConflictException":
+ log.info("OpenSearch data access policy %s already exists.", name)
+ raise
+
+ _create_security_policy(
+ name=encryption_policy_name,
+ policy_type="encryption",
+ policy={
+ "Rules": [{"Resource": [f"collection/{collection_name}"], "ResourceType": "collection"}],
+ "AWSOwnedKey": True,
+ },
+ )
+
+ _create_security_policy(
+ name=network_policy_name,
+ policy_type="network",
+ policy=[
+ {
+ "Rules": [{"Resource": [f"collection/{collection_name}"], "ResourceType": "collection"}],
+ "AllowFromPublic": True,
+ }
+ ],
+ )
+
+ _create_access_policy(
+ name=access_policy_name,
+ policy_type="data",
+ policy=[
+ {
+ "Rules": [
+ {
+ "Resource": [f"collection/{collection_name}"],
+ "Permission": [
+ "aoss:CreateCollectionItems",
+ "aoss:DeleteCollectionItems",
+ "aoss:UpdateCollectionItems",
+ "aoss:DescribeCollectionItems",
+ ],
+ "ResourceType": "collection",
+ },
+ {
+ "Resource": [f"index/{collection_name}/*"],
+ "Permission": [
+ "aoss:CreateIndex",
+ "aoss:DeleteIndex",
+ "aoss:UpdateIndex",
+ "aoss:DescribeIndex",
+ "aoss:ReadDocument",
+ "aoss:WriteDocument",
+ ],
+ "ResourceType": "index",
+ },
+ ],
+ "Principal": [(StsHook().conn.get_caller_identity()["Arn"]), bedrock_role_arn],
+ }
+ ],
+ )
+
+
+@task
+def create_collection(collection_name: str):
+ """
+ Call the Amazon OpenSearch Serverless API and create a collection with the provided name.
+
+ :param collection_name: The name of the Collection to create.
+ """
+ log.info("\nCreating collection: %s.", collection_name)
+ return aoss_client.create_collection(name=collection_name, type="VECTORSEARCH")["createCollectionDetail"][
+ "id"
+ ]
+
+
+@task
+def create_vector_index(collection_id: str, region: str):
+ """
+ Use the OpenSearchPy client to create the vector index for the Amazon Open Search Serverless Collection.
+
+ :param collection_id: ID of the collection to be indexed.
+ :param region: Name of the AWS region the collection resides in.
+ """
+ # Build the OpenSearch client
+ oss_client = OpenSearch(
+ hosts=[{"host": f"{collection_id}.{region}.aoss.amazonaws.com", "port": 443}],
+ http_auth=AWSV4SignerAuth(boto3.Session().get_credentials(), region, "aoss"),
+ use_ssl=True,
+ verify_certs=True,
+ connection_class=RequestsHttpConnection,
+ timeout=300,
+ )
+ index_config = {
+ "settings": {
+ "index.knn": "true",
+ "number_of_shards": 1,
+ "knn.algo_param.ef_search": 512,
+ "number_of_replicas": 0,
+ },
+ "mappings": {
+ "properties": {
+ "vector": {
+ "type": "knn_vector",
+ "dimension": 1536,
+ "method": {"name": "hnsw", "engine": "faiss", "space_type": "l2"},
+ },
+ "text": {"type": "text"},
+ "text-metadata": {"type": "text"},
+ }
+ },
+ }
+
+ retries = 35
+ while retries > 0:
+ try:
+ response = oss_client.indices.create(index=index_name, body=json.dumps(index_config))
+ log.info("Creating index: %s.", response)
+ break
+ except AuthorizationException as e:
+ # Index creation can take up to a minute and there is no (apparent?) way to check the current state.
+ log.info(
+ "Access denied; policy permissions have likely not yet propagated, %s tries remaining.",
+ retries,
+ )
+ log.debug(e)
+ retries -= 1
+ sleep(2)
+
+
+@task
+def copy_data_to_s3(bucket: str):
+ """
+ Download some sample data and upload it to 3S.
+
+ :param bucket: Name of the Amazon S3 bucket to send the data to.
+ """
+
+ # Monkey patch the list of names available for NamedTempFile so we can pick the names of the downloaded files.
+ backup_get_candidate_names = tempfile._get_candidate_names # type: ignore[attr-defined]
+ destinations = iter(
+ [
+ "AMZN-2022-Shareholder-Letter.pdf",
+ "AMZN-2021-Shareholder-Letter.pdf",
+ "AMZN-2020-Shareholder-Letter.pdf",
+ "AMZN-2019-Shareholder-Letter.pdf",
+ ]
+ )
+ tempfile._get_candidate_names = lambda: destinations # type: ignore[attr-defined]
+
+ # Download the sample data files, save them as named temp files using the names above, and upload to S3.
+ sources = [
+ "https://s2.q4cdn.com/299287126/files/doc_financials/2023/ar/2022-Shareholder-Letter.pdf",
+ "https://s2.q4cdn.com/299287126/files/doc_financials/2022/ar/2021-Shareholder-Letter.pdf",
+ "https://s2.q4cdn.com/299287126/files/doc_financials/2021/ar/Amazon-2020-Shareholder-Letter-and-1997-Shareholder-Letter.pdf",
+ "https://s2.q4cdn.com/299287126/files/doc_financials/2020/ar/2019-Shareholder-Letter.pdf",
+ ]
+
+ for source in sources:
+ with tempfile.NamedTemporaryFile(mode="w", prefix="") as data_file:
+ urlretrieve(source, data_file.name)
+ S3Hook().conn.upload_file(
+ Filename=data_file.name, Bucket=bucket, Key=os.path.basename(data_file.name)
+ )
+
+ # Revert the monkey patch.
+ tempfile._get_candidate_names = backup_get_candidate_names # type: ignore[attr-defined]
+ # Verify the path reversion worked.
+ with tempfile.NamedTemporaryFile(mode="w", prefix=""):
+ # If the reversion above did not apply correctly, this will fail with
+ # a StopIteration error because the iterator will run out of names.
+ ...
+
+
+@task
+def get_collection_arn(collection_id: str):
+ """
+ Return a collection ARN for a given collection ID.
+
+ :param collection_id: ID of the collection to be indexed.
+ """
+ return next(
+ colxn["arn"]
+ for colxn in aoss_client.list_collections()["collectionSummaries"]
+ if colxn["id"] == collection_id
+ )
+
+
+# [START howto_operator_bedrock_delete_data_source]
+@task(trigger_rule=TriggerRule.ALL_DONE)
+def delete_data_source(knowledge_base_id: str, data_source_id: str):
+ """
+ Delete the Amazon Bedrock data source created earlier.
+
+ .. seealso::
+ For more information on how to use this sensor, take a look at the guide:
+ :ref:`howto_operator:BedrockDeleteDataSource`
+
+ :param knowledge_base_id: The unique identifier of the knowledge base which the data source is attached to.
+ :param data_source_id: The unique identifier of the data source to delete.
+ """
+ log.info("Deleting data source %s from Knowledge Base %s.", data_source_id, knowledge_base_id)
+ bedrock_agent_client.delete_data_source(dataSourceId=data_source_id, knowledgeBaseId=knowledge_base_id)
+
+
+# [END howto_operator_bedrock_delete_data_source]
+
+
+# [START howto_operator_bedrock_delete_knowledge_base]
+@task(trigger_rule=TriggerRule.ALL_DONE)
+def delete_knowledge_base(knowledge_base_id: str):
+ """
+ Delete the Amazon Bedrock knowledge base created earlier.
+
+ .. seealso::
+ For more information on how to use this sensor, take a look at the guide:
+ :ref:`howto/operator:BedrockDeleteKnowledgeBase`
+
+ :param knowledge_base_id: The unique identifier of the knowledge base to delete.
+ """
+ log.info("Deleting Knowledge Base %s.", knowledge_base_id)
+ bedrock_agent_client.delete_knowledge_base(knowledgeBaseId=knowledge_base_id)
+
+
+# [END howto_operator_bedrock_delete_knowledge_base]
+
+
+@task(trigger_rule=TriggerRule.ALL_DONE)
+def delete_vector_index(collection_id: str):
+ """
+ Delete the vector index created earlier.
+
+ :param collection_id: ID of the collection to be indexed.
+ """
+ host = f"{collection_id}.{region_name}.aoss.amazonaws.com"
+ credentials = boto3.Session().get_credentials()
+ awsauth = AWSV4SignerAuth(credentials, region_name, "aoss")
+
+ # Build the OpenSearch client
+ oss_client = OpenSearch(
+ hosts=[{"host": host, "port": 443}],
+ http_auth=awsauth,
+ use_ssl=True,
+ verify_certs=True,
+ connection_class=RequestsHttpConnection,
+ timeout=300,
+ )
+ oss_client.indices.delete(index=index_name)
+
+
+@task(trigger_rule=TriggerRule.ALL_DONE)
+def delete_collection(collection_id: str):
+ """
+ Delete the OpenSearch collection created earlier.
+
+ :param collection_id: ID of the collection to be indexed.
+ """
+ log.info("Deleting collection %s.", collection_id)
+ aoss_client.delete_collection(id=collection_id)
+
+
+@task(trigger_rule=TriggerRule.ALL_DONE)
+def delete_opensearch_policies():
+ """Delete the security, network and data access policies created earlier."""
+
+ access_policies = aoss_client.list_access_policies(
+ type="data", resource=[f"collection/{vector_store_name}"]
+ )["accessPolicySummaries"]
+ log.info("Found access policies for %s: %s", vector_store_name, access_policies)
+ if not access_policies:
+ raise Exception("No access policies found?")
+ for policy in access_policies:
+ log.info("Deleting access policy for %s: %s", vector_store_name, policy["name"])
+ aoss_client.delete_access_policy(name=policy["name"], type="data")
+
+ for policy_type in ["encryption", "network"]:
+ policies = aoss_client.list_security_policies(
+ type=policy_type, resource=[f"collection/{vector_store_name}"]
+ )["securityPolicySummaries"]
+ if not policies:
+ raise Exception("No security policies found?")
+ log.info("Found %s security policies for %s: %s", policy_type, vector_store_name, policies)
+ for policy in policies:
+ log.info("Deleting %s security policy for %s: %s", policy_type, vector_store_name, policy["name"])
+ aoss_client.delete_security_policy(name=policy["name"], type=policy_type)
+
+
+with DAG(
+ dag_id=DAG_ID,
+ schedule="@once",
+ start_date=datetime(2021, 1, 1),
+ tags=["example"],
+ catchup=False,
+) as dag:
+ test_context = sys_test_context_task()
+ env_id = test_context["ENV_ID"]
+
+ aoss_client = OpenSearchServerlessHook().conn
+ bedrock_agent_client = BedrockAgentHook().conn
Review Comment:
They both get used a few times so I didn't want to recreate them multiple times. Will the `aws_con_id=None` skip the db call and fix the static check? For a system test, I think that's a fine solution. I can try it out and see. Thanks.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Amazon Bedrock - Knowledge Bases and Data Sources [airflow]
Posted by "ferruzzi (via GitHub)" <gi...@apache.org>.
ferruzzi commented on PR #39245:
URL: https://github.com/apache/airflow/pull/39245#issuecomment-2077942829
> Adding a how-to-guide section in provider.yaml which references the new doc should solve it
I SEE! Some of the integrations list a how-to and others don't, I'll add that in and see if that fixes it.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Amazon Bedrock - Knowledge Bases and Data Sources [airflow]
Posted by "ferruzzi (via GitHub)" <gi...@apache.org>.
ferruzzi commented on code in PR #39245:
URL: https://github.com/apache/airflow/pull/39245#discussion_r1585546006
##########
airflow/providers/amazon/aws/sensors/bedrock.py:
##########
@@ -211,3 +262,149 @@ def execute(self, context: Context) -> Any:
)
else:
super().execute(context=context)
+
+
+class BedrockKnowledgeBaseActiveSensor(BedrockAgentBaseSensor):
+ """
+ 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."
+
+ 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",
Review Comment:
if I modify poke from
```
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
if self.soft_fail:
raise AirflowSkipException(self.FAILURE_MESSAGE)
raise AirflowException(self.FAILURE_MESSAGE)
return state not in self.INTERMEDIATE_STATES
```
to (untested)
```
def poke(self, context: Context, **kwargs) -> bool:
state = kwargs.get("event").get("state") or self.get_state()
if state in self.FAILURE_STATES or state == "failure":
# TODO: remove this if block when min_airflow_version is set to higher than 2.7.1
if self.soft_fail:
raise AirflowSkipException(self.FAILURE_MESSAGE)
raise AirflowException(self.FAILURE_MESSAGE)
return state not in self.INTERMEDIATE_STATES
```
Then that would be the same thing without the extra get_state() call
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Amazon Bedrock - Knowledge Bases and Data Sources [airflow]
Posted by "Taragolis (via GitHub)" <gi...@apache.org>.
Taragolis commented on code in PR #39245:
URL: https://github.com/apache/airflow/pull/39245#discussion_r1584955631
##########
tests/system/providers/amazon/aws/example_bedrock_knowledge_base.py:
##########
@@ -0,0 +1,519 @@
+# 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
+
+import json
+import logging
+import os.path
+import tempfile
+from datetime import datetime
+from time import sleep
+from urllib.request import urlretrieve
+
+import boto3
+from botocore.exceptions import ClientError
+from opensearchpy import (
+ AuthorizationException,
+ AWSV4SignerAuth,
+ OpenSearch,
+ RequestsHttpConnection,
+)
+
+from airflow import DAG
+from airflow.decorators import task
+from airflow.providers.amazon.aws.hooks.bedrock import BedrockAgentHook
+from airflow.providers.amazon.aws.hooks.opensearch_serverless import OpenSearchServerlessHook
+from airflow.providers.amazon.aws.hooks.s3 import S3Hook
+from airflow.providers.amazon.aws.hooks.sts import StsHook
+from airflow.providers.amazon.aws.operators.bedrock import (
+ BedrockCreateDataSourceOperator,
+ BedrockCreateKnowledgeBaseOperator,
+ BedrockIngestDataOperator,
+)
+from airflow.providers.amazon.aws.operators.s3 import S3CreateBucketOperator, S3DeleteBucketOperator
+from airflow.providers.amazon.aws.sensors.bedrock import (
+ BedrockIngestionJobSensor,
+ BedrockKnowledgeBaseActiveSensor,
+)
+from airflow.providers.amazon.aws.sensors.opensearch_serverless import (
+ OpenSearchServerlessCollectionActiveSensor,
+)
+from airflow.utils.helpers import chain
+from airflow.utils.trigger_rule import TriggerRule
+from tests.system.providers.amazon.aws.utils import SystemTestContextBuilder
+
+###############################################################################
+# NOTE: The account running this test must first manually request access to
+# the `Titan Embeddings G1 - Text` foundation model via the Bedrock console.
+# Gaining access to the model can take 24 hours from the time of request.
+###############################################################################
+
+# Externally fetched variables:
+ROLE_ARN_KEY = "ROLE_ARN"
+sys_test_context_task = SystemTestContextBuilder().add_variable(ROLE_ARN_KEY).build()
+
+DAG_ID = "example_bedrock_knowledge_base"
+
+log = logging.getLogger(__name__)
+
+
+@task
+def create_opensearch_policies(bedrock_role_arn: str, collection_name: str):
+ """
+ Create security, network and data access policies within Amazon OpenSearch Serverless.
+
+ :param bedrock_role_arn: Arn of the Bedrock Knowledge Base Execution Role.
+ :param collection_name: Name of the OpenSearch collection to apply the policies to.
+ """
+
+ encryption_policy_name = f"{naming_prefix}rag-sp-{env_id}"
+ network_policy_name = f"{naming_prefix}rag-np-{env_id}"
+ access_policy_name = f"{naming_prefix}rag-ap-{env_id}"
+
+ def _create_security_policy(name, policy_type, policy):
+ try:
+ aoss_client.create_security_policy(name=name, policy=json.dumps(policy), type=policy_type)
+ except ClientError as e:
+ if e.response["Error"]["Code"] == "ConflictException":
+ log.info("OpenSearch security policy %s already exists.", name)
+ raise
+
+ def _create_access_policy(name, policy_type, policy):
+ try:
+ aoss_client.create_access_policy(name=name, policy=json.dumps(policy), type=policy_type)
+ except ClientError as e:
+ if e.response["Error"]["Code"] == "ConflictException":
+ log.info("OpenSearch data access policy %s already exists.", name)
+ raise
+
+ _create_security_policy(
+ name=encryption_policy_name,
+ policy_type="encryption",
+ policy={
+ "Rules": [{"Resource": [f"collection/{collection_name}"], "ResourceType": "collection"}],
+ "AWSOwnedKey": True,
+ },
+ )
+
+ _create_security_policy(
+ name=network_policy_name,
+ policy_type="network",
+ policy=[
+ {
+ "Rules": [{"Resource": [f"collection/{collection_name}"], "ResourceType": "collection"}],
+ "AllowFromPublic": True,
+ }
+ ],
+ )
+
+ _create_access_policy(
+ name=access_policy_name,
+ policy_type="data",
+ policy=[
+ {
+ "Rules": [
+ {
+ "Resource": [f"collection/{collection_name}"],
+ "Permission": [
+ "aoss:CreateCollectionItems",
+ "aoss:DeleteCollectionItems",
+ "aoss:UpdateCollectionItems",
+ "aoss:DescribeCollectionItems",
+ ],
+ "ResourceType": "collection",
+ },
+ {
+ "Resource": [f"index/{collection_name}/*"],
+ "Permission": [
+ "aoss:CreateIndex",
+ "aoss:DeleteIndex",
+ "aoss:UpdateIndex",
+ "aoss:DescribeIndex",
+ "aoss:ReadDocument",
+ "aoss:WriteDocument",
+ ],
+ "ResourceType": "index",
+ },
+ ],
+ "Principal": [(StsHook().conn.get_caller_identity()["Arn"]), bedrock_role_arn],
+ }
+ ],
+ )
+
+
+@task
+def create_collection(collection_name: str):
+ """
+ Call the Amazon OpenSearch Serverless API and create a collection with the provided name.
+
+ :param collection_name: The name of the Collection to create.
+ """
+ log.info("\nCreating collection: %s.", collection_name)
+ return aoss_client.create_collection(name=collection_name, type="VECTORSEARCH")["createCollectionDetail"][
+ "id"
+ ]
+
+
+@task
+def create_vector_index(collection_id: str, region: str):
+ """
+ Use the OpenSearchPy client to create the vector index for the Amazon Open Search Serverless Collection.
+
+ :param collection_id: ID of the collection to be indexed.
+ :param region: Name of the AWS region the collection resides in.
+ """
+ # Build the OpenSearch client
+ oss_client = OpenSearch(
+ hosts=[{"host": f"{collection_id}.{region}.aoss.amazonaws.com", "port": 443}],
+ http_auth=AWSV4SignerAuth(boto3.Session().get_credentials(), region, "aoss"),
+ use_ssl=True,
+ verify_certs=True,
+ connection_class=RequestsHttpConnection,
+ timeout=300,
+ )
+ index_config = {
+ "settings": {
+ "index.knn": "true",
+ "number_of_shards": 1,
+ "knn.algo_param.ef_search": 512,
+ "number_of_replicas": 0,
+ },
+ "mappings": {
+ "properties": {
+ "vector": {
+ "type": "knn_vector",
+ "dimension": 1536,
+ "method": {"name": "hnsw", "engine": "faiss", "space_type": "l2"},
+ },
+ "text": {"type": "text"},
+ "text-metadata": {"type": "text"},
+ }
+ },
+ }
+
+ retries = 35
+ while retries > 0:
+ try:
+ response = oss_client.indices.create(index=index_name, body=json.dumps(index_config))
+ log.info("Creating index: %s.", response)
+ break
+ except AuthorizationException as e:
+ # Index creation can take up to a minute and there is no (apparent?) way to check the current state.
+ log.info(
+ "Access denied; policy permissions have likely not yet propagated, %s tries remaining.",
+ retries,
+ )
+ log.debug(e)
+ retries -= 1
+ sleep(2)
+
+
+@task
+def copy_data_to_s3(bucket: str):
+ """
+ Download some sample data and upload it to 3S.
+
+ :param bucket: Name of the Amazon S3 bucket to send the data to.
+ """
+
+ # Monkey patch the list of names available for NamedTempFile so we can pick the names of the downloaded files.
+ backup_get_candidate_names = tempfile._get_candidate_names # type: ignore[attr-defined]
+ destinations = iter(
+ [
+ "AMZN-2022-Shareholder-Letter.pdf",
+ "AMZN-2021-Shareholder-Letter.pdf",
+ "AMZN-2020-Shareholder-Letter.pdf",
+ "AMZN-2019-Shareholder-Letter.pdf",
+ ]
+ )
+ tempfile._get_candidate_names = lambda: destinations # type: ignore[attr-defined]
+
+ # Download the sample data files, save them as named temp files using the names above, and upload to S3.
+ sources = [
+ "https://s2.q4cdn.com/299287126/files/doc_financials/2023/ar/2022-Shareholder-Letter.pdf",
+ "https://s2.q4cdn.com/299287126/files/doc_financials/2022/ar/2021-Shareholder-Letter.pdf",
+ "https://s2.q4cdn.com/299287126/files/doc_financials/2021/ar/Amazon-2020-Shareholder-Letter-and-1997-Shareholder-Letter.pdf",
+ "https://s2.q4cdn.com/299287126/files/doc_financials/2020/ar/2019-Shareholder-Letter.pdf",
+ ]
+
+ for source in sources:
+ with tempfile.NamedTemporaryFile(mode="w", prefix="") as data_file:
+ urlretrieve(source, data_file.name)
+ S3Hook().conn.upload_file(
+ Filename=data_file.name, Bucket=bucket, Key=os.path.basename(data_file.name)
+ )
+
+ # Revert the monkey patch.
+ tempfile._get_candidate_names = backup_get_candidate_names # type: ignore[attr-defined]
+ # Verify the path reversion worked.
+ with tempfile.NamedTemporaryFile(mode="w", prefix=""):
+ # If the reversion above did not apply correctly, this will fail with
+ # a StopIteration error because the iterator will run out of names.
+ ...
+
+
+@task
+def get_collection_arn(collection_id: str):
+ """
+ Return a collection ARN for a given collection ID.
+
+ :param collection_id: ID of the collection to be indexed.
+ """
+ return next(
+ colxn["arn"]
+ for colxn in aoss_client.list_collections()["collectionSummaries"]
+ if colxn["id"] == collection_id
+ )
+
+
+# [START howto_operator_bedrock_delete_data_source]
+@task(trigger_rule=TriggerRule.ALL_DONE)
+def delete_data_source(knowledge_base_id: str, data_source_id: str):
+ """
+ Delete the Amazon Bedrock data source created earlier.
+
+ .. seealso::
+ For more information on how to use this sensor, take a look at the guide:
+ :ref:`howto_operator:BedrockDeleteDataSource`
+
+ :param knowledge_base_id: The unique identifier of the knowledge base which the data source is attached to.
+ :param data_source_id: The unique identifier of the data source to delete.
+ """
+ log.info("Deleting data source %s from Knowledge Base %s.", data_source_id, knowledge_base_id)
+ bedrock_agent_client.delete_data_source(dataSourceId=data_source_id, knowledgeBaseId=knowledge_base_id)
+
+
+# [END howto_operator_bedrock_delete_data_source]
+
+
+# [START howto_operator_bedrock_delete_knowledge_base]
+@task(trigger_rule=TriggerRule.ALL_DONE)
+def delete_knowledge_base(knowledge_base_id: str):
+ """
+ Delete the Amazon Bedrock knowledge base created earlier.
+
+ .. seealso::
+ For more information on how to use this sensor, take a look at the guide:
+ :ref:`howto/operator:BedrockDeleteKnowledgeBase`
+
+ :param knowledge_base_id: The unique identifier of the knowledge base to delete.
+ """
+ log.info("Deleting Knowledge Base %s.", knowledge_base_id)
+ bedrock_agent_client.delete_knowledge_base(knowledgeBaseId=knowledge_base_id)
+
+
+# [END howto_operator_bedrock_delete_knowledge_base]
+
+
+@task(trigger_rule=TriggerRule.ALL_DONE)
+def delete_vector_index(collection_id: str):
+ """
+ Delete the vector index created earlier.
+
+ :param collection_id: ID of the collection to be indexed.
+ """
+ host = f"{collection_id}.{region_name}.aoss.amazonaws.com"
+ credentials = boto3.Session().get_credentials()
+ awsauth = AWSV4SignerAuth(credentials, region_name, "aoss")
+
+ # Build the OpenSearch client
+ oss_client = OpenSearch(
+ hosts=[{"host": host, "port": 443}],
+ http_auth=awsauth,
+ use_ssl=True,
+ verify_certs=True,
+ connection_class=RequestsHttpConnection,
+ timeout=300,
+ )
+ oss_client.indices.delete(index=index_name)
+
+
+@task(trigger_rule=TriggerRule.ALL_DONE)
+def delete_collection(collection_id: str):
+ """
+ Delete the OpenSearch collection created earlier.
+
+ :param collection_id: ID of the collection to be indexed.
+ """
+ log.info("Deleting collection %s.", collection_id)
+ aoss_client.delete_collection(id=collection_id)
+
+
+@task(trigger_rule=TriggerRule.ALL_DONE)
+def delete_opensearch_policies():
+ """Delete the security, network and data access policies created earlier."""
+
+ access_policies = aoss_client.list_access_policies(
+ type="data", resource=[f"collection/{vector_store_name}"]
+ )["accessPolicySummaries"]
+ log.info("Found access policies for %s: %s", vector_store_name, access_policies)
+ if not access_policies:
+ raise Exception("No access policies found?")
+ for policy in access_policies:
+ log.info("Deleting access policy for %s: %s", vector_store_name, policy["name"])
+ aoss_client.delete_access_policy(name=policy["name"], type="data")
+
+ for policy_type in ["encryption", "network"]:
+ policies = aoss_client.list_security_policies(
+ type=policy_type, resource=[f"collection/{vector_store_name}"]
+ )["securityPolicySummaries"]
+ if not policies:
+ raise Exception("No security policies found?")
+ log.info("Found %s security policies for %s: %s", policy_type, vector_store_name, policies)
+ for policy in policies:
+ log.info("Deleting %s security policy for %s: %s", policy_type, vector_store_name, policy["name"])
+ aoss_client.delete_security_policy(name=policy["name"], type=policy_type)
+
+
+with DAG(
+ dag_id=DAG_ID,
+ schedule="@once",
+ start_date=datetime(2021, 1, 1),
+ tags=["example"],
+ catchup=False,
+) as dag:
+ test_context = sys_test_context_task()
+ env_id = test_context["ENV_ID"]
+
+ aoss_client = OpenSearchServerlessHook().conn
+ bedrock_agent_client = BedrockAgentHook().conn
Review Comment:
This two lines responses for calls to the DB. If you would like to avoid it you need to move it inside of the tasks, where it required.
Or if you intends to use only default `botocore` strategy you might explicitly specify it by provide `aws_conn_id=None`
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Amazon Bedrock - Knowledge Bases and Data Sources [airflow]
Posted by "ferruzzi (via GitHub)" <gi...@apache.org>.
ferruzzi commented on code in PR #39245:
URL: https://github.com/apache/airflow/pull/39245#discussion_r1585748958
##########
airflow/providers/amazon/aws/sensors/bedrock.py:
##########
@@ -211,3 +262,149 @@ def execute(self, context: Context) -> Any:
)
else:
super().execute(context=context)
+
+
+class BedrockKnowledgeBaseActiveSensor(BedrockAgentBaseSensor):
+ """
+ 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."
+
+ 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",
Review Comment:
Yeah, I initially added it as an explicit parameter but it raised issues with the static checks for not matching the signature of super(). Adding `**kwargs` passed the tests and `event` will just get swallowed up in there. Since I'm not actually using it, I thought it was acceptable and in the end I decided it actually looked less confusing this way (as opposed to seeing 'event" there and wondering what you are supposed to give it if you aren't familiar with deferrables)
Are you alright with it how it is? Maybe there's another way around that? I can look if you care. If you are alright with it how it is, can you resolve this convo?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Amazon Bedrock - Knowledge Bases and Data Sources [airflow]
Posted by "ferruzzi (via GitHub)" <gi...@apache.org>.
ferruzzi commented on code in PR #39245:
URL: https://github.com/apache/airflow/pull/39245#discussion_r1585794448
##########
tests/system/providers/amazon/aws/example_bedrock_knowledge_base.py:
##########
@@ -0,0 +1,519 @@
+# Licensed to the Apache Software Foundation (ASF) under one
Review Comment:
done
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Amazon Bedrock - Knowledge Bases and Data Sources [airflow]
Posted by "Taragolis (via GitHub)" <gi...@apache.org>.
Taragolis commented on code in PR #39245:
URL: https://github.com/apache/airflow/pull/39245#discussion_r1585162253
##########
airflow/providers/amazon/aws/sensors/bedrock.py:
##########
@@ -68,7 +70,56 @@ 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
+ if self.soft_fail:
+ raise AirflowSkipException(self.FAILURE_MESSAGE)
+ raise AirflowException(self.FAILURE_MESSAGE)
+
+ return state not in self.INTERMEDIATE_STATES
+
+ @abc.abstractmethod
+ def get_state(self) -> str:
+ """Implement in subclasses."""
+
+
Review Comment:
If you would like to make generic from the generic you could do something like that
```python
_GenericBedrockHook = TypeVar("_GenericBedrockHook", BedrockAgentHook, BedrockHook)
class BedrockBaseSensor(AwsBaseSensor[_GenericBedrockHook]):
"""
General sensor behavior for Amazon Bedrock.
Subclasses must implement following methods:
- ``get_state()``
Subclasses must set the following fields:
- ``INTERMEDIATE_STATES``
- ``FAILURE_STATES``
- ``SUCCESS_STATES``
- ``FAILURE_MESSAGE``
:param deferrable: If True, the sensor will operate in deferrable mode. This mode requires aiobotocore
module to be installed.
(default: False, but can be overridden in config file by setting default_deferrable to True)
"""
INTERMEDIATE_STATES: tuple[str, ...]
FAILURE_STATES: tuple[str, ...]
SUCCESS_STATES: tuple[str, ...]
FAILURE_MESSAGE: str
ui_color = "#66c3ff"
aws_hook_class: type[_GenericBedrockHook]
...
class BedrockCustomizeModelCompletedSensor(BedrockBaseSensor[BedrockHook]):
aws_hook_class = BedrockHook
...
class BedrockKnowledgeBaseActiveSensor(BedrockBaseSensor[BedrockAgentHook]):
aws_hook_class = BedrockAgentHook
...
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Amazon Bedrock - Knowledge Bases and Data Sources [airflow]
Posted by "syedahsn (via GitHub)" <gi...@apache.org>.
syedahsn commented on code in PR #39245:
URL: https://github.com/apache/airflow/pull/39245#discussion_r1586500169
##########
airflow/providers/amazon/aws/sensors/bedrock.py:
##########
@@ -211,3 +262,149 @@ def execute(self, context: Context) -> Any:
)
else:
super().execute(context=context)
+
+
+class BedrockKnowledgeBaseActiveSensor(BedrockAgentBaseSensor):
+ """
+ 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."
+
+ 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",
Review Comment:
I don't see the option to resolve the conversation...
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Amazon Bedrock - Knowledge Bases and Data Sources [airflow]
Posted by "syedahsn (via GitHub)" <gi...@apache.org>.
syedahsn commented on code in PR #39245:
URL: https://github.com/apache/airflow/pull/39245#discussion_r1585346316
##########
airflow/providers/amazon/aws/sensors/bedrock.py:
##########
@@ -211,3 +262,149 @@ def execute(self, context: Context) -> Any:
)
else:
super().execute(context=context)
+
+
+class BedrockKnowledgeBaseActiveSensor(BedrockAgentBaseSensor):
+ """
+ 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."
+
+ 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",
Review Comment:
Why is the callback being set to `poke`? Shouldn't it be set to some method that evaluates whatever the Trigger returns (e.g. the `event` object)?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Amazon Bedrock - Knowledge Bases and Data Sources [airflow]
Posted by "ferruzzi (via GitHub)" <gi...@apache.org>.
ferruzzi commented on PR #39245:
URL: https://github.com/apache/airflow/pull/39245#issuecomment-2077711477
I'm really not sure what that failing static check is trying to tell me. Wouldn't mind a hand on that if someone knows what it means.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Amazon Bedrock - Knowledge Bases and Data Sources [airflow]
Posted by "vincbeck (via GitHub)" <gi...@apache.org>.
vincbeck commented on code in PR #39245:
URL: https://github.com/apache/airflow/pull/39245#discussion_r1579586655
##########
airflow/providers/amazon/aws/operators/bedrock.py:
##########
@@ -351,3 +353,288 @@ def execute_complete(self, context: Context, event: dict[str, Any] | None = None
self.log.info("Bedrock provisioned throughput job `%s` complete.", event["provisioned_model_id"])
return event["provisioned_model_id"]
+
+
+class BedrockCreateKnowledgeBaseOperator(AwsBaseOperator[BedrockAgentHook]):
+ """
+ Create a knowledge base that contains data sources used by Amazon Bedrock LLMs and Agents.
+
+ To create a knowledge base, you must first set up your data sources and configure a supported vector store.
+
+ .. seealso::
+ For more information on how to use this operator, take a look at the guide:
+ :ref:`howto/operator:BedrockCreateKnowledgeBaseOperator`
+
+ :param name: The name of the knowledge base. (templated)
+ :param embedding_model_arn: ARN of the model used to create vector embeddings for the knowledge base. (templated)
+ :param role_arn: The ARN of the IAM role with permissions to create the knowledge base. (templated)
+ :param storage_config: Configuration details of the vector database used for the knowledge base. (templated)
+ :param wait_for_indexing: Vector indexing can take some time and there is no apparent way to check the state
+ before trying to create the Knowledge Base. If this is True, and creation fails due to the index not
+ being available, the operator will wait and retry. (default: True) (templated)
+ :param indexing_error_retry_delay: Seconds between retries if an index error is encountered. (default 5) (templated)
+ :param indexing_error_max_attempts: Maximum number of times to retry when encountering an index error. (default 20) (templated)
+
+ :param wait_for_completion: Whether to wait for cluster to stop. (default: True)
+ :param waiter_delay: Time in seconds to wait between status checks. (default: 60)
+ :param waiter_max_attempts: Maximum number of attempts to check for job completion. (default: 20)
+ :param deferrable: If True, the operator will wait asynchronously for the cluster to stop.
+ This implies waiting for completion. This mode requires aiobotocore module to be installed.
+ (default: False)
+ :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
+ """
+
+ aws_hook_class = BedrockAgentHook
+ template_fields: Sequence[str] = aws_template_fields(
+ "name",
+ "embedding_model_arn",
+ "role_arn",
+ "storage_config",
+ "wait_for_indexing",
+ "indexing_error_retry_delay",
+ "indexing_error_max_attempts",
+ )
+
+ def __init__(
+ self,
+ name: str,
+ embedding_model_arn: str,
+ role_arn: str,
+ storage_config: dict[str, Any],
+ create_knowledge_base_kwargs: dict[str, Any] | None = None,
Review Comment:
Missing from docstring
##########
airflow/providers/amazon/aws/operators/bedrock.py:
##########
@@ -351,3 +353,288 @@ def execute_complete(self, context: Context, event: dict[str, Any] | None = None
self.log.info("Bedrock provisioned throughput job `%s` complete.", event["provisioned_model_id"])
return event["provisioned_model_id"]
+
+
+class BedrockCreateKnowledgeBaseOperator(AwsBaseOperator[BedrockAgentHook]):
+ """
+ Create a knowledge base that contains data sources used by Amazon Bedrock LLMs and Agents.
+
+ To create a knowledge base, you must first set up your data sources and configure a supported vector store.
+
+ .. seealso::
+ For more information on how to use this operator, take a look at the guide:
+ :ref:`howto/operator:BedrockCreateKnowledgeBaseOperator`
+
+ :param name: The name of the knowledge base. (templated)
+ :param embedding_model_arn: ARN of the model used to create vector embeddings for the knowledge base. (templated)
+ :param role_arn: The ARN of the IAM role with permissions to create the knowledge base. (templated)
+ :param storage_config: Configuration details of the vector database used for the knowledge base. (templated)
+ :param wait_for_indexing: Vector indexing can take some time and there is no apparent way to check the state
+ before trying to create the Knowledge Base. If this is True, and creation fails due to the index not
+ being available, the operator will wait and retry. (default: True) (templated)
+ :param indexing_error_retry_delay: Seconds between retries if an index error is encountered. (default 5) (templated)
+ :param indexing_error_max_attempts: Maximum number of times to retry when encountering an index error. (default 20) (templated)
+
+ :param wait_for_completion: Whether to wait for cluster to stop. (default: True)
+ :param waiter_delay: Time in seconds to wait between status checks. (default: 60)
+ :param waiter_max_attempts: Maximum number of attempts to check for job completion. (default: 20)
+ :param deferrable: If True, the operator will wait asynchronously for the cluster to stop.
+ This implies waiting for completion. This mode requires aiobotocore module to be installed.
+ (default: False)
+ :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
+ """
+
+ aws_hook_class = BedrockAgentHook
+ template_fields: Sequence[str] = aws_template_fields(
+ "name",
+ "embedding_model_arn",
+ "role_arn",
+ "storage_config",
+ "wait_for_indexing",
+ "indexing_error_retry_delay",
+ "indexing_error_max_attempts",
+ )
+
+ def __init__(
+ self,
+ name: str,
+ embedding_model_arn: str,
+ role_arn: str,
+ storage_config: dict[str, Any],
+ create_knowledge_base_kwargs: dict[str, Any] | None = None,
+ wait_for_indexing: bool = True,
+ indexing_error_retry_delay: int = 5, # seconds
+ indexing_error_max_attempts: int = 20,
+ wait_for_completion: bool = True,
+ waiter_delay: int = 60,
+ waiter_max_attempts: int = 20,
+ deferrable: bool = conf.getboolean("operators", "default_deferrable", fallback=False),
+ **kwargs,
+ ):
+ super().__init__(**kwargs)
+ self.name = name
+ self.role_arn = role_arn
+ self.storage_config = storage_config
+ self.create_knowledge_base_kwargs = create_knowledge_base_kwargs or {}
+ self.embedding_model_arn = embedding_model_arn
+ self.knowledge_base_config = {
+ "type": "VECTOR",
+ "vectorKnowledgeBaseConfiguration": {"embeddingModelArn": self.embedding_model_arn},
+ }
+ self.wait_for_indexing = wait_for_indexing
+ self.indexing_error_retry_delay = indexing_error_retry_delay
+ self.indexing_error_max_attempts = indexing_error_max_attempts
+
+ self.wait_for_completion = wait_for_completion
+ self.waiter_delay = waiter_delay
+ self.waiter_max_attempts = waiter_max_attempts
+ self.deferrable = deferrable
+
+ def execute_complete(self, context: Context, event: dict[str, Any] | None = None) -> str:
+ event = validate_execute_complete_event(event)
+
+ if event["status"] != "success":
+ raise AirflowException(f"Error while running job: {event}")
+
+ self.log.info("Bedrock knowledge base creation job `%s` complete.", self.name)
+ return self.hook.conn.get_knowledge_base(knowledgeBaseId=event["knowledge_base_id"])["knowledgeBase"][
+ "status"
+ ]
+
+ def execute(self, context: Context) -> str:
+ def _create_kb():
+ # This API call will return the following if the index has not completed, but there is no apparent
+ # way to check the state of the index beforehand, so retry on index failure if set to do so.
+ # botocore.errorfactory.ValidationException: An error occurred (ValidationException)
+ # when calling the CreateKnowledgeBase operation: The knowledge base storage configuration
+ # provided is invalid... no such index [bedrock-sample-rag-index-abc108]
+ try:
+ return self.hook.conn.create_knowledge_base(
+ name=self.name,
+ roleArn=self.role_arn,
+ knowledgeBaseConfiguration=self.knowledge_base_config,
+ storageConfiguration=self.storage_config,
+ **self.create_knowledge_base_kwargs,
+ )["knowledgeBase"]["knowledgeBaseId"]
+ except ClientError as error:
+ if all(
+ [
+ error.response["Error"]["Code"] == "ValidationException",
+ "no such index" in error.response["Error"]["Message"],
+ self.wait_for_indexing,
+ self.indexing_error_max_attempts > 0,
+ ]
+ ):
+ self.indexing_error_max_attempts -= 1
+ self.log.warning(
+ "Vector index not ready, retrying in %s seconds.", self.indexing_error_retry_delay
+ )
+ self.log.debug("%s retries remaining.", self.indexing_error_max_attempts)
+ sleep(self.indexing_error_retry_delay)
+ return _create_kb()
+ raise
+
+ self.log.info("Creating Amazon Bedrock Knowledge Base %s", self.name)
+ knowledge_base_id = _create_kb()
+
+ if self.deferrable:
+ self.log.info("Deferring for Knowledge base creation.")
+ self.defer(
+ trigger=BedrockKnowledgeBaseActiveTrigger(
+ knowledge_base_id=knowledge_base_id,
+ waiter_delay=self.waiter_delay,
+ waiter_max_attempts=self.waiter_max_attempts,
+ aws_conn_id=self.aws_conn_id,
+ ),
+ method_name="execute_complete",
+ )
+ if self.wait_for_completion:
+ self.log.info("Waiting for Knowledge Base creation.")
+ self.hook.get_waiter("knowledge_base_active").wait(
+ knowledgeBaseId=knowledge_base_id,
+ WaiterConfig={"Delay": self.waiter_delay, "MaxAttempts": self.waiter_max_attempts},
+ )
+
+ return knowledge_base_id
+
+
+class BedrockCreateDataSourceOperator(AwsBaseOperator[BedrockAgentHook]):
+ """
+ Set up an Amazon Bedrock Data Source to be added to an Amazon Bedrock Knowledge Base.
+
+ .. seealso::
+ For more information on how to use this operator, take a look at the guide:
+ :ref:`howto/operator:BedrockCreateDataSourceOperator`
+
+ :param name: name for the Amazon Bedrock Data Source being created. (templated).
+ :param bucket_name: The name of the Amazon S3 bucket to use for data source storage. (templated)
+ :param knowledge_base_id: The unique identifier of the knowledge base to which to add the data source. (templated)
+
+ :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
+ """
+
+ aws_hook_class = BedrockAgentHook
+
+ def __init__(
+ self,
+ name: str,
+ knowledge_base_id: str,
+ bucket_name: str | None = None,
+ create_data_source_kwargs: dict[str, Any] | None = None,
Review Comment:
Same
##########
airflow/providers/amazon/aws/sensors/opensearch_serverless.py:
##########
@@ -0,0 +1,110 @@
+# 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 typing import TYPE_CHECKING, Any, Sequence
+
+from airflow.exceptions import AirflowException, AirflowSkipException
+from airflow.providers.amazon.aws.hooks.opensearch_serverless import OpenSearchServerlessHook
+from airflow.providers.amazon.aws.sensors.base_aws import AwsBaseSensor
+from airflow.providers.amazon.aws.utils.mixins import aws_template_fields
+from airflow.utils.helpers import exactly_one
+
+if TYPE_CHECKING:
+ from airflow.utils.context import Context
+
+
+class OpenSearchServerlessCollectionActiveSensor(AwsBaseSensor[OpenSearchServerlessHook]):
+ """
+ Poll the state of the Collection until it reaches a terminal state; fails if the query fails.
+
+ .. seealso::
+ For more information on how to use this sensor, take a look at the guide:
+ :ref:`howto/sensor:OpenSearchServerlessCollectionAvailableSensor`
+
+ :param collection_id: A collection ID. You can't provide a name and an ID in the same request.
+ :param collection_name: A collection name. You can't provide a name and an ID in the same request.
+
+ :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)
Review Comment:
I could not find this parameter in this class neither in its parent classes. And you dont seem to use it in the implementation. Left over I guess.
##########
airflow/providers/amazon/aws/operators/bedrock.py:
##########
@@ -351,3 +353,288 @@ def execute_complete(self, context: Context, event: dict[str, Any] | None = None
self.log.info("Bedrock provisioned throughput job `%s` complete.", event["provisioned_model_id"])
return event["provisioned_model_id"]
+
+
+class BedrockCreateKnowledgeBaseOperator(AwsBaseOperator[BedrockAgentHook]):
+ """
+ Create a knowledge base that contains data sources used by Amazon Bedrock LLMs and Agents.
+
+ To create a knowledge base, you must first set up your data sources and configure a supported vector store.
+
+ .. seealso::
+ For more information on how to use this operator, take a look at the guide:
+ :ref:`howto/operator:BedrockCreateKnowledgeBaseOperator`
+
+ :param name: The name of the knowledge base. (templated)
+ :param embedding_model_arn: ARN of the model used to create vector embeddings for the knowledge base. (templated)
+ :param role_arn: The ARN of the IAM role with permissions to create the knowledge base. (templated)
+ :param storage_config: Configuration details of the vector database used for the knowledge base. (templated)
+ :param wait_for_indexing: Vector indexing can take some time and there is no apparent way to check the state
+ before trying to create the Knowledge Base. If this is True, and creation fails due to the index not
+ being available, the operator will wait and retry. (default: True) (templated)
+ :param indexing_error_retry_delay: Seconds between retries if an index error is encountered. (default 5) (templated)
+ :param indexing_error_max_attempts: Maximum number of times to retry when encountering an index error. (default 20) (templated)
+
+ :param wait_for_completion: Whether to wait for cluster to stop. (default: True)
+ :param waiter_delay: Time in seconds to wait between status checks. (default: 60)
+ :param waiter_max_attempts: Maximum number of attempts to check for job completion. (default: 20)
+ :param deferrable: If True, the operator will wait asynchronously for the cluster to stop.
+ This implies waiting for completion. This mode requires aiobotocore module to be installed.
+ (default: False)
+ :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
+ """
+
+ aws_hook_class = BedrockAgentHook
+ template_fields: Sequence[str] = aws_template_fields(
+ "name",
+ "embedding_model_arn",
+ "role_arn",
+ "storage_config",
+ "wait_for_indexing",
+ "indexing_error_retry_delay",
+ "indexing_error_max_attempts",
+ )
+
+ def __init__(
+ self,
+ name: str,
+ embedding_model_arn: str,
+ role_arn: str,
+ storage_config: dict[str, Any],
+ create_knowledge_base_kwargs: dict[str, Any] | None = None,
+ wait_for_indexing: bool = True,
+ indexing_error_retry_delay: int = 5, # seconds
+ indexing_error_max_attempts: int = 20,
+ wait_for_completion: bool = True,
+ waiter_delay: int = 60,
+ waiter_max_attempts: int = 20,
+ deferrable: bool = conf.getboolean("operators", "default_deferrable", fallback=False),
+ **kwargs,
+ ):
+ super().__init__(**kwargs)
+ self.name = name
+ self.role_arn = role_arn
+ self.storage_config = storage_config
+ self.create_knowledge_base_kwargs = create_knowledge_base_kwargs or {}
+ self.embedding_model_arn = embedding_model_arn
+ self.knowledge_base_config = {
+ "type": "VECTOR",
+ "vectorKnowledgeBaseConfiguration": {"embeddingModelArn": self.embedding_model_arn},
+ }
+ self.wait_for_indexing = wait_for_indexing
+ self.indexing_error_retry_delay = indexing_error_retry_delay
+ self.indexing_error_max_attempts = indexing_error_max_attempts
+
+ self.wait_for_completion = wait_for_completion
+ self.waiter_delay = waiter_delay
+ self.waiter_max_attempts = waiter_max_attempts
+ self.deferrable = deferrable
+
+ def execute_complete(self, context: Context, event: dict[str, Any] | None = None) -> str:
+ event = validate_execute_complete_event(event)
+
+ if event["status"] != "success":
+ raise AirflowException(f"Error while running job: {event}")
+
+ self.log.info("Bedrock knowledge base creation job `%s` complete.", self.name)
+ return self.hook.conn.get_knowledge_base(knowledgeBaseId=event["knowledge_base_id"])["knowledgeBase"][
+ "status"
+ ]
+
+ def execute(self, context: Context) -> str:
+ def _create_kb():
+ # This API call will return the following if the index has not completed, but there is no apparent
+ # way to check the state of the index beforehand, so retry on index failure if set to do so.
+ # botocore.errorfactory.ValidationException: An error occurred (ValidationException)
+ # when calling the CreateKnowledgeBase operation: The knowledge base storage configuration
+ # provided is invalid... no such index [bedrock-sample-rag-index-abc108]
+ try:
+ return self.hook.conn.create_knowledge_base(
+ name=self.name,
+ roleArn=self.role_arn,
+ knowledgeBaseConfiguration=self.knowledge_base_config,
+ storageConfiguration=self.storage_config,
+ **self.create_knowledge_base_kwargs,
+ )["knowledgeBase"]["knowledgeBaseId"]
+ except ClientError as error:
+ if all(
+ [
+ error.response["Error"]["Code"] == "ValidationException",
+ "no such index" in error.response["Error"]["Message"],
+ self.wait_for_indexing,
+ self.indexing_error_max_attempts > 0,
+ ]
+ ):
+ self.indexing_error_max_attempts -= 1
+ self.log.warning(
+ "Vector index not ready, retrying in %s seconds.", self.indexing_error_retry_delay
+ )
+ self.log.debug("%s retries remaining.", self.indexing_error_max_attempts)
+ sleep(self.indexing_error_retry_delay)
+ return _create_kb()
+ raise
+
+ self.log.info("Creating Amazon Bedrock Knowledge Base %s", self.name)
+ knowledge_base_id = _create_kb()
+
+ if self.deferrable:
+ self.log.info("Deferring for Knowledge base creation.")
+ self.defer(
+ trigger=BedrockKnowledgeBaseActiveTrigger(
+ knowledge_base_id=knowledge_base_id,
+ waiter_delay=self.waiter_delay,
+ waiter_max_attempts=self.waiter_max_attempts,
+ aws_conn_id=self.aws_conn_id,
+ ),
+ method_name="execute_complete",
+ )
+ if self.wait_for_completion:
+ self.log.info("Waiting for Knowledge Base creation.")
+ self.hook.get_waiter("knowledge_base_active").wait(
+ knowledgeBaseId=knowledge_base_id,
+ WaiterConfig={"Delay": self.waiter_delay, "MaxAttempts": self.waiter_max_attempts},
+ )
+
+ return knowledge_base_id
+
+
+class BedrockCreateDataSourceOperator(AwsBaseOperator[BedrockAgentHook]):
+ """
+ Set up an Amazon Bedrock Data Source to be added to an Amazon Bedrock Knowledge Base.
+
+ .. seealso::
+ For more information on how to use this operator, take a look at the guide:
+ :ref:`howto/operator:BedrockCreateDataSourceOperator`
+
+ :param name: name for the Amazon Bedrock Data Source being created. (templated).
+ :param bucket_name: The name of the Amazon S3 bucket to use for data source storage. (templated)
+ :param knowledge_base_id: The unique identifier of the knowledge base to which to add the data source. (templated)
+
+ :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
+ """
+
+ aws_hook_class = BedrockAgentHook
+
+ def __init__(
+ self,
+ name: str,
+ knowledge_base_id: str,
+ bucket_name: str | None = None,
+ create_data_source_kwargs: dict[str, Any] | None = None,
+ **kwargs,
+ ):
+ super().__init__(**kwargs)
+ self.name = name
+ self.knowledge_base_id = knowledge_base_id
+ self.bucket_name = bucket_name
+ self.create_data_source_kwargs = create_data_source_kwargs or {}
+
+ template_fields: Sequence[str] = aws_template_fields(
+ "name",
+ "bucket_name",
+ "knowledge_base_id",
+ )
+
+ def execute(self, context: Context) -> str:
+ create_ds_response = self.hook.conn.create_data_source(
+ name=self.name,
+ knowledgeBaseId=self.knowledge_base_id,
+ dataSourceConfiguration={
+ "type": "S3",
+ "s3Configuration": {"bucketArn": f"arn:aws:s3:::{self.bucket_name}"},
+ },
+ **self.create_data_source_kwargs,
+ )
+
+ return create_ds_response["dataSource"]["dataSourceId"]
+
+
+class BedrockIngestDataOperator(AwsBaseOperator[BedrockAgentHook]):
+ """
+ Begin an ingestion job, in which an Amazon Bedrock data source is added to an Amazon Bedrock knowledge base.
+
+ .. seealso::
+ For more information on how to use this operator, take a look at the guide:
+ :ref:`howto/operator:BedrockIngestDataOperator`
+
+ :param knowledge_base_id: The unique identifier of the knowledge base to which to add the data source. (templated)
+ :param data_source_id: The unique identifier of the data source to ingest. (templated)
+
+ :param wait_for_completion: Whether to wait for cluster to stop. (default: True)
+ :param waiter_delay: Time in seconds to wait between status checks. (default: 60)
+ :param waiter_max_attempts: Maximum number of attempts to check for job completion. (default: 10)
+ :param deferrable: If True, the operator will wait asynchronously for the cluster to stop.
+ This implies waiting for completion. This mode requires aiobotocore module to be installed.
+ (default: False)
+ :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
+ """
+
+ aws_hook_class = BedrockAgentHook
+
+ def __init__(
+ self,
+ knowledge_base_id: str,
+ data_source_id: str,
+ ingest_data_kwargs: dict[str, Any] | None = None,
Review Comment:
Ok I stop :)
##########
airflow/providers/amazon/aws/operators/bedrock.py:
##########
@@ -351,3 +353,288 @@ def execute_complete(self, context: Context, event: dict[str, Any] | None = None
self.log.info("Bedrock provisioned throughput job `%s` complete.", event["provisioned_model_id"])
return event["provisioned_model_id"]
+
+
+class BedrockCreateKnowledgeBaseOperator(AwsBaseOperator[BedrockAgentHook]):
+ """
+ Create a knowledge base that contains data sources used by Amazon Bedrock LLMs and Agents.
+
+ To create a knowledge base, you must first set up your data sources and configure a supported vector store.
+
+ .. seealso::
+ For more information on how to use this operator, take a look at the guide:
+ :ref:`howto/operator:BedrockCreateKnowledgeBaseOperator`
+
+ :param name: The name of the knowledge base. (templated)
+ :param embedding_model_arn: ARN of the model used to create vector embeddings for the knowledge base. (templated)
+ :param role_arn: The ARN of the IAM role with permissions to create the knowledge base. (templated)
+ :param storage_config: Configuration details of the vector database used for the knowledge base. (templated)
+ :param wait_for_indexing: Vector indexing can take some time and there is no apparent way to check the state
+ before trying to create the Knowledge Base. If this is True, and creation fails due to the index not
+ being available, the operator will wait and retry. (default: True) (templated)
+ :param indexing_error_retry_delay: Seconds between retries if an index error is encountered. (default 5) (templated)
+ :param indexing_error_max_attempts: Maximum number of times to retry when encountering an index error. (default 20) (templated)
+
+ :param wait_for_completion: Whether to wait for cluster to stop. (default: True)
+ :param waiter_delay: Time in seconds to wait between status checks. (default: 60)
+ :param waiter_max_attempts: Maximum number of attempts to check for job completion. (default: 20)
+ :param deferrable: If True, the operator will wait asynchronously for the cluster to stop.
+ This implies waiting for completion. This mode requires aiobotocore module to be installed.
+ (default: False)
+ :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
+ """
+
+ aws_hook_class = BedrockAgentHook
+ template_fields: Sequence[str] = aws_template_fields(
+ "name",
+ "embedding_model_arn",
+ "role_arn",
+ "storage_config",
+ "wait_for_indexing",
+ "indexing_error_retry_delay",
+ "indexing_error_max_attempts",
+ )
+
+ def __init__(
+ self,
+ name: str,
+ embedding_model_arn: str,
+ role_arn: str,
+ storage_config: dict[str, Any],
+ create_knowledge_base_kwargs: dict[str, Any] | None = None,
+ wait_for_indexing: bool = True,
+ indexing_error_retry_delay: int = 5, # seconds
+ indexing_error_max_attempts: int = 20,
+ wait_for_completion: bool = True,
+ waiter_delay: int = 60,
+ waiter_max_attempts: int = 20,
+ deferrable: bool = conf.getboolean("operators", "default_deferrable", fallback=False),
+ **kwargs,
+ ):
+ super().__init__(**kwargs)
+ self.name = name
+ self.role_arn = role_arn
+ self.storage_config = storage_config
+ self.create_knowledge_base_kwargs = create_knowledge_base_kwargs or {}
+ self.embedding_model_arn = embedding_model_arn
+ self.knowledge_base_config = {
+ "type": "VECTOR",
+ "vectorKnowledgeBaseConfiguration": {"embeddingModelArn": self.embedding_model_arn},
+ }
+ self.wait_for_indexing = wait_for_indexing
+ self.indexing_error_retry_delay = indexing_error_retry_delay
+ self.indexing_error_max_attempts = indexing_error_max_attempts
+
+ self.wait_for_completion = wait_for_completion
+ self.waiter_delay = waiter_delay
+ self.waiter_max_attempts = waiter_max_attempts
+ self.deferrable = deferrable
+
+ def execute_complete(self, context: Context, event: dict[str, Any] | None = None) -> str:
+ event = validate_execute_complete_event(event)
+
+ if event["status"] != "success":
+ raise AirflowException(f"Error while running job: {event}")
+
+ self.log.info("Bedrock knowledge base creation job `%s` complete.", self.name)
+ return self.hook.conn.get_knowledge_base(knowledgeBaseId=event["knowledge_base_id"])["knowledgeBase"][
+ "status"
+ ]
+
+ def execute(self, context: Context) -> str:
+ def _create_kb():
+ # This API call will return the following if the index has not completed, but there is no apparent
+ # way to check the state of the index beforehand, so retry on index failure if set to do so.
+ # botocore.errorfactory.ValidationException: An error occurred (ValidationException)
+ # when calling the CreateKnowledgeBase operation: The knowledge base storage configuration
+ # provided is invalid... no such index [bedrock-sample-rag-index-abc108]
+ try:
+ return self.hook.conn.create_knowledge_base(
+ name=self.name,
+ roleArn=self.role_arn,
+ knowledgeBaseConfiguration=self.knowledge_base_config,
+ storageConfiguration=self.storage_config,
+ **self.create_knowledge_base_kwargs,
+ )["knowledgeBase"]["knowledgeBaseId"]
+ except ClientError as error:
+ if all(
+ [
+ error.response["Error"]["Code"] == "ValidationException",
+ "no such index" in error.response["Error"]["Message"],
+ self.wait_for_indexing,
+ self.indexing_error_max_attempts > 0,
+ ]
+ ):
+ self.indexing_error_max_attempts -= 1
+ self.log.warning(
+ "Vector index not ready, retrying in %s seconds.", self.indexing_error_retry_delay
+ )
+ self.log.debug("%s retries remaining.", self.indexing_error_max_attempts)
+ sleep(self.indexing_error_retry_delay)
+ return _create_kb()
+ raise
+
+ self.log.info("Creating Amazon Bedrock Knowledge Base %s", self.name)
+ knowledge_base_id = _create_kb()
+
+ if self.deferrable:
+ self.log.info("Deferring for Knowledge base creation.")
+ self.defer(
+ trigger=BedrockKnowledgeBaseActiveTrigger(
+ knowledge_base_id=knowledge_base_id,
+ waiter_delay=self.waiter_delay,
+ waiter_max_attempts=self.waiter_max_attempts,
+ aws_conn_id=self.aws_conn_id,
+ ),
+ method_name="execute_complete",
+ )
+ if self.wait_for_completion:
+ self.log.info("Waiting for Knowledge Base creation.")
+ self.hook.get_waiter("knowledge_base_active").wait(
+ knowledgeBaseId=knowledge_base_id,
+ WaiterConfig={"Delay": self.waiter_delay, "MaxAttempts": self.waiter_max_attempts},
+ )
+
+ return knowledge_base_id
+
+
+class BedrockCreateDataSourceOperator(AwsBaseOperator[BedrockAgentHook]):
+ """
+ Set up an Amazon Bedrock Data Source to be added to an Amazon Bedrock Knowledge Base.
+
+ .. seealso::
+ For more information on how to use this operator, take a look at the guide:
+ :ref:`howto/operator:BedrockCreateDataSourceOperator`
+
+ :param name: name for the Amazon Bedrock Data Source being created. (templated).
+ :param bucket_name: The name of the Amazon S3 bucket to use for data source storage. (templated)
+ :param knowledge_base_id: The unique identifier of the knowledge base to which to add the data source. (templated)
+
+ :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
+ """
+
+ aws_hook_class = BedrockAgentHook
+
+ def __init__(
+ self,
+ name: str,
+ knowledge_base_id: str,
+ bucket_name: str | None = None,
+ create_data_source_kwargs: dict[str, Any] | None = None,
+ **kwargs,
+ ):
+ super().__init__(**kwargs)
+ self.name = name
+ self.knowledge_base_id = knowledge_base_id
+ self.bucket_name = bucket_name
+ self.create_data_source_kwargs = create_data_source_kwargs or {}
+
+ template_fields: Sequence[str] = aws_template_fields(
+ "name",
+ "bucket_name",
+ "knowledge_base_id",
+ )
+
+ def execute(self, context: Context) -> str:
+ create_ds_response = self.hook.conn.create_data_source(
+ name=self.name,
+ knowledgeBaseId=self.knowledge_base_id,
+ dataSourceConfiguration={
+ "type": "S3",
+ "s3Configuration": {"bucketArn": f"arn:aws:s3:::{self.bucket_name}"},
+ },
+ **self.create_data_source_kwargs,
+ )
+
+ return create_ds_response["dataSource"]["dataSourceId"]
+
+
+class BedrockIngestDataOperator(AwsBaseOperator[BedrockAgentHook]):
+ """
+ Begin an ingestion job, in which an Amazon Bedrock data source is added to an Amazon Bedrock knowledge base.
+
+ .. seealso::
+ For more information on how to use this operator, take a look at the guide:
+ :ref:`howto/operator:BedrockIngestDataOperator`
+
+ :param knowledge_base_id: The unique identifier of the knowledge base to which to add the data source. (templated)
+ :param data_source_id: The unique identifier of the data source to ingest. (templated)
+
+ :param wait_for_completion: Whether to wait for cluster to stop. (default: True)
+ :param waiter_delay: Time in seconds to wait between status checks. (default: 60)
+ :param waiter_max_attempts: Maximum number of attempts to check for job completion. (default: 10)
+ :param deferrable: If True, the operator will wait asynchronously for the cluster to stop.
+ This implies waiting for completion. This mode requires aiobotocore module to be installed.
+ (default: False)
+ :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
+ """
+
+ aws_hook_class = BedrockAgentHook
+
+ def __init__(
+ self,
+ knowledge_base_id: str,
+ data_source_id: str,
+ ingest_data_kwargs: dict[str, Any] | None = None,
+ wait_for_completion: bool = True,
+ waiter_delay: int = 60,
+ waiter_max_attempts: int = 10,
+ deferrable: bool = conf.getboolean("operators", "default_deferrable", fallback=False),
+ **kwargs,
+ ):
+ super().__init__(**kwargs)
+ self.knowledge_base_id = knowledge_base_id
+ self.data_source_id = data_source_id
+ self.ingest_data_kwargs = ingest_data_kwargs or {}
+
+ self.wait_for_completion = wait_for_completion
+ self.waiter_delay = waiter_delay
+ self.waiter_max_attempts = waiter_max_attempts
+ self.deferrable = deferrable
+
+ template_fields: Sequence[str] = aws_template_fields(
+ "knowledge_base_id",
+ "data_source_id",
+ )
+
+ def execute(self, context: Context) -> str:
+ ingestion_job_id = self.hook.conn.start_ingestion_job(
+ knowledgeBaseId=self.knowledge_base_id, dataSourceId=self.data_source_id
+ )["ingestionJob"]["ingestionJobId"]
+
+ if self.wait_for_completion:
Review Comment:
No deferrable option for this one?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Amazon Bedrock - Knowledge Bases and Data Sources [airflow]
Posted by "ferruzzi (via GitHub)" <gi...@apache.org>.
ferruzzi commented on PR #39245:
URL: https://github.com/apache/airflow/pull/39245#issuecomment-2080116389
Alright. @vincbeck I believe I have address the concerns you raised
I just ran the system test end to end three times:
```
default_args={deferrable=True, wait_for_completion=False}
```
```
default_args={deferrable=False, wait_for_completion=True}
```
```
default_args={deferrable=False, wait_for_completion=False}
```
and it passes all three ways.
While I was at it, I was pretty behind so I also rebased. Sorry for the force push.
I'll have to sort out that failing static check on Monday, it looks like maybe I have a boto call in top-level code somewhere in the system test, perhaps? Not sure.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Amazon Bedrock - Knowledge Bases and Data Sources [airflow]
Posted by "ferruzzi (via GitHub)" <gi...@apache.org>.
ferruzzi commented on code in PR #39245:
URL: https://github.com/apache/airflow/pull/39245#discussion_r1585546006
##########
airflow/providers/amazon/aws/sensors/bedrock.py:
##########
@@ -211,3 +262,149 @@ def execute(self, context: Context) -> Any:
)
else:
super().execute(context=context)
+
+
+class BedrockKnowledgeBaseActiveSensor(BedrockAgentBaseSensor):
+ """
+ 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."
+
+ 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",
Review Comment:
if I modify poke from
```
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
if self.soft_fail:
raise AirflowSkipException(self.FAILURE_MESSAGE)
raise AirflowException(self.FAILURE_MESSAGE)
return state not in self.INTERMEDIATE_STATES
```
to (untested)
```
def poke(self, context: Context, **kwargs) -> bool:
state = kwargs.gget("event").get("state") or self.get_state()
if state in self.FAILURE_STATES or state == "failure":
# TODO: remove this if block when min_airflow_version is set to higher than 2.7.1
if self.soft_fail:
raise AirflowSkipException(self.FAILURE_MESSAGE)
raise AirflowException(self.FAILURE_MESSAGE)
return state not in self.INTERMEDIATE_STATES
```
Then that would be the same thing without the extra get_state() call
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Amazon Bedrock - Knowledge Bases and Data Sources [airflow]
Posted by "ferruzzi (via GitHub)" <gi...@apache.org>.
ferruzzi commented on code in PR #39245:
URL: https://github.com/apache/airflow/pull/39245#discussion_r1585647311
##########
tests/system/providers/amazon/aws/example_bedrock_knowledge_base.py:
##########
@@ -0,0 +1,519 @@
+# Licensed to the Apache Software Foundation (ASF) under one
Review Comment:
Some of this needs adjusting, templated fields aren't working right with the way I wrote this. Fix is coming,
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Amazon Bedrock - Knowledge Bases and Data Sources [airflow]
Posted by "ferruzzi (via GitHub)" <gi...@apache.org>.
ferruzzi commented on code in PR #39245:
URL: https://github.com/apache/airflow/pull/39245#discussion_r1581497990
##########
airflow/providers/amazon/aws/sensors/opensearch_serverless.py:
##########
@@ -0,0 +1,110 @@
+# 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 typing import TYPE_CHECKING, Any, Sequence
+
+from airflow.exceptions import AirflowException, AirflowSkipException
+from airflow.providers.amazon.aws.hooks.opensearch_serverless import OpenSearchServerlessHook
+from airflow.providers.amazon.aws.sensors.base_aws import AwsBaseSensor
+from airflow.providers.amazon.aws.utils.mixins import aws_template_fields
+from airflow.utils.helpers import exactly_one
+
+if TYPE_CHECKING:
+ from airflow.utils.context import Context
+
+
+class OpenSearchServerlessCollectionActiveSensor(AwsBaseSensor[OpenSearchServerlessHook]):
+ """
+ Poll the state of the Collection until it reaches a terminal state; fails if the query fails.
+
+ .. seealso::
+ For more information on how to use this sensor, take a look at the guide:
+ :ref:`howto/sensor:OpenSearchServerlessCollectionAvailableSensor`
+
+ :param collection_id: A collection ID. You can't provide a name and an ID in the same request.
+ :param collection_name: A collection name. You can't provide a name and an ID in the same request.
+
+ :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)
Review Comment:
Implemented.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Amazon Bedrock - Knowledge Bases and Data Sources [airflow]
Posted by "ferruzzi (via GitHub)" <gi...@apache.org>.
ferruzzi commented on code in PR #39245:
URL: https://github.com/apache/airflow/pull/39245#discussion_r1581512161
##########
airflow/providers/amazon/aws/operators/bedrock.py:
##########
@@ -351,3 +353,288 @@ def execute_complete(self, context: Context, event: dict[str, Any] | None = None
self.log.info("Bedrock provisioned throughput job `%s` complete.", event["provisioned_model_id"])
return event["provisioned_model_id"]
+
+
+class BedrockCreateKnowledgeBaseOperator(AwsBaseOperator[BedrockAgentHook]):
+ """
+ Create a knowledge base that contains data sources used by Amazon Bedrock LLMs and Agents.
+
+ To create a knowledge base, you must first set up your data sources and configure a supported vector store.
+
+ .. seealso::
+ For more information on how to use this operator, take a look at the guide:
+ :ref:`howto/operator:BedrockCreateKnowledgeBaseOperator`
+
+ :param name: The name of the knowledge base. (templated)
+ :param embedding_model_arn: ARN of the model used to create vector embeddings for the knowledge base. (templated)
+ :param role_arn: The ARN of the IAM role with permissions to create the knowledge base. (templated)
+ :param storage_config: Configuration details of the vector database used for the knowledge base. (templated)
+ :param wait_for_indexing: Vector indexing can take some time and there is no apparent way to check the state
+ before trying to create the Knowledge Base. If this is True, and creation fails due to the index not
+ being available, the operator will wait and retry. (default: True) (templated)
+ :param indexing_error_retry_delay: Seconds between retries if an index error is encountered. (default 5) (templated)
+ :param indexing_error_max_attempts: Maximum number of times to retry when encountering an index error. (default 20) (templated)
+
+ :param wait_for_completion: Whether to wait for cluster to stop. (default: True)
+ :param waiter_delay: Time in seconds to wait between status checks. (default: 60)
+ :param waiter_max_attempts: Maximum number of attempts to check for job completion. (default: 20)
+ :param deferrable: If True, the operator will wait asynchronously for the cluster to stop.
+ This implies waiting for completion. This mode requires aiobotocore module to be installed.
+ (default: False)
+ :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
+ """
+
+ aws_hook_class = BedrockAgentHook
+ template_fields: Sequence[str] = aws_template_fields(
+ "name",
+ "embedding_model_arn",
+ "role_arn",
+ "storage_config",
+ "wait_for_indexing",
+ "indexing_error_retry_delay",
+ "indexing_error_max_attempts",
+ )
+
+ def __init__(
+ self,
+ name: str,
+ embedding_model_arn: str,
+ role_arn: str,
+ storage_config: dict[str, Any],
+ create_knowledge_base_kwargs: dict[str, Any] | None = None,
+ wait_for_indexing: bool = True,
+ indexing_error_retry_delay: int = 5, # seconds
+ indexing_error_max_attempts: int = 20,
+ wait_for_completion: bool = True,
+ waiter_delay: int = 60,
+ waiter_max_attempts: int = 20,
+ deferrable: bool = conf.getboolean("operators", "default_deferrable", fallback=False),
+ **kwargs,
+ ):
+ super().__init__(**kwargs)
+ self.name = name
+ self.role_arn = role_arn
+ self.storage_config = storage_config
+ self.create_knowledge_base_kwargs = create_knowledge_base_kwargs or {}
+ self.embedding_model_arn = embedding_model_arn
+ self.knowledge_base_config = {
+ "type": "VECTOR",
+ "vectorKnowledgeBaseConfiguration": {"embeddingModelArn": self.embedding_model_arn},
+ }
+ self.wait_for_indexing = wait_for_indexing
+ self.indexing_error_retry_delay = indexing_error_retry_delay
+ self.indexing_error_max_attempts = indexing_error_max_attempts
+
+ self.wait_for_completion = wait_for_completion
+ self.waiter_delay = waiter_delay
+ self.waiter_max_attempts = waiter_max_attempts
+ self.deferrable = deferrable
+
+ def execute_complete(self, context: Context, event: dict[str, Any] | None = None) -> str:
+ event = validate_execute_complete_event(event)
+
+ if event["status"] != "success":
+ raise AirflowException(f"Error while running job: {event}")
+
+ self.log.info("Bedrock knowledge base creation job `%s` complete.", self.name)
+ return self.hook.conn.get_knowledge_base(knowledgeBaseId=event["knowledge_base_id"])["knowledgeBase"][
+ "status"
+ ]
+
+ def execute(self, context: Context) -> str:
+ def _create_kb():
+ # This API call will return the following if the index has not completed, but there is no apparent
+ # way to check the state of the index beforehand, so retry on index failure if set to do so.
+ # botocore.errorfactory.ValidationException: An error occurred (ValidationException)
+ # when calling the CreateKnowledgeBase operation: The knowledge base storage configuration
+ # provided is invalid... no such index [bedrock-sample-rag-index-abc108]
+ try:
+ return self.hook.conn.create_knowledge_base(
+ name=self.name,
+ roleArn=self.role_arn,
+ knowledgeBaseConfiguration=self.knowledge_base_config,
+ storageConfiguration=self.storage_config,
+ **self.create_knowledge_base_kwargs,
+ )["knowledgeBase"]["knowledgeBaseId"]
+ except ClientError as error:
+ if all(
+ [
+ error.response["Error"]["Code"] == "ValidationException",
+ "no such index" in error.response["Error"]["Message"],
+ self.wait_for_indexing,
+ self.indexing_error_max_attempts > 0,
+ ]
+ ):
+ self.indexing_error_max_attempts -= 1
+ self.log.warning(
+ "Vector index not ready, retrying in %s seconds.", self.indexing_error_retry_delay
+ )
+ self.log.debug("%s retries remaining.", self.indexing_error_max_attempts)
+ sleep(self.indexing_error_retry_delay)
+ return _create_kb()
+ raise
+
+ self.log.info("Creating Amazon Bedrock Knowledge Base %s", self.name)
+ knowledge_base_id = _create_kb()
+
+ if self.deferrable:
+ self.log.info("Deferring for Knowledge base creation.")
+ self.defer(
+ trigger=BedrockKnowledgeBaseActiveTrigger(
+ knowledge_base_id=knowledge_base_id,
+ waiter_delay=self.waiter_delay,
+ waiter_max_attempts=self.waiter_max_attempts,
+ aws_conn_id=self.aws_conn_id,
+ ),
+ method_name="execute_complete",
+ )
+ if self.wait_for_completion:
+ self.log.info("Waiting for Knowledge Base creation.")
+ self.hook.get_waiter("knowledge_base_active").wait(
+ knowledgeBaseId=knowledge_base_id,
+ WaiterConfig={"Delay": self.waiter_delay, "MaxAttempts": self.waiter_max_attempts},
+ )
+
+ return knowledge_base_id
+
+
+class BedrockCreateDataSourceOperator(AwsBaseOperator[BedrockAgentHook]):
+ """
+ Set up an Amazon Bedrock Data Source to be added to an Amazon Bedrock Knowledge Base.
+
+ .. seealso::
+ For more information on how to use this operator, take a look at the guide:
+ :ref:`howto/operator:BedrockCreateDataSourceOperator`
+
+ :param name: name for the Amazon Bedrock Data Source being created. (templated).
+ :param bucket_name: The name of the Amazon S3 bucket to use for data source storage. (templated)
+ :param knowledge_base_id: The unique identifier of the knowledge base to which to add the data source. (templated)
+
+ :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
+ """
+
+ aws_hook_class = BedrockAgentHook
+
+ def __init__(
+ self,
+ name: str,
+ knowledge_base_id: str,
+ bucket_name: str | None = None,
+ create_data_source_kwargs: dict[str, Any] | None = None,
+ **kwargs,
+ ):
+ super().__init__(**kwargs)
+ self.name = name
+ self.knowledge_base_id = knowledge_base_id
+ self.bucket_name = bucket_name
+ self.create_data_source_kwargs = create_data_source_kwargs or {}
+
+ template_fields: Sequence[str] = aws_template_fields(
+ "name",
+ "bucket_name",
+ "knowledge_base_id",
+ )
+
+ def execute(self, context: Context) -> str:
+ create_ds_response = self.hook.conn.create_data_source(
+ name=self.name,
+ knowledgeBaseId=self.knowledge_base_id,
+ dataSourceConfiguration={
+ "type": "S3",
+ "s3Configuration": {"bucketArn": f"arn:aws:s3:::{self.bucket_name}"},
+ },
+ **self.create_data_source_kwargs,
+ )
+
+ return create_ds_response["dataSource"]["dataSourceId"]
+
+
+class BedrockIngestDataOperator(AwsBaseOperator[BedrockAgentHook]):
+ """
+ Begin an ingestion job, in which an Amazon Bedrock data source is added to an Amazon Bedrock knowledge base.
+
+ .. seealso::
+ For more information on how to use this operator, take a look at the guide:
+ :ref:`howto/operator:BedrockIngestDataOperator`
+
+ :param knowledge_base_id: The unique identifier of the knowledge base to which to add the data source. (templated)
+ :param data_source_id: The unique identifier of the data source to ingest. (templated)
+
+ :param wait_for_completion: Whether to wait for cluster to stop. (default: True)
+ :param waiter_delay: Time in seconds to wait between status checks. (default: 60)
+ :param waiter_max_attempts: Maximum number of attempts to check for job completion. (default: 10)
+ :param deferrable: If True, the operator will wait asynchronously for the cluster to stop.
+ This implies waiting for completion. This mode requires aiobotocore module to be installed.
+ (default: False)
+ :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
+ """
+
+ aws_hook_class = BedrockAgentHook
+
+ def __init__(
+ self,
+ knowledge_base_id: str,
+ data_source_id: str,
+ ingest_data_kwargs: dict[str, Any] | None = None,
+ wait_for_completion: bool = True,
+ waiter_delay: int = 60,
+ waiter_max_attempts: int = 10,
+ deferrable: bool = conf.getboolean("operators", "default_deferrable", fallback=False),
+ **kwargs,
+ ):
+ super().__init__(**kwargs)
+ self.knowledge_base_id = knowledge_base_id
+ self.data_source_id = data_source_id
+ self.ingest_data_kwargs = ingest_data_kwargs or {}
+
+ self.wait_for_completion = wait_for_completion
+ self.waiter_delay = waiter_delay
+ self.waiter_max_attempts = waiter_max_attempts
+ self.deferrable = deferrable
+
+ template_fields: Sequence[str] = aws_template_fields(
+ "knowledge_base_id",
+ "data_source_id",
+ )
+
+ def execute(self, context: Context) -> str:
+ ingestion_job_id = self.hook.conn.start_ingestion_job(
+ knowledgeBaseId=self.knowledge_base_id, dataSourceId=self.data_source_id
+ )["ingestionJob"]["ingestionJobId"]
+
+ if self.wait_for_completion:
Review Comment:
implemented
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Amazon Bedrock - Knowledge Bases and Data Sources [airflow]
Posted by "ferruzzi (via GitHub)" <gi...@apache.org>.
ferruzzi commented on PR #39245:
URL: https://github.com/apache/airflow/pull/39245#issuecomment-2083839357
Alright, got all the tests passing and rebased since it's been a few days. That was an adventure, sorry about that.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Amazon Bedrock - Knowledge Bases and Data Sources [airflow]
Posted by "ferruzzi (via GitHub)" <gi...@apache.org>.
ferruzzi commented on code in PR #39245:
URL: https://github.com/apache/airflow/pull/39245#discussion_r1585541983
##########
airflow/providers/amazon/aws/sensors/bedrock.py:
##########
@@ -211,3 +262,149 @@ def execute(self, context: Context) -> Any:
)
else:
super().execute(context=context)
+
+
+class BedrockKnowledgeBaseActiveSensor(BedrockAgentBaseSensor):
+ """
+ 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."
+
+ 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",
Review Comment:
I think this makes sense. I could write another method that will check the event state, but poke is already doing that. It results in one extra API call (the extra poke) but makes the code much nicer. If you look at the execute_complete methods int he other sensors, all they do is `print state and if state != "success" then raise an exception`, that's just a copy/paste subset of the existing poke method.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Amazon Bedrock - Knowledge Bases and Data Sources [airflow]
Posted by "syedahsn (via GitHub)" <gi...@apache.org>.
syedahsn commented on code in PR #39245:
URL: https://github.com/apache/airflow/pull/39245#discussion_r1585669891
##########
airflow/providers/amazon/aws/sensors/bedrock.py:
##########
@@ -211,3 +262,149 @@ def execute(self, context: Context) -> Any:
)
else:
super().execute(context=context)
+
+
+class BedrockKnowledgeBaseActiveSensor(BedrockAgentBaseSensor):
+ """
+ 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."
+
+ 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",
Review Comment:
That makes sense to me. I think the extra call is worth the clarity. One thing I noticed is that `poke` doesn't accept `event` as a parameter. I'm not sure how important it is the the functionality (I'm sure you've tested it), but the docs seem to strongly recommend it:
>When your operator resumes, Airflow adds a context object and an event object to the kwargs passed to the method_name method. This event object contains the payload from the trigger event that resumed your operator. Depending on the trigger, this can be useful to your operator, like it’s a status code or URL to fetch results. Or, it might be unimportant information, like a datetime. Your method_name method, however, _must_ accept context and event as a keyword argument.
I don't feel too strongly about it either way.
LGTM
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Amazon Bedrock - Knowledge Bases and Data Sources [airflow]
Posted by "vincbeck (via GitHub)" <gi...@apache.org>.
vincbeck commented on PR #39245:
URL: https://github.com/apache/airflow/pull/39245#issuecomment-2077399322
Not a big deal but you could have split this PR in 2; Bedrock and Opensearch. Especially because you do not mention opensearch in the PR title.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Amazon Bedrock - Knowledge Bases and Data Sources [airflow]
Posted by "ferruzzi (via GitHub)" <gi...@apache.org>.
ferruzzi commented on code in PR #39245:
URL: https://github.com/apache/airflow/pull/39245#discussion_r1580004957
##########
airflow/providers/amazon/aws/sensors/opensearch_serverless.py:
##########
@@ -0,0 +1,110 @@
+# 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 typing import TYPE_CHECKING, Any, Sequence
+
+from airflow.exceptions import AirflowException, AirflowSkipException
+from airflow.providers.amazon.aws.hooks.opensearch_serverless import OpenSearchServerlessHook
+from airflow.providers.amazon.aws.sensors.base_aws import AwsBaseSensor
+from airflow.providers.amazon.aws.utils.mixins import aws_template_fields
+from airflow.utils.helpers import exactly_one
+
+if TYPE_CHECKING:
+ from airflow.utils.context import Context
+
+
+class OpenSearchServerlessCollectionActiveSensor(AwsBaseSensor[OpenSearchServerlessHook]):
+ """
+ Poll the state of the Collection until it reaches a terminal state; fails if the query fails.
+
+ .. seealso::
+ For more information on how to use this sensor, take a look at the guide:
+ :ref:`howto/sensor:OpenSearchServerlessCollectionAvailableSensor`
+
+ :param collection_id: A collection ID. You can't provide a name and an ID in the same request.
+ :param collection_name: A collection name. You can't provide a name and an ID in the same request.
+
+ :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: 20)
+ :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 = ("CREATING",)
+ FAILURE_STATES = (
+ "DELETING",
+ "FAILED",
+ )
+ SUCCESS_STATES = ("ACTIVE",)
+ FAILURE_MESSAGE = "OpenSearch Serverless Collection sensor failed"
+ INVALID_ARGS_MESSAGE = "Either collection_ids or collection_names must be provided, not both."
+
+ aws_hook_class = OpenSearchServerlessHook
+ template_fields: Sequence[str] = aws_template_fields(
+ "collection_id",
+ "collection_name",
+ )
+ ui_color = "#66c3ff"
+
+ def __init__(
+ self,
+ *,
+ collection_id: str | None = None,
+ collection_name: str | None = None,
+ poke_interval: int = 10,
+ max_retries: int = 120,
Review Comment:
This default doesn't match the docstring; fix incoming.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Amazon Bedrock - Knowledge Bases and Data Sources [airflow]
Posted by "ferruzzi (via GitHub)" <gi...@apache.org>.
ferruzzi commented on code in PR #39245:
URL: https://github.com/apache/airflow/pull/39245#discussion_r1585236367
##########
tests/system/providers/amazon/aws/example_bedrock_knowledge_base.py:
##########
@@ -0,0 +1,519 @@
+# 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
+
+import json
+import logging
+import os.path
+import tempfile
+from datetime import datetime
+from time import sleep
+from urllib.request import urlretrieve
+
+import boto3
+from botocore.exceptions import ClientError
+from opensearchpy import (
+ AuthorizationException,
+ AWSV4SignerAuth,
+ OpenSearch,
+ RequestsHttpConnection,
+)
+
+from airflow import DAG
+from airflow.decorators import task
+from airflow.providers.amazon.aws.hooks.bedrock import BedrockAgentHook
+from airflow.providers.amazon.aws.hooks.opensearch_serverless import OpenSearchServerlessHook
+from airflow.providers.amazon.aws.hooks.s3 import S3Hook
+from airflow.providers.amazon.aws.hooks.sts import StsHook
+from airflow.providers.amazon.aws.operators.bedrock import (
+ BedrockCreateDataSourceOperator,
+ BedrockCreateKnowledgeBaseOperator,
+ BedrockIngestDataOperator,
+)
+from airflow.providers.amazon.aws.operators.s3 import S3CreateBucketOperator, S3DeleteBucketOperator
+from airflow.providers.amazon.aws.sensors.bedrock import (
+ BedrockIngestionJobSensor,
+ BedrockKnowledgeBaseActiveSensor,
+)
+from airflow.providers.amazon.aws.sensors.opensearch_serverless import (
+ OpenSearchServerlessCollectionActiveSensor,
+)
+from airflow.utils.helpers import chain
+from airflow.utils.trigger_rule import TriggerRule
+from tests.system.providers.amazon.aws.utils import SystemTestContextBuilder
+
+###############################################################################
+# NOTE: The account running this test must first manually request access to
+# the `Titan Embeddings G1 - Text` foundation model via the Bedrock console.
+# Gaining access to the model can take 24 hours from the time of request.
+###############################################################################
+
+# Externally fetched variables:
+ROLE_ARN_KEY = "ROLE_ARN"
+sys_test_context_task = SystemTestContextBuilder().add_variable(ROLE_ARN_KEY).build()
+
+DAG_ID = "example_bedrock_knowledge_base"
+
+log = logging.getLogger(__name__)
+
+
+@task
+def create_opensearch_policies(bedrock_role_arn: str, collection_name: str):
+ """
+ Create security, network and data access policies within Amazon OpenSearch Serverless.
+
+ :param bedrock_role_arn: Arn of the Bedrock Knowledge Base Execution Role.
+ :param collection_name: Name of the OpenSearch collection to apply the policies to.
+ """
+
+ encryption_policy_name = f"{naming_prefix}rag-sp-{env_id}"
+ network_policy_name = f"{naming_prefix}rag-np-{env_id}"
+ access_policy_name = f"{naming_prefix}rag-ap-{env_id}"
+
+ def _create_security_policy(name, policy_type, policy):
+ try:
+ aoss_client.create_security_policy(name=name, policy=json.dumps(policy), type=policy_type)
+ except ClientError as e:
+ if e.response["Error"]["Code"] == "ConflictException":
+ log.info("OpenSearch security policy %s already exists.", name)
+ raise
+
+ def _create_access_policy(name, policy_type, policy):
+ try:
+ aoss_client.create_access_policy(name=name, policy=json.dumps(policy), type=policy_type)
+ except ClientError as e:
+ if e.response["Error"]["Code"] == "ConflictException":
+ log.info("OpenSearch data access policy %s already exists.", name)
+ raise
+
+ _create_security_policy(
+ name=encryption_policy_name,
+ policy_type="encryption",
+ policy={
+ "Rules": [{"Resource": [f"collection/{collection_name}"], "ResourceType": "collection"}],
+ "AWSOwnedKey": True,
+ },
+ )
+
+ _create_security_policy(
+ name=network_policy_name,
+ policy_type="network",
+ policy=[
+ {
+ "Rules": [{"Resource": [f"collection/{collection_name}"], "ResourceType": "collection"}],
+ "AllowFromPublic": True,
+ }
+ ],
+ )
+
+ _create_access_policy(
+ name=access_policy_name,
+ policy_type="data",
+ policy=[
+ {
+ "Rules": [
+ {
+ "Resource": [f"collection/{collection_name}"],
+ "Permission": [
+ "aoss:CreateCollectionItems",
+ "aoss:DeleteCollectionItems",
+ "aoss:UpdateCollectionItems",
+ "aoss:DescribeCollectionItems",
+ ],
+ "ResourceType": "collection",
+ },
+ {
+ "Resource": [f"index/{collection_name}/*"],
+ "Permission": [
+ "aoss:CreateIndex",
+ "aoss:DeleteIndex",
+ "aoss:UpdateIndex",
+ "aoss:DescribeIndex",
+ "aoss:ReadDocument",
+ "aoss:WriteDocument",
+ ],
+ "ResourceType": "index",
+ },
+ ],
+ "Principal": [(StsHook().conn.get_caller_identity()["Arn"]), bedrock_role_arn],
+ }
+ ],
+ )
+
+
+@task
+def create_collection(collection_name: str):
+ """
+ Call the Amazon OpenSearch Serverless API and create a collection with the provided name.
+
+ :param collection_name: The name of the Collection to create.
+ """
+ log.info("\nCreating collection: %s.", collection_name)
+ return aoss_client.create_collection(name=collection_name, type="VECTORSEARCH")["createCollectionDetail"][
+ "id"
+ ]
+
+
+@task
+def create_vector_index(collection_id: str, region: str):
+ """
+ Use the OpenSearchPy client to create the vector index for the Amazon Open Search Serverless Collection.
+
+ :param collection_id: ID of the collection to be indexed.
+ :param region: Name of the AWS region the collection resides in.
+ """
+ # Build the OpenSearch client
+ oss_client = OpenSearch(
+ hosts=[{"host": f"{collection_id}.{region}.aoss.amazonaws.com", "port": 443}],
+ http_auth=AWSV4SignerAuth(boto3.Session().get_credentials(), region, "aoss"),
+ use_ssl=True,
+ verify_certs=True,
+ connection_class=RequestsHttpConnection,
+ timeout=300,
+ )
+ index_config = {
+ "settings": {
+ "index.knn": "true",
+ "number_of_shards": 1,
+ "knn.algo_param.ef_search": 512,
+ "number_of_replicas": 0,
+ },
+ "mappings": {
+ "properties": {
+ "vector": {
+ "type": "knn_vector",
+ "dimension": 1536,
+ "method": {"name": "hnsw", "engine": "faiss", "space_type": "l2"},
+ },
+ "text": {"type": "text"},
+ "text-metadata": {"type": "text"},
+ }
+ },
+ }
+
+ retries = 35
+ while retries > 0:
+ try:
+ response = oss_client.indices.create(index=index_name, body=json.dumps(index_config))
+ log.info("Creating index: %s.", response)
+ break
+ except AuthorizationException as e:
+ # Index creation can take up to a minute and there is no (apparent?) way to check the current state.
+ log.info(
+ "Access denied; policy permissions have likely not yet propagated, %s tries remaining.",
+ retries,
+ )
+ log.debug(e)
+ retries -= 1
+ sleep(2)
+
+
+@task
+def copy_data_to_s3(bucket: str):
+ """
+ Download some sample data and upload it to 3S.
+
+ :param bucket: Name of the Amazon S3 bucket to send the data to.
+ """
+
+ # Monkey patch the list of names available for NamedTempFile so we can pick the names of the downloaded files.
+ backup_get_candidate_names = tempfile._get_candidate_names # type: ignore[attr-defined]
+ destinations = iter(
+ [
+ "AMZN-2022-Shareholder-Letter.pdf",
+ "AMZN-2021-Shareholder-Letter.pdf",
+ "AMZN-2020-Shareholder-Letter.pdf",
+ "AMZN-2019-Shareholder-Letter.pdf",
+ ]
+ )
+ tempfile._get_candidate_names = lambda: destinations # type: ignore[attr-defined]
+
+ # Download the sample data files, save them as named temp files using the names above, and upload to S3.
+ sources = [
+ "https://s2.q4cdn.com/299287126/files/doc_financials/2023/ar/2022-Shareholder-Letter.pdf",
+ "https://s2.q4cdn.com/299287126/files/doc_financials/2022/ar/2021-Shareholder-Letter.pdf",
+ "https://s2.q4cdn.com/299287126/files/doc_financials/2021/ar/Amazon-2020-Shareholder-Letter-and-1997-Shareholder-Letter.pdf",
+ "https://s2.q4cdn.com/299287126/files/doc_financials/2020/ar/2019-Shareholder-Letter.pdf",
+ ]
+
+ for source in sources:
+ with tempfile.NamedTemporaryFile(mode="w", prefix="") as data_file:
+ urlretrieve(source, data_file.name)
+ S3Hook().conn.upload_file(
+ Filename=data_file.name, Bucket=bucket, Key=os.path.basename(data_file.name)
+ )
+
+ # Revert the monkey patch.
+ tempfile._get_candidate_names = backup_get_candidate_names # type: ignore[attr-defined]
+ # Verify the path reversion worked.
+ with tempfile.NamedTemporaryFile(mode="w", prefix=""):
+ # If the reversion above did not apply correctly, this will fail with
+ # a StopIteration error because the iterator will run out of names.
+ ...
+
+
+@task
+def get_collection_arn(collection_id: str):
+ """
+ Return a collection ARN for a given collection ID.
+
+ :param collection_id: ID of the collection to be indexed.
+ """
+ return next(
+ colxn["arn"]
+ for colxn in aoss_client.list_collections()["collectionSummaries"]
+ if colxn["id"] == collection_id
+ )
+
+
+# [START howto_operator_bedrock_delete_data_source]
+@task(trigger_rule=TriggerRule.ALL_DONE)
+def delete_data_source(knowledge_base_id: str, data_source_id: str):
+ """
+ Delete the Amazon Bedrock data source created earlier.
+
+ .. seealso::
+ For more information on how to use this sensor, take a look at the guide:
+ :ref:`howto_operator:BedrockDeleteDataSource`
+
+ :param knowledge_base_id: The unique identifier of the knowledge base which the data source is attached to.
+ :param data_source_id: The unique identifier of the data source to delete.
+ """
+ log.info("Deleting data source %s from Knowledge Base %s.", data_source_id, knowledge_base_id)
+ bedrock_agent_client.delete_data_source(dataSourceId=data_source_id, knowledgeBaseId=knowledge_base_id)
+
+
+# [END howto_operator_bedrock_delete_data_source]
+
+
+# [START howto_operator_bedrock_delete_knowledge_base]
+@task(trigger_rule=TriggerRule.ALL_DONE)
+def delete_knowledge_base(knowledge_base_id: str):
+ """
+ Delete the Amazon Bedrock knowledge base created earlier.
+
+ .. seealso::
+ For more information on how to use this sensor, take a look at the guide:
+ :ref:`howto/operator:BedrockDeleteKnowledgeBase`
+
+ :param knowledge_base_id: The unique identifier of the knowledge base to delete.
+ """
+ log.info("Deleting Knowledge Base %s.", knowledge_base_id)
+ bedrock_agent_client.delete_knowledge_base(knowledgeBaseId=knowledge_base_id)
+
+
+# [END howto_operator_bedrock_delete_knowledge_base]
+
+
+@task(trigger_rule=TriggerRule.ALL_DONE)
+def delete_vector_index(collection_id: str):
+ """
+ Delete the vector index created earlier.
+
+ :param collection_id: ID of the collection to be indexed.
+ """
+ host = f"{collection_id}.{region_name}.aoss.amazonaws.com"
+ credentials = boto3.Session().get_credentials()
+ awsauth = AWSV4SignerAuth(credentials, region_name, "aoss")
+
+ # Build the OpenSearch client
+ oss_client = OpenSearch(
+ hosts=[{"host": host, "port": 443}],
+ http_auth=awsauth,
+ use_ssl=True,
+ verify_certs=True,
+ connection_class=RequestsHttpConnection,
+ timeout=300,
+ )
+ oss_client.indices.delete(index=index_name)
+
+
+@task(trigger_rule=TriggerRule.ALL_DONE)
+def delete_collection(collection_id: str):
+ """
+ Delete the OpenSearch collection created earlier.
+
+ :param collection_id: ID of the collection to be indexed.
+ """
+ log.info("Deleting collection %s.", collection_id)
+ aoss_client.delete_collection(id=collection_id)
+
+
+@task(trigger_rule=TriggerRule.ALL_DONE)
+def delete_opensearch_policies():
+ """Delete the security, network and data access policies created earlier."""
+
+ access_policies = aoss_client.list_access_policies(
+ type="data", resource=[f"collection/{vector_store_name}"]
+ )["accessPolicySummaries"]
+ log.info("Found access policies for %s: %s", vector_store_name, access_policies)
+ if not access_policies:
+ raise Exception("No access policies found?")
+ for policy in access_policies:
+ log.info("Deleting access policy for %s: %s", vector_store_name, policy["name"])
+ aoss_client.delete_access_policy(name=policy["name"], type="data")
+
+ for policy_type in ["encryption", "network"]:
+ policies = aoss_client.list_security_policies(
+ type=policy_type, resource=[f"collection/{vector_store_name}"]
+ )["securityPolicySummaries"]
+ if not policies:
+ raise Exception("No security policies found?")
+ log.info("Found %s security policies for %s: %s", policy_type, vector_store_name, policies)
+ for policy in policies:
+ log.info("Deleting %s security policy for %s: %s", policy_type, vector_store_name, policy["name"])
+ aoss_client.delete_security_policy(name=policy["name"], type=policy_type)
+
+
+with DAG(
+ dag_id=DAG_ID,
+ schedule="@once",
+ start_date=datetime(2021, 1, 1),
+ tags=["example"],
+ catchup=False,
+) as dag:
+ test_context = sys_test_context_task()
+ env_id = test_context["ENV_ID"]
+
+ aoss_client = OpenSearchServerlessHook().conn
+ bedrock_agent_client = BedrockAgentHook().conn
Review Comment:
Looks like that did it. Cheers.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Amazon Bedrock - Knowledge Bases and Data Sources [airflow]
Posted by "ferruzzi (via GitHub)" <gi...@apache.org>.
ferruzzi commented on code in PR #39245:
URL: https://github.com/apache/airflow/pull/39245#discussion_r1585350222
##########
airflow/providers/amazon/aws/sensors/bedrock.py:
##########
@@ -68,7 +70,56 @@ 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
+ if self.soft_fail:
+ raise AirflowSkipException(self.FAILURE_MESSAGE)
+ raise AirflowException(self.FAILURE_MESSAGE)
+
+ return state not in self.INTERMEDIATE_STATES
+
+ @abc.abstractmethod
+ def get_state(self) -> str:
+ """Implement in subclasses."""
+
+
Review Comment:
AH! I see, thanks. I think I like the idea, but maybe I'll do that in a separate PR. What do you think? Does it feel worth doing? Does it have to be now or can we let it stand how it is for now?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Amazon Bedrock - Knowledge Bases and Data Sources [airflow]
Posted by "ferruzzi (via GitHub)" <gi...@apache.org>.
ferruzzi commented on code in PR #39245:
URL: https://github.com/apache/airflow/pull/39245#discussion_r1581460944
##########
airflow/providers/amazon/aws/sensors/bedrock.py:
##########
@@ -68,7 +70,56 @@ 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
+ if self.soft_fail:
+ raise AirflowSkipException(self.FAILURE_MESSAGE)
+ raise AirflowException(self.FAILURE_MESSAGE)
+
+ return state not in self.INTERMEDIATE_STATES
+
+ @abc.abstractmethod
+ def get_state(self) -> str:
+ """Implement in subclasses."""
+
+
Review Comment:
@Taragolis - These two base sensors are identical other than the aws_hook_class (BedrockHook vs BedrockAgentHook) and the hook name in the parent class. I'm not really familiar with how you did the `AwsBaseSensor[BedrockAgentHook]` thing, is it possible to combine these into one BaseBedrockSensor? What would that look like?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Amazon Bedrock - Knowledge Bases and Data Sources [airflow]
Posted by "Taragolis (via GitHub)" <gi...@apache.org>.
Taragolis commented on code in PR #39245:
URL: https://github.com/apache/airflow/pull/39245#discussion_r1585542063
##########
airflow/providers/amazon/aws/sensors/bedrock.py:
##########
@@ -68,7 +70,56 @@ 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
+ if self.soft_fail:
+ raise AirflowSkipException(self.FAILURE_MESSAGE)
+ raise AirflowException(self.FAILURE_MESSAGE)
+
+ return state not in self.INTERMEDIATE_STATES
+
+ @abc.abstractmethod
+ def get_state(self) -> str:
+ """Implement in subclasses."""
+
+
Review Comment:
I do not have personal preferences, so it could be done by the separate PR or even keep as it is.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Amazon Bedrock - Knowledge Bases and Data Sources [airflow]
Posted by "ferruzzi (via GitHub)" <gi...@apache.org>.
ferruzzi commented on code in PR #39245:
URL: https://github.com/apache/airflow/pull/39245#discussion_r1585748958
##########
airflow/providers/amazon/aws/sensors/bedrock.py:
##########
@@ -211,3 +262,149 @@ def execute(self, context: Context) -> Any:
)
else:
super().execute(context=context)
+
+
+class BedrockKnowledgeBaseActiveSensor(BedrockAgentBaseSensor):
+ """
+ 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."
+
+ 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",
Review Comment:
Yeah, I initially added it as an explicit parameter but it raised issues with the static checks for not matching the signature of super(). Adding `**kwargs` passed the tests and `event` will just get swallowed up in there. Since I'm not actually using it, I thought it was acceptable and in the end I decided it actually looked less confusing this way (as opposed to seeing 'event" there and wondering what you are supposed to give it if you aren't familiar with deferrables)
Are you alright with it how it is? Maybe there's another way around that? I can look if you care.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Amazon Bedrock - Knowledge Bases and Data Sources [airflow]
Posted by "ferruzzi (via GitHub)" <gi...@apache.org>.
ferruzzi commented on PR #39245:
URL: https://github.com/apache/airflow/pull/39245#issuecomment-2087900203
Assuming the CI goes green, I'm done.
@vincbeck - you may want to have a peek at the changes since you approved, or not.
@Taragolis - I ended up doing the generic base sensor your way and it worked perfectly. Thanks!
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Amazon Bedrock - Knowledge Bases and Data Sources [airflow]
Posted by "syedahsn (via GitHub)" <gi...@apache.org>.
syedahsn commented on code in PR #39245:
URL: https://github.com/apache/airflow/pull/39245#discussion_r1586497806
##########
airflow/providers/amazon/aws/sensors/bedrock.py:
##########
@@ -211,3 +262,149 @@ def execute(self, context: Context) -> Any:
)
else:
super().execute(context=context)
+
+
+class BedrockKnowledgeBaseActiveSensor(BedrockAgentBaseSensor):
+ """
+ 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."
+
+ 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",
Review Comment:
I'm good with it as is. Just wanted to make sure it was a conscious decision as opposed to an oversight.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Amazon Bedrock - Knowledge Bases and Data Sources [airflow]
Posted by "ferruzzi (via GitHub)" <gi...@apache.org>.
ferruzzi commented on PR #39245:
URL: https://github.com/apache/airflow/pull/39245#issuecomment-2084181237
how could the change in [6d5cdd2](https://github.com/apache/airflow/pull/39245/commits/6d5cdd27fecea43655826eb3212d022befc6c581) have broken three test which were all passing before that commit? It's copy and pasted dag declaration from the rest of our system tests.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] Amazon Bedrock - Knowledge Bases and Data Sources [airflow]
Posted by "Taragolis (via GitHub)" <gi...@apache.org>.
Taragolis commented on code in PR #39245:
URL: https://github.com/apache/airflow/pull/39245#discussion_r1585263688
##########
tests/system/providers/amazon/aws/example_bedrock_knowledge_base.py:
##########
@@ -0,0 +1,519 @@
+# 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
+
+import json
+import logging
+import os.path
+import tempfile
+from datetime import datetime
+from time import sleep
+from urllib.request import urlretrieve
+
+import boto3
+from botocore.exceptions import ClientError
+from opensearchpy import (
+ AuthorizationException,
+ AWSV4SignerAuth,
+ OpenSearch,
+ RequestsHttpConnection,
+)
+
+from airflow import DAG
+from airflow.decorators import task
+from airflow.providers.amazon.aws.hooks.bedrock import BedrockAgentHook
+from airflow.providers.amazon.aws.hooks.opensearch_serverless import OpenSearchServerlessHook
+from airflow.providers.amazon.aws.hooks.s3 import S3Hook
+from airflow.providers.amazon.aws.hooks.sts import StsHook
+from airflow.providers.amazon.aws.operators.bedrock import (
+ BedrockCreateDataSourceOperator,
+ BedrockCreateKnowledgeBaseOperator,
+ BedrockIngestDataOperator,
+)
+from airflow.providers.amazon.aws.operators.s3 import S3CreateBucketOperator, S3DeleteBucketOperator
+from airflow.providers.amazon.aws.sensors.bedrock import (
+ BedrockIngestionJobSensor,
+ BedrockKnowledgeBaseActiveSensor,
+)
+from airflow.providers.amazon.aws.sensors.opensearch_serverless import (
+ OpenSearchServerlessCollectionActiveSensor,
+)
+from airflow.utils.helpers import chain
+from airflow.utils.trigger_rule import TriggerRule
+from tests.system.providers.amazon.aws.utils import SystemTestContextBuilder
+
+###############################################################################
+# NOTE: The account running this test must first manually request access to
+# the `Titan Embeddings G1 - Text` foundation model via the Bedrock console.
+# Gaining access to the model can take 24 hours from the time of request.
+###############################################################################
+
+# Externally fetched variables:
+ROLE_ARN_KEY = "ROLE_ARN"
+sys_test_context_task = SystemTestContextBuilder().add_variable(ROLE_ARN_KEY).build()
+
+DAG_ID = "example_bedrock_knowledge_base"
+
+log = logging.getLogger(__name__)
+
+
+@task
+def create_opensearch_policies(bedrock_role_arn: str, collection_name: str):
+ """
+ Create security, network and data access policies within Amazon OpenSearch Serverless.
+
+ :param bedrock_role_arn: Arn of the Bedrock Knowledge Base Execution Role.
+ :param collection_name: Name of the OpenSearch collection to apply the policies to.
+ """
+
+ encryption_policy_name = f"{naming_prefix}rag-sp-{env_id}"
+ network_policy_name = f"{naming_prefix}rag-np-{env_id}"
+ access_policy_name = f"{naming_prefix}rag-ap-{env_id}"
+
+ def _create_security_policy(name, policy_type, policy):
+ try:
+ aoss_client.create_security_policy(name=name, policy=json.dumps(policy), type=policy_type)
+ except ClientError as e:
+ if e.response["Error"]["Code"] == "ConflictException":
+ log.info("OpenSearch security policy %s already exists.", name)
+ raise
+
+ def _create_access_policy(name, policy_type, policy):
+ try:
+ aoss_client.create_access_policy(name=name, policy=json.dumps(policy), type=policy_type)
+ except ClientError as e:
+ if e.response["Error"]["Code"] == "ConflictException":
+ log.info("OpenSearch data access policy %s already exists.", name)
+ raise
+
+ _create_security_policy(
+ name=encryption_policy_name,
+ policy_type="encryption",
+ policy={
+ "Rules": [{"Resource": [f"collection/{collection_name}"], "ResourceType": "collection"}],
+ "AWSOwnedKey": True,
+ },
+ )
+
+ _create_security_policy(
+ name=network_policy_name,
+ policy_type="network",
+ policy=[
+ {
+ "Rules": [{"Resource": [f"collection/{collection_name}"], "ResourceType": "collection"}],
+ "AllowFromPublic": True,
+ }
+ ],
+ )
+
+ _create_access_policy(
+ name=access_policy_name,
+ policy_type="data",
+ policy=[
+ {
+ "Rules": [
+ {
+ "Resource": [f"collection/{collection_name}"],
+ "Permission": [
+ "aoss:CreateCollectionItems",
+ "aoss:DeleteCollectionItems",
+ "aoss:UpdateCollectionItems",
+ "aoss:DescribeCollectionItems",
+ ],
+ "ResourceType": "collection",
+ },
+ {
+ "Resource": [f"index/{collection_name}/*"],
+ "Permission": [
+ "aoss:CreateIndex",
+ "aoss:DeleteIndex",
+ "aoss:UpdateIndex",
+ "aoss:DescribeIndex",
+ "aoss:ReadDocument",
+ "aoss:WriteDocument",
+ ],
+ "ResourceType": "index",
+ },
+ ],
+ "Principal": [(StsHook().conn.get_caller_identity()["Arn"]), bedrock_role_arn],
+ }
+ ],
+ )
+
+
+@task
+def create_collection(collection_name: str):
+ """
+ Call the Amazon OpenSearch Serverless API and create a collection with the provided name.
+
+ :param collection_name: The name of the Collection to create.
+ """
+ log.info("\nCreating collection: %s.", collection_name)
+ return aoss_client.create_collection(name=collection_name, type="VECTORSEARCH")["createCollectionDetail"][
+ "id"
+ ]
+
+
+@task
+def create_vector_index(collection_id: str, region: str):
+ """
+ Use the OpenSearchPy client to create the vector index for the Amazon Open Search Serverless Collection.
+
+ :param collection_id: ID of the collection to be indexed.
+ :param region: Name of the AWS region the collection resides in.
+ """
+ # Build the OpenSearch client
+ oss_client = OpenSearch(
+ hosts=[{"host": f"{collection_id}.{region}.aoss.amazonaws.com", "port": 443}],
+ http_auth=AWSV4SignerAuth(boto3.Session().get_credentials(), region, "aoss"),
+ use_ssl=True,
+ verify_certs=True,
+ connection_class=RequestsHttpConnection,
+ timeout=300,
+ )
+ index_config = {
+ "settings": {
+ "index.knn": "true",
+ "number_of_shards": 1,
+ "knn.algo_param.ef_search": 512,
+ "number_of_replicas": 0,
+ },
+ "mappings": {
+ "properties": {
+ "vector": {
+ "type": "knn_vector",
+ "dimension": 1536,
+ "method": {"name": "hnsw", "engine": "faiss", "space_type": "l2"},
+ },
+ "text": {"type": "text"},
+ "text-metadata": {"type": "text"},
+ }
+ },
+ }
+
+ retries = 35
+ while retries > 0:
+ try:
+ response = oss_client.indices.create(index=index_name, body=json.dumps(index_config))
+ log.info("Creating index: %s.", response)
+ break
+ except AuthorizationException as e:
+ # Index creation can take up to a minute and there is no (apparent?) way to check the current state.
+ log.info(
+ "Access denied; policy permissions have likely not yet propagated, %s tries remaining.",
+ retries,
+ )
+ log.debug(e)
+ retries -= 1
+ sleep(2)
+
+
+@task
+def copy_data_to_s3(bucket: str):
+ """
+ Download some sample data and upload it to 3S.
+
+ :param bucket: Name of the Amazon S3 bucket to send the data to.
+ """
+
+ # Monkey patch the list of names available for NamedTempFile so we can pick the names of the downloaded files.
+ backup_get_candidate_names = tempfile._get_candidate_names # type: ignore[attr-defined]
+ destinations = iter(
+ [
+ "AMZN-2022-Shareholder-Letter.pdf",
+ "AMZN-2021-Shareholder-Letter.pdf",
+ "AMZN-2020-Shareholder-Letter.pdf",
+ "AMZN-2019-Shareholder-Letter.pdf",
+ ]
+ )
+ tempfile._get_candidate_names = lambda: destinations # type: ignore[attr-defined]
+
+ # Download the sample data files, save them as named temp files using the names above, and upload to S3.
+ sources = [
+ "https://s2.q4cdn.com/299287126/files/doc_financials/2023/ar/2022-Shareholder-Letter.pdf",
+ "https://s2.q4cdn.com/299287126/files/doc_financials/2022/ar/2021-Shareholder-Letter.pdf",
+ "https://s2.q4cdn.com/299287126/files/doc_financials/2021/ar/Amazon-2020-Shareholder-Letter-and-1997-Shareholder-Letter.pdf",
+ "https://s2.q4cdn.com/299287126/files/doc_financials/2020/ar/2019-Shareholder-Letter.pdf",
+ ]
+
+ for source in sources:
+ with tempfile.NamedTemporaryFile(mode="w", prefix="") as data_file:
+ urlretrieve(source, data_file.name)
+ S3Hook().conn.upload_file(
+ Filename=data_file.name, Bucket=bucket, Key=os.path.basename(data_file.name)
+ )
+
+ # Revert the monkey patch.
+ tempfile._get_candidate_names = backup_get_candidate_names # type: ignore[attr-defined]
+ # Verify the path reversion worked.
+ with tempfile.NamedTemporaryFile(mode="w", prefix=""):
+ # If the reversion above did not apply correctly, this will fail with
+ # a StopIteration error because the iterator will run out of names.
+ ...
+
+
+@task
+def get_collection_arn(collection_id: str):
+ """
+ Return a collection ARN for a given collection ID.
+
+ :param collection_id: ID of the collection to be indexed.
+ """
+ return next(
+ colxn["arn"]
+ for colxn in aoss_client.list_collections()["collectionSummaries"]
+ if colxn["id"] == collection_id
+ )
+
+
+# [START howto_operator_bedrock_delete_data_source]
+@task(trigger_rule=TriggerRule.ALL_DONE)
+def delete_data_source(knowledge_base_id: str, data_source_id: str):
+ """
+ Delete the Amazon Bedrock data source created earlier.
+
+ .. seealso::
+ For more information on how to use this sensor, take a look at the guide:
+ :ref:`howto_operator:BedrockDeleteDataSource`
+
+ :param knowledge_base_id: The unique identifier of the knowledge base which the data source is attached to.
+ :param data_source_id: The unique identifier of the data source to delete.
+ """
+ log.info("Deleting data source %s from Knowledge Base %s.", data_source_id, knowledge_base_id)
+ bedrock_agent_client.delete_data_source(dataSourceId=data_source_id, knowledgeBaseId=knowledge_base_id)
+
+
+# [END howto_operator_bedrock_delete_data_source]
+
+
+# [START howto_operator_bedrock_delete_knowledge_base]
+@task(trigger_rule=TriggerRule.ALL_DONE)
+def delete_knowledge_base(knowledge_base_id: str):
+ """
+ Delete the Amazon Bedrock knowledge base created earlier.
+
+ .. seealso::
+ For more information on how to use this sensor, take a look at the guide:
+ :ref:`howto/operator:BedrockDeleteKnowledgeBase`
+
+ :param knowledge_base_id: The unique identifier of the knowledge base to delete.
+ """
+ log.info("Deleting Knowledge Base %s.", knowledge_base_id)
+ bedrock_agent_client.delete_knowledge_base(knowledgeBaseId=knowledge_base_id)
+
+
+# [END howto_operator_bedrock_delete_knowledge_base]
+
+
+@task(trigger_rule=TriggerRule.ALL_DONE)
+def delete_vector_index(collection_id: str):
+ """
+ Delete the vector index created earlier.
+
+ :param collection_id: ID of the collection to be indexed.
+ """
+ host = f"{collection_id}.{region_name}.aoss.amazonaws.com"
+ credentials = boto3.Session().get_credentials()
+ awsauth = AWSV4SignerAuth(credentials, region_name, "aoss")
+
+ # Build the OpenSearch client
+ oss_client = OpenSearch(
+ hosts=[{"host": host, "port": 443}],
+ http_auth=awsauth,
+ use_ssl=True,
+ verify_certs=True,
+ connection_class=RequestsHttpConnection,
+ timeout=300,
+ )
+ oss_client.indices.delete(index=index_name)
+
+
+@task(trigger_rule=TriggerRule.ALL_DONE)
+def delete_collection(collection_id: str):
+ """
+ Delete the OpenSearch collection created earlier.
+
+ :param collection_id: ID of the collection to be indexed.
+ """
+ log.info("Deleting collection %s.", collection_id)
+ aoss_client.delete_collection(id=collection_id)
+
+
+@task(trigger_rule=TriggerRule.ALL_DONE)
+def delete_opensearch_policies():
+ """Delete the security, network and data access policies created earlier."""
+
+ access_policies = aoss_client.list_access_policies(
+ type="data", resource=[f"collection/{vector_store_name}"]
+ )["accessPolicySummaries"]
+ log.info("Found access policies for %s: %s", vector_store_name, access_policies)
+ if not access_policies:
+ raise Exception("No access policies found?")
+ for policy in access_policies:
+ log.info("Deleting access policy for %s: %s", vector_store_name, policy["name"])
+ aoss_client.delete_access_policy(name=policy["name"], type="data")
+
+ for policy_type in ["encryption", "network"]:
+ policies = aoss_client.list_security_policies(
+ type=policy_type, resource=[f"collection/{vector_store_name}"]
+ )["securityPolicySummaries"]
+ if not policies:
+ raise Exception("No security policies found?")
+ log.info("Found %s security policies for %s: %s", policy_type, vector_store_name, policies)
+ for policy in policies:
+ log.info("Deleting %s security policy for %s: %s", policy_type, vector_store_name, policy["name"])
+ aoss_client.delete_security_policy(name=policy["name"], type=policy_type)
+
+
+with DAG(
+ dag_id=DAG_ID,
+ schedule="@once",
+ start_date=datetime(2021, 1, 1),
+ tags=["example"],
+ catchup=False,
+) as dag:
+ test_context = sys_test_context_task()
+ env_id = test_context["ENV_ID"]
+
+ aoss_client = OpenSearchServerlessHook().conn
+ bedrock_agent_client = BedrockAgentHook().conn
Review Comment:
Yeah, `aws_con_id=None` skip get connection from the DB / env variable / secrets backends and only use configuration from hook
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org