Thursday, March 14, 2024

Create AI Agent in AWS with Boto3 Code

 This video is a step-by-step tutorial with code as how to create Amazon Bedrock AI agents with boto3 in Python to integrate with Lambda.



Code used: Just use any lambda with it of your choice.


import logging
import boto3
import time
import yaml
import json
import io
from botocore.exceptions import ClientError

def create_agent(bedrock, agent_name, foundation_model, role_arn, instruction):
    try:
        # Create a low-level client with the service name
        response = bedrock.create_agent(
            agentName=agent_name,
            foundationModel=foundation_model,
            agentResourceRoleArn=role_arn,
            instruction=instruction,
        )
    except ClientError as e:
        logging.error(f"Couldn't create agent due to: {e}")
        raise
    else:
        return response["agent"]

def create_agent_action_group(bedrock, name, description, agent_id, agent_version, function_arn, api_schema):
    try:
        response = bedrock.create_agent_action_group(
            actionGroupName=name,
            description=description,
            agentId=agent_id,
            agentVersion=agent_version,
            actionGroupExecutor={"lambda": function_arn},
            apiSchema={"payload": api_schema},
        )
        agent_action_group = response["agentActionGroup"]
    except ClientError as e:
        print(f"Error: Couldn't create agent action group. Here's why: {e}")
        raise
    else:
        return agent_action_group

def prepare_agent(bedrock, agent_id):
    try:
        prepared_agent_details = bedrock.prepare_agent(agentId=agent_id)
    except ClientError as e:
        print(f"Couldn't prepare agent. {e}")
        raise
    else:
        return prepared_agent_details

def create_agent_alias(bedrock, name, agent_id):
    try:
        response = bedrock.create_agent_alias(
            agentAliasName=name, agentId=agent_id
        )
        agent_alias = response["agentAlias"]
    except ClientError as e:
        print(f"Couldn't create agent alias. {e}")
        raise
    else:
        return agent_alias



def main():
    # Define your parameters
    bedrock = boto3.client(service_name='bedrock-agent',region_name='us-east-1')
    agent_name = 'AstroAI'
    foundation_model = 'anthropic.claude-v2'
    role_arn = 'bedrock role arn'
    instruction = 'Your task is to generate unique and insightful daily horoscopes for individuals \
                   based on their zodiac sign. Start by analyzing the general characteristics and common \
                   themes associated with each zodiac sign. Consider traits, challenges, opportunities, \
                   and the emotional and physical wellbeing of individuals under each sign. Use this \
                   understanding to create personalized, relevant, and engaging horoscopes that offer \
                   guidance, reflection, and encouragement for the day ahead. Ensure the horoscopes \
                   are varied and resonate with the unique qualities of each sign, contributing \
                   positively to the users day.'

    # Call the create_agent function
    try:
        agent = create_agent(bedrock, agent_name, foundation_model, role_arn, instruction)
        agent_id = agent['agentId']
        print(f"Agent created successfully: {agent_id}")
    except ClientError:
        print("Failed to create the agent.")

    time.sleep(10)

    try:
        with open("api_schema.yaml") as file:
            api_schema=json.dumps(yaml.safe_load(file))
            name="AstroGroup"
            description="AI Astrologer"
            agent_version="DRAFT"
            function_arn="arn:aws:lambda:us-east-1::function:horoscope"
            agentgroup = create_agent_action_group(bedrock, name, description, agent_id, agent_version, function_arn, api_schema)                
            print(agentgroup['actionGroupId'])
    except ClientError as e:
        print(f"Couldn't create agent action group. Here's why: {e}")
        raise        

    time.sleep(5)

    agentprepared = prepare_agent(bedrock, agent_id)                
    print(agentprepared)

    time.sleep(20)

    agentalias = create_agent_alias(bedrock, name, agent_id)
    print(agentalias['agentAliasId'])

if __name__ == "__main__":
    main()

No comments: