{"id":10315,"date":"2025-12-09T02:13:28","date_gmt":"2025-12-09T10:13:28","guid":{"rendered":"https:\/\/www.couchbase.com\/developers\/tutorials\/aws-bedrock-agents-custom-control\/"},"modified":"2025-12-09T02:13:28","modified_gmt":"2025-12-09T10:13:28","slug":"aws-bedrock-agents-custom-control","status":"publish","type":"tutorials","link":"https:\/\/www.couchbase.com\/pt\/developers\/tutorials\/aws-bedrock-agents-custom-control\/","title":{"rendered":"Building Intelligent Agents with AWS Bedrock (Custom Control)"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\"><a href=\"https:\/\/github.com\/couchbase-examples\/vector-search-cookbook\/tree\/main\/awsbedrock-agents\/custom-control-approach\/Bedrock_Agents_Custom_Control.ipynb\">View Source<\/a><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This notebook demonstrates the Custom Control approach for implementing AWS Bedrock agents with Couchbase Vector Search. In this approach, the agent returns control to the application for function execution.<\/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 Custom Control approach for AWS Bedrock Agents. For comparison, you might also want to check out the Lambda Approach, which uses AWS Lambda functions to execute agent tools instead of handling them directly in your application code.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The Lambda approach offers better separation of concerns and scalability, but requires more setup. You can find that implementation here: <a href=\"https:\/\/developer.couchbase.com\/tutorial-aws-bedrock-agents-lambda\">Lambda Approach Notebook<\/a>\nNote: If the link above doesn&#8217;t work in your Jupyter environment, you can navigate to the file manually in the <code>awsbedrock-agents\/lambda-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 Custom Control approach gives the application invoking the agent the responsibility of executing the agent&#8217;s defined functions (tools). When the agent decides to use a tool, it sends a <code>returnControl<\/code> event back to the calling application, which then executes the function locally and (optionally) returns the result to the agent to continue processing.<\/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:<\/strong><\/p>\n<ul>\n<li>Define instructions (prompt) for the agent.<\/li>\n<li>Define the function schema (tools the agent can use, e.g., <code>researcher_functions<\/code>, <code>writer_functions<\/code> in the example).<\/li>\n<\/ul>\n<\/li>\n\n\n<li>\n<p><strong>Create Agent in Bedrock:<\/strong><\/p>\n<ul>\n<li>Use <code>bedrock_agent_client.create_agent<\/code> to create the agent, providing the instructions and foundation model.<\/li>\n<li>The example&#8217;s <code>create_agent<\/code> function includes logic to check for existing agents and potentially delete\/recreate them if they are in a non-functional state.<\/li>\n<\/ul>\n<\/li>\n\n\n<li>\n<p><strong>Create Action Group (Custom Control):<\/strong><\/p>\n<ul>\n<li>Use <code>bedrock_agent_client.create_agent_action_group<\/code>.<\/li>\n<li>Crucially, set the <code>actionGroupExecutor<\/code> to <code>{\"customControl\": \"RETURN_CONTROL\"}<\/code>. This tells Bedrock to pause execution and return control to the caller when a function in this group needs to be run.<\/li>\n<li>Provide the <code>functionSchema<\/code> defined earlier.<\/li>\n<\/ul>\n<\/li>\n\n\n<li>\n<p><strong>Prepare Agent:<\/strong><\/p>\n<ul>\n<li>Use <code>bedrock_agent_client.prepare_agent<\/code> to make the agent ready for invocation.<\/li>\n<li>The <code>wait_for_agent_status<\/code> utility function polls until the agent reaches a <code>PREPARED<\/code> or <code>Available<\/code> state.<\/li>\n<\/ul>\n<\/li>\n\n\n<li>\n<p><strong>Create Agent Alias:<\/strong><\/p>\n<ul>\n<li>An alias (e.g., &#8220;v1&#8221;) is created using <code>bedrock_agent_client.create_agent_alias<\/code> for invoking the agent.<\/li>\n<\/ul>\n<\/li>\n\n\n<li>\n<p><strong>Invoke Agent &amp; Handle Return Control (Custom Control Flow)<\/strong><\/p>\n<p>When the application invokes a Bedrock agent and the agent decides to use a tool, the &#8220;Custom Control&#8221; mechanism takes effect. Instead of Bedrock running the tool, it sends a <code>returnControl<\/code> event back to the application. The code then parses this event to identify the requested function and its parameters, executes that function locally using the application&#8217;s resources (like a vector store), and the result of this local execution becomes the final output for that specific agent interaction. If further steps are needed with another agent, a new, separate agent invocation is made using this output.<\/p>\n<ul>\n<li>Application calls <code>invoke_agent<\/code> to interact with Bedrock.<\/li>\n<li>Agent signals tool use via a <code>returnControl<\/code> event in the response stream.<\/li>\n<li>Application parses the event, extracting function name and parameters.<\/li>\n<li>Application executes the specified function locally, accessing its own resources.<\/li>\n<li><strong>The output from this local function execution is the final result for that agent&#8217;s turn.<\/strong><\/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>Full Control:<\/strong> The application has complete control over the execution environment and logic of the tools.<\/li>\n\n\n<li><strong>Direct State Access:<\/strong> Tools can directly access application memory, state, and resources (like the <code>vector_store<\/code> object in the example) without needing separate deployment or complex configuration passing.<\/li>\n\n\n<li><strong>Simpler Local Development:<\/strong> Can be easier to test and debug locally as the tool execution happens within the same process.<\/li>\n\n\n<li><strong>Flexibility:<\/strong> Allows integration with any library or service available to the application.<\/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>Application Burden:<\/strong> The application code is responsible for implementing and executing the tool logic.<\/li>\n\n\n<li><strong>Scalability:<\/strong> The scalability of tool execution is tied to the scalability of the application itself.<\/li>\n\n\n<li><strong>Tighter Coupling:<\/strong> The agent&#8217;s functionality is more tightly coupled with the application code.<\/li>\n\n\n<li><strong>Interaction Model:<\/strong> The specific implementation shown requires chaining separate agent invocations rather than letting the agent continue processing within a single turn after a tool is used. Implementing the latter (returning results via <code>ReturnControl<\/code>) adds complexity to the application&#8217;s handling of the <code>invoke_agent<\/code> response\/request cycle.<\/li>\n\n<\/ul>\n\n\n\n<h3 id=\"h-setup-and-configuration\" class=\"wp-block-heading\">Setup and Configuration<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">First, let&#8217;s import the necessary libraries and set up our environment:<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code>import json\nimport logging\nimport os\nimport time\nimport uuid\nfrom datetime import timedelta\n\nimport boto3\nfrom botocore.exceptions import ClientError\nfrom couchbase.auth import PasswordAuthenticator\nfrom couchbase.cluster import Cluster\nfrom couchbase.exceptions import (InternalServerFailureException,\n                                  QueryIndexAlreadyExistsException,\n                                  ServiceUnavailableException)\nfrom couchbase.management.buckets import CreateBucketSettings\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\n# Setup logging\nlogging.basicConfig(level=logging.INFO, format=&#039;%(asctime)s - %(levelname)s - %(message)s&#039;)\n<\/code><\/pre>\n\n\n\n<h3 id=\"h-load-environment-variables\" class=\"wp-block-heading\">Load Environment Variables<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Load environment variables from the .env file. Make sure to create a .env file with the necessary credentials before running this notebook.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code># Load environment variables\nload_dotenv()\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;)\nCB_BUCKET_NAME = os.getenv(&quot;CB_BUCKET_NAME&quot;, &quot;vector-search-testing&quot;)\nSCOPE_NAME = os.getenv(&quot;SCOPE_NAME&quot;, &quot;shared&quot;)\nCOLLECTION_NAME = os.getenv(&quot;COLLECTION_NAME&quot;, &quot;bedrock&quot;)\nINDEX_NAME = os.getenv(&quot;INDEX_NAME&quot;, &quot;vector_search_bedrock&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# Check if required environment variables are set\nrequired_vars = [&quot;AWS_ACCESS_KEY_ID&quot;, &quot;AWS_SECRET_ACCESS_KEY&quot;]\nmissing_vars = [var for var in required_vars if not os.getenv(var)]\nif missing_vars:\n    logging.warning(f&quot;Missing required environment variables: {&#039;, &#039;.join(missing_vars)}&quot;)\n    logging.warning(&quot;Please set these variables in your .env file&quot;)\nelse:\n    logging.info(&quot;All required environment variables are set&quot;)\n<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>2025-05-08 13:34:15,605 - INFO - All required environment variables are set\n<\/code><\/pre>\n\n\n\n<h3 id=\"h-initialize-aws-clients\" class=\"wp-block-heading\">Initialize AWS Clients<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Set up the AWS clients for Bedrock and other services:<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code># Initialize AWS session\nsession = 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\n# Initialize AWS clients from session\nbedrock_client = session.client(&#039;bedrock&#039;)\nbedrock_agent_client = session.client(&#039;bedrock-agent&#039;)\nbedrock_runtime = session.client(&#039;bedrock-runtime&#039;)\nbedrock_runtime_client = session.client(&#039;bedrock-agent-runtime&#039;)\niam_client = session.client(&#039;iam&#039;)\n\nlogging.info(&quot;AWS clients initialized successfully&quot;)\n<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>2025-05-08 13:34:15,836 - INFO - AWS clients initialized successfully\n<\/code><\/pre>\n\n\n\n<h3 id=\"h-set-up-couchbase-and-vector-store\" class=\"wp-block-heading\">Set Up Couchbase and Vector Store<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Now let&#8217;s set up the Couchbase connection, collections, and vector store:<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code># Connect to Couchbase\nauth = PasswordAuthenticator(CB_USERNAME, CB_PASSWORD)\noptions = ClusterOptions(auth)\ncluster = Cluster(CB_HOST, options)\ncluster.wait_until_ready(timedelta(seconds=5))\nlogging.info(&quot;Successfully connected to Couchbase&quot;)\n<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>2025-05-08 13:34:17,966 - INFO - Successfully connected to Couchbase\n<\/code><\/pre>\n\n\n\n<h3 id=\"h-create-couchbase-bucket-scope-and-collection\" class=\"wp-block-heading\">Create Couchbase Bucket, Scope, and Collection<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The following code block ensures that the necessary Couchbase bucket, scope, and collection are available.\nIt will create them if they don&#8217;t exist, and also clear any existing documents from the collection to start fresh.<\/p>\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 fail on Capella<\/p>\n<\/blockquote>\n\n\n\n<pre class=\"wp-block-code language-python\"><code># Set up collection\ntry:\n    # Check if bucket exists, create if it doesn&#039;t\n    try:\n        bucket = cluster.bucket(CB_BUCKET_NAME)\n        logging.info(f&quot;Bucket &#039;{CB_BUCKET_NAME}&#039; exists.&quot;)\n    except Exception as e:\n        logging.info(f&quot;Bucket &#039;{CB_BUCKET_NAME}&#039; does not exist. Creating it...&quot;)\n        bucket_settings = CreateBucketSettings(\n            name=CB_BUCKET_NAME,\n            bucket_type=&#039;couchbase&#039;,\n            ram_quota_mb=1024,\n            flush_enabled=True,\n            num_replicas=0\n        )\n        cluster.buckets().create_bucket(bucket_settings)\n        bucket = cluster.bucket(CB_BUCKET_NAME)\n        logging.info(f&quot;Bucket &#039;{CB_BUCKET_NAME}&#039; created successfully.&quot;)\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(scope.name == SCOPE_NAME for scope in scopes)\n\n    if not scope_exists and SCOPE_NAME != &quot;_default&quot;:\n        logging.info(f&quot;Scope &#039;{SCOPE_NAME}&#039; does not exist. Creating it...&quot;)\n        bucket_manager.create_scope(SCOPE_NAME)\n        logging.info(f&quot;Scope &#039;{SCOPE_NAME}&#039; created successfully.&quot;)\n\n    # Check if collection exists, create if it doesn&#039;t\n    collections = bucket_manager.get_all_scopes()\n    collection_exists = any(\n        scope.name == SCOPE_NAME and COLLECTION_NAME in [col.name for col in scope.collections]\n        for scope in collections\n    )\n\n    if not collection_exists:\n        logging.info(f&quot;Collection &#039;{COLLECTION_NAME}&#039; does not exist. Creating it...&quot;)\n        bucket_manager.create_collection(SCOPE_NAME, COLLECTION_NAME)\n        logging.info(f&quot;Collection &#039;{COLLECTION_NAME}&#039; created successfully.&quot;)\n    else:\n        logging.info(f&quot;Collection &#039;{COLLECTION_NAME}&#039; already exists. Skipping creation.&quot;)\n\n    # Wait for collection to be ready\n    collection = bucket.scope(SCOPE_NAME).collection(COLLECTION_NAME)\n    time.sleep(2)  # Give the collection time to be ready for queries\n\n    # Ensure primary index exists\n    try:\n        cluster.query(f&quot;CREATE PRIMARY INDEX IF NOT EXISTS ON `{CB_BUCKET_NAME}`.`{SCOPE_NAME}`.`{COLLECTION_NAME}`&quot;).execute()\n        logging.info(&quot;Primary index present or created successfully.&quot;)\n    except Exception as e:\n        logging.error(f&quot;Error creating primary index: {str(e)}&quot;)\n\n    # Clear all documents in the collection\n    try:\n        query = f&quot;DELETE FROM `{CB_BUCKET_NAME}`.`{SCOPE_NAME}`.`{COLLECTION_NAME}`&quot;\n        cluster.query(query).execute()\n        logging.info(&quot;All documents cleared from the collection.&quot;)\n    except Exception as e:\n        logging.warning(f&quot;Error while clearing documents: {str(e)}. The collection might be empty.&quot;)\n\nexcept Exception as e:\n    logging.error(f&quot;Error setting up collection: {str(e)}&quot;)\n    raise\n<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>2025-05-08 13:34:19,133 - INFO - Bucket &#039;vector-search-testing&#039; exists.\n2025-05-08 13:34:21,149 - INFO - Collection &#039;bedrock&#039; already exists. Skipping creation.\n2025-05-08 13:34:24,304 - INFO - Primary index present or created successfully.\n2025-05-08 13:34:24,529 - INFO - All documents cleared from the collection.\n<\/code><\/pre>\n\n\n\n<h3 id=\"h-configure-couchbase-search-index\" class=\"wp-block-heading\">Configure Couchbase Search Index<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">This section focuses on setting up the Couchbase Search Index, which is essential for enabling vector search capabilities.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>The code will load an index definition from a local JSON file named <code>aws_index.json<\/code>.<\/li>\n\n\n<li><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.<\/li>\n\n<\/ul>\n\n\n\n<pre class=\"wp-block-code language-python\"><code># Set up search indexes\ntry:\n    # Construct path relative to the script file\n    # In a notebook, __file__ is not defined, so use os.getcwd() instead\n    script_dir = os.getcwd()\n    index_file_path = os.path.join(script_dir, &#039;aws_index.json&#039;)\n    # Load index definition from file\n    with open(index_file_path, &#039;r&#039;) as file:\n        index_definition = json.load(file)\n        logging.info(f&quot;Loaded index definition from aws_index.json&quot;)\nexcept Exception as e:\n    logging.error(f&quot;Error loading index definition: {str(e)}&quot;)\n    raise\n\ntry:\n    scope_index_manager = cluster.bucket(CB_BUCKET_NAME).scope(SCOPE_NAME).search_indexes()\n\n    # Check if index already exists\n    existing_indexes = scope_index_manager.get_all_indexes()\n    index_name = index_definition[&quot;name&quot;]\n\n    if index_name in [index.name for index in existing_indexes]:\n        logging.info(f&quot;Index &#039;{index_name}&#039; found&quot;)\n    else:\n        logging.info(f&quot;Creating new index &#039;{index_name}&#039;...&quot;)\n\n    # Create SearchIndex object from JSON definition\n    search_index = SearchIndex.from_json(index_definition)\n\n    # Upsert the index (create if not exists, update if exists)\n    scope_index_manager.upsert_index(search_index)\n    logging.info(f&quot;Index &#039;{index_name}&#039; successfully created\/updated.&quot;)\n\nexcept QueryIndexAlreadyExistsException:\n    logging.info(f&quot;Index &#039;{index_name}&#039; already exists. Skipping creation\/update.&quot;)\nexcept ServiceUnavailableException:\n    logging.error(&quot;Search service is not available. Please ensure the Search service is enabled in your Couchbase cluster.&quot;)\nexcept InternalServerFailureException as e:\n    logging.error(f&quot;Internal server error: {str(e)}&quot;)\n    raise\n<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>2025-05-08 13:34:24,537 - INFO - Loaded index definition from aws_index.json\n2025-05-08 13:34:25,659 - INFO - Index &#039;vector_search_bedrock&#039; found\n2025-05-08 13:34:26,348 - INFO - Index &#039;vector_search_bedrock&#039; already exists. Skipping creation\/update.\n<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code language-python\"><code># Initialize Bedrock runtime client for embeddings\nembeddings = BedrockEmbeddings(\n    client=bedrock_runtime,\n    model_id=&quot;amazon.titan-embed-text-v2:0&quot;\n)\nlogging.info(&quot;Successfully created Bedrock embeddings client&quot;)\n\n# Initialize vector store\nvector_store = CouchbaseSearchVectorStore(\n    cluster=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)\nlogging.info(&quot;Successfully created vector store&quot;)\n<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>2025-05-08 13:34:26,353 - INFO - Successfully created Bedrock embeddings client\n2025-05-08 13:34:29,660 - INFO - Successfully created vector store\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Let&#8217;s load the documents from the documents.json file and add them to our vector store:<\/p>\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><\/p>\n<\/blockquote>\n\n\n\n<pre class=\"wp-block-code language-python\"><code># Load documents from JSON file\ntry:\n    # In a notebook, __file__ is not defined, so use os.getcwd() instead\n    script_dir = os.getcwd()\n    documents_file_path = os.path.join(script_dir, &#039;documents.json&#039;)\n    with open(documents_file_path, &#039;r&#039;) as f:\n        data = json.load(f)\n        documents = data.get(&#039;documents&#039;, [])\n    logging.info(f&quot;Loaded {len(documents)} documents from documents.json&quot;)\nexcept Exception as e:\n    logging.error(f&quot;Error loading documents: {str(e)}&quot;)\n    raise\n\n# Add documents to vector store\nlogging.info(f&quot;Adding {len(documents)} documents to vector store...&quot;)\nfor i, doc in enumerate(documents, 1):\n    text = doc.get(&#039;text&#039;, &#039;&#039;)\n    metadata = doc.get(&#039;metadata&#039;, {})\n\n    # Ensure metadata is a dictionary before adding\n    if isinstance(metadata, str):\n        try:\n            metadata = json.loads(metadata)\n        except json.JSONDecodeError:\n            logging.warning(f&quot;Warning: Could not parse metadata for document {i}. Using empty metadata.&quot;)\n            metadata = {}\n    elif not isinstance(metadata, dict):\n        logging.warning(f&quot;Warning: Metadata for document {i} is not a dict or valid JSON string. Using empty metadata.&quot;)\n        metadata = {}\n\n    doc_id = vector_store.add_texts([text], [metadata])[0]\n    logging.info(f&quot;Added document {i}\/{len(documents)} with ID: {doc_id}&quot;)\n\n    # Add small delay between requests\n    time.sleep(1)\n\nlogging.info(f&quot;nProcessing complete: {len(documents)}\/{len(documents)} documents added successfully&quot;)\n<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>2025-05-08 13:34:29,670 - INFO - Loaded 7 documents from documents.json\n2025-05-08 13:34:29,670 - INFO - Adding 7 documents to vector store...\n2025-05-08 13:34:31,637 - INFO - Added document 1\/7 with ID: 884e8caae84545aa9e4735538b38f373\n2025-05-08 13:34:33,211 - INFO - Added document 2\/7 with ID: 61b9d4c9c5ee42a8a51e44ef0b55942a\n2025-05-08 13:34:34,784 - INFO - Added document 3\/7 with ID: c7cb7541a9004ead83b9b393bc44a9b5\n2025-05-08 13:34:36,886 - INFO - Added document 4\/7 with ID: c8b07eae2e3a42c1a8114397bc8bfa67\n2025-05-08 13:34:38,534 - INFO - Added document 5\/7 with ID: a4356e0801564ad1b2f3ccdf05284375\n2025-05-08 13:34:40,129 - INFO - Added document 6\/7 with ID: 647d0fddba8f4bb38fd66d291a669bb2\n2025-05-08 13:34:42,140 - INFO - Added document 7\/7 with ID: 3b57038a7a234992927756cb3307738f\n2025-05-08 13:34:43,142 - INFO - \nProcessing complete: 7\/7 documents added successfully\n<\/code><\/pre>\n\n\n\n<h3 id=\"h-custom-control-approach-implementation\" class=\"wp-block-heading\">Custom Control Approach Implementation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Now let&#8217;s implement the Custom Control approach for Bedrock agents. In this approach, the agent returns control to the application for function execution.<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code># Function to wait for agent status\ndef wait_for_agent_status(bedrock_agent_client, agent_id, target_statuses=[&#039;Available&#039;, &#039;PREPARED&#039;, &#039;NOT_PREPARED&#039;], max_attempts=30, delay=2):\n    &quot;&quot;&quot;Wait for agent to reach any of the target statuses&quot;&quot;&quot;\n    for attempt in range(max_attempts):\n        try:\n            response = bedrock_agent_client.get_agent(agentId=agent_id)\n            current_status = response[&#039;agent&#039;][&#039;agentStatus&#039;]\n\n            if current_status in target_statuses:\n                logging.info(f&quot;Agent {agent_id} reached status: {current_status}&quot;)\n                return current_status\n            elif current_status == &#039;FAILED&#039;:\n                logging.error(f&quot;Agent {agent_id} failed&quot;)\n                return &#039;FAILED&#039;\n\n            logging.info(f&quot;Agent status: {current_status}, waiting... (attempt {attempt + 1}\/{max_attempts})&quot;)\n            time.sleep(delay)\n\n        except Exception as e:\n            logging.error(f&quot;Error checking agent status: {str(e)}&quot;)\n            time.sleep(delay)\n\n    return current_status\n<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code language-python\"><code># Function to create a Bedrock agent with Custom Control action groups\ndef create_agent(bedrock_agent_client, name, instructions, functions, model_id=&quot;amazon.nova-pro-v1:0&quot;, agent_role_arn=None):\n    &quot;&quot;&quot;Create a Bedrock agent with Custom Control action groups&quot;&quot;&quot;\n    try:\n        # List existing agents\n        existing_agents = bedrock_agent_client.list_agents()\n        existing_agent = next(\n            (agent for agent in existing_agents[&#039;agentSummaries&#039;]\n             if agent[&#039;agentName&#039;] == name),\n            None\n        )\n\n        # Handle existing agent\n        if existing_agent:\n            agent_id = existing_agent[&#039;agentId&#039;]\n            logging.info(f&quot;Found existing agent &#039;{name}&#039; with ID: {agent_id}&quot;)\n\n            # Check agent status\n            response = bedrock_agent_client.get_agent(agentId=agent_id)\n            status = response[&#039;agent&#039;][&#039;agentStatus&#039;]\n\n            if status in [&#039;NOT_PREPARED&#039;, &#039;FAILED&#039;]:\n                logging.info(f&quot;Deleting agent &#039;{name}&#039; with status {status}&quot;)\n                bedrock_agent_client.delete_agent(agentId=agent_id)\n                time.sleep(10)  # Wait after deletion\n                existing_agent = None\n\n        # Create new agent if needed\n        if not existing_agent:\n            logging.info(f&quot;Creating new agent &#039;{name}&#039;&quot;)\n            agent_params = {\n                &quot;agentName&quot;: name,\n                &quot;description&quot;: f&quot;{name.title()} agent for document operations&quot;,\n                &quot;instruction&quot;: instructions,\n                &quot;idleSessionTTLInSeconds&quot;: 1800,\n                &quot;foundationModel&quot;: model_id\n            }\n            \n            if agent_role_arn:\n                agent_params[&quot;agentResourceRoleArn&quot;] = agent_role_arn\n                \n            agent = bedrock_agent_client.create_agent(**agent_params)\n            agent_id = agent[&#039;agent&#039;][&#039;agentId&#039;]\n            logging.info(f&quot;Created new agent &#039;{name}&#039; with ID: {agent_id}&quot;)\n        else:\n            agent_id = existing_agent[&#039;agentId&#039;]\n\n        # Wait for initial creation if needed\n        status = wait_for_agent_status(bedrock_agent_client, agent_id, target_statuses=[&#039;NOT_PREPARED&#039;, &#039;PREPARED&#039;, &#039;Available&#039;])\n        if status not in [&#039;NOT_PREPARED&#039;, &#039;PREPARED&#039;, &#039;Available&#039;]:\n            raise Exception(f&quot;Agent failed to reach valid state: {status}&quot;)\n\n        # Create action group if needed\n        try:\n            bedrock_agent_client.create_agent_action_group(\n                agentId=agent_id,\n                agentVersion=&quot;DRAFT&quot;,\n                actionGroupExecutor={&quot;customControl&quot;: &quot;RETURN_CONTROL&quot;},  # This is the key for Custom Control\n                actionGroupName=f&quot;{name}_actions&quot;,\n                functionSchema={&quot;functions&quot;: functions},\n                description=f&quot;Action group for {name} operations&quot;\n            )\n            logging.info(f&quot;Created action group for agent &#039;{name}&#039;&quot;)\n            time.sleep(5)\n        except bedrock_agent_client.exceptions.ConflictException:\n            logging.info(f&quot;Action group already exists for agent &#039;{name}&#039;&quot;)\n\n        # Prepare agent if needed\n        if status == &#039;NOT_PREPARED&#039;:\n            try:\n                logging.info(f&quot;Starting preparation for agent &#039;{name}&#039;&quot;)\n                bedrock_agent_client.prepare_agent(agentId=agent_id)\n                status = wait_for_agent_status(\n                    bedrock_agent_client,\n                    agent_id,\n                    target_statuses=[&#039;PREPARED&#039;, &#039;Available&#039;]\n                )\n                logging.info(f&quot;Agent &#039;{name}&#039; preparation completed with status: {status}&quot;)\n            except Exception as e:\n                logging.error(f&quot;Error during preparation: {str(e)}&quot;)\n\n        # Handle alias creation\/retrieval\n        try:\n            aliases = bedrock_agent_client.list_agent_aliases(agentId=agent_id)\n            alias = next((a for a in aliases[&#039;agentAliasSummaries&#039;] if a[&#039;agentAliasName&#039;] == &#039;v1&#039;), None)\n\n            if not alias:\n                logging.info(f&quot;Creating new alias for agent &#039;{name}&#039;&quot;)\n                alias = bedrock_agent_client.create_agent_alias(\n                    agentId=agent_id,\n                    agentAliasName=&quot;v1&quot;\n                )\n                alias_id = alias[&#039;agentAlias&#039;][&#039;agentAliasId&#039;]\n            else:\n                alias_id = alias[&#039;agentAliasId&#039;]\n                logging.info(f&quot;Using existing alias for agent &#039;{name}&#039;&quot;)\n\n            logging.info(f&quot;Successfully configured agent &#039;{name}&#039; with ID: {agent_id} and alias: {alias_id}&quot;)\n            return agent_id, alias_id\n\n        except Exception as e:\n            logging.error(f&quot;Error managing alias: {str(e)}&quot;)\n            raise\n\n    except Exception as e:\n        logging.error(f&quot;Error creating\/updating agent: {str(e)}&quot;)\n        raise\n<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code language-python\"><code># Function to invoke a Bedrock agent\ndef invoke_agent(bedrock_runtime_client, agent_id, alias_id, input_text, session_id=None, vector_store=None):\n    &quot;&quot;&quot;Invoke a Bedrock agent&quot;&quot;&quot;\n    if session_id is None:\n        session_id = str(uuid.uuid4())\n\n    try:\n        logging.info(f&quot;Invoking agent with input: {input_text}&quot;)\n\n        response = bedrock_runtime_client.invoke_agent(\n            agentId=agent_id,\n            agentAliasId=alias_id,\n            sessionId=session_id,\n            inputText=input_text,\n            enableTrace=True\n        )\n\n        result = &quot;&quot;\n\n        for event in response[&#039;completion&#039;]:\n            # Process text chunks\n            if &#039;chunk&#039; in event:\n                chunk = event[&#039;chunk&#039;][&#039;bytes&#039;].decode(&#039;utf-8&#039;)\n                result += chunk\n\n            # Handle custom control return\n            if &#039;returnControl&#039; in event:\n                return_control = event[&#039;returnControl&#039;]\n                invocation_inputs = return_control.get(&#039;invocationInputs&#039;, [])\n\n                if invocation_inputs:\n                    function_input = invocation_inputs[0].get(&#039;functionInvocationInput&#039;, {})\n                    action_group = function_input.get(&#039;actionGroup&#039;)\n                    function_name = function_input.get(&#039;function&#039;)\n                    parameters = function_input.get(&#039;parameters&#039;, [])\n\n                    # Convert parameters to a dictionary\n                    param_dict = {}\n                    for param in parameters:\n                        param_dict[param.get(&#039;name&#039;)] = param.get(&#039;value&#039;)\n\n                    logging.info(f&quot;Function call: {action_group}::{function_name}&quot;)\n\n                    # Handle search_documents function\n                    if function_name == &#039;search_documents&#039;:\n                        query = param_dict.get(&#039;query&#039;)\n                        k = int(param_dict.get(&#039;k&#039;, 3))\n\n                        logging.info(f&quot;Searching for: {query}, k={k}&quot;)\n\n                        if vector_store:\n                            # Perform the search\n                            docs = vector_store.similarity_search(query, k=k)\n\n                            # Format results\n                            search_results = [doc.page_content for doc in docs]\n                            logging.info(f&quot;Found {len(search_results)} results&quot;)\n\n                            # Format the response\n                            result = f&quot;Search results for &#039;{query}&#039;:nn&quot;\n                            for i, content in enumerate(search_results):\n                                result += f&quot;Result {i+1}: {content}nn&quot;\n                        else:\n                            logging.error(&quot;Vector store not available&quot;)\n                            result = &quot;Error: Vector store not available&quot;\n\n                    # Handle format_content function\n                    elif function_name == &#039;format_content&#039;:\n                        content = param_dict.get(&#039;content&#039;)\n                        style = param_dict.get(&#039;style&#039;, &#039;user-friendly&#039;)\n\n                        logging.info(f&quot;Formatting content in {style} style&quot;)\n\n                        # Check if content is valid\n                        if content and content != &#039;?&#039;:\n                            result = f&quot;Formatted in {style} style: {content}&quot;\n                        else:\n                            result = &quot;No content provided to format.&quot;\n                    else:\n                        logging.error(f&quot;Unknown function: {function_name}&quot;)\n                        result = f&quot;Error: Unknown function {function_name}&quot;\n\n        if not result.strip():\n            logging.warning(&quot;Received empty response from agent&quot;)\n\n        return result\n\n    except Exception as e:\n        logging.error(f&quot;Error invoking agent: {str(e)}&quot;)\n        raise RuntimeError(f&quot;Failed to invoke agent: {str(e)}&quot;)\n<\/code><\/pre>\n\n\n\n<h3 id=\"h-define-agent-instructions-and-functions\" class=\"wp-block-heading\">Define Agent Instructions and Functions<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Now let&#8217;s define the instructions and functions for our agents:<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code># Researcher agent instructions and functions\nresearcher_instructions = &quot;&quot;&quot;\nYou are a Research Assistant that helps users find relevant information in documents.\nYour capabilities include:\n1. Searching through documents using semantic similarity\n2. Providing relevant document excerpts\n3. Answering questions based on document content\n&quot;&quot;&quot;\n\nresearcher_functions = [\n    {\n        &quot;name&quot;: &quot;search_documents&quot;,\n        &quot;description&quot;: &quot;Search for relevant documents using semantic similarity&quot;,\n        &quot;parameters&quot;: {\n            &quot;query&quot;: {\n                &quot;type&quot;: &quot;string&quot;,\n                &quot;description&quot;: &quot;The search query&quot;,\n                &quot;required&quot;: True\n            },\n            &quot;k&quot;: {\n                &quot;type&quot;: &quot;integer&quot;,\n                &quot;description&quot;: &quot;Number of results to return&quot;,\n                &quot;required&quot;: False\n            }\n        },\n        &quot;requireConfirmation&quot;: &quot;DISABLED&quot;\n    }\n]\n\n# Writer agent instructions and functions\nwriter_instructions = &quot;&quot;&quot;\nYou are a Content Writer Assistant that helps format and present research findings.\nYour capabilities include:\n1. Formatting research findings in a user-friendly way\n2. Creating clear and engaging summaries\n3. Organizing information logically\n4. Highlighting key insights\n&quot;&quot;&quot;\n\nwriter_functions = [\n    {\n        &quot;name&quot;: &quot;format_content&quot;,\n        &quot;description&quot;: &quot;Format and present research findings&quot;,\n        &quot;parameters&quot;: {\n            &quot;content&quot;: {\n                &quot;type&quot;: &quot;string&quot;,\n                &quot;description&quot;: &quot;The research findings to format&quot;,\n                &quot;required&quot;: True\n            },\n            &quot;style&quot;: {\n                &quot;type&quot;: &quot;string&quot;,\n                &quot;description&quot;: &quot;The desired presentation style (e.g., summary, detailed, bullet points)&quot;,\n                &quot;required&quot;: False\n            }\n        },\n        &quot;requireConfirmation&quot;: &quot;DISABLED&quot;\n    }\n]\n<\/code><\/pre>\n\n\n\n<h3 id=\"h-run-custom-control-approach\" class=\"wp-block-heading\">Run Custom Control Approach<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Now let&#8217;s run the Custom Control approach with our agents:<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code># Get or Create IAM Role\nagent_role_name = &quot;BedrockExecutionRoleForAgents_CustomControl&quot;\ntrust_policy = {\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;: &quot;bedrock.amazonaws.com&quot;\n            },\n            &quot;Action&quot;: &quot;sts:AssumeRole&quot;\n        }\n    ]\n}\npolicy_arn_to_attach = &quot;arn:aws:iam::aws:policy\/AmazonBedrockFullAccess&quot;\n\ntry:\n    role_response = iam_client.get_role(RoleName=agent_role_name)\n    agent_role_arn = role_response[&#039;Role&#039;][&#039;Arn&#039;]\n    logging.info(f&quot;Found existing IAM role &#039;{agent_role_name}&#039; with ARN: {agent_role_arn}&quot;)\nexcept ClientError as e:\n    if e.response[&#039;Error&#039;][&#039;Code&#039;] == &#039;NoSuchEntity&#039;:\n        logging.info(f&quot;IAM role &#039;{agent_role_name}&#039; not found. Creating...&quot;)\n        try:\n            role_response = iam_client.create_role(\n                RoleName=agent_role_name,\n                AssumeRolePolicyDocument=json.dumps(trust_policy),\n                Description=&quot;IAM role for Bedrock Agents execution&quot;\n            )\n            agent_role_arn = role_response[&#039;Role&#039;][&#039;Arn&#039;]\n            logging.info(f&quot;Created IAM role &#039;{agent_role_name}&#039; with ARN: {agent_role_arn}&quot;)\n            # Wait a bit for the role to be fully available before attaching policy\n            time.sleep(10)\n        except ClientError as create_error:\n            logging.error(f&quot;Error creating IAM role &#039;{agent_role_name}&#039;: {create_error}&quot;)\n            agent_role_arn = None\n    else:\n        logging.error(f&quot;Error getting IAM role &#039;{agent_role_name}&#039;: {e}&quot;)\n        agent_role_arn = None\n\n# Attach the policy if not already attached\nif agent_role_arn:\n    try:\n        attached_policies = iam_client.list_attached_role_policies(RoleName=agent_role_name)\n        if not any(p[&#039;PolicyArn&#039;] == policy_arn_to_attach for p in attached_policies.get(&#039;AttachedPolicies&#039;, [])):\n            logging.info(f&quot;Attaching policy &#039;{policy_arn_to_attach}&#039; to role &#039;{agent_role_name}&#039;...&quot;)\n            iam_client.attach_role_policy(\n                RoleName=agent_role_name,\n                PolicyArn=policy_arn_to_attach\n            )\n            logging.info(f&quot;Policy &#039;{policy_arn_to_attach}&#039; attached successfully.&quot;)\n            # Wait a bit for the policy attachment to propagate\n            time.sleep(5)\n        else:\n            logging.info(f&quot;Policy &#039;{policy_arn_to_attach}&#039; already attached to role &#039;{agent_role_name}&#039;.&quot;)\n    except ClientError as attach_error:\n        logging.warning(f&quot;Error attaching policy to role &#039;{agent_role_name}&#039;: {attach_error}&quot;)\n<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>2025-05-08 13:34:44,254 - INFO - Found existing IAM role &#039;BedrockExecutionRoleForAgents_CustomControl&#039; with ARN: arn:aws:iam::598307997273:role\/BedrockExecutionRoleForAgents_CustomControl\n2025-05-08 13:34:44,547 - INFO - Policy &#039;arn:aws:iam::aws:policy\/AmazonBedrockFullAccess&#039; already attached to role &#039;BedrockExecutionRoleForAgents_CustomControl&#039;.\n<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code language-python\"><code># Create researcher agent\nresearcher_id = None\nresearcher_alias = None\n\nif agent_role_arn:\n    try:\n        researcher_id, researcher_alias = create_agent(\n            bedrock_agent_client,\n            &quot;researcher&quot;,\n            researcher_instructions,\n            researcher_functions,\n            agent_role_arn=agent_role_arn\n        )\n        logging.info(f&quot;Researcher agent created with ID: {researcher_id} and alias: {researcher_alias}&quot;)\n    except Exception as e:\n        logging.error(f&quot;Failed to create researcher agent: {str(e)}&quot;)\nelse:\n    logging.error(&quot;No agent role ARN available for researcher agent creation&quot;)\n<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>2025-05-08 13:34:45,303 - INFO - Found existing agent &#039;researcher&#039; with ID: FF1OSFJIJF\n2025-05-08 13:34:46,399 - INFO - Agent FF1OSFJIJF reached status: PREPARED\n2025-05-08 13:34:46,712 - INFO - Action group already exists for agent &#039;researcher&#039;\n2025-05-08 13:34:46,996 - INFO - Using existing alias for agent &#039;researcher&#039;\n2025-05-08 13:34:46,997 - INFO - Successfully configured agent &#039;researcher&#039; with ID: FF1OSFJIJF and alias: RQVFGLBCZP\n2025-05-08 13:34:46,997 - INFO - Researcher agent created with ID: FF1OSFJIJF and alias: RQVFGLBCZP\n<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code language-python\"><code># Create writer agent\nwriter_id = None\nwriter_alias = None\n\nif agent_role_arn:\n    try:\n        writer_id, writer_alias = create_agent(\n            bedrock_agent_client,\n            &quot;writer&quot;,\n            writer_instructions,\n            writer_functions,\n            agent_role_arn=agent_role_arn\n        )\n        logging.info(f&quot;Writer agent created with ID: {writer_id} and alias: {writer_alias}&quot;)\n    except Exception as e:\n        logging.error(f&quot;Failed to create writer agent: {str(e)}&quot;)\nelse:\n    logging.error(&quot;No agent role ARN available for writer agent creation&quot;)\n\nif not any([researcher_id, writer_id]):\n    # Adjust error message based on whether role setup failed\n    if not agent_role_arn:\n        raise RuntimeError(&quot;Failed to create agents because IAM role setup failed.&quot;)\n    else:\n        raise RuntimeError(&quot;Failed to create any agents despite successful IAM role setup.&quot;)\n<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>2025-05-08 13:34:47,279 - INFO - Found existing agent &#039;writer&#039; with ID: JDA8S8SRS1\n2025-05-08 13:34:48,178 - INFO - Agent JDA8S8SRS1 reached status: PREPARED\n2025-05-08 13:34:48,498 - INFO - Action group already exists for agent &#039;writer&#039;\n2025-05-08 13:34:48,797 - INFO - Using existing alias for agent &#039;writer&#039;\n2025-05-08 13:34:48,797 - INFO - Successfully configured agent &#039;writer&#039; with ID: JDA8S8SRS1 and alias: 3SFKJGSGNQ\n2025-05-08 13:34:48,798 - INFO - Writer agent created with ID: JDA8S8SRS1 and alias: 3SFKJGSGNQ\n<\/code><\/pre>\n\n\n\n<h3 id=\"h-test-the-agents\" class=\"wp-block-heading\">Test the Agents<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Let&#8217;s test our agents by asking the researcher agent to search for information and the writer agent to format the results:<\/p>\n\n\n\n<pre class=\"wp-block-code language-python\"><code># Test researcher agent\nif researcher_id and researcher_alias:\n    researcher_response = invoke_agent(\n        bedrock_runtime_client,\n        researcher_id,\n        researcher_alias,\n        &quot;What is unique about the Cline AI assistant? Use the search_documents function to find relevant information.&quot;,\n        vector_store=vector_store\n    )\n    print(&quot;nResearcher Response:n&quot;, researcher_response)\nelse:\n    logging.error(&quot;Researcher agent not available for testing&quot;)\n<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>2025-05-08 13:34:48,808 - INFO - Invoking agent with input: What is unique about the Cline AI assistant? Use the search_documents function to find relevant information.\n2025-05-08 13:34:51,478 - INFO - Function call: researcher_actions::search_documents\n2025-05-08 13:34:51,478 - INFO - Searching for: What is unique about the Cline AI assistant?, k=3\n2025-05-08 13:34:52,791 - INFO - Found 3 results\n\n\n\nResearcher Response:\n Search results for &#039;What is unique about the Cline AI assistant?&#039;:\n\nResult 1: The Cline AI assistant, developed by Saoud Rizwan, is a unique system that combines vector search capabilities with Amazon Bedrock agents. Unlike traditional chatbots, it uses a sophisticated multi-agent architecture where specialized agents handle different aspects of document processing and interaction.\n\nResult 2: One of Cline&#039;s key features is its ability to create MCP (Model Context Protocol) servers on the fly. This allows users to extend the system&#039;s capabilities by adding new tools and resources that connect to external APIs, all while maintaining a secure and non-interactive environment.\n\nResult 3: The browser automation capabilities in Cline are implemented through Puppeteer, allowing the system to interact with web interfaces in a controlled 900x600 pixel window. This enables testing of web applications, verification of changes, and even general web browsing tasks.\n<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code language-python\"><code># Test writer agent\nif writer_id and writer_alias and &quot;researcher_response&quot; in locals():\n    writer_response = invoke_agent(\n        bedrock_runtime_client,\n        writer_id,\n        writer_alias,\n        f&quot;Format this research finding using the format_content function: {researcher_response}&quot;,\n        vector_store=vector_store\n    )\n    print(&quot;nWriter Response:n&quot;, writer_response)\nelse:\n    logging.error(&quot;Writer agent not available for testing or no researcher response to format&quot;)\n<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>2025-05-08 13:34:52,798 - INFO - Invoking agent with input: Format this research finding using the format_content function: Search results for &#039;What is unique about the Cline AI assistant?&#039;:\n\nResult 1: The Cline AI assistant, developed by Saoud Rizwan, is a unique system that combines vector search capabilities with Amazon Bedrock agents. Unlike traditional chatbots, it uses a sophisticated multi-agent architecture where specialized agents handle different aspects of document processing and interaction.\n\nResult 2: One of Cline&#039;s key features is its ability to create MCP (Model Context Protocol) servers on the fly. This allows users to extend the system&#039;s capabilities by adding new tools and resources that connect to external APIs, all while maintaining a secure and non-interactive environment.\n\nResult 3: The browser automation capabilities in Cline are implemented through Puppeteer, allowing the system to interact with web interfaces in a controlled 900x600 pixel window. This enables testing of web applications, verification of changes, and even general web browsing tasks.\n\n\n2025-05-08 13:34:55,730 - INFO - Function call: writer_actions::format_content\n2025-05-08 13:34:55,730 - INFO - Formatting content in summary style\n\n\n\nWriter Response:\n Formatted in summary style: The Cline AI assistant, developed by Saoud Rizwan, is a unique system that combines vector search capabilities with Amazon Bedrock agents. Unlike traditional chatbots, it uses a sophisticated multi-agent architecture where specialized agents handle different aspects of document processing and interaction. One of Cline&#039;s key features is its ability to create MCP (Model Context Protocol) servers on the fly. This allows users to extend the system&#039;s capabilities by adding new tools and resources that connect to external APIs, all while maintaining a secure and non-interactive environment. The browser automation capabilities in Cline are implemented through Puppeteer, allowing the system to interact with web interfaces in a controlled 900x600 pixel window. This enables testing of web applications, verification of changes, and even general web browsing tasks.\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 Custom Control approach for implementing AWS Bedrock agents with Couchbase Vector Search. This approach allows the agent to return control to the application for function execution, providing more flexibility and control over the agent&#8217;s behavior.<\/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>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>Custom Control<\/strong>: We implemented the Custom Control approach, where the agent returns control to the application for function execution.<\/li>\n\n\n<li><strong>Function Handling<\/strong>: We handled the agent&#8217;s function calls in the application code, allowing for more control and flexibility.<\/li>\n\n<\/ol>\n\n\n\n<p class=\"wp-block-paragraph\">This approach is particularly useful when you need more control over the agent&#8217;s behavior or when you want to integrate the agent with existing systems and data sources.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>View Source This notebook demonstrates the Custom Control approach for implementing AWS Bedrock agents with Couchbase Vector Search. In this approach, the agent returns control to the application for function execution. We&#8217;ll implement a multi-agent architecture with specialized agents for different tasks: Alternative Approaches This notebook demonstrates the Custom Control approach for AWS Bedrock Agents. [&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-10315","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 AWS Bedrock (Custom Control) - 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\/pt\/developers\/tutorials\/aws-bedrock-agents-custom-control\/\" \/>\n<meta property=\"og:locale\" content=\"pt_BR\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Building Intelligent Agents with AWS Bedrock (Custom Control)\" \/>\n<meta property=\"og:description\" content=\"View Source This notebook demonstrates the Custom Control approach for implementing AWS Bedrock agents with Couchbase Vector Search. In this approach, the agent returns control to the application for function execution. We&#8217;ll implement a multi-agent architecture with specialized agents for different tasks: Alternative Approaches This notebook demonstrates the Custom Control approach for AWS Bedrock Agents. [&hellip;]\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.couchbase.com\/pt\/developers\/tutorials\/aws-bedrock-agents-custom-control\/\" \/>\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=\"28 minutos\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/www.couchbase.com\\\/pt\\\/developers\\\/tutorials\\\/aws-bedrock-agents-custom-control\\\/\",\"url\":\"https:\\\/\\\/www.couchbase.com\\\/pt\\\/developers\\\/tutorials\\\/aws-bedrock-agents-custom-control\\\/\",\"name\":\"Building Intelligent Agents with AWS Bedrock (Custom Control) - Couchbase\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/www.couchbase.com\\\/pt\\\/#website\"},\"datePublished\":\"2025-12-09T10:13:28+00:00\",\"breadcrumb\":{\"@id\":\"https:\\\/\\\/www.couchbase.com\\\/pt\\\/developers\\\/tutorials\\\/aws-bedrock-agents-custom-control\\\/#breadcrumb\"},\"inLanguage\":\"pt-BR\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/www.couchbase.com\\\/pt\\\/developers\\\/tutorials\\\/aws-bedrock-agents-custom-control\\\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/www.couchbase.com\\\/pt\\\/developers\\\/tutorials\\\/aws-bedrock-agents-custom-control\\\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\\\/\\\/www.couchbase.com\\\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Building Intelligent Agents with AWS Bedrock (Custom Control)\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/www.couchbase.com\\\/pt\\\/#website\",\"url\":\"https:\\\/\\\/www.couchbase.com\\\/pt\\\/\",\"name\":\"Couchbase\",\"description\":\"The Operational Data Platform for AI\u2122\",\"publisher\":{\"@id\":\"https:\\\/\\\/www.couchbase.com\\\/pt\\\/#organization\"},\"alternateName\":\"Couchbase, Inc.\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/www.couchbase.com\\\/pt\\\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"pt-BR\"},{\"@type\":\"Organization\",\"@id\":\"https:\\\/\\\/www.couchbase.com\\\/pt\\\/#organization\",\"name\":\"Couchbase\",\"alternateName\":\"Couchbase, Inc.\",\"url\":\"https:\\\/\\\/www.couchbase.com\\\/pt\\\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"pt-BR\",\"@id\":\"https:\\\/\\\/www.couchbase.com\\\/pt\\\/#\\\/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\\\/pt\\\/#\\\/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 AWS Bedrock (Custom Control) - 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\/pt\/developers\/tutorials\/aws-bedrock-agents-custom-control\/","og_locale":"pt_BR","og_type":"article","og_title":"Building Intelligent Agents with AWS Bedrock (Custom Control)","og_description":"View Source This notebook demonstrates the Custom Control approach for implementing AWS Bedrock agents with Couchbase Vector Search. In this approach, the agent returns control to the application for function execution. We&#8217;ll implement a multi-agent architecture with specialized agents for different tasks: Alternative Approaches This notebook demonstrates the Custom Control approach for AWS Bedrock Agents. [&hellip;]","og_url":"https:\/\/www.couchbase.com\/pt\/developers\/tutorials\/aws-bedrock-agents-custom-control\/","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":"28 minutos"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"WebPage","@id":"https:\/\/www.couchbase.com\/pt\/developers\/tutorials\/aws-bedrock-agents-custom-control\/","url":"https:\/\/www.couchbase.com\/pt\/developers\/tutorials\/aws-bedrock-agents-custom-control\/","name":"Building Intelligent Agents with AWS Bedrock (Custom Control) - Couchbase","isPartOf":{"@id":"https:\/\/www.couchbase.com\/pt\/#website"},"datePublished":"2025-12-09T10:13:28+00:00","breadcrumb":{"@id":"https:\/\/www.couchbase.com\/pt\/developers\/tutorials\/aws-bedrock-agents-custom-control\/#breadcrumb"},"inLanguage":"pt-BR","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.couchbase.com\/pt\/developers\/tutorials\/aws-bedrock-agents-custom-control\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/www.couchbase.com\/pt\/developers\/tutorials\/aws-bedrock-agents-custom-control\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/www.couchbase.com\/"},{"@type":"ListItem","position":2,"name":"Building Intelligent Agents with AWS Bedrock (Custom Control)"}]},{"@type":"WebSite","@id":"https:\/\/www.couchbase.com\/pt\/#website","url":"https:\/\/www.couchbase.com\/pt\/","name":"Couchbase","description":"The Operational Data Platform for AI\u2122","publisher":{"@id":"https:\/\/www.couchbase.com\/pt\/#organization"},"alternateName":"Couchbase, Inc.","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.couchbase.com\/pt\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"pt-BR"},{"@type":"Organization","@id":"https:\/\/www.couchbase.com\/pt\/#organization","name":"Couchbase","alternateName":"Couchbase, Inc.","url":"https:\/\/www.couchbase.com\/pt\/","logo":{"@type":"ImageObject","inLanguage":"pt-BR","@id":"https:\/\/www.couchbase.com\/pt\/#\/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\/pt\/#\/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":"A Couchbase \u00e9 uma empresa de software de banco de dados com sede em San Jose, Calif\u00f3rnia, que fornece uma plataforma de dados operacional para a intelig\u00eancia artificial utilizada por centenas de empresas globais.","legalName":"Couchbase, Inc.","foundingDate":"2011-01-01"}]}},"acf":[],"permalink_manager":null,"_links":{"self":[{"href":"https:\/\/www.couchbase.com\/pt\/wp-json\/wp\/v2\/tutorials\/10315","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.couchbase.com\/pt\/wp-json\/wp\/v2\/tutorials"}],"about":[{"href":"https:\/\/www.couchbase.com\/pt\/wp-json\/wp\/v2\/types\/tutorials"}],"version-history":[{"count":0,"href":"https:\/\/www.couchbase.com\/pt\/wp-json\/wp\/v2\/tutorials\/10315\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.couchbase.com\/pt\/wp-json\/wp\/v2\/media?parent=10315"}],"wp:term":[{"taxonomy":"tutorial-languages","embeddable":true,"href":"https:\/\/www.couchbase.com\/pt\/wp-json\/wp\/v2\/tutorial-languages?post=10315"},{"taxonomy":"tutorial-tags","embeddable":true,"href":"https:\/\/www.couchbase.com\/pt\/wp-json\/wp\/v2\/tutorial-tags?post=10315"},{"taxonomy":"tutorial-technologies","embeddable":true,"href":"https:\/\/www.couchbase.com\/pt\/wp-json\/wp\/v2\/tutorial-technologies?post=10315"},{"taxonomy":"tutorial-types","embeddable":true,"href":"https:\/\/www.couchbase.com\/pt\/wp-json\/wp\/v2\/tutorial-types?post=10315"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}