{"id":10301,"date":"2026-01-20T21:54:23","date_gmt":"2026-01-21T05:54:23","guid":{"rendered":"https:\/\/www.couchbase.com\/developers\/tutorials\/aws-bedrock-agents-lambda\/"},"modified":"2026-01-20T21:54:23","modified_gmt":"2026-01-21T05:54:23","slug":"aws-bedrock-agents-lambda","status":"publish","type":"tutorials","link":"https:\/\/www.couchbase.com\/it\/developers\/tutorials\/aws-bedrock-agents-lambda\/","title":{"rendered":"Building Intelligent Agents with Amazon Bedrock (Lambda)"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\"><a href=\"https:\/\/github.com\/couchbase-examples\/vector-search-cookbook\/tree\/main\/awsbedrock-agents\/lambda-approach\/Bedrock_Agents_Lambda.ipynb\">View Source<\/a><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This notebook demonstrates the Lambda approach for implementing AWS Bedrock agents with Couchbase Vector Search. In this approach, the agent invokes AWS Lambda functions to execute operations.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">We&#8217;ll implement a multi-agent architecture with specialized agents for different tasks:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Researcher Agent<\/strong>: Searches for relevant documents in the vector store<\/li>\n\n\n<li><strong>Writer Agent<\/strong>: Formats and presents the research findings<\/li>\n\n<\/ul>\n\n\n\n<h3 id=\"h-alternative-approaches\" class=\"wp-block-heading\">Alternative Approaches<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">This notebook demonstrates the Lambda Approach for AWS Bedrock Agents. For comparison, you might also want to check out the Custom Control Approach, which handles agent tools directly in your application code instead of using AWS Lambda functions.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The Custom Control approach offers simpler setup and more direct control, but may not scale as well. You can find that implementation here: <a href=\"https:\/\/developer.couchbase.com\/tutorial-aws-bedrock-agents-custom-control\">Custom Control Approach Notebook<\/a><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Note: If the link above doesn&#8217;t work in your Jupyter environment, you can navigate to the file manually in the <code>awsbedrock-agents\/custom-control-approach\/<\/code> directory.<\/p>\n\n\n\n<h3 id=\"h-overview\" class=\"wp-block-heading\">Overview<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The Lambda approach for AWS Bedrock Agents delegates the execution of an agent&#8217;s defined functions (tools) to backend AWS Lambda functions. When the agent decides to use a tool, Bedrock directly invokes the corresponding Lambda function that you&#8217;ve specified in the agent&#8217;s action group configuration. This Lambda function receives the parameters from the agent, executes the necessary logic (e.g., querying a Couchbase vector store, calling other APIs, performing computations), and then returns the result to the Bedrock Agent. The agent can then use this result to continue its reasoning process or formulate a final response to the user. This architecture promotes a clean separation of concerns, allows tool logic to be developed and scaled independently, and leverages the serverless capabilities of AWS Lambda.<\/p>\n\n\n\n<h3 id=\"h-key-steps-amp-concepts\" class=\"wp-block-heading\">Key Steps &amp; Concepts<\/h3>\n\n\n\n<ol class=\"wp-block-list\">\n<li>\n<p><strong>Define Agent Instructions &amp; Tool Schema:<\/strong><\/p>\n<ul>\n<li><strong>Instructions:<\/strong> Craft a clear prompt that tells the agent its purpose, capabilities, and how it should behave (e.g., &#8220;You are a research assistant that uses the SearchAndFormat tool&#8230;&#8221;).<\/li>\n<li><strong>Function Schema:<\/strong> Define the structure of the tool(s) the agent can use. In this notebook, we define a single tool (e.g., <code>searchAndFormatDocuments<\/code>) that the agent will call. This schema specifies the function name, description, and its input parameters (e.g., <code>query<\/code>, <code>k<\/code>, <code>style<\/code>). This schema acts as the contract between the agent and the Lambda function.<\/li>\n<\/ul>\n<\/li>\n\n\n<li>\n<p><strong>Implement Lambda Handler Function:<\/strong><\/p>\n<ul>\n<li>Create an AWS Lambda function (e.g., <code>bedrock_agent_search_and_format.py<\/code>) that contains the actual Python code to execute the tool&#8217;s logic.<\/li>\n<li><strong>Event Handling:<\/strong> The Lambda handler receives an event payload from Bedrock. This payload includes details like the API path (which corresponds to the function name in the schema), HTTP method, and the parameters supplied by the agent.<\/li>\n<li><strong>Business Logic:<\/strong> Inside the Lambda, parse the incoming event, extract parameters, and perform the required actions. For this notebook, this involves:\n<ul>\n<li>Connecting to Couchbase.<\/li>\n<li>Initializing the Bedrock Embeddings client.<\/li>\n<li>Performing a vector similarity search using the provided query and <code>k<\/code> value.<\/li>\n<li>Optionally, formatting the search results based on the <code>style<\/code> parameter (though in this specific example, the formatting is largely illustrative and the LLM does the heavy lifting of presentation).<\/li>\n<\/ul>\n<\/li>\n<li><strong>Response Structure:<\/strong> The Lambda must return a JSON response in a specific format that Bedrock expects. This response typically includes the <code>actionGroup<\/code>, <code>apiPath<\/code>, <code>httpMethod<\/code>, <code>httpStatusCode<\/code>, and a <code>responseBody<\/code> containing the result of the tool execution (e.g., the search results as a string).<\/li>\n<li><strong>Deployment:<\/strong> Package the Lambda function with its dependencies (e.g., <code>requirements.txt<\/code>) into a .zip file. This notebook includes helper functions to automate packaging (using a <code>Makefile<\/code>) and deployment, including uploading to S3 if the package is large. The Lambda also needs an IAM role with permissions to run, write logs, and interact with Bedrock and any other required AWS services.<\/li>\n<li><strong>Environment Variables:<\/strong> The Lambda function is configured with environment variables (e.g., Couchbase connection details, Bedrock model IDs) to allow it to connect to necessary services without hardcoding credentials. These are set during the Lambda creation\/update process in the notebook.<\/li>\n<\/ul>\n<\/li>\n\n\n<li>\n<p><strong>Create Agent in AWS Bedrock:<\/strong><\/p>\n<ul>\n<li>Use the <code>bedrock_agent_client.create_agent<\/code> SDK call. Provide the agent name, the ARN of the IAM role it will assume, the foundation model ID (e.g., Claude Sonnet), and the instructions defined in step 1.<\/li>\n<\/ul>\n<\/li>\n\n\n<li>\n<p><strong>Create Agent Action Group (Linking to Lambda):<\/strong><\/p>\n<ul>\n<li>Use <code>bedrock_agent_client.create_agent_action_group<\/code>.<\/li>\n<li><strong><code>actionGroupExecutor<\/code>:<\/strong> This is the crucial part for the Lambda approach. Set it to <code>{'lambda': 'arn:aws:lambda:&lt;region&gt;:&lt;account_id&gt;:function:&lt;lambda_function_name&gt;'}<\/code>. This tells Bedrock to invoke your specific Lambda function when this action group is triggered.<\/li>\n<li><strong><code>functionSchema<\/code>:<\/strong> Provide the function schema defined in step 1. This allows the agent to understand how to call the Lambda function (i.e., what parameters to send).<\/li>\n<li>Give the action group a name (e.g., <code>SearchAndFormatActionGroup<\/code>).<\/li>\n<\/ul>\n<\/li>\n\n\n<li>\n<p><strong>Prepare Agent:<\/strong><\/p>\n<ul>\n<li>Call <code>bedrock_agent_client.prepare_agent<\/code> with the <code>agentId<\/code>. This makes the DRAFT version of the agent (with its newly configured action group) ready for use. The notebook includes a custom waiter to poll until the agent status is <code>PREPARED<\/code>.<\/li>\n<\/ul>\n<\/li>\n\n\n<li>\n<p><strong>Create or Update Agent Alias:<\/strong><\/p>\n<ul>\n<li>An alias (e.g., <code>prod<\/code>) is used to invoke a specific version of the agent. The notebook checks if an alias exists and creates one if not, pointing to the latest prepared (DRAFT) version. Use <code>bedrock_agent_client.create_agent_alias<\/code> or <code>update_agent_alias<\/code>.<\/li>\n<\/ul>\n<\/li>\n\n\n<li>\n<p><strong>Invoke Agent:<\/strong><\/p>\n<ul>\n<li>Use <code>bedrock_agent_runtime_client.invoke_agent<\/code>, providing the <code>agentId<\/code>, <code>agentAliasId<\/code>, a unique <code>sessionId<\/code>, and the user&#8217;s <code>inputText<\/code> (prompt).<\/li>\n<li>Bedrock takes over: when the agent decides to use the tool from the action group, Bedrock transparently calls the configured Lambda function with the necessary parameters.<\/li>\n<li>The Lambda executes, returns its result to the agent, and the agent uses this result to generate its final response.<\/li>\n<li>Your application code simply waits for and processes the final streaming response from the <code>invoke_agent<\/code> call. Unlike the Custom Control approach, there&#8217;s no <code>returnControl<\/code> event for the application to handle for tool execution; Bedrock manages the Lambda invocation directly.<\/li>\n<\/ul>\n<\/li>\n\n<\/ol>\n\n\n\n<h3 id=\"h-pros\" class=\"wp-block-heading\">Pros<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Decoupling &amp; Modularity:<\/strong> Tool execution logic is encapsulated within Lambda functions, separate from the main application code. This allows for independent development, deployment, and scaling of tools.<\/li>\n\n\n<li><strong>Scalability &amp; Serverless:<\/strong> Leverages the inherent scalability, concurrency, and pay-per-use benefits of AWS Lambda for tool execution.<\/li>\n\n\n<li><strong>Managed Execution Environment:<\/strong> AWS manages the underlying infrastructure, runtime environment, and invocation mechanism for the Lambda functions.<\/li>\n\n\n<li><strong>Simpler Application-Level Code:<\/strong> The application that invokes the Bedrock agent doesn&#8217;t need to implement the tool&#8217;s logic itself or handle <code>returnControl<\/code> events for function execution, as Bedrock orchestrates the call to Lambda directly.<\/li>\n\n<\/ul>\n\n\n\n<h3 id=\"h-cons\" class=\"wp-block-heading\">Cons<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Deployment &amp; Configuration Overhead:<\/strong> Requires setting up, packaging, configuring dependencies, and deploying separate Lambda functions. IAM roles and permissions for Lambdas also need careful management.<\/li>\n\n\n<li><strong>State Management:<\/strong> If tools need to share state or complex context with the Lambda function, this must be explicitly passed, often via environment variables or by including necessary lookup logic within the Lambda itself.<\/li>\n\n\n<li><strong>Cold Starts:<\/strong> AWS Lambda cold starts can introduce latency the first time a function is invoked after a period of inactivity, potentially affecting agent response time.<\/li>\n\n\n<li><strong>Debugging Complexity:<\/strong> Troubleshooting can be more involved as it spans across the Bedrock Agent service, the Lambda service, and potentially other services the Lambda interacts with (like Couchbase). Centralized logging (e.g., CloudWatch Logs for Lambda) is essential.<\/li>\n\n\n<li><strong>Cost:<\/strong> Incurs costs associated with Lambda invocations, execution duration, and any resources used by the Lambda (e.g., data transfer, provisioned concurrency if used).<\/li>\n\n<\/ul>\n\n\n\n<h3 id=\"h-1--imports\" class=\"wp-block-heading\">1. Imports<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">This section imports all necessary Python libraries. These include:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Standard libraries: <code>json<\/code> for data handling, <code>logging<\/code> for progress and error messages, <code>os<\/code> for interacting with the operating system (e.g., file paths), <code>subprocess<\/code> for running external commands (like <code>make<\/code> for Lambda packaging), <code>time<\/code> for delays, <code>traceback<\/code> for detailed error reporting, <code>uuid<\/code> for generating unique identifiers, and <code>shutil<\/code> for file operations.<\/li>\n\n\n<li><code>boto3<\/code> and <code>botocore<\/code>: The AWS SDK for Python, used to interact with AWS services like Bedrock, IAM, Lambda, and S3. Specific configurations (<code>Config<\/code>) and waiters are also imported for robust client interactions.<\/li>\n\n\n<li><code>couchbase<\/code>: The official Couchbase SDK for Python, used for connecting to and interacting with the Couchbase cluster, including managing buckets, collections, and search indexes. Specific exception classes are imported for error handling.<\/li>\n\n\n<li><code>dotenv<\/code>: For loading environment variables from a <code>.env<\/code> file, which helps manage configuration settings like API keys and connection strings securely.<\/li>\n\n\n<li><code>langchain_aws<\/code> and <code>langchain_couchbase<\/code>: Libraries from the LangChain ecosystem. <code>BedrockEmbeddings<\/code> is used to generate text embeddings via Amazon Bedrock, and <code>CouchbaseSearchVectorStore<\/code> provides an interface for using Couchbase as a vector store in LangChain applications.<\/li>\n\n<\/ul>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>import json\nimport logging\nimport os\nimport shutil\nimport subprocess\nimport time\nimport traceback\nimport uuid\nfrom datetime import timedelta\n\nimport boto3\nfrom botocore.config import Config\nfrom botocore.exceptions import ClientError\nfrom botocore.waiter import WaiterModel, create_waiter_with_client\nfrom couchbase.auth import PasswordAuthenticator\nfrom couchbase.cluster import Cluster\nfrom couchbase.exceptions import (BucketNotFoundException, CouchbaseException,\n                                  QueryIndexAlreadyExistsException)\nfrom couchbase.management.buckets import BucketSettings, BucketType\nfrom couchbase.management.collections import CollectionSpec\nfrom couchbase.management.search import SearchIndex\nfrom couchbase.options import ClusterOptions\nfrom dotenv import load_dotenv\nfrom langchain_aws import BedrockEmbeddings\nfrom langchain_couchbase.vectorstores import CouchbaseSearchVectorStore\n<\/code><\/pre>\n\n\n\n<h3 id=\"h-2--configuration\" class=\"wp-block-heading\">2. Configuration<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">This section handles the initial setup of essential configurations for the notebook:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Logging:<\/strong> Configures the <code>logging<\/code> module to output messages with a specific format (timestamp, level, message), which helps in tracking the script&#8217;s execution and diagnosing issues.<\/li>\n\n\n<li><strong>Environment Variables:<\/strong> Attempts to load environment variables from a <code>.env<\/code> file located either in the current directory or the parent directory. This is a common practice to keep sensitive information like credentials and hostnames out of the codebase. If the <code>.env<\/code> file is not found, the script will rely on variables already set in the execution environment.<\/li>\n\n\n<li><strong>Couchbase Settings:<\/strong> Defines variables for connecting to Couchbase, including the host, username, password, and the names for the bucket, scope, collection, and search index that will be used for this experiment. Default values are provided if specific environment variables are not set.<\/li>\n\n\n<li><strong>AWS Settings:<\/strong> Defines variables for AWS configuration, such as the region, access key ID, secret access key, and AWS account ID. These are crucial for <code>boto3<\/code> to interact with AWS services.<\/li>\n\n\n<li><strong>Bedrock Model IDs:<\/strong> Specifies the model identifiers for the Amazon Bedrock text embedding model (e.g., <code>amazon.titan-embed-text-v2:0<\/code>) and the foundation model to be used by the agent (e.g., <code>anthropic.claude-3-sonnet-20240229-v1:0<\/code>).<\/li>\n\n\n<li><strong>File Paths:<\/strong> Sets up variables for various file paths used throughout the notebook, such as the directory for schemas, the path to the Couchbase search index JSON definition, and the path to the JSON file containing documents to be loaded into the vector store. Using <code>os.getcwd()<\/code> makes these paths relative to the notebook&#8217;s current working directory.<\/li>\n\n<\/ul>\n\n\n\n<pre class=\"wp-block-code language-python\"><code># Setup logging\nlogging.basicConfig(level=logging.INFO, format=&#039;%(asctime)s - %(levelname)s - %(message)s&#039;)\nlogger = logging.getLogger(__name__)\n\n# Load environment variables from project root .env\n# In a notebook environment, &#039;__file__&#039; is not defined. Use a relative path or absolute path directly.\n# Assuming the notebook is run from the &#039;lambda-experiments&#039; directory\ndotenv_path = os.path.join(os.getcwd(), &#039;.env&#039;) # Or specify the full path if needed\nlogger.info(f&quot;Attempting to load .env file from: {dotenv_path}&quot;)\nif os.path.exists(dotenv_path):\n    load_dotenv(dotenv_path=dotenv_path)\n    logger.info(&quot;.env file loaded successfully.&quot;)\nelse:\n    # Try loading from parent directory if not found in current\n    parent_dotenv_path = os.path.join(os.path.dirname(os.getcwd()), &#039;.env&#039;)\n    if os.path.exists(parent_dotenv_path):\n        load_dotenv(dotenv_path=parent_dotenv_path)\n        logger.info(f&quot;.env file loaded successfully from parent directory: {parent_dotenv_path}&quot;)\n    else:\n        logger.warning(f&quot;.env file not found at {dotenv_path} or {parent_dotenv_path}. Relying on environment variables.&quot;)\n\n\n# Couchbase Configuration\nCB_HOST = os.getenv(&quot;CB_HOST&quot;, &quot;couchbase:\/\/localhost&quot;)\nCB_USERNAME = os.getenv(&quot;CB_USERNAME&quot;, &quot;Administrator&quot;)\nCB_PASSWORD = os.getenv(&quot;CB_PASSWORD&quot;, &quot;password&quot;)\n# Using a new bucket\/scope\/collection for experiments to avoid conflicts\nCB_BUCKET_NAME = os.getenv(&quot;CB_BUCKET_NAME&quot;, &quot;vector-search-exp&quot;)\nSCOPE_NAME = os.getenv(&quot;SCOPE_NAME&quot;, &quot;bedrock_exp&quot;)\nCOLLECTION_NAME = os.getenv(&quot;COLLECTION_NAME&quot;, &quot;docs_exp&quot;)\nINDEX_NAME = os.getenv(&quot;INDEX_NAME&quot;, &quot;vector_search_bedrock_exp&quot;)\n\n# AWS Configuration\nAWS_REGION = os.getenv(&quot;AWS_REGION&quot;, &quot;us-east-1&quot;)\nAWS_ACCESS_KEY_ID = os.getenv(&quot;AWS_ACCESS_KEY_ID&quot;)\nAWS_SECRET_ACCESS_KEY = os.getenv(&quot;AWS_SECRET_ACCESS_KEY&quot;)\nAWS_ACCOUNT_ID = os.getenv(&quot;AWS_ACCOUNT_ID&quot;)\n\n# Bedrock Model IDs\nEMBEDDING_MODEL_ID = &quot;amazon.titan-embed-text-v2:0&quot;\nAGENT_MODEL_ID = &quot;anthropic.claude-3-sonnet-20240229-v1:0&quot; # Using Sonnet for the agent\n\n# Paths (relative to the notebook&#039;s execution directory)\nSCRIPT_DIR = os.getcwd() # Use current working directory for notebook context\nSCHEMAS_DIR = os.path.join(SCRIPT_DIR, &#039;schemas&#039;) # New Schemas Dir\nSEARCH_FORMAT_SCHEMA_PATH = os.path.join(SCHEMAS_DIR, &#039;search_and_format_schema.json&#039;) # Added\nINDEX_JSON_PATH = os.path.join(SCRIPT_DIR, &#039;aws_index.json&#039;) # Keep\nDOCS_JSON_PATH = os.path.join(SCRIPT_DIR, &#039;documents.json&#039;) # Changed to load from script&#039;s directory\n<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>2025-06-09 13:39:41,393 - INFO - Attempting to load .env file from: \/Users\/kaustavghosh\/Desktop\/vector-search-cookbook\/awsbedrock-agents\/lambda-approach\/.env\n2025-06-09 13:39:41,395 - INFO - .env file loaded successfully.\n<\/code><\/pre>\n\n\n\n<h3 id=\"h-3--helper-functions\" class=\"wp-block-heading\">3. Helper Functions<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">This section defines a comprehensive suite of helper functions to modularize the various operations required throughout the notebook. These functions encapsulate specific tasks, making the main execution flow cleaner and easier to understand. The categories of helper functions include:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Environment and Client Initialization:<\/strong> Checking for necessary environment variables and setting up AWS SDK (<code>boto3<\/code>) clients for services like IAM, Lambda, Bedrock, and S3.<\/li>\n\n\n<li><strong>Couchbase Interaction:<\/strong> Connecting to the Couchbase cluster, and robustly setting up buckets, scopes, collections, and search indexes. Includes functions to clear data from collections for clean experimental runs.<\/li>\n\n\n<li><strong>IAM Role Management:<\/strong> Creating or retrieving the necessary IAM roles with appropriate trust policies and permissions that allow Bedrock Agents and Lambda functions to operate and interact with other AWS services securely.<\/li>\n\n\n<li><strong>Lambda Function Deployment:<\/strong> A set of functions to manage the lifecycle of the Lambda function that the agent will invoke. This includes packaging the Lambda code and its dependencies (using a <code>Makefile<\/code>), uploading the deployment package (to S3 if it&#8217;s large), creating or updating the Lambda function in AWS, and deleting it for cleanup.<\/li>\n\n\n<li><strong>Bedrock Agent Resource Management:<\/strong> Functions for creating the Bedrock Agent itself, defining its action groups (which link the agent to the Lambda function via its ARN and define the tool schema), preparing the agent to make it invocable, and managing agent aliases. Also includes functions to delete these agent resources for cleanup.<\/li>\n\n\n<li><strong>Agent Invocation:<\/strong> A function to test the fully configured agent by sending it a prompt and processing its streamed response, including any trace information for debugging.<\/li>\n\n<\/ul>\n\n\n\n<h4 id=\"h-3-1-checkenvironmentvariables\" class=\"wp-block-heading\">3.1 check_environment_variables<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">This function verifies that all critical environment variables required for the script to run (e.g., AWS credentials, Couchbase password, AWS Account ID) are set. It logs an error and returns <code>False<\/code> if any are missing, otherwise logs success and returns <code>True<\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>def check_environment_variables():\n    &quot;&quot;&quot;Check if required environment variables are set.&quot;&quot;&quot;\n    required_vars = [&quot;AWS_ACCESS_KEY_ID&quot;, &quot;AWS_SECRET_ACCESS_KEY&quot;, &quot;AWS_ACCOUNT_ID&quot;, &quot;CB_PASSWORD&quot;]\n    missing_vars = [var for var in required_vars if not os.getenv(var)]\n    if missing_vars:\n        logger.error(f&quot;Missing required environment variables: {&#039;, &#039;.join(missing_vars)}&quot;)\n        logger.error(&quot;Please set these variables in your environment or .env file&quot;)\n        return False\n    logger.info(&quot;All required environment variables are set.&quot;)\n    return True\n<\/code><\/pre>\n\n\n\n<h4 id=\"h-3-2-initializeawsclients\" class=\"wp-block-heading\">3.2 initialize_aws_clients<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">This function sets up and returns the necessary AWS SDK (<code>boto3<\/code>) clients for interacting with various AWS services. It initializes clients for Bedrock Runtime (for embeddings and agent invocation), IAM (for managing roles and policies), Lambda (for deploying and managing Lambda functions), Bedrock Agent (for creating and managing agents), and Bedrock Agent Runtime (for invoking agents). It uses credentials and region from the environment configuration and includes a custom configuration (<code>agent_config<\/code>) with longer timeouts and retries, which is particularly important for Bedrock Agent operations that can take more time, like agent preparation.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>def initialize_aws_clients():\n    &quot;&quot;&quot;Initialize required AWS clients.&quot;&quot;&quot;\n    try:\n        logger.info(f&quot;Initializing AWS clients in region: {AWS_REGION}&quot;)\n        session = boto3.Session(\n            aws_access_key_id=AWS_ACCESS_KEY_ID,\n            aws_secret_access_key=AWS_SECRET_ACCESS_KEY,\n            region_name=AWS_REGION\n        )\n        # Use a config with longer timeouts for agent operations\n        agent_config = Config(\n            connect_timeout=120,\n            read_timeout=600, # Agent preparation can take time\n            retries={&#039;max_attempts&#039;: 5, &#039;mode&#039;: &#039;adaptive&#039;}\n        )\n        bedrock_runtime = session.client(&#039;bedrock-runtime&#039;, region_name=AWS_REGION)\n        iam_client = session.client(&#039;iam&#039;, region_name=AWS_REGION) \n        lambda_client = session.client(&#039;lambda&#039;, region_name=AWS_REGION)\n        bedrock_agent_client = session.client(&#039;bedrock-agent&#039;, region_name=AWS_REGION, config=agent_config) # Add agent client\n        bedrock_agent_runtime_client = session.client(&#039;bedrock-agent-runtime&#039;, region_name=AWS_REGION, config=agent_config) # Add agent runtime client\n        logger.info(&quot;AWS clients initialized successfully.&quot;)\n        return bedrock_runtime, iam_client, lambda_client, bedrock_agent_client, bedrock_agent_runtime_client # Return agent runtime client\n    except Exception as e:\n        logger.error(f&quot;Error initializing AWS clients: {e}&quot;)\n        raise\n<\/code><\/pre>\n\n\n\n<h4 id=\"h-3-3-connectcouchbase\" class=\"wp-block-heading\">3.3 connect_couchbase<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">This function establishes a connection to the Couchbase cluster using the connection string (<code>CB_HOST<\/code>), username, and password from the environment configuration. It uses <code>PasswordAuthenticator<\/code> for authentication and <code>ClusterOptions<\/code> for potentially customizing connection parameters (though commented out in the example, it shows where timeouts could be set). It waits for the cluster to be ready before returning the <code>Cluster<\/code> object, ensuring that subsequent operations can be performed reliably.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>def connect_couchbase():\n    &quot;&quot;&quot;Connect to Couchbase cluster.&quot;&quot;&quot;\n    try:\n        logger.info(f&quot;Connecting to Couchbase cluster at {CB_HOST}...&quot;)\n        auth = PasswordAuthenticator(CB_USERNAME, CB_PASSWORD)\n        # Use robust options\n        options = ClusterOptions(\n             auth,\n        )\n        cluster = Cluster(CB_HOST, options)\n        cluster.wait_until_ready(timedelta(seconds=10)) # Wait longer if needed\n        logger.info(&quot;Successfully connected to Couchbase.&quot;)\n        return cluster\n    except CouchbaseException as e:\n        logger.error(f&quot;Couchbase connection error: {e}&quot;)\n        raise\n    except Exception as e:\n        logger.error(f&quot;Unexpected error connecting to Couchbase: {e}&quot;)\n        raise\n<\/code><\/pre>\n\n\n\n<h4 id=\"h-3-4-setupcollection\" class=\"wp-block-heading\">3.4 setup_collection<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">This comprehensive function is responsible for ensuring that the required Couchbase bucket, scope, and collection are available for the agent&#8217;s vector store. It performs the following steps idempotently:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Checks if the specified bucket (<code>bucket_name<\/code>) exists. If not, it creates the bucket with defined settings (e.g., RAM quota, flush enabled). It includes a pause to allow the bucket to become ready.<\/li>\n\n\n<li>Checks if the specified scope (<code>scope_name<\/code>) exists within the bucket. If not, it creates the scope and includes a brief pause.<\/li>\n\n\n<li>Checks if the specified collection (<code>collection_name<\/code>) exists within the scope. If not, it creates the collection using a <code>CollectionSpec<\/code> and pauses.<\/li>\n\n\n<li>Ensures that a primary N1QL index exists on the collection, creating it if it&#8217;s missing. This is often useful for administrative queries or simpler lookups, though not strictly for vector search itself.\nFinally, it returns a <code>Collection<\/code> object representing the target collection for further operations.<\/li>\n\n<\/ul>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p class=\"wp-block-paragraph\">Note: Bucket Creation will not work on Capella.<\/p>\n<\/blockquote>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>def setup_collection(cluster, bucket_name, scope_name, collection_name):\n    &quot;&quot;&quot;Set up Couchbase collection (Original Logic from lamda-approach)&quot;&quot;&quot;\n    logger.info(f&quot;Setting up collection: {bucket_name}\/{scope_name}\/{collection_name}&quot;)\n    try:\n        # Check if bucket exists, create if it doesn&#039;t\n        try:\n            bucket = cluster.bucket(bucket_name)\n            logger.info(f&quot;Bucket &#039;{bucket_name}&#039; exists.&quot;)\n        except BucketNotFoundException:\n            logger.info(f&quot;Bucket &#039;{bucket_name}&#039; does not exist. Creating it...&quot;)\n            # Use BucketSettings with potentially lower RAM for experiment\n            bucket_settings = BucketSettings(\n                name=bucket_name,\n                bucket_type=BucketType.COUCHBASE,\n                ram_quota_mb=256, # Adjusted from 1024\n                flush_enabled=True,\n                num_replicas=0\n            )\n            try:\n                 cluster.buckets().create_bucket(bucket_settings)\n                 # Wait longer after bucket creation\n                 logger.info(f&quot;Bucket &#039;{bucket_name}&#039; created. Waiting for ready state (10s)...&quot;)\n                 time.sleep(10) \n                 bucket = cluster.bucket(bucket_name) # Re-assign bucket object\n            except Exception as create_e:\n                 logger.error(f&quot;Failed to create bucket &#039;{bucket_name}&#039;: {create_e}&quot;)\n                 raise\n        except Exception as e:\n             logger.error(f&quot;Error getting bucket &#039;{bucket_name}&#039;: {e}&quot;)\n             raise\n\n        bucket_manager = bucket.collections()\n\n        # Check if scope exists, create if it doesn&#039;t\n        scopes = bucket_manager.get_all_scopes()\n        scope_exists = any(s.name == scope_name for s in scopes)\n\n        if not scope_exists:\n            logger.info(f&quot;Scope &#039;{scope_name}&#039; does not exist. Creating it...&quot;)\n            try:\n                 bucket_manager.create_scope(scope_name)\n                 logger.info(f&quot;Scope &#039;{scope_name}&#039; created. Waiting (2s)...&quot;)\n                 time.sleep(2)\n            except CouchbaseException as e:\n                 # Handle potential race condition or already exists error more robustly\n                 if &quot;already exists&quot; in str(e).lower() or &quot;scope_exists&quot; in str(e).lower():\n                      logger.info(f&quot;Scope &#039;{scope_name}&#039; likely already exists (caught during creation attempt).&quot;)\n                 else:\n                      logger.error(f&quot;Failed to create scope &#039;{scope_name}&#039;: {e}&quot;)\n                      raise\n        else:\n             logger.info(f&quot;Scope &#039;{scope_name}&#039; already exists.&quot;)\n\n        # Check if collection exists, create if it doesn&#039;t\n        # Re-fetch scopes in case it was just created\n        scopes = bucket_manager.get_all_scopes()\n        collection_exists = False\n        for s in scopes:\n             if s.name == scope_name:\n                  if any(c.name == collection_name for c in s.collections):\n                       collection_exists = True\n                       break\n        \n        if not collection_exists:\n            logger.info(f&quot;Collection &#039;{collection_name}&#039; does not exist in scope &#039;{scope_name}&#039;. Creating it...&quot;)\n            try:\n                # Use CollectionSpec\n                collection_spec = CollectionSpec(collection_name, scope_name)\n                bucket_manager.create_collection(collection_spec)\n                logger.info(f&quot;Collection &#039;{collection_name}&#039; created. Waiting (2s)...&quot;)\n                time.sleep(2)\n            except CouchbaseException as e:\n                 if &quot;already exists&quot; in str(e).lower() or &quot;collection_exists&quot; in str(e).lower():\n                     logger.info(f&quot;Collection &#039;{collection_name}&#039; likely already exists (caught during creation attempt).&quot;)\n                 else:\n                     logger.error(f&quot;Failed to create collection &#039;{collection_name}&#039;: {e}&quot;)\n                     raise\n        else:\n            logger.info(f&quot;Collection &#039;{collection_name}&#039; already exists.&quot;)\n\n        # Ensure primary index exists\n        try:\n            logger.info(f&quot;Ensuring primary index exists on `{bucket_name}`.`{scope_name}`.`{collection_name}`...&quot;)\n            cluster.query(f&quot;CREATE PRIMARY INDEX IF NOT EXISTS ON `{bucket_name}`.`{scope_name}`.`{collection_name}`&quot;).execute()\n            logger.info(&quot;Primary index present or created successfully.&quot;)\n        except Exception as e:\n            logger.error(f&quot;Error creating primary index: {str(e)}&quot;)\n            # Decide if this is fatal\n\n        logger.info(&quot;Collection setup complete.&quot;)\n        # Return the collection object for use\n        return cluster.bucket(bucket_name).scope(scope_name).collection(collection_name)\n\n    except Exception as e:\n        logger.error(f&quot;Error setting up collection: {str(e)}&quot;)\n        logger.error(traceback.format_exc())\n        raise\n<\/code><\/pre>\n\n\n\n<h4 id=\"h-3-5-setupsearchindex\" class=\"wp-block-heading\">3.5 setup_search_index<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">This function is responsible for creating or updating the Couchbase Search index required for vector similarity search. Key operations include:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Loading the index definition from a specified JSON file (<code>index_definition_path<\/code>).<\/li>\n\n\n<li>Dynamically updating the loaded index definition to use the correct <code>index_name<\/code> and <code>sourceName<\/code> (bucket name) provided as arguments. This allows for a template index definition file to be reused.<\/li>\n\n\n<li>Using the <code>SearchIndexManager<\/code> (obtained from the cluster object) to <code>upsert_index<\/code>. Upserting means the index will be created if it doesn&#8217;t exist, or updated if an index with the same name already exists. This makes the operation idempotent.<\/li>\n\n\n<li>After submitting the upsert operation, it includes a pause (<code>time.sleep<\/code>) to allow Couchbase some time to start the indexing process in the background.<\/li>\n\n<\/ul>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p class=\"wp-block-paragraph\"><strong>Important Note:<\/strong> The provided <code>aws_index.json<\/code> file has hardcoded references for the bucket, scope, and collection names. If you have used different names for your bucket, scope, or collection than the defaults specified in this notebook or your <code>.env<\/code> file, you <strong>must<\/strong> modify the <code>aws_index.json<\/code> file to reflect your custom names before running the next cell.<\/p>\n<\/blockquote>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>def setup_search_index(cluster, index_name, bucket_name, scope_name, collection_name, index_definition_path):\n    &quot;&quot;&quot;Set up search indexes (Original Logic, adapted) &quot;&quot;&quot;\n    try:\n        logger.info(f&quot;Looking for index definition at: {index_definition_path}&quot;)\n        if not os.path.exists(index_definition_path):\n             logger.error(f&quot;Index definition file not found: {index_definition_path}&quot;)\n             raise FileNotFoundError(f&quot;Index definition file not found: {index_definition_path}&quot;)\n\n        with open(index_definition_path, &#039;r&#039;) as file:\n            index_definition = json.load(file)\n            index_definition[&#039;name&#039;] = index_name\n            index_definition[&#039;sourceName&#039;] = bucket_name\n            logger.info(f&quot;Loaded index definition from {index_definition_path}, ensuring name is &#039;{index_name}&#039; and source is &#039;{bucket_name}&#039;.&quot;)\n\n    except Exception as e:\n        logger.error(f&quot;Error loading index definition: {str(e)}&quot;)\n        raise\n\n    try:\n        # Use the SearchIndexManager from the Cluster object for cluster-level indexes\n        # Or use scope-level if the index JSON is structured for that\n        # Assuming cluster level based on original script structure for upsert\n        search_index_manager = cluster.search_indexes()\n\n        # Create SearchIndex object from potentially modified JSON definition\n        search_index = SearchIndex.from_json(index_definition)\n\n        # Upsert the index (create if not exists, update if exists)\n        logger.info(f&quot;Upserting search index &#039;{index_name}&#039;...&quot;)\n        search_index_manager.upsert_index(search_index)\n\n        # Wait for indexing\n        logger.info(f&quot;Index &#039;{index_name}&#039; upsert operation submitted. Waiting for indexing (10s)...&quot;)\n        time.sleep(10)\n\n        logger.info(f&quot;Search index &#039;{index_name}&#039; setup complete.&quot;)\n\n    except QueryIndexAlreadyExistsException:\n        # This exception might not be correct for SearchIndexManager\n        # Upsert should handle exists cases, but log potential specific errors\n        logger.warning(f&quot;Search index &#039;{index_name}&#039; likely already existed (caught QueryIndexAlreadyExistsException, check if applicable). Upsert attempted.&quot;)\n    except CouchbaseException as e:\n        logger.error(f&quot;Couchbase error during search index setup for &#039;{index_name}&#039;: {e}&quot;)\n        raise\n    except Exception as e:\n        logger.error(f&quot;Unexpected error during search index setup for &#039;{index_name}&#039;: {e}&quot;)\n        raise\n<\/code><\/pre>\n\n\n\n<h4 id=\"h-3-6-clearcollection\" class=\"wp-block-heading\">3.6 clear_collection<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">This utility function is used to delete all documents from a specified Couchbase collection. It constructs and executes a N1QL <code>DELETE<\/code> query targeting the given bucket, scope, and collection. This is useful for ensuring a clean state before loading new data for an experiment, preventing interference from previous runs. It also attempts to log the number of mutations (deleted documents) if the query metrics are available.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>def clear_collection(cluster, bucket_name, scope_name, collection_name):\n    &quot;&quot;&quot;Delete all documents from the specified collection (Original Logic).&quot;&quot;&quot;\n    try:\n        logger.warning(f&quot;Attempting to clear all documents from `{bucket_name}`.`{scope_name}`.`{collection_name}`...&quot;)\n        query = f&quot;DELETE FROM `{bucket_name}`.`{scope_name}`.`{collection_name}`&quot;\n        result = cluster.query(query).execute()\n        # Try to get mutation count, handle if not available\n        mutation_count = 0\n        try:\n             metrics_data = result.meta_data().metrics()\n             if metrics_data:\n                  mutation_count = metrics_data.mutation_count()\n        except Exception as metrics_e:\n             logger.warning(f&quot;Could not retrieve mutation count after delete: {metrics_e}&quot;)\n        logger.info(f&quot;Successfully cleared documents from the collection (approx. {mutation_count} mutations).&quot;)\n    except Exception as e:\n        logger.error(f&quot;Error clearing documents from collection: {e}. Collection might be empty or index not ready.&quot;)\n<\/code><\/pre>\n\n\n\n<h4 id=\"h-3-7-createagentrole\" class=\"wp-block-heading\">3.7 create_agent_role<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">This function creates or updates the necessary IAM (Identity and Access Management) role that the Bedrock Agent and its associated Lambda function will assume. The role needs permissions to interact with AWS services on your behalf. Key aspects of this function are:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Assume Role Policy:<\/strong> Defines which AWS services (principals) are allowed to assume this role. In this case, it allows both <code>lambda.amazonaws.com<\/code> (for the Lambda function execution) and <code>bedrock.amazonaws.com<\/code> (for the Bedrock Agent service itself).<\/li>\n\n\n<li><strong>Idempotency:<\/strong> It first checks if a role with the specified <code>role_name<\/code> already exists.\n<ul>\n<li>If it exists, the function retrieves its ARN and updates its trust policy to ensure it matches the required configuration.<\/li>\n<li>If it doesn&#8217;t exist, it creates a new IAM role with the defined assume role policy and description.<\/li>\n<\/ul>\n<\/li>\n\n\n<li><strong>Permissions Policies:<\/strong>\n<ul>\n<li>Attaches the AWS managed policy <code>AWSLambdaBasicExecutionRole<\/code>, which grants the Lambda function permissions to write logs to CloudWatch.<\/li>\n<li>Creates and attaches an inline policy (<code>LambdaBasicLoggingPermissions<\/code>) for more specific logging permissions if needed, scoped to the Lambda log group.<\/li>\n<li>Creates and attaches an inline policy (<code>BedrockAgentPermissions<\/code>) granting broad <code>bedrock:*<\/code> permissions. For production, these permissions should be scoped down to the minimum required.<\/li>\n<\/ul>\n<\/li>\n\n\n<li><strong>Propagation Delays:<\/strong> Includes <code>time.sleep<\/code> calls after creating the role and after attaching policies to allow time for the changes to propagate within AWS, which helps prevent subsequent operations from failing due to eventual consistency issues.\nIt returns the ARN (Amazon Resource Name) of the created or updated IAM role, which is then used when creating the Bedrock Agent and the Lambda function.<\/li>\n\n<\/ul>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>def create_agent_role(iam_client, role_name, aws_account_id):\n    &quot;&quot;&quot;Creates or gets the IAM role for the Bedrock Agent Lambda functions.&quot;&quot;&quot;\n    logger.info(f&quot;Checking\/Creating IAM role: {role_name}&quot;)\n    assume_role_policy_document = {\n        &quot;Version&quot;: &quot;2012-10-17&quot;,\n        &quot;Statement&quot;: [\n            {\n                &quot;Effect&quot;: &quot;Allow&quot;,\n                &quot;Principal&quot;: {\n                    &quot;Service&quot;: [\n                        &quot;lambda.amazonaws.com&quot;,\n                        &quot;bedrock.amazonaws.com&quot; \n                    ]\n                },\n                &quot;Action&quot;: &quot;sts:AssumeRole&quot;\n            }\n        ]\n    }\n\n    role_arn = None\n    try:\n        # Check if role exists\n        get_role_response = iam_client.get_role(RoleName=role_name)\n        role_arn = get_role_response[&#039;Role&#039;][&#039;Arn&#039;]\n        logger.info(f&quot;IAM role &#039;{role_name}&#039; already exists with ARN: {role_arn}&quot;)\n        \n        # Ensure trust policy is up-to-date\n        logger.info(f&quot;Updating trust policy for existing role &#039;{role_name}&#039;...&quot;)\n        iam_client.update_assume_role_policy(\n            RoleName=role_name,\n            PolicyDocument=json.dumps(assume_role_policy_document)\n        )\n        logger.info(f&quot;Trust policy updated for role &#039;{role_name}&#039;.&quot;)\n\n    except iam_client.exceptions.NoSuchEntityException:\n        logger.info(f&quot;IAM role &#039;{role_name}&#039; not found. Creating...&quot;)\n        try:\n            create_role_response = iam_client.create_role(\n                RoleName=role_name,\n                AssumeRolePolicyDocument=json.dumps(assume_role_policy_document),\n                Description=&#039;IAM role for Bedrock Agent Lambda functions (Experiment)&#039;,\n                MaxSessionDuration=3600\n            )\n            role_arn = create_role_response[&#039;Role&#039;][&#039;Arn&#039;]\n            logger.info(f&quot;Successfully created IAM role &#039;{role_name}&#039; with ARN: {role_arn}&quot;)\n            # Wait after role creation before attaching policies\n            logger.info(&quot;Waiting 15s for role creation propagation...&quot;)\n            time.sleep(15)\n        except ClientError as e:\n            logger.error(f&quot;Error creating IAM role &#039;{role_name}&#039;: {e}&quot;)\n            raise\n            \n    except ClientError as e:\n        logger.error(f&quot;Error getting\/updating IAM role &#039;{role_name}&#039;: {e}&quot;)\n        raise\n        \n    # Attach basic execution policy (idempotent)\n    try:\n        logger.info(f&quot;Attaching basic Lambda execution policy to role &#039;{role_name}&#039;...&quot;)\n        iam_client.attach_role_policy(\n            RoleName=role_name,\n            PolicyArn=&#039;arn:aws:iam::aws:policy\/service-role\/AWSLambdaBasicExecutionRole&#039;\n        )\n        logger.info(&quot;Attached basic Lambda execution policy.&quot;)\n    except ClientError as e:\n        logger.error(f&quot;Error attaching basic Lambda execution policy: {e}&quot;)\n        # Don&#039;t necessarily raise, might already be attached or other issue\n        \n    # Add minimal inline policy for logging (can be expanded later if needed)\n    basic_inline_policy_name = &quot;LambdaBasicLoggingPermissions&quot;\n    basic_inline_policy_doc = {\n        &quot;Version&quot;: &quot;2012-10-17&quot;,\n        &quot;Statement&quot;: [\n            {\n                &quot;Effect&quot;: &quot;Allow&quot;,\n                &quot;Action&quot;: [\n                    &quot;logs:CreateLogGroup&quot;,\n                    &quot;logs:CreateLogStream&quot;,\n                    &quot;logs:PutLogEvents&quot;\n                ],\n                &quot;Resource&quot;: f&quot;arn:aws:logs:{AWS_REGION}:{aws_account_id}:log-group:\/aws\/lambda\/*:*&quot; # Scope down logs if possible\n            }\n            # Add S3 permissions here ONLY if Lambda code explicitly needs it\n        ]\n    }\n    \n    # Add Bedrock permissions policy\n    bedrock_policy_name = &quot;BedrockAgentPermissions&quot;\n    bedrock_policy_doc = {\n        &quot;Version&quot;: &quot;2012-10-17&quot;,\n        &quot;Statement&quot;: [\n            {\n                &quot;Effect&quot;: &quot;Allow&quot;,\n                &quot;Action&quot;: [\n                    &quot;bedrock:*&quot;\n                ],\n                &quot;Resource&quot;: &quot;*&quot;  # You can scope this down to specific agents\/models if needed\n            }\n        ]\n    }\n    try:\n        logger.info(f&quot;Putting basic inline policy &#039;{basic_inline_policy_name}&#039; for role &#039;{role_name}&#039;...&quot;)\n        iam_client.put_role_policy(\n            RoleName=role_name,\n            PolicyName=basic_inline_policy_name,\n            PolicyDocument=json.dumps(basic_inline_policy_doc)\n        )\n        logger.info(f&quot;Successfully put inline policy &#039;{basic_inline_policy_name}&#039;.&quot;)\n        \n        # Add Bedrock permissions policy\n        logger.info(f&quot;Putting Bedrock permissions policy &#039;{bedrock_policy_name}&#039; for role &#039;{role_name}&#039;...&quot;)\n        iam_client.put_role_policy(\n            RoleName=role_name,\n            PolicyName=bedrock_policy_name,\n            PolicyDocument=json.dumps(bedrock_policy_doc)\n        )\n        logger.info(f&quot;Successfully put inline policy &#039;{bedrock_policy_name}&#039;.&quot;)\n        \n        logger.info(&quot;Waiting 10s for policy changes to propagate...&quot;)\n        time.sleep(10)\n    except ClientError as e:\n        logger.error(f&quot;Error putting inline policy: {e}&quot;)\n        # Decide if this is fatal\n        \n    if not role_arn:\n         raise Exception(f&quot;Failed to create or retrieve ARN for role {role_name}&quot;)\n         \n    return role_arn\n<\/code><\/pre>\n\n\n\n<h4 id=\"h-3-8-lambda-deployment-functions\" class=\"wp-block-heading\">3.8 Lambda Deployment Functions<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">This subsection groups together several helper functions dedicated to managing the deployment lifecycle of the AWS Lambda function that will serve as the tool executor for the Bedrock Agent. These functions handle packaging the Lambda code, managing its dependencies, deploying it to AWS, and cleaning up resources.<\/p>\n\n\n\n<h5 id=\"h-3-8-1-deletelambdafunction\" class=\"wp-block-heading\">3.8.1 delete_lambda_function<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">This function is designed to safely delete an AWS Lambda function. Before attempting to delete the function itself, it tries to remove any permissions associated with it (specifically, the permission allowing Bedrock to invoke it, using a predictable statement ID). It then checks if the function exists and, if so, proceeds with the deletion. The function includes a brief pause after initiating deletion, as the process is asynchronous. It returns <code>True<\/code> if deletion was attempted\/occurred and <code>False<\/code> if the function didn&#8217;t exist or if an error occurred during the process.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>def delete_lambda_function(lambda_client, function_name):\n    &quot;&quot;&quot;Delete Lambda function if it exists, attempting to remove permissions first.&quot;&quot;&quot;\n    logger.info(f&quot;Attempting to delete Lambda function: {function_name}...&quot;)\n    try:\n        # Use a predictable statement ID added by create_lambda_function\n        statement_id = f&quot;AllowBedrockInvokeBasic-{function_name}&quot;\n        try:\n            logger.info(f&quot;Attempting to remove permission {statement_id} from {function_name}...&quot;)\n            lambda_client.remove_permission(\n                FunctionName=function_name,\n                StatementId=statement_id\n            )\n            logger.info(f&quot;Successfully removed permission {statement_id} from {function_name}.&quot;)\n            time.sleep(2) # Allow time for permission removal\n        except lambda_client.exceptions.ResourceNotFoundException:\n            logger.info(f&quot;Permission {statement_id} not found on {function_name}. Skipping removal.&quot;)\n        except ClientError as perm_e:\n            # Log error but continue with deletion attempt\n            logger.warning(f&quot;Error removing permission {statement_id} from {function_name}: {str(perm_e)}&quot;)\n\n        # Check if function exists before attempting deletion\n        lambda_client.get_function(FunctionName=function_name)\n        logger.info(f&quot;Function {function_name} exists. Deleting...&quot;)\n        lambda_client.delete_function(FunctionName=function_name)\n\n        # Wait for deletion to complete using a waiter\n        logger.info(f&quot;Waiting for {function_name} to be deleted...&quot;)\n        time.sleep(10) # Simple delay after delete call\n        logger.info(f&quot;Function {function_name} deletion initiated.&quot;)\n\n        return True # Indicates deletion was attempted\/occurred\n\n    except lambda_client.exceptions.ResourceNotFoundException:\n        logger.info(f&quot;Lambda function &#039;{function_name}&#039; does not exist. No need to delete.&quot;)\n        return False # Indicates function didn&#039;t exist\n    except Exception as e:\n        logger.error(f&quot;Error during deletion process for Lambda function &#039;{function_name}&#039;: {str(e)}&quot;)\n        # Depending on severity, might want to raise or just return False\n        return False # Indicates an error occurred beyond not found\n<\/code><\/pre>\n\n\n\n<h5 id=\"h-3-8-2-uploadtos3\" class=\"wp-block-heading\">3.8.2 upload_to_s3<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">This function handles uploading a Lambda deployment package (a .zip file) to Amazon S3. This is necessary when the package size exceeds the direct upload limit for Lambda. Key features include:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Bucket Management:<\/strong> It generates a unique S3 bucket name (prefixed with <code>lambda-deployment-<\/code>) using the AWS account ID and a timestamp, or a fallback UUID if the account ID isn&#8217;t available. It checks if this bucket exists and creates it if not, ensuring the correct region is specified for bucket creation. It also uses a waiter to ensure the bucket is available before proceeding.<\/li>\n\n\n<li><strong>S3 Key Generation:<\/strong> Creates a unique S3 key (object path) for the uploaded file, incorporating the original filename and a UUID to prevent collisions.<\/li>\n\n\n<li><strong>Multipart Upload:<\/strong> For large files (currently &gt; 100MB in the code, though the Lambda direct upload limit is typically around 50MB for the zip, and 250MB unzipped including layers, so S3 is used for packages over ~45-50MB in this notebook), it uses <code>boto3.s3.transfer.S3Transfer<\/code> for robust multipart uploads. For smaller files, it uses a standard <code>put_object<\/code> call.<\/li>\n\n\n<li><strong>Retry Configuration:<\/strong> Initializes the S3 and STS clients with a configuration that includes increased timeouts and retries for better resilience.\nIt returns a dictionary containing the <code>S3Bucket<\/code> and <code>S3Key<\/code> of the uploaded package, which is then used by the <code>create_lambda_function<\/code>.<\/li>\n\n<\/ul>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>def upload_to_s3(zip_file, region, bucket_name=None):\n    &quot;&quot;&quot;Upload zip file to S3 with retry logic and return S3 location.&quot;&quot;&quot;\n    logger.info(f&quot;Preparing to upload {zip_file} to S3 in region {region}...&quot;)\n    # Configure the client with increased timeouts\n    config = Config(\n        connect_timeout=60,\n        read_timeout=300,\n        retries={&#039;max_attempts&#039;: 3, &#039;mode&#039;: &#039;adaptive&#039;}\n    )\n\n    s3_client = boto3.client(&#039;s3&#039;, region_name=region, config=config)\n    sts_client = boto3.client(&#039;sts&#039;, region_name=region, config=config)\n\n    # Determine bucket name\n    if bucket_name is None:\n        try:\n            account_id = sts_client.get_caller_identity().get(&#039;Account&#039;)\n            timestamp = int(time.time())\n            bucket_name = f&quot;lambda-deployment-{account_id}-{timestamp}&quot;\n            logger.info(f&quot;Generated unique S3 bucket name: {bucket_name}&quot;)\n        except Exception as e:\n            fallback_id = uuid.uuid4().hex[:12]\n            bucket_name = f&quot;lambda-deployment-{fallback_id}&quot;\n            logger.warning(f&quot;Error getting account ID ({e}). Using fallback bucket name: {bucket_name}&quot;)\n\n    # Create bucket if needed\n    try:\n        s3_client.head_bucket(Bucket=bucket_name)\n        logger.info(f&quot;Using existing S3 bucket: {bucket_name}&quot;)\n    except ClientError as e:\n        error_code = int(e.response[&#039;Error&#039;][&#039;Code&#039;])\n        if error_code == 404:\n            logger.info(f&quot;Creating S3 bucket: {bucket_name}...&quot;)\n            try:\n                if region == &#039;us-east-1&#039;:\n                    s3_client.create_bucket(Bucket=bucket_name)\n                else:\n                    s3_client.create_bucket(\n                        Bucket=bucket_name,\n                        CreateBucketConfiguration={&#039;LocationConstraint&#039;: region}\n                    )\n                logger.info(f&quot;Created S3 bucket: {bucket_name}. Waiting for availability...&quot;)\n                waiter = s3_client.get_waiter(&#039;bucket_exists&#039;)\n                waiter.wait(Bucket=bucket_name, WaiterConfig={&#039;Delay&#039;: 5, &#039;MaxAttempts&#039;: 12})\n                logger.info(f&quot;Bucket {bucket_name} is available.&quot;)\n            except Exception as create_e:\n                logger.error(f&quot;Error creating bucket &#039;{bucket_name}&#039;: {create_e}&quot;)\n                raise\n        else:\n            logger.error(f&quot;Error checking bucket &#039;{bucket_name}&#039;: {e}&quot;)\n            raise\n\n    # Upload file\n    s3_key = f&quot;lambda\/{os.path.basename(zip_file)}-{uuid.uuid4().hex[:8]}&quot;\n    try:\n        logger.info(f&quot;Uploading {zip_file} to s3:\/\/{bucket_name}\/{s3_key}...&quot;)\n        file_size = os.path.getsize(zip_file)\n        if file_size &gt; 100 * 1024 * 1024:  # Use multipart for files &gt; 100MB\n            logger.info(&quot;Using multipart upload for large file...&quot;)\n            transfer_config = boto3.s3.transfer.TransferConfig(\n                multipart_threshold=10 * 1024 * 1024, max_concurrency=10,\n                multipart_chunksize=10 * 1024 * 1024, use_threads=True\n            )\n            s3_transfer = boto3.s3.transfer.S3Transfer(client=s3_client, config=transfer_config)\n            s3_transfer.upload_file(zip_file, bucket_name, s3_key)\n        else:\n            with open(zip_file, &#039;rb&#039;) as f:\n                s3_client.put_object(Bucket=bucket_name, Key=s3_key, Body=f)\n\n        logger.info(f&quot;Successfully uploaded to s3:\/\/{bucket_name}\/{s3_key}&quot;)\n        return {&#039;S3Bucket&#039;: bucket_name, &#039;S3Key&#039;: s3_key}\n\n    except Exception as upload_e:\n        logger.error(f&quot;S3 upload failed: {upload_e}&quot;)\n        raise\n<\/code><\/pre>\n\n\n\n<h5 id=\"h-3-8-3-packagefunction\" class=\"wp-block-heading\">3.8.3 package_function<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">This function automates the process of packaging the Lambda function code and its dependencies into a .zip file, ready for deployment. It relies on a <code>Makefile<\/code> located in the <code>source_dir<\/code> (which is <code>lambda_functions<\/code> in this notebook). The steps are:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Path Setup:<\/strong> Defines various paths for source files, the temporary packaging directory, the <code>Makefile<\/code>, and the final output .zip file.<\/li>\n\n\n<li><strong>File Preparation:<\/strong> It copies the specific Lambda handler script (e.g., <code>bedrock_agent_search_and_format.py<\/code>) to <code>lambda_function.py<\/code> within the <code>source_dir<\/code> because the <code>Makefile<\/code> is likely configured to look for a generic <code>lambda_function.py<\/code>.<\/li>\n\n\n<li><strong>Execute Makefile:<\/strong> It runs a <code>make clean package<\/code> command using <code>subprocess.check_call<\/code>. The <code>make<\/code> command is executed with the <code>source_dir<\/code> as its current working directory. The Makefile is responsible for creating a virtual environment, installing dependencies from <code>requirements.txt<\/code> into a temporary <code>package_dir<\/code>, and then zipping the contents of this directory along with <code>lambda_function.py<\/code> into <code>lambda_package.zip<\/code> within the <code>source_dir<\/code>.<\/li>\n\n\n<li><strong>Output Handling:<\/strong> After the <code>make<\/code> command successfully completes, it moves and renames the generated <code>lambda_package.zip<\/code> from the <code>source_dir<\/code> to the specified <code>build_dir<\/code> (the notebook&#8217;s current directory in this case) with a name like <code>function_name.zip<\/code>.<\/li>\n\n\n<li><strong>Cleanup:<\/strong> In a <code>finally<\/code> block, it cleans up the temporary <code>lambda_function.py<\/code> copied earlier and any intermediate <code>lambda_package.zip<\/code> left in the <code>source_dir<\/code> (e.g., if the rename\/move failed).\nThe function returns the path to the final .zip file.<\/li>\n\n<\/ol>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>def package_function(function_name, source_dir, build_dir):\n    &quot;&quot;&quot;Package Lambda function using Makefile found in source_dir.&quot;&quot;&quot;\n    # source_dir is where the .py, requirements.txt, Makefile live (e.g., lambda_functions)\n    # build_dir is where packaging happens and final zip ends up (e.g., lambda-experiments)\n    makefile_path = os.path.join(source_dir, &#039;Makefile&#039;)\n    # Temp build dir inside source_dir, as Makefile expects relative paths\n    temp_package_dir = os.path.join(source_dir, &#039;package_dir&#039;) \n    # Requirements file is in source_dir\n    source_req_path = os.path.join(source_dir, &#039;requirements.txt&#039;) \n    # Target requirements path inside source_dir (needed for Makefile)\n    # target_req_path = os.path.join(source_dir, &#039;requirements.txt&#039;) # No copy needed if running make in source_dir\n    source_func_script_path = os.path.join(source_dir, f&#039;{function_name}.py&#039;)\n    # Target function script path inside source_dir, renamed for Makefile install_deps copy\n    target_func_script_path = os.path.join(source_dir, &#039;lambda_function.py&#039;) \n    # Make output zip is created inside source_dir\n    make_output_zip = os.path.join(source_dir, &#039;lambda_package.zip&#039;) \n    # Final zip path is in the build_dir (one level up from source_dir)\n    final_zip_path = os.path.join(build_dir, f&#039;{function_name}.zip&#039;)\n\n    logger.info(f&quot;--- Packaging function {function_name} --- &quot;)\n    logger.info(f&quot;Source Dir (Makefile location &amp; make cwd): {source_dir}&quot;)\n    logger.info(f&quot;Build Dir (Final zip location): {build_dir}&quot;)\n\n    if not os.path.exists(source_func_script_path):\n        raise FileNotFoundError(f&quot;Source function script not found: {source_func_script_path}&quot;)\n    if not os.path.exists(source_req_path):\n        raise FileNotFoundError(f&quot;Source requirements file not found: {source_req_path}&quot;)\n    if not os.path.exists(makefile_path):\n        raise FileNotFoundError(f&quot;Makefile not found at: {makefile_path}&quot;)\n\n    # Ensure no leftover target script from previous failed run\n    if os.path.exists(target_func_script_path):\n        logger.warning(f&quot;Removing existing target script: {target_func_script_path}&quot;)\n        os.remove(target_func_script_path)\n\n    try:\n        # 1. No need to create lambda subdir in build_dir\n\n        # 2. Copy source function script to source_dir as lambda_function.py\n        logger.info(f&quot;Copying {source_func_script_path} to {target_func_script_path}&quot;)\n        shutil.copy(source_func_script_path, target_func_script_path)\n        # Requirements file is already in source_dir, no copy needed.\n\n        # 3. Run make command (execute from source_dir where Makefile is)\n        make_command = [\n            &#039;make&#039;,\n            &#039;-f&#039;, makefile_path, # Still specify Makefile path explicitly\n            &#039;clean&#039;, # Clean first\n            &#039;package&#039;,\n            # &#039;PYTHON_VERSION=python3.9&#039; # Let Makefile use its default or system default\n        ]\n        logger.info(f&quot;Running make command: {&#039; &#039;.join(make_command)} (in {source_dir})&quot;)\n        # Run make from source_dir; relative paths in Makefile should now work\n        subprocess.check_call(make_command, cwd=source_dir, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)\n        logger.info(&quot;Make command completed successfully.&quot;)\n\n        # 4. Check for output zip in source_dir and rename\/move to build_dir\n        if not os.path.exists(make_output_zip):\n            raise FileNotFoundError(f&quot;Makefile did not produce expected output: {make_output_zip}&quot;)\n\n        logger.info(f&quot;Moving and renaming {make_output_zip} to {final_zip_path}&quot;)\n        if os.path.exists(final_zip_path):\n             logger.warning(f&quot;Removing existing final zip: {final_zip_path}&quot;)\n             os.remove(final_zip_path)\n        # Use shutil.move for cross-filesystem safety if needed, os.rename is fine here\n        os.rename(make_output_zip, final_zip_path) \n        logger.info(f&quot;Zip file ready: {final_zip_path}&quot;)\n\n        return final_zip_path\n\n    except subprocess.CalledProcessError as e:\n        logger.error(f&quot;Error running Makefile for {function_name}: {e}&quot;)\n        stderr_output = &quot;(No stderr captured)&quot;\n        if e.stderr:\n             try:\n                  stderr_output = e.stderr.decode()\n             except Exception:\n                  stderr_output = &quot;(Could not decode stderr)&quot;\n        logger.error(f&quot;Make stderr: {stderr_output}&quot;)\n        raise\n    except Exception as e:\n        logger.error(f&quot;Error packaging function {function_name} using Makefile: {str(e)}&quot;)\n        logger.error(traceback.format_exc())\n        raise\n    finally:\n        # 5. Clean up intermediate files in source_dir\n        if os.path.exists(target_func_script_path):\n            logger.info(f&quot;Cleaning up temporary script: {target_func_script_path}&quot;)\n            os.remove(target_func_script_path)\n        if os.path.exists(make_output_zip): # If rename failed\n            logger.warning(f&quot;Cleaning up intermediate zip in source dir: {make_output_zip}&quot;)\n            os.remove(make_output_zip)\n<\/code><\/pre>\n\n\n\n<h5 id=\"h-3-8-4-createlambdafunction\" class=\"wp-block-heading\">3.8.4 create_lambda_function<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">This is a key function that handles the creation or update of the AWS Lambda function. It incorporates several important aspects for robustness and proper configuration:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Package Handling:<\/strong> It checks the size of the deployment .zip file. If it&#8217;s over a threshold (45MB in this code, as Lambda has limits for direct uploads), it calls <code>upload_to_s3<\/code> to upload the package to S3 and uses the S3 location for deployment. Otherwise, it reads the .zip file content directly for deployment.<\/li>\n\n\n<li><strong>Configuration:<\/strong> Defines common arguments for Lambda creation\/update, including the function name, runtime (<code>python3.9<\/code>), IAM role ARN, handler name, timeout, memory size, and crucial environment variables (Couchbase details, Bedrock model IDs) that the Lambda will need at runtime.<\/li>\n\n\n<li><strong>Idempotency &amp; Retry Logic:<\/strong> It first attempts to create the Lambda function.\n<ul>\n<li>If it encounters a <code>ResourceConflictException<\/code> (meaning the function already exists), it then attempts to update the function&#8217;s code and configuration.<\/li>\n<li>It includes a retry loop for both creation and update operations to handle potential throttling or other transient AWS issues, with an exponential backoff strategy.<\/li>\n<\/ul>\n<\/li>\n\n\n<li><strong>Permissions:<\/strong> After successfully creating or updating the Lambda, it adds a resource-based policy (permission) to the Lambda function. This permission specifically allows the Bedrock service (<code>bedrock.amazonaws.com<\/code>) to invoke this Lambda function. It uses a predictable <code>StatementId<\/code> and handles potential conflicts if the permission already exists.<\/li>\n\n\n<li><strong>Waiters:<\/strong> It uses <code>boto3<\/code> waiters (<code>function_active_v2<\/code> after creation, <code>function_updated_v2<\/code> after update) to pause execution until the Lambda function becomes fully active and ready, preventing issues where subsequent operations might target a Lambda that isn&#8217;t fully initialized.\nThe function returns the ARN of the successfully created or updated Lambda function.<\/li>\n\n<\/ul>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>def create_lambda_function(lambda_client, function_name, handler, role_arn, zip_file, region):\n    &quot;&quot;&quot;Create or update Lambda function with retry logic.&quot;&quot;&quot;\n    logger.info(f&quot;Deploying Lambda function {function_name} from {zip_file}...&quot;)\n\n    # Configure the client with increased timeouts for potentially long creation\n    config = Config(\n        connect_timeout=120,\n        read_timeout=300,\n        retries={&#039;max_attempts&#039;: 5, &#039;mode&#039;: &#039;adaptive&#039;}\n    )\n    lambda_client_local = boto3.client(&#039;lambda&#039;, region_name=region, config=config)\n\n    # Check zip file size\n    zip_size_mb = 0\n    try:\n        zip_size_bytes = os.path.getsize(zip_file)\n        zip_size_mb = zip_size_bytes \/ (1024 * 1024)\n        logger.info(f&quot;Zip file size: {zip_size_mb:.2f} MB&quot;)\n    except OSError as e:\n         logger.error(f&quot;Could not get size of zip file {zip_file}: {e}&quot;)\n         raise # Cannot proceed without zip file\n\n    use_s3 = zip_size_mb &gt; 45 # Use S3 for packages over ~45MB\n    s3_location = None\n    zip_content = None\n\n    if use_s3:\n        logger.info(f&quot;Package size ({zip_size_mb:.2f} MB) requires S3 deployment.&quot;)\n        s3_location = upload_to_s3(zip_file, region)\n        if not s3_location:\n             raise Exception(&quot;Failed to upload Lambda package to S3.&quot;)\n    else:\n         logger.info(&quot;Deploying package directly.&quot;)\n         try:\n             with open(zip_file, &#039;rb&#039;) as f:\n                 zip_content = f.read()\n         except OSError as e:\n              logger.error(f&quot;Could not read zip file {zip_file}: {e}&quot;)\n              raise\n\n    # Define common create\/update args\n    common_args = {\n        &#039;FunctionName&#039;: function_name,\n        &#039;Runtime&#039;: &#039;python3.9&#039;,\n        &#039;Role&#039;: role_arn,\n        &#039;Handler&#039;: handler,\n        &#039;Timeout&#039;: 180,\n        &#039;MemorySize&#039;: 1536, # Adjust as needed\n        # Env vars loaded from main script env or .env\n        &#039;Environment&#039;: {\n            &#039;Variables&#039;: {\n                &#039;CB_HOST&#039;: os.getenv(&#039;CB_HOST&#039;, &#039;couchbase:\/\/localhost&#039;),\n                &#039;CB_USERNAME&#039;: os.getenv(&#039;CB_USERNAME&#039;, &#039;Administrator&#039;),\n                &#039;CB_PASSWORD&#039;: os.getenv(&#039;CB_PASSWORD&#039;, &#039;password&#039;),\n                &#039;CB_BUCKET_NAME&#039;: os.getenv(&#039;CB_BUCKET_NAME&#039;, &#039;vector-search-exp&#039;),\n                &#039;SCOPE_NAME&#039;: os.getenv(&#039;SCOPE_NAME&#039;, &#039;bedrock_exp&#039;),\n                &#039;COLLECTION_NAME&#039;: os.getenv(&#039;COLLECTION_NAME&#039;, &#039;docs_exp&#039;),\n                &#039;INDEX_NAME&#039;: os.getenv(&#039;INDEX_NAME&#039;, &#039;vector_search_bedrock_exp&#039;),\n                &#039;EMBEDDING_MODEL_ID&#039;: os.getenv(&#039;EMBEDDING_MODEL_ID&#039;, EMBEDDING_MODEL_ID),\n                &#039;AGENT_MODEL_ID&#039;: os.getenv(&#039;AGENT_MODEL_ID&#039;, AGENT_MODEL_ID)\n            }\n        }\n    }\n\n    if use_s3:\n        code_arg = {&#039;S3Bucket&#039;: s3_location[&#039;S3Bucket&#039;], &#039;S3Key&#039;: s3_location[&#039;S3Key&#039;]}\n    else:\n        code_arg = {&#039;ZipFile&#039;: zip_content}\n\n    max_retries = 3\n    base_delay = 10\n    for attempt in range(1, max_retries + 1):\n        try:\n            logger.info(f&quot;Creating function &#039;{function_name}&#039; (attempt {attempt}\/{max_retries})...&quot;)\n            create_args = common_args.copy()\n            create_args[&#039;Code&#039;] = code_arg\n            create_args[&#039;Publish&#039;] = True # Publish a version\n\n            create_response = lambda_client_local.create_function(**create_args)\n            function_arn = create_response[&#039;FunctionArn&#039;]\n            logger.info(f&quot;Successfully created function &#039;{function_name}&#039; with ARN: {function_arn}&quot;)\n\n            # Add basic invoke permission after creation\n            time.sleep(5) # Give function time to be fully created before adding policy\n            statement_id = f&quot;AllowBedrockInvokeBasic-{function_name}&quot;\n            try:\n                logger.info(f&quot;Adding basic invoke permission ({statement_id}) to {function_name}...&quot;)\n                lambda_client_local.add_permission(\n                    FunctionName=function_name,\n                    StatementId=statement_id,\n                    Action=&#039;lambda:InvokeFunction&#039;,\n                    Principal=&#039;bedrock.amazonaws.com&#039;\n                )\n                logger.info(f&quot;Successfully added basic invoke permission {statement_id}.&quot;)\n            except lambda_client_local.exceptions.ResourceConflictException:\n                 logger.info(f&quot;Permission {statement_id} already exists for {function_name}. Skipping add.&quot;)\n            except ClientError as perm_e:\n                logger.warning(f&quot;Failed to add basic invoke permission {statement_id} to {function_name}: {perm_e}&quot;)\n\n            # Wait for function to be Active\n            logger.info(f&quot;Waiting for function &#039;{function_name}&#039; to become active...&quot;)\n            waiter = lambda_client_local.get_waiter(&#039;function_active_v2&#039;)\n            waiter.wait(FunctionName=function_name, WaiterConfig={&#039;Delay&#039;: 5, &#039;MaxAttempts&#039;: 24})\n            logger.info(f&quot;Function &#039;{function_name}&#039; is active.&quot;)\n\n            return function_arn # Return ARN upon successful creation\n\n        except lambda_client_local.exceptions.ResourceConflictException:\n             logger.warning(f&quot;Function &#039;{function_name}&#039; already exists. Attempting to update code...&quot;)\n             try:\n                 if use_s3:\n                     update_response = lambda_client_local.update_function_code(\n                         FunctionName=function_name,\n                         S3Bucket=s3_location[&#039;S3Bucket&#039;],\n                         S3Key=s3_location[&#039;S3Key&#039;],\n                         Publish=True\n                     )\n                 else:\n                     update_response = lambda_client_local.update_function_code(\n                         FunctionName=function_name,\n                         ZipFile=zip_content,\n                         Publish=True\n                     )\n                 function_arn = update_response[&#039;FunctionArn&#039;]\n                 logger.info(f&quot;Successfully updated function code for &#039;{function_name}&#039;. New version ARN: {function_arn}&quot;)\n                 \n                 # Also update configuration just in case\n                 try:\n                      logger.info(f&quot;Updating configuration for &#039;{function_name}&#039;...&quot;)\n                      lambda_client_local.update_function_configuration(**common_args)\n                      logger.info(f&quot;Configuration updated for &#039;{function_name}&#039;.&quot;)\n                 except ClientError as conf_e:\n                      logger.warning(f&quot;Could not update configuration for &#039;{function_name}&#039;: {conf_e}&quot;)\n                 \n                 # Re-verify invoke permission after update\n                 time.sleep(5)\n                 statement_id = f&quot;AllowBedrockInvokeBasic-{function_name}&quot;\n                 try:\n                     logger.info(f&quot;Verifying\/Adding basic invoke permission ({statement_id}) after update...&quot;)\n                     lambda_client_local.add_permission(\n                         FunctionName=function_name,\n                         StatementId=statement_id,\n                         Action=&#039;lambda:InvokeFunction&#039;,\n                         Principal=&#039;bedrock.amazonaws.com&#039;\n                     )\n                     logger.info(f&quot;Successfully added\/verified basic invoke permission {statement_id}.&quot;)\n                 except lambda_client_local.exceptions.ResourceConflictException:\n                     logger.info(f&quot;Permission {statement_id} already exists for {function_name}. Skipping add.&quot;)\n                 except ClientError as perm_e:\n                     logger.warning(f&quot;Failed to add\/verify basic invoke permission {statement_id} after update: {perm_e}&quot;)\n\n                 # Wait for function to be Active after update\n                 logger.info(f&quot;Waiting for function &#039;{function_name}&#039; update to complete...&quot;)\n                 waiter = lambda_client_local.get_waiter(&#039;function_updated_v2&#039;)\n                 waiter.wait(FunctionName=function_name, WaiterConfig={&#039;Delay&#039;: 5, &#039;MaxAttempts&#039;: 24})\n                 logger.info(f&quot;Function &#039;{function_name}&#039; update complete.&quot;)\n                 \n                 return function_arn # Return ARN after successful update\n\n             except ClientError as update_e:\n                 logger.error(f&quot;Failed to update function &#039;{function_name}&#039;: {update_e}&quot;)\n                 if attempt &lt; max_retries:\n                      delay = base_delay * (2 ** (attempt - 1))\n                      logger.info(f&quot;Retrying update in {delay} seconds...&quot;)\n                      time.sleep(delay)\n                 else:\n                      logger.error(&quot;Maximum update retries reached. Deployment failed.&quot;)\n                      raise update_e\n                      \n        except ClientError as e:\n            # Handle throttling or other retryable errors\n            error_code = e.response.get(&#039;Error&#039;, {}).get(&#039;Code&#039;)\n            if error_code in [&#039;ThrottlingException&#039;, &#039;ProvisionedConcurrencyConfigNotFoundException&#039;, &#039;EC2ThrottledException&#039;] or &#039;Rate exceeded&#039; in str(e):\n                logger.warning(f&quot;Retryable error on attempt {attempt}: {e}&quot;)\n                if attempt &lt; max_retries:\n                    delay = base_delay * (2 ** (attempt - 1)) + (uuid.uuid4().int % 5)\n                    logger.info(f&quot;Retrying in {delay} seconds...&quot;)\n                    time.sleep(delay)\n                else:\n                    logger.error(&quot;Maximum retries reached after retryable error. Deployment failed.&quot;)\n                    raise e\n            else:\n                logger.error(f&quot;Error creating\/updating Lambda &#039;{function_name}&#039;: {e}&quot;)\n                logger.error(traceback.format_exc()) # Log full traceback for unexpected errors\n                raise e # Re-raise non-retryable or unexpected errors\n        except Exception as e:\n             logger.error(f&quot;Unexpected error during Lambda deployment: {e}&quot;)\n             logger.error(traceback.format_exc())\n             raise e\n             \n    # If loop completes without returning, something went wrong\n    raise Exception(f&quot;Failed to deploy Lambda function {function_name} after {max_retries} attempts.&quot;)\n<\/code><\/pre>\n\n\n\n<h4 id=\"h-3-9-agent-resource-deletion-functions\" class=\"wp-block-heading\">3.9 Agent Resource Deletion Functions<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">This subsection provides helper functions to manage the cleanup of AWS Bedrock Agent resources. Creating agents, action groups, and aliases results in persistent configurations in AWS. These functions are essential for maintaining a clean environment, especially during experimentation and development, by allowing for the removal of these resources when they are no longer needed or before recreating them in a subsequent run.<\/p>\n\n\n\n<h5 id=\"h-3-9-1-getagentbyname\" class=\"wp-block-heading\">3.9.1 get_agent_by_name<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">This utility function searches for an existing Bedrock Agent by its name. Since the AWS SDK&#8217;s <code>get_agent<\/code> requires an <code>agentId<\/code>, and you often work with human-readable names, this function bridges that gap. It uses the <code>list_agents<\/code> operation (with a paginator to handle potentially many agents in an account) and iterates through the summaries, comparing the <code>agentName<\/code> field. If a match is found, it returns the corresponding <code>agentId<\/code>. If no agent with the given name is found or an error occurs during listing, it returns <code>None<\/code>.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>def get_agent_by_name(agent_client, agent_name):\n    &quot;&quot;&quot;Find an agent ID by its name using list_agents.&quot;&quot;&quot;\n    logger.info(f&quot;Attempting to find agent by name: {agent_name}&quot;)\n    try:\n        paginator = agent_client.get_paginator(&#039;list_agents&#039;)\n        for page in paginator.paginate():\n            for agent_summary in page.get(&#039;agentSummaries&#039;, []):\n                if agent_summary.get(&#039;agentName&#039;) == agent_name:\n                    agent_id = agent_summary.get(&#039;agentId&#039;)\n                    logger.info(f&quot;Found agent &#039;{agent_name}&#039; with ID: {agent_id}&quot;)\n                    return agent_id\n        logger.info(f&quot;Agent &#039;{agent_name}&#039; not found.&quot;)\n        return None\n    except ClientError as e:\n        logger.error(f&quot;Error listing agents to find &#039;{agent_name}&#039;: {e}&quot;)\n        return None # Treat as not found if error occurs\n<\/code><\/pre>\n\n\n\n<h5 id=\"h-3-9-2-deleteactiongroup\" class=\"wp-block-heading\">3.9.2 delete_action_group<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">This function handles the deletion of a specific action group associated with a Bedrock Agent. Action groups are always tied to the <code>DRAFT<\/code> version of an agent. It calls <code>delete_agent_action_group<\/code>, providing the <code>agentId<\/code>, <code>agentVersion='DRAFT'<\/code>, and the <code>actionGroupId<\/code>. It uses <code>skipResourceInUseCheck=True<\/code> to force deletion, which can be useful if the agent is in a state (like <code>PREPARING<\/code>) that might otherwise prevent immediate deletion. The function includes error handling for cases where the action group is not found or if a conflict occurs (e.g., agent is busy), attempting a retry after a delay in case of a conflict. It returns <code>True<\/code> if deletion was successful or the group was not found, and <code>False<\/code> if an unrecoverable error occurred.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>def delete_action_group(agent_client, agent_id, action_group_id):\n    &quot;&quot;&quot;Deletes a specific action group for an agent.&quot;&quot;&quot;\n    logger.info(f&quot;Attempting to delete action group {action_group_id} for agent {agent_id}...&quot;)\n    try:\n        agent_client.delete_agent_action_group(\n            agentId=agent_id,\n            agentVersion=&#039;DRAFT&#039;, # Action groups are tied to the DRAFT version\n            actionGroupId=action_group_id,\n            skipResourceInUseCheck=True # Force deletion even if in use (e.g., during prepare)\n        )\n        logger.info(f&quot;Successfully deleted action group {action_group_id} for agent {agent_id}.&quot;)\n        time.sleep(5) # Short pause after deletion\n        return True\n    except agent_client.exceptions.ResourceNotFoundException:\n        logger.info(f&quot;Action group {action_group_id} not found for agent {agent_id}. Skipping deletion.&quot;)\n        return False\n    except ClientError as e:\n        # Handle potential throttling or conflict if prepare is happening\n        error_code = e.response.get(&#039;Error&#039;, {}).get(&#039;Code&#039;)\n        if error_code == &#039;ConflictException&#039;:\n            logger.warning(f&quot;Conflict deleting action group {action_group_id} (agent might be preparing\/busy). Retrying once after delay...&quot;)\n            time.sleep(15)\n            try:\n                agent_client.delete_agent_action_group(\n                    agentId=agent_id, agentVersion=&#039;DRAFT&#039;, actionGroupId=action_group_id, skipResourceInUseCheck=True\n                )\n                logger.info(f&quot;Successfully deleted action group {action_group_id} after retry.&quot;)\n                return True\n            except Exception as retry_e:\n                 logger.error(f&quot;Error deleting action group {action_group_id} on retry: {retry_e}&quot;)\n                 return False\n        else:\n            logger.error(f&quot;Error deleting action group {action_group_id} for agent {agent_id}: {e}&quot;)\n            return False\n<\/code><\/pre>\n\n\n\n<h5 id=\"h-3-9-3-deleteagentandresources\" class=\"wp-block-heading\">3.9.3 delete_agent_and_resources<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">This function orchestrates the complete cleanup of a Bedrock Agent and its associated components. Its process is:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Find Agent:<\/strong> It first calls <code>get_agent_by_name<\/code> to retrieve the <code>agentId<\/code> for the specified <code>agent_name<\/code>. If the agent isn&#8217;t found, it exits gracefully.<\/li>\n\n\n<li><strong>Delete Action Groups:<\/strong> It lists all action groups associated with the <code>DRAFT<\/code> version of the agent. For each action group found, it calls <code>delete_action_group<\/code> to remove it.<\/li>\n\n\n<li><strong>Delete Agent:<\/strong> After attempting to delete all action groups, it proceeds to delete the agent itself using <code>delete_agent<\/code> with <code>skipResourceInUseCheck=True<\/code> to force the deletion.<\/li>\n\n\n<li><strong>Wait for Deletion:<\/strong> It includes a custom polling loop to wait for the agent to be fully deleted by repeatedly calling <code>get_agent<\/code> and checking for a <code>ResourceNotFoundException<\/code>. This ensures that subsequent operations (like recreating an agent with the same name) are less likely to encounter conflicts.<\/li>\n\n<\/ol>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>def delete_agent_and_resources(agent_client, agent_name):\n    &quot;&quot;&quot;Deletes the agent and its associated action groups.&quot;&quot;&quot;\n    agent_id = get_agent_by_name(agent_client, agent_name)\n    if not agent_id:\n        logger.info(f&quot;Agent &#039;{agent_name}&#039; not found, no deletion needed.&quot;)\n        return\n\n    logger.warning(f&quot;--- Deleting Agent Resources for &#039;{agent_name}&#039; (ID: {agent_id}) ---&quot;)\n\n    # 1. Delete Action Groups\n    try:\n        logger.info(f&quot;Listing action groups for agent {agent_id}...&quot;)\n        action_groups = agent_client.list_agent_action_groups(\n            agentId=agent_id,\n            agentVersion=&#039;DRAFT&#039; # List groups for the DRAFT version\n        ).get(&#039;actionGroupSummaries&#039;, [])\n\n        if action_groups:\n            logger.info(f&quot;Found {len(action_groups)} action groups to delete.&quot;)\n            for ag in action_groups:\n                delete_action_group(agent_client, agent_id, ag[&#039;actionGroupId&#039;])\n        else:\n            logger.info(&quot;No action groups found to delete.&quot;)\n\n    except ClientError as e:\n        logger.error(f&quot;Error listing action groups for agent {agent_id}: {e}&quot;)\n        # Continue to agent deletion attempt even if listing fails\n\n    # 2. Delete the Agent\n    try:\n        logger.info(f&quot;Attempting to delete agent {agent_id} (&#039;{agent_name}&#039;)...&quot;)\n        agent_client.delete_agent(agentId=agent_id, skipResourceInUseCheck=True) # Force delete\n\n        # Wait for agent deletion (custom waiter logic might be needed if no standard waiter)\n        logger.info(f&quot;Waiting up to 2 minutes for agent {agent_id} deletion...&quot;)\n        deleted = False\n        for _ in range(24): # Check every 5 seconds for 2 minutes\n            try:\n                agent_client.get_agent(agentId=agent_id)\n                time.sleep(5)\n            except agent_client.exceptions.ResourceNotFoundException:\n                logger.info(f&quot;Agent {agent_id} successfully deleted.&quot;)\n                deleted = True\n                break\n            except ClientError as e:\n                 # Handle potential throttling during check\n                 error_code = e.response.get(&#039;Error&#039;, {}).get(&#039;Code&#039;)\n                 if error_code == &#039;ThrottlingException&#039;:\n                     logger.warning(&quot;Throttled while checking agent deletion status, continuing wait...&quot;)\n                     time.sleep(10)\n                 else:\n                     logger.error(f&quot;Error checking agent deletion status: {e}&quot;)\n                     # Break checking loop on unexpected error\n                     break\n        if not deleted:\n             logger.warning(f&quot;Agent {agent_id} deletion confirmation timed out.&quot;)\n\n    except agent_client.exceptions.ResourceNotFoundException:\n        logger.info(f&quot;Agent {agent_id} (&#039;{agent_name}&#039;) already deleted or not found.&quot;)\n    except ClientError as e:\n        logger.error(f&quot;Error deleting agent {agent_id}: {e}&quot;)\n\n    logger.info(f&quot;--- Agent Resource Deletion Complete for &#039;{agent_name}&#039; ---&quot;)\n<\/code><\/pre>\n\n\n\n<h4 id=\"h-3-10-agent-creation-functions\" class=\"wp-block-heading\">3.10 Agent Creation Functions<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">This subsection contains functions dedicated to the setup and configuration of the Bedrock Agent itself, including its core definition, action groups that link it to tools (Lambda functions), and the preparation process that makes it ready for invocation.<\/p>\n\n\n\n<h5 id=\"h-3-10-1-createagent\" class=\"wp-block-heading\">3.10.1 create_agent<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">This function creates a new Bedrock Agent. It takes the desired <code>agent_name<\/code>, the <code>agent_role_arn<\/code> (obtained from <code>create_agent_role<\/code>), and the <code>foundation_model_id<\/code> (e.g., for Claude Sonnet) as input. Key configurations include:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Instruction:<\/strong> A detailed prompt that defines the agent&#8217;s persona, capabilities, and how it should use its tools. The instruction in this notebook guides the agent to use a single &#8220;SearchAndFormat&#8221; tool and present results directly.<\/li>\n\n\n<li><strong><code>idleSessionTTLInSeconds<\/code>:<\/strong> Sets a timeout for how long an agent session can remain idle.<\/li>\n\n\n<li><strong>Description:<\/strong> A brief description for the agent.\nAfter calling <code>create_agent<\/code>, the function logs the initial response details (ID, ARN, status). It then enters a polling loop to wait until the agent&#8217;s status moves out of the <code>CREATING<\/code> state, typically to <code>NOT_PREPARED<\/code>. If the agent creation fails and enters a <code>FAILED<\/code> state, it raises an exception. It returns the <code>agent_id<\/code> and <code>agent_arn<\/code> upon successful initiation of creation.<\/li>\n\n<\/ul>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>def create_agent(agent_client, agent_name, agent_role_arn, foundation_model_id):\n    &quot;&quot;&quot;Creates a new Bedrock Agent.&quot;&quot;&quot;\n    logger.info(f&quot;--- Creating Agent: {agent_name} ---&quot;)\n    try:\n        # Updated Instruction for single tool\n        instruction = (\n            &quot;You are a helpful research assistant. Your primary function is to use the SearchAndFormat tool &quot;\n            &quot;to find relevant documents based on user queries and format them. &quot; \n            &quot;Use the user&#039;s query for the search, and specify a formatting style if requested, otherwise use the default. &quot;\n            &quot;Present the formatted results returned by the tool directly to the user.&quot;\n            &quot;Only use the tool provided. Do not add your own knowledge.&quot;\n        )\n\n        response = agent_client.create_agent(\n            agentName=agent_name,\n            agentResourceRoleArn=agent_role_arn,\n            foundationModel=foundation_model_id,\n            instruction=instruction,\n            idleSessionTTLInSeconds=1800, # 30 minutes\n            description=f&quot;Experimental agent for Couchbase search and content formatting ({foundation_model_id})&quot;\n            # promptOverrideConfiguration={} # Optional: Add later if needed\n        )\n        agent_info = response.get(&#039;agent&#039;)\n        agent_id = agent_info.get(&#039;agentId&#039;)\n        agent_arn = agent_info.get(&#039;agentArn&#039;)\n        agent_status = agent_info.get(&#039;agentStatus&#039;)\n        logger.info(f&quot;Agent creation initiated. Name: {agent_name}, ID: {agent_id}, ARN: {agent_arn}, Status: {agent_status}&quot;)\n\n        # Wait for agent to become NOT_PREPARED (initial state after creation)\n        # Using custom waiter logic as there might not be a standard one for this transition\n        logger.info(f&quot;Waiting for agent {agent_id} to reach initial state...&quot;)\n        for _ in range(12): # Check for up to 1 minute\n             current_status = agent_client.get_agent(agentId=agent_id)[&#039;agent&#039;][&#039;agentStatus&#039;]\n             logger.info(f&quot;Agent {agent_id} status: {current_status}&quot;)\n             if current_status != &#039;CREATING&#039;: # Expect NOT_PREPARED or FAILED\n                  break\n             time.sleep(5)\n\n        final_status = agent_client.get_agent(agentId=agent_id)[&#039;agent&#039;][&#039;agentStatus&#039;]\n        if final_status == &#039;FAILED&#039;:\n            logger.error(f&quot;Agent {agent_id} creation failed.&quot;)\n            # Optionally retrieve failure reasons if API provides them\n            raise Exception(f&quot;Agent creation failed for {agent_name}&quot;)\n        else:\n             logger.info(f&quot;Agent {agent_id} successfully created (Status: {final_status}).&quot;)\n             \n        return agent_id, agent_arn\n\n    except ClientError as e:\n        logger.error(f&quot;Error creating agent &#039;{agent_name}&#039;: {e}&quot;)\n        raise\n<\/code><\/pre>\n\n\n\n<h5 id=\"h-3-10-2-createactiongroup\" class=\"wp-block-heading\">3.10.2 create_action_group<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">This function creates or updates an action group for the specified agent. Action groups define the tools an agent can use. In this Lambda-based approach, the action group links the agent to the Lambda function that implements the tool. Key steps include:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Function Schema Definition:<\/strong> It programmatically defines a <code>function_schema_details<\/code> dictionary. This schema describes the tool (<code>searchAndFormatDocuments<\/code>) that the Lambda function provides, including its name, description, and expected input parameters (<code>query<\/code>, <code>k<\/code>, <code>style<\/code>) with their types and whether they are required. This schema is what the agent uses to understand how to invoke the tool.<\/li>\n\n\n<li><strong>Idempotency:<\/strong> It first checks if an action group with the given <code>action_group_name<\/code> already exists for the <code>DRAFT<\/code> version of the agent.\n<ul>\n<li>If it exists, it attempts to update the existing action group using <code>update_agent_action_group<\/code>, ensuring the <code>actionGroupExecutor<\/code> points to the correct Lambda ARN and that it uses the <code>functionSchema<\/code> (for defining the tool via its signature) rather than an OpenAPI schema.<\/li>\n<li>If it doesn&#8217;t exist, it creates a new action group using <code>create_agent_action_group<\/code>.<\/li>\n<\/ul>\n<\/li>\n\n\n<li><strong><code>actionGroupExecutor<\/code>:<\/strong> This is set to <code>{'lambda': function_arn}<\/code>, where <code>function_arn<\/code> is the ARN of the deployed Lambda function. This tells Bedrock to invoke this Lambda when the agent decides to use a tool from this action group.<\/li>\n\n\n<li><strong><code>functionSchema<\/code> Parameter:<\/strong> The <code>functionSchema<\/code> (containing the <code>function_schema_details<\/code>) is provided to the <code>create_agent_action_group<\/code> or <code>update_agent_action_group<\/code> call. This method of defining tools is simpler for single functions compared to providing a full OpenAPI schema, which is also an option for more complex APIs.<\/li>\n\n\n<li><strong>State:<\/strong> The action group is explicitly set to <code>ENABLED<\/code>.\nA brief pause is added after creation\/update to allow changes to propagate. The function returns the <code>actionGroupId<\/code>.<\/li>\n\n<\/ul>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>def create_action_group(agent_client, agent_id, action_group_name, function_arn, schema_path=None):\n    &quot;&quot;&quot;Creates an action group for the agent using Define with function details.&quot;&quot;&quot;\n    logger.info(f&quot;--- Creating\/Updating Action Group (Function Details): {action_group_name} for Agent: {agent_id} ---&quot;)\n    logger.info(f&quot;Lambda ARN: {function_arn}&quot;)\n\n    # Define function schema details (for functionSchema parameter)\n    function_schema_details = {\n        &#039;functions&#039;: [\n            {\n                &#039;name&#039;: &#039;searchAndFormatDocuments&#039;, # Function name agent will call\n                &#039;description&#039;: &#039;Performs vector search based on query, retrieves documents, and formats results using specified style.&#039;,\n                &#039;parameters&#039;: {\n                    &#039;query&#039;: {\n                        &#039;description&#039;: &#039;The search query text.&#039;,\n                        &#039;type&#039;: &#039;string&#039;,\n                        &#039;required&#039;: True\n                    },\n                    &#039;k&#039;: {\n                        &#039;description&#039;: &#039;The maximum number of documents to retrieve.&#039;,\n                        &#039;type&#039;: &#039;integer&#039;,\n                        &#039;required&#039;: False # Making optional as Lambda has default\n                    },\n                    &#039;style&#039;: {\n                        &#039;description&#039;: &#039;The desired formatting style for the results (e.g., &#039;bullet points&#039;, &#039;paragraph&#039;, &#039;summary&#039;).&#039;,\n                        &#039;type&#039;: &#039;string&#039;,\n                        &#039;required&#039;: False # Making optional as Lambda has default\n                    }\n                }\n            }\n        ]\n    }\n\n    try:\n        # Check if Action Group already exists for the DRAFT version\n        try:\n             logger.info(f&quot;Checking if action group &#039;{action_group_name}&#039; already exists for agent {agent_id} DRAFT version...&quot;)\n             paginator = agent_client.get_paginator(&#039;list_agent_action_groups&#039;)\n             existing_group = None\n             for page in paginator.paginate(agentId=agent_id, agentVersion=&#039;DRAFT&#039;):\n                 for ag_summary in page.get(&#039;actionGroupSummaries&#039;, []):\n                      if ag_summary.get(&#039;actionGroupName&#039;) == action_group_name:\n                           existing_group = ag_summary\n                           break\n                 if existing_group:\n                      break\n             \n             if existing_group:\n                 ag_id = existing_group[&#039;actionGroupId&#039;]\n                 logger.warning(f&quot;Action Group &#039;{action_group_name}&#039; (ID: {ag_id}) already exists for agent {agent_id} DRAFT. Attempting update to Function Details.&quot;)\n                 # Update existing action group - REMOVE apiSchema, ADD functionSchema\n                 response = agent_client.update_agent_action_group(\n                     agentId=agent_id,\n                     agentVersion=&#039;DRAFT&#039;,\n                     actionGroupId=ag_id,\n                     actionGroupName=action_group_name,\n                     actionGroupExecutor={&#039;lambda&#039;: function_arn},\n                     functionSchema={ # Use functionSchema\n                         &#039;functions&#039;: function_schema_details[&#039;functions&#039;] # Pass the list with the correct key\n                     },\n                     actionGroupState=&#039;ENABLED&#039;\n                 )\n                 ag_info = response.get(&#039;agentActionGroup&#039;)\n                 logger.info(f&quot;Successfully updated Action Group &#039;{action_group_name}&#039; (ID: {ag_info.get(&#039;actionGroupId&#039;)}) to use Function Details.&quot;)\n                 return ag_info.get(&#039;actionGroupId&#039;)\n             else:\n                  logger.info(f&quot;Action group &#039;{action_group_name}&#039; does not exist. Creating new with Function Details.&quot;)\n\n        except ClientError as e:\n             logger.error(f&quot;Error checking for existing action group &#039;{action_group_name}&#039;: {e}. Proceeding with creation attempt.&quot;)\n\n\n        # Create new action group if not found or update failed implicitly\n        response = agent_client.create_agent_action_group(\n            agentId=agent_id,\n            agentVersion=&#039;DRAFT&#039;, \n            actionGroupName=action_group_name,\n            actionGroupExecutor={\n                &#039;lambda&#039;: function_arn \n            },\n            functionSchema={ # Use functionSchema\n                 &#039;functions&#039;: function_schema_details[&#039;functions&#039;] # Pass the list with the correct key\n            },\n            actionGroupState=&#039;ENABLED&#039; \n        )\n        ag_info = response.get(&#039;agentActionGroup&#039;)\n        ag_id = ag_info.get(&#039;actionGroupId&#039;)\n        logger.info(f&quot;Successfully created Action Group &#039;{action_group_name}&#039; with ID: {ag_id} using Function Details.&quot;)\n        time.sleep(5) # Pause after creation\/update\n        return ag_id\n\n    except ClientError as e:\n        logger.error(f&quot;Error creating\/updating action group &#039;{action_group_name}&#039; using Function Details: {e}&quot;)\n        raise\n<\/code><\/pre>\n\n\n\n<h5 id=\"h-3-10-3-prepareagent\" class=\"wp-block-heading\">3.10.3 prepare_agent<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">This function initiates the preparation of the <code>DRAFT<\/code> version of the Bedrock Agent and waits for this process to complete. Preparation involves Bedrock compiling the agent&#8217;s configuration (instructions, action groups, model settings) and making it ready for invocation.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>It calls <code>bedrock_agent_client.prepare_agent(agentId=agent_id)<\/code>.<\/li>\n\n\n<li><strong>Custom Waiter:<\/strong> It then uses a custom-defined <code>boto3<\/code> waiter (<code>AgentPrepared<\/code>) to poll the agent&#8217;s status. The waiter configuration specifies:\n<ul>\n<li><code>delay<\/code>: How often to check (e.g., every 30 seconds).<\/li>\n<li><code>operation<\/code>: The SDK call to make for checking (<code>GetAgent<\/code>).<\/li>\n<li><code>maxAttempts<\/code>: How many times to check before timing out (e.g., 20 attempts, for a total of up to 10 minutes).<\/li>\n<li><code>acceptors<\/code>: Conditions that determine success, failure, or retry. It succeeds if <code>agent.agentStatus<\/code> becomes <code>PREPARED<\/code>, fails if it becomes <code>FAILED<\/code>, and retries if it&#8217;s <code>UPDATING<\/code> (though <code>PREPARING<\/code> is the more typical intermediate state here).\nIf the waiter times out or the agent preparation results in a <code>FAILED<\/code> status, an exception is raised. This step is crucial because an agent cannot be invoked (or an alias reliably pointed to its version) until it is successfully prepared.<\/li>\n<\/ul>\n<\/li>\n\n<\/ul>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>def prepare_agent(agent_client, agent_id):\n    &quot;&quot;&quot;Prepares the DRAFT version of the agent.&quot;&quot;&quot;\n    logger.info(f&quot;--- Preparing Agent: {agent_id} ---&quot;)\n    try:\n        response = agent_client.prepare_agent(agentId=agent_id)\n        agent_version = response.get(&#039;agentVersion&#039;) # Should be DRAFT\n        prepared_at = response.get(&#039;preparedAt&#039;)\n        status = response.get(&#039;agentStatus&#039;) # Should be PREPARING\n        logger.info(f&quot;Agent preparation initiated for version &#039;{agent_version}&#039;. Status: {status}. Prepared At: {prepared_at}&quot;)\n\n        # Wait for preparation to complete (PREPARED or FAILED)\n        logger.info(f&quot;Waiting for agent {agent_id} preparation to complete (up to 10 minutes)...&quot;)\n        # Define a simple waiter config\n        waiter_config = {\n            &#039;version&#039;: 2,\n            &#039;waiters&#039;: {\n                &#039;AgentPrepared&#039;: {\n                    &#039;delay&#039;: 30, # Check every 30 seconds\n                    &#039;operation&#039;: &#039;GetAgent&#039;,\n                    &#039;maxAttempts&#039;: 20, # Max 10 minutes\n                    &#039;acceptors&#039;: [\n                        {\n                            &#039;matcher&#039;: &#039;path&#039;,\n                            &#039;expected&#039;: &#039;PREPARED&#039;,\n                            &#039;argument&#039;: &#039;agent.agentStatus&#039;,\n                            &#039;state&#039;: &#039;success&#039;\n                        },\n                        {\n                            &#039;matcher&#039;: &#039;path&#039;,\n                            &#039;expected&#039;: &#039;FAILED&#039;,\n                            &#039;argument&#039;: &#039;agent.agentStatus&#039;,\n                            &#039;state&#039;: &#039;failure&#039;\n                        },\n                        {\n                            &#039;matcher&#039;: &#039;path&#039;,\n                            &#039;expected&#039;: &#039;UPDATING&#039;, # Can happen during prep? Treat as retryable\n                            &#039;argument&#039;: &#039;agent.agentStatus&#039;,\n                            &#039;state&#039;: &#039;retry&#039;\n                        }\n                    ]\n                }\n            }\n        }\n        waiter_model = WaiterModel(waiter_config)\n        custom_waiter = create_waiter_with_client(&#039;AgentPrepared&#039;, waiter_model, agent_client)\n\n        try: # Outer try for both preparation and alias handling\n             custom_waiter.wait(agentId=agent_id)\n             logger.info(f&quot;Agent {agent_id} successfully prepared.&quot;)\n\n        except Exception as e: # Outer except catches prepare_agent wait errors OR unhandled alias errors\n            logger.error(f&quot;Agent {agent_id} preparation failed or timed out (or alias error): {e}&quot;)\n            # Check final status if possible\n            try:\n                final_status = agent_client.get_agent(agentId=agent_id)[&#039;agent&#039;][&#039;agentStatus&#039;]\n                logger.error(f&quot;Final agent status: {final_status}&quot;)\n            except Exception as get_e:\n                logger.error(f&quot;Could not retrieve final agent status after wait failure: {get_e}&quot;)\n            raise Exception(f&quot;Agent preparation or alias setup failed for {agent_id}&quot;)\n\n    except Exception as e:\n        logger.error(f&quot;Error preparing agent {agent_id}: {e}&quot;)\n        # Handle error, maybe exit\n        raise e # Re-raise the exception\n<\/code><\/pre>\n\n\n\n<h4 id=\"h-3-11-agent-invocation-function\" class=\"wp-block-heading\">3.11 Agent Invocation Function<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">This subsection provides the function used to interact with the prepared and aliased Bedrock Agent, sending it a prompt and processing its response.<\/p>\n\n\n\n<h5 id=\"h-3-11-1-testagentinvocation\" class=\"wp-block-heading\">3.11.1 test_agent_invocation<\/h5>\n\n\n\n<p class=\"wp-block-paragraph\">This function is responsible for invoking the configured Bedrock Agent and handling its response. Key operations include:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Invocation:<\/strong> Calls <code>bedrock_agent_runtime_client.invoke_agent<\/code> with the <code>agentId<\/code>, <code>agentAliasId<\/code>, a unique <code>sessionId<\/code> (generated for each invocation in this script), the user&#8217;s <code>prompt<\/code> (inputText), and <code>enableTrace=True<\/code> to get detailed trace information for debugging.<\/li>\n\n\n<li><strong>Stream Processing:<\/strong> The agent&#8217;s response is a stream. The function iterates through the events in this stream (<code>response.get('completion', [])<\/code>).\n<ul>\n<li><strong><code>chunk<\/code> events:<\/strong> These contain parts of the agent&#8217;s textual response. The function decodes these byte chunks (UTF-8) and concatenates them to form the <code>completion_text<\/code>.<\/li>\n<li><strong><code>trace<\/code> events:<\/strong> If <code>enableTrace<\/code> was true, these events provide detailed insight into the agent&#8217;s internal operations, such as which foundation model was called, the input to the model, any tool invocations (though in the Lambda approach, the tool invocation itself is handled by Bedrock calling Lambda, the trace might show the agent deciding to call it and the result from it), and rationale. The function collects these trace parts.<\/li>\n<\/ul>\n<\/li>\n\n\n<li><strong>Logging:<\/strong> It logs the final combined <code>completion_text<\/code> and a summary of the trace events, which can be very helpful for understanding the agent&#8217;s decision-making process and debugging any issues with tool invocation or response generation.\nIt returns the final textual response from the agent.<\/li>\n\n<\/ul>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>def test_agent_invocation(agent_runtime_client, agent_id, agent_alias_id, session_id, prompt):\n    &quot;&quot;&quot;Invokes the agent and prints the response.&quot;&quot;&quot;\n    logger.info(f&quot;--- Testing Agent Invocation (Agent ID: {agent_id}, Alias: {agent_alias_id}) ---&quot;)\n    logger.info(f&quot;Session ID: {session_id}&quot;)\n    logger.info(f&quot;Prompt: &quot;{prompt}&quot;&quot;)\n\n    try:\n        response = agent_runtime_client.invoke_agent(\n            agentId=agent_id,\n            agentAliasId=agent_alias_id,\n            sessionId=session_id,\n            inputText=prompt,\n            enableTrace=True # Enable trace for debugging\n        )\n\n        logger.info(&quot;Agent invocation successful. Processing response...&quot;)\n        completion_text = &quot;&quot;\n        trace_events = []\n\n        # The response is a stream. Iterate through the chunks.\n        for event in response.get(&#039;completion&#039;, []):\n            if &#039;chunk&#039; in event:\n                data = event[&#039;chunk&#039;].get(&#039;bytes&#039;, b&#039;&#039;)\n                decoded_chunk = data.decode(&#039;utf-8&#039;)\n                completion_text += decoded_chunk\n            elif &#039;trace&#039; in event:\n                trace_part = event[&#039;trace&#039;].get(&#039;trace&#039;)\n                if trace_part:\n                     trace_events.append(trace_part)\n            else:\n                 logger.warning(f&quot;Unhandled event type in stream: {event}&quot;)\n\n        # Log final combined response\n        logger.info(f&quot;--- Agent Final Response ---{completion_text}&quot;)\n        \n        # Keep trace summary log (optional, can be removed if too verbose)\n        if trace_events:\n             logger.info(&quot;--- Invocation Trace Summary ---&quot;)\n             for i, trace in enumerate(trace_events):\n                  trace_type = trace.get(&#039;type&#039;)\n                  step_type = trace.get(&#039;orchestration&#039;, {}).get(&#039;stepType&#039;)\n                  model_invocation_input = trace.get(&#039;modelInvocationInput&#039;)\n                  if model_invocation_input:\n                      fm_input = model_invocation_input.get(&#039;text&#039;,\n                          json.dumps(model_invocation_input.get(&#039;invocationInput&#039;,{}).get(&#039;toolConfiguration&#039;,{})) # Handle tool input\n                      )\n                  log_line = f&quot;Trace {i+1}: Type={trace_type}, Step={step_type}&quot;\n                  rationale = trace.get(&#039;rationale&#039;, {}).get(&#039;text&#039;)\n                  if rationale: log_line += f&quot;, Rationale=&quot;{rationale[:100]}...&quot;&quot;\n                  logger.info(log_line) # Log summary line\n\n        return completion_text\n\n    except ClientError as e:\n        logger.error(f&quot;Error invoking agent: {e}&quot;)\n        logger.error(traceback.format_exc())\n        return None\n    except Exception as e:\n         logger.error(f&quot;Unexpected error during agent invocation: {e}&quot;)\n         logger.error(traceback.format_exc())\n         return None\n<\/code><\/pre>\n\n\n\n<h3 id=\"h-4--main-execution-flow\" class=\"wp-block-heading\">4. Main Execution Flow<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">This is the primary section of the notebook where all the previously defined helper functions are called in sequence to set up the complete Bedrock Agent environment with a Lambda-backed tool, and then test its invocation. The flow is designed to be largely idempotent where possible, meaning it can often be re-run, and it will attempt to clean up or reuse existing resources before creating new ones (e.g., IAM roles, Lambda functions, agents). The major steps are outlined below:<\/p>\n\n\n\n<h4 id=\"h-4-1-initial-setup\" class=\"wp-block-heading\">4.1 Initial Setup<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">This first step in the main execution flow performs essential preliminary tasks:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Logs a starting message for the script execution.<\/li>\n\n\n<li>Calls <code>check_environment_variables()<\/code> to ensure all required environment variables (AWS credentials, Couchbase password, etc.) are set. If not, it raises an <code>EnvironmentError<\/code> to halt execution, as the subsequent steps depend on these variables.<\/li>\n\n\n<li>Calls <code>initialize_aws_clients()<\/code> to get the necessary <code>boto3<\/code> client objects for Bedrock, IAM, Lambda, etc.<\/li>\n\n\n<li>Calls <code>connect_couchbase()<\/code> to establish a connection to the Couchbase cluster.\nIf any of these critical initialization steps fail, an exception is raised to stop the notebook&#8217;s execution, preventing errors in later stages.<\/li>\n\n<\/ol>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>logger.info(&quot;--- Starting Bedrock Agent Experiment Script ---&quot;)\n\nif not check_environment_variables():\n    # In a notebook, raising an exception might be better than exit(1)\n    raise EnvironmentError(&quot;Missing required environment variables. Check logs.&quot;)\n\n# Initialize all clients, including the agent client\ntry:\n    bedrock_runtime_client, iam_client, lambda_client, bedrock_agent_client, bedrock_agent_runtime_client = initialize_aws_clients()\n    cb_cluster = connect_couchbase()\n    logger.info(&quot;AWS clients and Couchbase connection initialized.&quot;)\nexcept Exception as e:\n    logger.error(f&quot;Initialization failed: {e}&quot;)\n    raise # Re-raise the exception to stop execution\n<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>2025-06-09 13:39:41,643 - INFO - --- Starting Bedrock Agent Experiment Script ---\n2025-06-09 13:39:41,644 - INFO - All required environment variables are set.\n2025-06-09 13:39:41,644 - INFO - Initializing AWS clients in region: us-east-1\n2025-06-09 13:39:42,002 - INFO - AWS clients initialized successfully.\n2025-06-09 13:39:42,002 - INFO - Connecting to Couchbase cluster at couchbases:\/\/cb.hlcup4o4jmjr55yf.cloud.couchbase.com...\n2025-06-09 13:39:44,131 - INFO - Successfully connected to Couchbase.\n2025-06-09 13:39:44,132 - INFO - AWS clients and Couchbase connection initialized.\n<\/code><\/pre>\n\n\n\n<h4 id=\"h-4-2-couchbase-setup\" class=\"wp-block-heading\">4.2 Couchbase Setup<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">This block focuses on preparing the Couchbase environment to serve as the vector store for the agent. It involves:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Calling <code>setup_collection()<\/code>: This helper function ensures that the target Couchbase bucket, scope, and collection (defined by <code>CB_BUCKET_NAME<\/code>, <code>SCOPE_NAME<\/code>, <code>COLLECTION_NAME<\/code>) are created if they don&#8217;t already exist. It also ensures a primary index is present on the collection.<\/li>\n\n\n<li>Calling <code>setup_search_index()<\/code>: This creates or updates the Couchbase Search index (named by <code>INDEX_NAME<\/code>) using the definition from <code>INDEX_JSON_PATH<\/code>. This search index is crucial for performing vector similarity searches.<\/li>\n\n\n<li>Calling <code>clear_collection()<\/code>: This function deletes all existing documents from the target collection. This step ensures that each run of the notebook starts with a clean slate, preventing data from previous experiments from interfering with the current one.\nIf any part of this Couchbase setup fails, an exception is logged and re-raised to stop further execution.<\/li>\n\n<\/ol>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>try:\n    # Use the setup functions with the script&#039;s config variables\n    cb_collection = setup_collection(cb_cluster, CB_BUCKET_NAME, SCOPE_NAME, COLLECTION_NAME)\n    logger.info(f&quot;Couchbase collection &#039;{CB_BUCKET_NAME}.{SCOPE_NAME}.{COLLECTION_NAME}&#039; setup complete.&quot;)\n\n    # Pass required args to setup_search_index\n    setup_search_index(cb_cluster, INDEX_NAME, CB_BUCKET_NAME, SCOPE_NAME, COLLECTION_NAME, INDEX_JSON_PATH)\n    logger.info(f&quot;Couchbase search index &#039;{INDEX_NAME}&#039; setup complete.&quot;)\n\n    # Clear any existing documents from previous runs\n    clear_collection(cb_cluster, CB_BUCKET_NAME, SCOPE_NAME, COLLECTION_NAME)\n    logger.info(&quot;Cleared any existing documents from the collection.&quot;)\nexcept Exception as e:\n    logger.error(f&quot;Couchbase setup failed: {e}&quot;)\n    raise\n<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>2025-06-09 13:39:44,140 - INFO - Setting up collection: vector-search-testing\/shared\/bedrock\n2025-06-09 13:39:45,245 - INFO - Bucket &#039;vector-search-testing&#039; exists.\n2025-06-09 13:39:46,219 - INFO - Scope &#039;shared&#039; already exists.\n2025-06-09 13:39:47,149 - INFO - Collection &#039;bedrock&#039; already exists.\n2025-06-09 13:39:47,152 - INFO - Ensuring primary index exists on `vector-search-testing`.`shared`.`bedrock`...\n2025-06-09 13:39:48,185 - INFO - Primary index present or created successfully.\n2025-06-09 13:39:48,186 - INFO - Collection setup complete.\n2025-06-09 13:39:48,187 - INFO - Couchbase collection &#039;vector-search-testing.shared.bedrock&#039; setup complete.\n2025-06-09 13:39:48,187 - INFO - Looking for index definition at: \/Users\/kaustavghosh\/Desktop\/vector-search-cookbook\/awsbedrock-agents\/lambda-approach\/aws_index.json\n2025-06-09 13:39:48,192 - INFO - Loaded index definition from \/Users\/kaustavghosh\/Desktop\/vector-search-cookbook\/awsbedrock-agents\/lambda-approach\/aws_index.json, ensuring name is &#039;vector_search_bedrock&#039; and source is &#039;vector-search-testing&#039;.\n2025-06-09 13:39:48,193 - INFO - Upserting search index &#039;vector_search_bedrock&#039;...\n2025-06-09 13:39:48,880 - WARNING - Search index &#039;vector_search_bedrock&#039; likely already existed (caught QueryIndexAlreadyExistsException, check if applicable). Upsert attempted.\n2025-06-09 13:39:48,881 - INFO - Couchbase search index &#039;vector_search_bedrock&#039; setup complete.\n2025-06-09 13:39:48,881 - WARNING - Attempting to clear all documents from `vector-search-testing`.`shared`.`bedrock`...\n2025-06-09 13:39:49,141 - WARNING - Could not retrieve mutation count after delete: &#039;list&#039; object has no attribute &#039;meta_data&#039;\n2025-06-09 13:39:49,142 - INFO - Successfully cleared documents from the collection (approx. 0 mutations).\n2025-06-09 13:39:49,143 - INFO - Cleared any existing documents from the collection.\n<\/code><\/pre>\n\n\n\n<h4 id=\"h-4-3-vector-store-initialization-and-data-loading\" class=\"wp-block-heading\">4.3 Vector Store Initialization and Data Loading<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">With the Couchbase infrastructure in place, this section prepares the LangChain vector store and populates it with data:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Initialize <code>BedrockEmbeddings<\/code>:<\/strong> Creates an instance of the <code>BedrockEmbeddings<\/code> client, specifying the <code>EMBEDDING_MODEL_ID<\/code> (e.g., Amazon Titan Text Embeddings V2). This client will be used by the vector store to convert text documents into numerical embeddings for similarity searching.<\/li>\n\n\n<li><strong>Initialize <code>CouchbaseSearchVectorStore<\/code>:<\/strong> Creates an instance of <code>CouchbaseSearchVectorStore<\/code>. This LangChain component acts as an abstraction layer over the Couchbase collection and search index, providing methods for adding documents and performing similarity searches. It&#8217;s configured with the Couchbase cluster connection, bucket\/scope\/collection names, the embeddings client, and the search index name.<\/li>\n\n\n<li><strong>Load Documents from JSON:<\/strong> Reads document data from the <code>DOCS_JSON_PATH<\/code> file. This file is expected to contain a list of documents, each with <code>text<\/code> and <code>metadata<\/code> fields.<\/li>\n\n\n<li><strong>Add Documents to Vector Store:<\/strong> If documents are loaded, their texts and metadatas are extracted. The <code>vector_store.add_texts()<\/code> method is then called to process these documents: each document&#8217;s text is converted into an embedding (using the <code>BedrockEmbeddings<\/code> client), and both the text and its embedding (along with metadata) are stored in the Couchbase collection. The search index (<code>INDEX_NAME<\/code>) is then updated to include these new vectors, making them searchable.\nError handling is included to catch issues like file not found or problems during embedding generation or data insertion.<\/li>\n\n<\/ol>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p class=\"wp-block-paragraph\">Note: <code>documents.json<\/code> contains the documents that we want to load into our vector store. As an example, we have added a few documents to the file from <a href=\"https:\/\/cline.bot\/\">https:\/\/cline.bot\/<\/a>\nLet&#8217;s load the documents from the documents.json file and add them to our vector store:<\/p>\n<\/blockquote>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>try:\n    logger.info(f&quot;Initializing Bedrock Embeddings client with model: {EMBEDDING_MODEL_ID}&quot;)\n    embeddings = BedrockEmbeddings(\n        client=bedrock_runtime_client,\n        model_id=EMBEDDING_MODEL_ID\n    )\n    logger.info(&quot;Successfully created Bedrock embeddings client.&quot;)\n\n    logger.info(f&quot;Initializing CouchbaseSearchVectorStore with index: {INDEX_NAME}&quot;)\n    vector_store = CouchbaseSearchVectorStore(\n        cluster=cb_cluster,\n        bucket_name=CB_BUCKET_NAME,\n        scope_name=SCOPE_NAME,\n        collection_name=COLLECTION_NAME,\n        embedding=embeddings,\n        index_name=INDEX_NAME\n    )\n    logger.info(&quot;Successfully created Couchbase vector store.&quot;)\n\n    # Load documents from JSON file\n    logger.info(f&quot;Looking for documents at: {DOCS_JSON_PATH}&quot;)\n    if not os.path.exists(DOCS_JSON_PATH):\n         logger.error(f&quot;Documents file not found: {DOCS_JSON_PATH}&quot;)\n         raise FileNotFoundError(f&quot;Documents file not found: {DOCS_JSON_PATH}&quot;)\n\n    with open(DOCS_JSON_PATH, &#039;r&#039;) as f:\n        data = json.load(f)\n        documents_to_load = data.get(&#039;documents&#039;, [])\n    logger.info(f&quot;Loaded {len(documents_to_load)} documents from {DOCS_JSON_PATH}&quot;)\n\n    # Add documents to vector store\n    if documents_to_load:\n        logger.info(f&quot;Adding {len(documents_to_load)} documents to vector store...&quot;)\n        texts = [doc.get(&#039;text&#039;, &#039;&#039;) for doc in documents_to_load]\n        metadatas = []\n        for i, doc in enumerate(documents_to_load):\n            metadata_raw = doc.get(&#039;metadata&#039;, {})\n            if isinstance(metadata_raw, str):\n                try:\n                    metadata = json.loads(metadata_raw)\n                    if not isinstance(metadata, dict):\n                         logger.warning(f&quot;Metadata for doc {i} parsed from string is not a dict: {metadata}. Using empty dict.&quot;)\n                         metadata = {}\n                except json.JSONDecodeError:\n                    logger.warning(f&quot;Could not parse metadata string for doc {i}: {metadata_raw}. Using empty dict.&quot;)\n                    metadata = {}\n            elif isinstance(metadata_raw, dict):\n                metadata = metadata_raw\n            else:\n                logger.warning(f&quot;Metadata for doc {i} is not a string or dict: {metadata_raw}. Using empty dict.&quot;)\n                metadata = {}\n            metadatas.append(metadata)\n\n        inserted_ids = vector_store.add_texts(texts=texts, metadatas=metadatas)\n        logger.info(f&quot;Successfully added {len(inserted_ids)} documents to the vector store.&quot;)\n    else:\n         logger.warning(&quot;No documents found in the JSON file to add.&quot;)\n\nexcept FileNotFoundError as e:\n     logger.error(f&quot;Setup failed: {e}&quot;)\n     raise\nexcept Exception as e:\n    logger.error(f&quot;Error during vector store setup or data loading: {e}&quot;)\n    logger.error(traceback.format_exc())\n    raise \n\nlogger.info(&quot;--- Couchbase Setup and Data Loading Complete ---&quot;)\n<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>2025-06-09 13:39:49,152 - INFO - Initializing Bedrock Embeddings client with model: amazon.titan-embed-text-v2:0\n2025-06-09 13:39:49,153 - INFO - Successfully created Bedrock embeddings client.\n2025-06-09 13:39:49,153 - INFO - Initializing CouchbaseSearchVectorStore with index: vector_search_bedrock\n2025-06-09 13:39:52,549 - INFO - Successfully created Couchbase vector store.\n2025-06-09 13:39:52,549 - INFO - Looking for documents at: \/Users\/kaustavghosh\/Desktop\/vector-search-cookbook\/awsbedrock-agents\/lambda-approach\/documents.json\n2025-06-09 13:39:52,551 - INFO - Loaded 7 documents from \/Users\/kaustavghosh\/Desktop\/vector-search-cookbook\/awsbedrock-agents\/lambda-approach\/documents.json\n2025-06-09 13:39:52,551 - INFO - Adding 7 documents to vector store...\n2025-06-09 13:39:56,544 - INFO - Successfully added 7 documents to the vector store.\n2025-06-09 13:39:56,545 - INFO - --- Couchbase Setup and Data Loading Complete ---\n<\/code><\/pre>\n\n\n\n<h4 id=\"h-4-4-create-iam-role\" class=\"wp-block-heading\">4.4 Create IAM Role<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">This step ensures that the necessary IAM (Identity and Access Management) role for the Bedrock Agent and its Lambda function is in place.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>It defines a <code>agent_role_name<\/code> (e.g., <code>bedrock_agent_lambda_exp_role<\/code>).<\/li>\n\n\n<li>It calls the <code>create_agent_role()<\/code> helper function. This function (described in section 3.7) either creates a new IAM role with this name or updates an existing one.<\/li>\n\n\n<li>The role is configured with a trust policy allowing both the Bedrock service and the Lambda service to assume it.<\/li>\n\n\n<li>It attaches necessary permissions policies, including <code>AWSLambdaBasicExecutionRole<\/code> for Lambda logging and custom inline policies for Bedrock access and any other required permissions.<\/li>\n\n\n<li>The AWS Account ID, needed for defining precise resource ARNs in policies, is fetched dynamically using the STS client if not already available as an environment variable.\nThe ARN of this role (<code>agent_role_arn<\/code>) is stored, as it&#8217;s a required parameter for creating both the Bedrock Agent and the AWS Lambda function that the agent will invoke.<\/li>\n\n<\/ul>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>agent_role_name = &quot;bedrock_agent_lambda_exp_role&quot;\ntry:\n    # Ensure AWS_ACCOUNT_ID is loaded correctly\n    if not AWS_ACCOUNT_ID:\n        logger.info(&quot;Attempting to fetch AWS Account ID...&quot;)\n        sts_client = boto3.client(&#039;sts&#039;, region_name=AWS_REGION)\n        AWS_ACCOUNT_ID = sts_client.get_caller_identity().get(&#039;Account&#039;)\n        if not AWS_ACCOUNT_ID:\n            raise ValueError(&quot;AWS Account ID could not be determined. Please set the AWS_ACCOUNT_ID environment variable.&quot;)\n        logger.info(f&quot;Fetched AWS Account ID: {AWS_ACCOUNT_ID}&quot;)\n        \n    agent_role_arn = create_agent_role(iam_client, agent_role_name, AWS_ACCOUNT_ID)\n    logger.info(f&quot;Agent IAM Role ARN: {agent_role_arn}&quot;)\nexcept Exception as e:\n    logger.error(f&quot;Failed to create\/verify IAM role: {e}&quot;)\n    logger.error(traceback.format_exc())\n    raise\n<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>2025-06-09 13:39:56,553 - INFO - Checking\/Creating IAM role: bedrock_agent_lambda_exp_role\n2025-06-09 13:39:57,454 - INFO - IAM role &#039;bedrock_agent_lambda_exp_role&#039; already exists with ARN: arn:aws:iam::598307997273:role\/bedrock_agent_lambda_exp_role\n2025-06-09 13:39:57,454 - INFO - Updating trust policy for existing role &#039;bedrock_agent_lambda_exp_role&#039;...\n2025-06-09 13:39:57,710 - INFO - Trust policy updated for role &#039;bedrock_agent_lambda_exp_role&#039;.\n2025-06-09 13:39:57,710 - INFO - Attaching basic Lambda execution policy to role &#039;bedrock_agent_lambda_exp_role&#039;...\n2025-06-09 13:39:57,973 - INFO - Attached basic Lambda execution policy.\n2025-06-09 13:39:57,974 - INFO - Putting basic inline policy &#039;LambdaBasicLoggingPermissions&#039; for role &#039;bedrock_agent_lambda_exp_role&#039;...\n2025-06-09 13:39:58,240 - INFO - Successfully put inline policy &#039;LambdaBasicLoggingPermissions&#039;.\n2025-06-09 13:39:58,240 - INFO - Putting Bedrock permissions policy &#039;BedrockAgentPermissions&#039; for role &#039;bedrock_agent_lambda_exp_role&#039;...\n2025-06-09 13:39:58,607 - INFO - Successfully put inline policy &#039;BedrockAgentPermissions&#039;.\n2025-06-09 13:39:58,608 - INFO - Waiting 10s for policy changes to propagate...\n2025-06-09 13:40:08,612 - INFO - Agent IAM Role ARN: arn:aws:iam::598307997273:role\/bedrock_agent_lambda_exp_role\n<\/code><\/pre>\n\n\n\n<h4 id=\"h-4-5-deploy-lambda-function\" class=\"wp-block-heading\">4.5 Deploy Lambda Function<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">This section orchestrates the deployment of the AWS Lambda function that will execute the agent&#8217;s <code>searchAndFormatDocuments<\/code> tool. The process involves several steps managed by the helper functions:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Define Lambda Details:<\/strong> Specifies the <code>search_format_lambda_name<\/code> (e.g., <code>bedrock_agent_search_format_exp<\/code>), the <code>lambda_source_dir<\/code> (where the Lambda&#8217;s Python script and <code>Makefile<\/code> are located), and <code>lambda_build_dir<\/code> (where the final .zip package will be placed).<\/li>\n\n\n<li><strong>Cleanup Old Lambdas (Optional but Recommended):<\/strong> Calls <code>delete_lambda_function<\/code> for potentially conflicting older Lambda functions (e.g., separate researcher\/writer Lambdas from previous experiments or an old version of the current combined Lambda). This ensures a cleaner environment, especially during iterative development.<\/li>\n\n\n<li><strong>Package Lambda:<\/strong> Calls <code>package_function()<\/code>. This helper (described in 3.8.3) uses the <code>Makefile<\/code> in <code>lambda_source_dir<\/code> to install dependencies, prepare the handler script (<code>bedrock_agent_search_and_format.py<\/code>), and create a .zip deployment package (<code>search_format_zip_path<\/code>).<\/li>\n\n\n<li><strong>Create\/Update Lambda in AWS:<\/strong> Calls <code>create_lambda_function()<\/code>. This helper (described in 3.8.4) takes the .zip package and either creates a new Lambda function in AWS or updates an existing one. It handles S3 upload for large packages, sets environment variables (like Couchbase connection info and Bedrock model IDs), configures the IAM role, runtime, handler, timeout, and memory. It also adds permissions for Bedrock to invoke the Lambda and waits for the Lambda to become active.<\/li>\n\n\n<li><strong>Cleanup Deployment Package:<\/strong> After successful deployment, the local .zip file is removed to save space.\nThe ARN of the deployed Lambda (<code>search_format_lambda_arn<\/code>) is stored, as it&#8217;s needed to link this Lambda to the Bedrock Agent&#8217;s action group.<\/li>\n\n<\/ol>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>search_format_lambda_name = &quot;bedrock_agent_search_format_exp&quot;\n# Adjust source\/build dirs for notebook context if necessary\nlambda_source_dir = os.path.join(SCRIPT_DIR, &#039;lambda_functions&#039;) \nlambda_build_dir = SCRIPT_DIR # Final zip ends up in the notebook&#039;s directory\n\nlogger.info(&quot;--- Starting Lambda Deployment (Single Function) --- &quot;)\nsearch_format_lambda_arn = None\nsearch_format_zip_path = None\n\ntry:\n    # Delete old lambdas if they exist (optional, but good cleanup)\n    logger.info(&quot;Deleting potentially conflicting old Lambda functions...&quot;)\n    delete_lambda_function(lambda_client, &quot;bedrock_agent_researcher_exp&quot;)\n    delete_lambda_function(lambda_client, &quot;bedrock_agent_writer_exp&quot;)\n    # Delete the new lambda if it exists from a previous run\n    delete_lambda_function(lambda_client, search_format_lambda_name)\n    logger.info(&quot;Old Lambda deletion checks complete.&quot;)\n\n    logger.info(f&quot;Packaging Lambda function &#039;{search_format_lambda_name}&#039;...&quot;)\n    search_format_zip_path = package_function(&quot;bedrock_agent_search_and_format&quot;, lambda_source_dir, lambda_build_dir)\n    logger.info(f&quot;Lambda function packaged at: {search_format_zip_path}&quot;)\n\n    logger.info(f&quot;Creating\/Updating Lambda function &#039;{search_format_lambda_name}&#039;...&quot;)\n    search_format_lambda_arn = create_lambda_function(\n        lambda_client=lambda_client, function_name=search_format_lambda_name,\n        handler=&#039;lambda_function.lambda_handler&#039;, role_arn=agent_role_arn,\n        zip_file=search_format_zip_path, region=AWS_REGION\n    )\n    logger.info(f&quot;Search\/Format Lambda Deployed: {search_format_lambda_arn}&quot;)\n\nexcept FileNotFoundError as e:\n     logger.error(f&quot;Lambda packaging failed: Required file not found. {e}&quot;)\n     raise\nexcept Exception as e:\n    logger.error(f&quot;Lambda deployment failed: {e}&quot;)\n    logger.error(traceback.format_exc())\n    raise\nfinally:\n    logger.info(&quot;Cleaning up deployment zip file...&quot;)\n    if search_format_zip_path and os.path.exists(search_format_zip_path):\n        try:\n            os.remove(search_format_zip_path)\n            logger.info(f&quot;Removed zip file: {search_format_zip_path}&quot;)\n        except OSError as e:\n            logger.warning(f&quot;Could not remove zip file {search_format_zip_path}: {e}&quot;)\n\nlogger.info(&quot;--- Lambda Deployment Complete --- &quot;)\n<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>2025-06-09 13:40:08,624 - INFO - --- Starting Lambda Deployment (Single Function) --- \n2025-06-09 13:40:08,626 - INFO - Deleting potentially conflicting old Lambda functions...\n2025-06-09 13:40:08,626 - INFO - Attempting to delete Lambda function: bedrock_agent_researcher_exp...\n2025-06-09 13:40:08,626 - INFO - Attempting to remove permission AllowBedrockInvokeBasic-bedrock_agent_researcher_exp from bedrock_agent_researcher_exp...\n2025-06-09 13:40:09,490 - INFO - Permission AllowBedrockInvokeBasic-bedrock_agent_researcher_exp not found on bedrock_agent_researcher_exp. Skipping removal.\n2025-06-09 13:40:09,794 - INFO - Lambda function &#039;bedrock_agent_researcher_exp&#039; does not exist. No need to delete.\n2025-06-09 13:40:09,795 - INFO - Attempting to delete Lambda function: bedrock_agent_writer_exp...\n2025-06-09 13:40:09,796 - INFO - Attempting to remove permission AllowBedrockInvokeBasic-bedrock_agent_writer_exp from bedrock_agent_writer_exp...\n2025-06-09 13:40:10,082 - INFO - Permission AllowBedrockInvokeBasic-bedrock_agent_writer_exp not found on bedrock_agent_writer_exp. Skipping removal.\n2025-06-09 13:40:10,387 - INFO - Lambda function &#039;bedrock_agent_writer_exp&#039; does not exist. No need to delete.\n2025-06-09 13:40:10,387 - INFO - Attempting to delete Lambda function: bedrock_agent_search_format_exp...\n2025-06-09 13:40:10,387 - INFO - Attempting to remove permission AllowBedrockInvokeBasic-bedrock_agent_search_format_exp from bedrock_agent_search_format_exp...\n2025-06-09 13:40:10,686 - INFO - Successfully removed permission AllowBedrockInvokeBasic-bedrock_agent_search_format_exp from bedrock_agent_search_format_exp.\n2025-06-09 13:40:13,060 - INFO - Function bedrock_agent_search_format_exp exists. Deleting...\n2025-06-09 13:40:13,594 - INFO - Waiting for bedrock_agent_search_format_exp to be deleted...\n2025-06-09 13:40:23,596 - INFO - Function bedrock_agent_search_format_exp deletion initiated.\n2025-06-09 13:40:23,597 - INFO - Old Lambda deletion checks complete.\n2025-06-09 13:40:23,598 - INFO - Packaging Lambda function &#039;bedrock_agent_search_format_exp&#039;...\n2025-06-09 13:40:23,599 - INFO - --- Packaging function bedrock_agent_search_and_format --- \n2025-06-09 13:40:23,602 - INFO - Source Dir (Makefile location &amp; make cwd): \/Users\/kaustavghosh\/Desktop\/vector-search-cookbook\/awsbedrock-agents\/lambda-approach\/lambda_functions\n2025-06-09 13:40:23,602 - INFO - Build Dir (Final zip location): \/Users\/kaustavghosh\/Desktop\/vector-search-cookbook\/awsbedrock-agents\/lambda-approach\n2025-06-09 13:40:23,603 - INFO - Copying \/Users\/kaustavghosh\/Desktop\/vector-search-cookbook\/awsbedrock-agents\/lambda-approach\/lambda_functions\/bedrock_agent_search_and_format.py to \/Users\/kaustavghosh\/Desktop\/vector-search-cookbook\/awsbedrock-agents\/lambda-approach\/lambda_functions\/lambda_function.py\n2025-06-09 13:40:23,605 - INFO - Running make command: make -f \/Users\/kaustavghosh\/Desktop\/vector-search-cookbook\/awsbedrock-agents\/lambda-approach\/lambda_functions\/Makefile clean package (in \/Users\/kaustavghosh\/Desktop\/vector-search-cookbook\/awsbedrock-agents\/lambda-approach\/lambda_functions)\n2025-06-09 13:40:50,341 - INFO - Make command completed successfully.\n2025-06-09 13:40:50,343 - INFO - Moving and renaming \/Users\/kaustavghosh\/Desktop\/vector-search-cookbook\/awsbedrock-agents\/lambda-approach\/lambda_functions\/lambda_package.zip to \/Users\/kaustavghosh\/Desktop\/vector-search-cookbook\/awsbedrock-agents\/lambda-approach\/bedrock_agent_search_and_format.zip\n\n... (output truncated for brevity)\n<\/code><\/pre>\n\n\n\n<h4 id=\"h-4-6-agent-setup\" class=\"wp-block-heading\">4.6 Agent Setup<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">This part of the script focuses on creating the Bedrock Agent itself.<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Define Agent Name:<\/strong> An <code>agent_name<\/code> is defined (e.g., <code>couchbase_search_format_agent_exp<\/code>).<\/li>\n\n\n<li><strong>Cleanup Existing Agent (Idempotency):<\/strong> It calls <code>delete_agent_and_resources()<\/code> first. This helper function (described in 3.9.3) attempts to find an agent with the same name and, if found, deletes it along with its action groups and aliases. This ensures that each run starts with a clean slate for the agent, preventing conflicts or issues from previous configurations.<\/li>\n\n\n<li><strong>Create New Agent:<\/strong> After the cleanup attempt, it calls <code>create_agent()<\/code>. This helper function (described in 3.10.1) creates a new Bedrock Agent with the specified name, the IAM role ARN (<code>agent_role_arn<\/code>), the foundation model ID (<code>AGENT_MODEL_ID<\/code>), and a set of instructions guiding the agent on how to behave and use its tools.\nThe <code>agent_id<\/code> and <code>agent_arn<\/code> returned by <code>create_agent()<\/code> are stored for subsequent steps like creating action groups and preparing the agent.<\/li>\n\n<\/ol>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>agent_name = f&quot;couchbase_search_format_agent_exp&quot;\nagent_id = None\nagent_arn = None\nalias_name = &quot;prod&quot; # Define alias name here\n# agent_alias_id_to_use will be set later after preparation\n\n# 1. Attempt to find and delete existing agent to ensure a clean state\nlogger.info(f&quot;Checking for and deleting existing agent: {agent_name}&quot;)\ntry:\n    delete_agent_and_resources(bedrock_agent_client, agent_name) # Handles finding and deleting\n    logger.info(f&quot;Deletion process completed for any existing agent named {agent_name}.&quot;)\nexcept Exception as e:\n    # Log error during find\/delete but proceed to creation attempt\n    logger.error(f&quot;Error during agent finding\/deletion phase: {e}. Proceeding to creation attempt.&quot;)\n\n# 2. Always attempt to create the agent after the delete phase\nlogger.info(f&quot;--- Creating Agent: {agent_name} ---&quot;)\ntry:\n    agent_id, agent_arn = create_agent(\n        agent_client=bedrock_agent_client,\n        agent_name=agent_name,\n        agent_role_arn=agent_role_arn,\n        foundation_model_id=AGENT_MODEL_ID\n    )\n    if not agent_id:\n        raise Exception(&quot;create_agent function did not return a valid agent ID.&quot;)\n    logger.info(f&quot;Agent created successfully. ID: {agent_id}, ARN: {agent_arn}&quot;)\nexcept Exception as e:\n    logger.error(f&quot;Failed to create agent &#039;{agent_name}&#039;: {e}&quot;)\n    logger.error(traceback.format_exc())\n    raise\n<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>2025-06-09 13:41:12,317 - INFO - Checking for and deleting existing agent: couchbase_search_format_agent_exp\n2025-06-09 13:41:12,318 - INFO - Attempting to find agent by name: couchbase_search_format_agent_exp\n2025-06-09 13:41:13,172 - INFO - Found agent &#039;couchbase_search_format_agent_exp&#039; with ID: 8CZXA8LJJH\n2025-06-09 13:41:13,172 - WARNING - --- Deleting Agent Resources for &#039;couchbase_search_format_agent_exp&#039; (ID: 8CZXA8LJJH) ---\n2025-06-09 13:41:13,172 - INFO - Listing action groups for agent 8CZXA8LJJH...\n2025-06-09 13:41:13,472 - INFO - Found 1 action groups to delete.\n2025-06-09 13:41:13,473 - INFO - Attempting to delete action group GKWWTGZVHJ for agent 8CZXA8LJJH...\n2025-06-09 13:41:13,794 - INFO - Successfully deleted action group GKWWTGZVHJ for agent 8CZXA8LJJH.\n2025-06-09 13:41:18,797 - INFO - Attempting to delete agent 8CZXA8LJJH (&#039;couchbase_search_format_agent_exp&#039;)...\n2025-06-09 13:41:19,108 - INFO - Waiting up to 2 minutes for agent 8CZXA8LJJH deletion...\n2025-06-09 13:41:25,109 - INFO - Agent 8CZXA8LJJH successfully deleted.\n2025-06-09 13:41:25,110 - INFO - --- Agent Resource Deletion Complete for &#039;couchbase_search_format_agent_exp&#039; ---\n2025-06-09 13:41:25,111 - INFO - Deletion process completed for any existing agent named couchbase_search_format_agent_exp.\n2025-06-09 13:41:25,111 - INFO - --- Creating Agent: couchbase_search_format_agent_exp ---\n2025-06-09 13:41:25,112 - INFO - --- Creating Agent: couchbase_search_format_agent_exp ---\n2025-06-09 13:41:25,623 - INFO - Agent creation initiated. Name: couchbase_search_format_agent_exp, ID: 7BTR61MXVF, ARN: arn:aws:bedrock:us-east-1:598307997273:agent\/7BTR61MXVF, Status: CREATING\n2025-06-09 13:41:25,625 - INFO - Waiting for agent 7BTR61MXVF to reach initial state...\n2025-06-09 13:41:26,201 - INFO - Agent 7BTR61MXVF status: CREATING\n2025-06-09 13:41:31,658 - INFO - Agent 7BTR61MXVF status: NOT_PREPARED\n2025-06-09 13:41:32,110 - INFO - Agent 7BTR61MXVF successfully created (Status: NOT_PREPARED).\n2025-06-09 13:41:32,111 - INFO - Agent created successfully. ID: 7BTR61MXVF, ARN: arn:aws:bedrock:us-east-1:598307997273:agent\/7BTR61MXVF\n<\/code><\/pre>\n\n\n\n<h4 id=\"h-4-7-action-group-setup\" class=\"wp-block-heading\">4.7 Action Group Setup<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Once the agent is created and the Lambda function is deployed, this step links them together by creating an Action Group.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>It defines an <code>action_group_name<\/code> (e.g., <code>SearchAndFormatActionGroup<\/code>).<\/li>\n\n\n<li>It calls the <code>create_action_group()<\/code> helper function (described in 3.10.2). This function is responsible for:\n<ul>\n<li>Taking the <code>agent_id<\/code> and the <code>search_format_lambda_arn<\/code> (the ARN of the deployed Lambda function) as input.<\/li>\n<li>Defining the <code>functionSchema<\/code> which tells the agent how to use the Lambda function (i.e., the tool name <code>searchAndFormatDocuments<\/code> and its parameters like <code>query<\/code>, <code>k<\/code>, <code>style<\/code>).<\/li>\n<li>Setting the <code>actionGroupExecutor<\/code> to point to the Lambda ARN, so Bedrock knows which Lambda to invoke.<\/li>\n<li>Creating a new action group or updating an existing one with the same name for the <code>DRAFT<\/code> version of the agent.<\/li>\n<\/ul>\n<\/li>\n\n\n<li>A 30-second pause (<code>time.sleep(30)<\/code>) is added after the action group setup. This is a crucial step to give AWS services enough time to propagate the changes and ensure that the agent is aware of the newly configured or updated action group before proceeding to the preparation phase. Without such a delay, the preparation step might fail or not correctly incorporate the action group.<\/li>\n\n<\/ul>\n\n\n\n<pre class=\"wp-block-code language-python\"><code># --- Action Group Creation\/Update (Now assumes agent_id is valid) ---\naction_group_name = &quot;SearchAndFormatActionGroup&quot;\naction_group_id = None\ntry:\n    if not agent_id:\n        raise ValueError(&quot;Agent ID is not set. Cannot create action group.&quot;)\n    if not search_format_lambda_arn:\n        raise ValueError(&quot;Lambda ARN is not set. Cannot create action group.&quot;)\n        \n    logger.info(f&quot;Creating\/Updating Action Group &#039;{action_group_name}&#039; for agent {agent_id}...&quot;)\n    action_group_id = create_action_group(\n        agent_client=bedrock_agent_client,\n        agent_id=agent_id,\n        action_group_name=action_group_name,\n        function_arn=search_format_lambda_arn,\n        # schema_path=None # No longer needed explicitly if default is None\n    )\n    if not action_group_id:\n        raise Exception(&quot;create_action_group did not return a valid ID.&quot;)\n    logger.info(f&quot;Action Group &#039;{action_group_name}&#039; created\/updated with ID: {action_group_id}&quot;)\n\n    # Add a slightly longer wait after action group modification\/creation\n    logger.info(&quot;Waiting 30s after action group setup before preparing agent...&quot;)\n    time.sleep(30)\nexcept Exception as e:\n    logger.error(f&quot;Failed to set up action group: {e}&quot;)\n    logger.error(traceback.format_exc())\n    raise\n<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>2025-06-09 13:41:32,119 - INFO - Creating\/Updating Action Group &#039;SearchAndFormatActionGroup&#039; for agent 7BTR61MXVF...\n2025-06-09 13:41:32,120 - INFO - --- Creating\/Updating Action Group (Function Details): SearchAndFormatActionGroup for Agent: 7BTR61MXVF ---\n2025-06-09 13:41:32,121 - INFO - Lambda ARN: arn:aws:lambda:us-east-1:598307997273:function:bedrock_agent_search_format_exp\n2025-06-09 13:41:32,122 - INFO - Checking if action group &#039;SearchAndFormatActionGroup&#039; already exists for agent 7BTR61MXVF DRAFT version...\n2025-06-09 13:41:32,412 - INFO - Action group &#039;SearchAndFormatActionGroup&#039; does not exist. Creating new with Function Details.\n2025-06-09 13:41:32,806 - INFO - Successfully created Action Group &#039;SearchAndFormatActionGroup&#039; with ID: 7XTTI9XFOX using Function Details.\n2025-06-09 13:41:37,812 - INFO - Action Group &#039;SearchAndFormatActionGroup&#039; created\/updated with ID: 7XTTI9XFOX\n2025-06-09 13:41:37,812 - INFO - Waiting 30s after action group setup before preparing agent...\n<\/code><\/pre>\n\n\n\n<h4 id=\"h-4-8-prepare-agent-and-handle-alias\" class=\"wp-block-heading\">4.8 Prepare Agent and Handle Alias<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">After the agent and its action group (linking to the Lambda tool) are defined, this section makes the agent ready for use and assigns an alias to it:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Prepare Agent:<\/strong> It calls the <code>prepare_agent()<\/code> helper function (described in 3.10.3). This function initiates the preparation process for the <code>DRAFT<\/code> version of the agent and uses a custom waiter to wait until the agent&#8217;s status becomes <code>PREPARED<\/code>. This step is vital as it compiles all agent configurations.<\/li>\n\n\n<li><strong>Alias Handling (Create or Update):<\/strong> Once the agent is successfully prepared:\n<ul>\n<li>An <code>alias_name<\/code> (e.g., <code>prod<\/code>) is defined.<\/li>\n<li>The code checks if an alias with this name already exists for the agent using <code>list_agent_aliases<\/code>.<\/li>\n<li>If the alias exists, its ID (<code>agent_alias_id_to_use<\/code>) is retrieved. The notebook assumes the existing alias will correctly point to the latest prepared version (DRAFT) or could be updated if necessary (though direct update logic for the alias to point to a specific version isn&#8217;t explicitly shown here beyond creation).<\/li>\n<li>If the alias does not exist, <code>create_agent_alias()<\/code> is called. This creates a new alias that, by default, points to the latest prepared version of the agent (which is the <code>DRAFT<\/code> version that was just prepared).<\/li>\n<li>A brief pause (<code>time.sleep(10)<\/code>) is added to allow the alias changes to propagate.\nThe <code>agent_alias_id_to_use<\/code> is now ready for invoking the agent.<\/li>\n<\/ul>\n<\/li>\n\n<\/ol>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>agent_alias_id_to_use = None # Initialize alias ID\nalias_name = &quot;prod&quot; # Make sure alias_name is defined\nif agent_id:\n    logger.info(f&quot;--- Preparing Agent: {agent_id} ---&quot;)\n    preparation_successful = False\n    try:\n        # prepare_agent now ONLY prepares, doesn&#039;t handle alias or return its ID\n        prepare_agent(bedrock_agent_client, agent_id) \n        logger.info(f&quot;Agent {agent_id} preparation seems complete (waiter succeeded).&quot;)\n        preparation_successful = True # Flag success\n\n    except Exception as e: # Catch errors from preparation\n        logger.error(f&quot;Error during agent preparation for {agent_id}: {e}&quot;)\n        logger.error(traceback.format_exc())\n        raise\n\n    # --- Alias Handling (runs only if preparation succeeded) ---\n    if preparation_successful:\n        logger.info(f&quot;--- Setting up Alias &#039;{alias_name}&#039; for Agent {agent_id} ---&quot;) # Add log\n        try:\n            # --- Alias Creation\/Update Logic (Copied\/adapted from main.py&#039;s __main__) ---\n            logger.info(f&quot;Checking for alias &#039;{alias_name}&#039; for agent {agent_id}...&quot;)\n            existing_alias = None\n            paginator = bedrock_agent_client.get_paginator(&#039;list_agent_aliases&#039;)\n            for page in paginator.paginate(agentId=agent_id):\n                for alias_summary in page.get(&#039;agentAliasSummaries&#039;, []):\n                    if alias_summary.get(&#039;agentAliasName&#039;) == alias_name:\n                        existing_alias = alias_summary\n                        break\n                if existing_alias:\n                    break\n            \n            if existing_alias:\n                agent_alias_id_to_use = existing_alias[&#039;agentAliasId&#039;]\n                logger.info(f&quot;Using existing alias &#039;{alias_name}&#039; with ID: {agent_alias_id_to_use}.&quot;)\n                # Optional: Update alias to point to DRAFT if needed, \n                # but create_agent_alias defaults to latest prepared (DRAFT) so just checking existence is often enough.\n            else:\n                logger.info(f&quot;Alias &#039;{alias_name}&#039; not found. Creating new alias...&quot;)\n                create_alias_response = bedrock_agent_client.create_agent_alias(\n                    agentId=agent_id,\n                    agentAliasName=alias_name\n                    # routingConfiguration removed - defaults to latest prepared (DRAFT)\n                )\n                agent_alias_id_to_use = create_alias_response.get(&#039;agentAlias&#039;, {}).get(&#039;agentAliasId&#039;)\n                logger.info(f&quot;Successfully created alias &#039;{alias_name}&#039; with ID: {agent_alias_id_to_use}. (Defaults to latest prepared version - DRAFT)&quot;)\n\n            if not agent_alias_id_to_use:\n                    raise ValueError(f&quot;Failed to get a valid alias ID for &#039;{alias_name}&#039;&quot;)\n\n            logger.info(f&quot;Waiting 10s for alias &#039;{alias_name}&#039; changes to propagate...&quot;)\n            time.sleep(10)\n            logger.info(f&quot;Agent {agent_id} preparation and alias &#039;{alias_name}&#039; ({agent_alias_id_to_use}) setup complete.&quot;)\n\n\n        except Exception as alias_e: # Catch errors from alias logic\n            logger.error(f&quot;Failed to create\/update alias &#039;{alias_name}&#039; for agent {agent_id}: {alias_e}&quot;)\n            logger.error(traceback.format_exc())\n            raise\nelse:\n    logger.error(&quot;Agent ID not available, skipping preparation and alias setup.&quot;)\n<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>2025-06-09 13:42:07,835 - INFO - --- Preparing Agent: 7BTR61MXVF ---\n2025-06-09 13:42:07,836 - INFO - --- Preparing Agent: 7BTR61MXVF ---\n2025-06-09 13:42:08,338 - INFO - Agent preparation initiated for version &#039;DRAFT&#039;. Status: PREPARING. Prepared At: 2025-06-09 08:12:08.237735+00:00\n2025-06-09 13:42:08,338 - INFO - Waiting for agent 7BTR61MXVF preparation to complete (up to 10 minutes)...\n2025-06-09 13:42:39,237 - INFO - Agent 7BTR61MXVF successfully prepared.\n2025-06-09 13:42:39,238 - INFO - Agent 7BTR61MXVF preparation seems complete (waiter succeeded).\n2025-06-09 13:42:39,238 - INFO - --- Setting up Alias &#039;prod&#039; for Agent 7BTR61MXVF ---\n2025-06-09 13:42:39,239 - INFO - Checking for alias &#039;prod&#039; for agent 7BTR61MXVF...\n2025-06-09 13:42:39,526 - INFO - Alias &#039;prod&#039; not found. Creating new alias...\n2025-06-09 13:42:39,902 - INFO - Successfully created alias &#039;prod&#039; with ID: Y8YNYUDFFZ. (Defaults to latest prepared version - DRAFT)\n2025-06-09 13:42:39,903 - INFO - Waiting 10s for alias &#039;prod&#039; changes to propagate...\n2025-06-09 13:42:49,907 - INFO - Agent 7BTR61MXVF preparation and alias &#039;prod&#039; (Y8YNYUDFFZ) setup complete.\n<\/code><\/pre>\n\n\n\n<h4 id=\"h-4-9-test-agent-invocation\" class=\"wp-block-heading\">4.9 Test Agent Invocation<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">This is the final operational step where the fully configured Bedrock Agent is tested.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>It first checks if both <code>agent_id<\/code> and <code>agent_alias_id_to_use<\/code> are available (i.e., the previous setup steps were successful).<\/li>\n\n\n<li>A unique <code>session_id<\/code> is generated for this specific interaction.<\/li>\n\n\n<li>A <code>test_prompt<\/code> is defined (e.g., &#8220;Search for information about Project Chimera and format the results using bullet points.&#8221;). This prompt is designed to trigger the agent&#8217;s tool (<code>searchAndFormatDocuments<\/code>).<\/li>\n\n\n<li>It then calls the <code>test_agent_invocation()<\/code> helper function (described in 3.11.1). This function sends the prompt to the Bedrock Agent Runtime using the specified agent ID and alias ID.<\/li>\n\n\n<li>The <code>test_agent_invocation<\/code> function handles the streaming response from the agent, concatenates the text chunks, logs trace information for debugging, and prints the agent&#8217;s final completion.\nThis step demonstrates an end-to-end test of the agent: receiving a prompt, deciding to use its Lambda-backed tool, Bedrock invoking the Lambda, the Lambda executing (performing search and formatting), returning results to the agent, and the agent formulating a final response to the user.<\/li>\n\n<\/ul>\n\n\n\n<pre class=\"wp-block-code language-python\"><code># --- Test Invocation ---\n# Agent ID and custom alias ID should be valid here\nif agent_id and agent_alias_id_to_use: # Check both are set\n     session_id = str(uuid.uuid4()) \n     test_prompt = &quot;Search for information about Project Chimera and format the results using bullet points.&quot;\n     logger.info(f&quot;--- Invoking Agent {agent_id} using Alias &#039;{alias_name}&#039; ({agent_alias_id_to_use}) ---&quot;) # Updated log\n     try:\n         completion = test_agent_invocation(\n             agent_runtime_client=bedrock_agent_runtime_client,\n             agent_id=agent_id,\n             agent_alias_id=agent_alias_id_to_use, \n             session_id=session_id,\n             prompt=test_prompt\n         )\n         if completion is None:\n              logger.error(&quot;Agent invocation failed.&quot;)\n     except Exception as e:\n          logger.error(f&quot;Error during test invocation: {e}&quot;)\n          logger.error(traceback.format_exc())\nelse:\n     logger.error(&quot;Agent ID or Alias ID not available, skipping invocation test.&quot;)\n<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>2025-06-09 13:42:49,923 - INFO - --- Invoking Agent 7BTR61MXVF using Alias &#039;prod&#039; (Y8YNYUDFFZ) ---\n2025-06-09 13:42:49,924 - INFO - --- Testing Agent Invocation (Agent ID: 7BTR61MXVF, Alias: Y8YNYUDFFZ) ---\n2025-06-09 13:42:49,925 - INFO - Session ID: 6529a5a7-0b58-4c7d-8682-20353a8f09c3\n2025-06-09 13:42:49,925 - INFO - Prompt: &quot;Search for information about Project Chimera and format the results using bullet points.&quot;\n2025-06-09 13:42:50,894 - INFO - Agent invocation successful. Processing response...\n2025-06-09 13:43:05,971 - INFO - --- Agent Final Response ---\u2022 Project Chimera combines quantum entanglement communication with neural networks for secure, real-time data analysis across distributed nodes. Lead developer: Dr. Aris Thorne.\n\n\u2022 Chimera operates in two modes:\n    - &#039;Quantum Sync&#039; for high-fidelity data transfer\n    - &#039;Neural Inference&#039; for localized edge processing based on the synced data.\n\n\u2022 A key aspect of Chimera is its &quot;Ephemeral Key Protocol&quot; (EKP), which generates one-time quantum keys for each transmission, ensuring absolute forward secrecy.\n2025-06-09 13:43:05,973 - INFO - --- Invocation Trace Summary ---\n2025-06-09 13:43:05,975 - INFO - Trace 1: Type=None, Step=None\n2025-06-09 13:43:05,975 - INFO - Trace 2: Type=None, Step=None\n2025-06-09 13:43:05,976 - INFO - Trace 3: Type=None, Step=None\n2025-06-09 13:43:05,976 - INFO - Trace 4: Type=None, Step=None\n2025-06-09 13:43:05,977 - INFO - Trace 5: Type=None, Step=None\n2025-06-09 13:43:05,977 - INFO - Trace 6: Type=None, Step=None\n2025-06-09 13:43:05,978 - INFO - Trace 7: Type=None, Step=None\n2025-06-09 13:43:05,978 - INFO - Trace 8: Type=None, Step=None\n<\/code><\/pre>\n\n\n\n<h3 id=\"h-conclusion\" class=\"wp-block-heading\">Conclusion<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">In this notebook, we&#8217;ve demonstrated the Lambda approach for implementing AWS Bedrock agents with Couchbase Vector Search. This approach allows the agent to invoke AWS Lambda functions to execute operations, providing better scalability and separation of concerns.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Key components of this implementation include:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Vector Store Setup<\/strong>: We set up a Couchbase vector store to store and search documents using semantic similarity.<\/li>\n\n\n<li><strong>Lambda Function Deployment<\/strong>: We deployed Lambda functions that handle the agent&#8217;s function calls.<\/li>\n\n\n<li><strong>Agent Creation<\/strong>: We created two specialized agents &#8211; a researcher agent for searching documents and a writer agent for formatting results.<\/li>\n\n\n<li><strong>Lambda Integration<\/strong>: We integrated the agents with Lambda functions, allowing them to execute operations in a serverless environment.<\/li>\n\n<\/ol>\n\n\n\n<p class=\"wp-block-paragraph\">This approach is particularly useful for production environments where scalability and separation of concerns are important. The Lambda functions can be deployed independently and can access other AWS services, providing more flexibility and power.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>View Source This notebook demonstrates the Lambda approach for implementing AWS Bedrock agents with Couchbase Vector Search. In this approach, the agent invokes AWS Lambda functions to execute operations. We&#8217;ll implement a multi-agent architecture with specialized agents for different tasks: Alternative Approaches This notebook demonstrates the Lambda Approach for AWS Bedrock Agents. For comparison, you [&hellip;]<\/p>\n","protected":false},"author":0,"featured_media":0,"menu_order":0,"template":"","meta":{"_acf_changed":false,"inline_featured_image":false,"_acf":"","footnotes":""},"tutorial-languages":[606],"tutorial-tags":[626,607],"tutorial-technologies":[613],"tutorial-types":[555],"class_list":["post-10301","tutorials","type-tutorials","status-publish","hentry","tutorial-languages-python","tutorial-tags-amazon-bedrock","tutorial-tags-artificial-intelligence","tutorial-technologies-vector-search","tutorial-types-tutorial"],"yoast_head":"<!-- This site is optimized with the Yoast SEO Premium plugin v28.8 (Yoast SEO v28.9) - https:\/\/yoast.com\/product\/yoast-seo-premium-wordpress\/ -->\n<title>Building Intelligent Agents with Amazon Bedrock (Lambda) - Couchbase<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.couchbase.com\/it\/developers\/tutorials\/aws-bedrock-agents-lambda\/\" \/>\n<meta property=\"og:locale\" content=\"it_IT\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Building Intelligent Agents with Amazon Bedrock (Lambda)\" \/>\n<meta property=\"og:description\" content=\"View Source This notebook demonstrates the Lambda approach for implementing AWS Bedrock agents with Couchbase Vector Search. In this approach, the agent invokes AWS Lambda functions to execute operations. We&#8217;ll implement a multi-agent architecture with specialized agents for different tasks: Alternative Approaches This notebook demonstrates the Lambda Approach for AWS Bedrock Agents. For comparison, you [&hellip;]\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.couchbase.com\/it\/developers\/tutorials\/aws-bedrock-agents-lambda\/\" \/>\n<meta property=\"og:site_name\" content=\"Couchbase\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/Couchbase\/\" \/>\n<meta property=\"og:image\" content=\"https:\/\/www.couchbase.com\/wp-content\/uploads\/2026\/10\/Cloud-2.png\" \/>\n\t<meta property=\"og:image:width\" content=\"2548\" \/>\n\t<meta property=\"og:image:height\" content=\"1171\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:site\" content=\"@couchbase\" \/>\n<meta name=\"twitter:label1\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data1\" content=\"93 minuti\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/www.couchbase.com\\\/it\\\/developers\\\/tutorials\\\/aws-bedrock-agents-lambda\\\/\",\"url\":\"https:\\\/\\\/www.couchbase.com\\\/it\\\/developers\\\/tutorials\\\/aws-bedrock-agents-lambda\\\/\",\"name\":\"Building Intelligent Agents with Amazon Bedrock (Lambda) - Couchbase\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/www.couchbase.com\\\/it\\\/#website\"},\"datePublished\":\"2026-01-21T05:54:23+00:00\",\"breadcrumb\":{\"@id\":\"https:\\\/\\\/www.couchbase.com\\\/it\\\/developers\\\/tutorials\\\/aws-bedrock-agents-lambda\\\/#breadcrumb\"},\"inLanguage\":\"it-IT\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/www.couchbase.com\\\/it\\\/developers\\\/tutorials\\\/aws-bedrock-agents-lambda\\\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/www.couchbase.com\\\/it\\\/developers\\\/tutorials\\\/aws-bedrock-agents-lambda\\\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\\\/\\\/www.couchbase.com\\\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Building Intelligent Agents with Amazon Bedrock (Lambda)\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/www.couchbase.com\\\/it\\\/#website\",\"url\":\"https:\\\/\\\/www.couchbase.com\\\/it\\\/\",\"name\":\"Couchbase\",\"description\":\"The Operational Data Platform for AI\u2122\",\"publisher\":{\"@id\":\"https:\\\/\\\/www.couchbase.com\\\/it\\\/#organization\"},\"alternateName\":\"Couchbase, Inc.\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/www.couchbase.com\\\/it\\\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"it-IT\"},{\"@type\":\"Organization\",\"@id\":\"https:\\\/\\\/www.couchbase.com\\\/it\\\/#organization\",\"name\":\"Couchbase\",\"alternateName\":\"Couchbase, Inc.\",\"url\":\"https:\\\/\\\/www.couchbase.com\\\/it\\\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"it-IT\",\"@id\":\"https:\\\/\\\/www.couchbase.com\\\/it\\\/#\\\/schema\\\/logo\\\/image\\\/\",\"url\":\"https:\\\/\\\/www.couchbase.com\\\/wp-content\\\/uploads\\\/2026\\\/11\\\/Couchbase_Logo_Couchbase_Token_Red-1.png\",\"contentUrl\":\"https:\\\/\\\/www.couchbase.com\\\/wp-content\\\/uploads\\\/2026\\\/11\\\/Couchbase_Logo_Couchbase_Token_Red-1.png\",\"width\":1129,\"height\":1129,\"caption\":\"Couchbase\"},\"image\":{\"@id\":\"https:\\\/\\\/www.couchbase.com\\\/it\\\/#\\\/schema\\\/logo\\\/image\\\/\"},\"sameAs\":[\"https:\\\/\\\/www.facebook.com\\\/Couchbase\\\/\",\"https:\\\/\\\/x.com\\\/couchbase\",\"https:\\\/\\\/www.youtube.com\\\/c\\\/CouchbaseServer\",\"https:\\\/\\\/www.linkedin.com\\\/company\\\/couchbase\\\/\",\"https:\\\/\\\/github.com\\\/couchbase\\\/\",\"https:\\\/\\\/en.wikipedia.org\\\/wiki\\\/Couchbase,_Inc.\"],\"description\":\"Couchbase is a database software company headquartered in San Jose, California, providing an operational data platform for AI used by hundreds of global enterprises.\",\"legalName\":\"Couchbase, Inc.\",\"foundingDate\":\"2011-01-01\"}]}<\/script>\n<!-- \/ Yoast SEO Premium plugin. -->","yoast_head_json":{"title":"Building Intelligent Agents with Amazon Bedrock (Lambda) - Couchbase","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.couchbase.com\/it\/developers\/tutorials\/aws-bedrock-agents-lambda\/","og_locale":"it_IT","og_type":"article","og_title":"Building Intelligent Agents with Amazon Bedrock (Lambda)","og_description":"View Source This notebook demonstrates the Lambda approach for implementing AWS Bedrock agents with Couchbase Vector Search. In this approach, the agent invokes AWS Lambda functions to execute operations. We&#8217;ll implement a multi-agent architecture with specialized agents for different tasks: Alternative Approaches This notebook demonstrates the Lambda Approach for AWS Bedrock Agents. For comparison, you [&hellip;]","og_url":"https:\/\/www.couchbase.com\/it\/developers\/tutorials\/aws-bedrock-agents-lambda\/","og_site_name":"Couchbase","article_publisher":"https:\/\/www.facebook.com\/Couchbase\/","og_image":[{"width":2548,"height":1171,"url":"https:\/\/www.couchbase.com\/wp-content\/uploads\/2026\/10\/Cloud-2.png","type":"image\/png"}],"twitter_card":"summary_large_image","twitter_site":"@couchbase","twitter_misc":{"Est. reading time":"93 minuti"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"WebPage","@id":"https:\/\/www.couchbase.com\/it\/developers\/tutorials\/aws-bedrock-agents-lambda\/","url":"https:\/\/www.couchbase.com\/it\/developers\/tutorials\/aws-bedrock-agents-lambda\/","name":"Building Intelligent Agents with Amazon Bedrock (Lambda) - Couchbase","isPartOf":{"@id":"https:\/\/www.couchbase.com\/it\/#website"},"datePublished":"2026-01-21T05:54:23+00:00","breadcrumb":{"@id":"https:\/\/www.couchbase.com\/it\/developers\/tutorials\/aws-bedrock-agents-lambda\/#breadcrumb"},"inLanguage":"it-IT","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.couchbase.com\/it\/developers\/tutorials\/aws-bedrock-agents-lambda\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/www.couchbase.com\/it\/developers\/tutorials\/aws-bedrock-agents-lambda\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/www.couchbase.com\/"},{"@type":"ListItem","position":2,"name":"Building Intelligent Agents with Amazon Bedrock (Lambda)"}]},{"@type":"WebSite","@id":"https:\/\/www.couchbase.com\/it\/#website","url":"https:\/\/www.couchbase.com\/it\/","name":"Couchbase","description":"The Operational Data Platform for AI\u2122","publisher":{"@id":"https:\/\/www.couchbase.com\/it\/#organization"},"alternateName":"Couchbase, Inc.","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.couchbase.com\/it\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"it-IT"},{"@type":"Organization","@id":"https:\/\/www.couchbase.com\/it\/#organization","name":"Couchbase","alternateName":"Couchbase, Inc.","url":"https:\/\/www.couchbase.com\/it\/","logo":{"@type":"ImageObject","inLanguage":"it-IT","@id":"https:\/\/www.couchbase.com\/it\/#\/schema\/logo\/image\/","url":"https:\/\/www.couchbase.com\/wp-content\/uploads\/2026\/11\/Couchbase_Logo_Couchbase_Token_Red-1.png","contentUrl":"https:\/\/www.couchbase.com\/wp-content\/uploads\/2026\/11\/Couchbase_Logo_Couchbase_Token_Red-1.png","width":1129,"height":1129,"caption":"Couchbase"},"image":{"@id":"https:\/\/www.couchbase.com\/it\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/Couchbase\/","https:\/\/x.com\/couchbase","https:\/\/www.youtube.com\/c\/CouchbaseServer","https:\/\/www.linkedin.com\/company\/couchbase\/","https:\/\/github.com\/couchbase\/","https:\/\/en.wikipedia.org\/wiki\/Couchbase,_Inc."],"description":"Couchbase \u00e8 una societ\u00e0 di software per database con sede a San Jose, in California, che fornisce una piattaforma operativa per i dati utilizzata da centinaia di aziende globali.","legalName":"Couchbase, Inc.","foundingDate":"2011-01-01"}]}},"acf":[],"permalink_manager":null,"_links":{"self":[{"href":"https:\/\/www.couchbase.com\/it\/wp-json\/wp\/v2\/tutorials\/10301","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.couchbase.com\/it\/wp-json\/wp\/v2\/tutorials"}],"about":[{"href":"https:\/\/www.couchbase.com\/it\/wp-json\/wp\/v2\/types\/tutorials"}],"version-history":[{"count":0,"href":"https:\/\/www.couchbase.com\/it\/wp-json\/wp\/v2\/tutorials\/10301\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.couchbase.com\/it\/wp-json\/wp\/v2\/media?parent=10301"}],"wp:term":[{"taxonomy":"tutorial-languages","embeddable":true,"href":"https:\/\/www.couchbase.com\/it\/wp-json\/wp\/v2\/tutorial-languages?post=10301"},{"taxonomy":"tutorial-tags","embeddable":true,"href":"https:\/\/www.couchbase.com\/it\/wp-json\/wp\/v2\/tutorial-tags?post=10301"},{"taxonomy":"tutorial-technologies","embeddable":true,"href":"https:\/\/www.couchbase.com\/it\/wp-json\/wp\/v2\/tutorial-technologies?post=10301"},{"taxonomy":"tutorial-types","embeddable":true,"href":"https:\/\/www.couchbase.com\/it\/wp-json\/wp\/v2\/tutorial-types?post=10301"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}