CreateKnowledgeBase 搭配 AWS SDK 使用 - AWS SDK 程式碼範例

文件 AWS 開發套件範例 GitHub 儲存庫中有更多可用的 AWS SDK 範例

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

CreateKnowledgeBase 搭配 AWS SDK 使用

以下程式碼範例顯示如何使用 CreateKnowledgeBase

Python
SDK for Python (Boto3)
注意

GitHub 上提供更多範例。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

建立 Amazon Bedrock 知識庫。

def create_knowledge_base(bedrock_agent_client, name, role_arn, description=None): """ Creates a new knowledge base. Args: bedrock_agent_client: The Boto3 Bedrock Agent client. name (str): The name of the knowledge base. role_arn (str): The ARN of the IAM role that the knowledge base assumes to access resources. description (str, optional): A description of the knowledge base. Returns: dict: The details of the created knowledge base. """ try: kwargs = { "name": name, "roleArn": role_arn, "knowledgeBaseConfiguration": { "type": "VECTOR", "vectorKnowledgeBaseConfiguration": { "embeddingModelArn": "arn:aws:bedrock:us-east-1::foundation-model/amazon.titan-embed-text-v1" } }, "storageConfiguration": { "type": "OPENSEARCH_SERVERLESS", # Note: You will need to create an OpenSearch Serverless collection first and replace this ARN # with your actual collection ARN from the OpenSearch console. If you use the console instead, # you can use the quick-create flow to have Knowledge Bases create the collection for you. "opensearchServerlessConfiguration": { "collectionArn": "arn:aws:aoss:us-east-1::123456789012:collection/abcdefgh12345678defgh", "fieldMapping": { "metadataField": "metadata", "textField": "text", "vectorField": "vector" }, "vectorIndexName": "test-uuid" }, }, "clientToken": "test-client-token-" + str(uuid.uuid4()) } if description: kwargs["description"] = description response = bedrock_agent_client.create_knowledge_base(**kwargs) logger.info("Created knowledge base with ID: %s", response["knowledgeBase"]["knowledgeBaseId"]) return response["knowledgeBase"] except ClientError as err: logger.error( "Couldn't create knowledge base. Here's why: %s: %s", err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise
  • 如需 API 詳細資訊,請參閱《適用於 AWS Python (Boto3) 的 SDK API 參考》中的 CreateKnowledgeBase