Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore(bedrock): agent refactoring #833

Merged
merged 41 commits into from
Jan 9, 2025
Merged

Conversation

aws-rafams
Copy link
Contributor

@aws-rafams aws-rafams commented Dec 3, 2024

Fixes #731, #767, #747

  • Interfaces
  • Unit Testing
  • Integ Testing

By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of the project license.

@aws-rafams aws-rafams requested a review from a team as a code owner December 3, 2024 14:13
@aws-rafams aws-rafams marked this pull request as draft December 3, 2024 14:13
@aws-rafams aws-rafams changed the title refactor(bedrock): Agent refactoring refactor(bedrock): agent refactoring Dec 3, 2024
@aws-rafams aws-rafams changed the title refactor(bedrock): agent refactoring chore(bedrock): agent refactoring Dec 3, 2024
@krokoko
Copy link
Collaborator

krokoko commented Dec 12, 2024

Testing to override default prompt for an agent:

const prompt_path = path.join(__dirname, 'pre-processing.txt');

    const file = readFileSync(prompt_path, 'utf-8');
    
    const agent = new bedrock.Agent(this, 'Agent', {
      foundationModel: bedrock.BedrockFoundationModel.AMAZON_NOVA_LITE_V1,
      instruction: 'You are a helpful and friendly agent that answers questions about literature.',
      userInputEnabled: true,
      codeInterpreterEnabled: false,
      shouldPrepareAgent:true,
      promptOverrideConfiguration: bedrock.PromptOverrideConfiguration.fromSteps(
        [
          {
            stepType: bedrock.AgentStepType.PRE_PROCESSING,
            stepEnabled: true,
            customPromptTemplate: file,
            inferenceConfig: {
              temperature: 0.0,
              topP: 1,
              topK: 250,
              maximumLength: 1,
              stopSequences: ["\n\nHuman:"],
            },
          }
        ]
      )
    });

Seems to work fine:

image

Need to test more scenarios

@krokoko
Copy link
Collaborator

krokoko commented Dec 12, 2024

Adding a guardrail fails:

// create your agent

const guardrails = new bedrock.Guardrail(this, "bedrockGuardrails", {
      name: "my-BedrockGuardrails",
      description: "Legal ethical guardrails.",
    });

    guardrails.addDeniedTopicFilter(bedrock.Topic.FINANCIAL_ADVICE);

    agent.addGuardrail(guardrails);

synth fails with:

validation-helpers.ts:98
    throw new Error(errors.join('\n'));
          ^
Error: The field version with value "${Token[TOKEN.1058]}" does not match the required pattern /^(([0-9]{1,8})|(DRAFT))$/
    at Object.throwIfInvalid (.../src/common/helpers/validation-helpers.ts:98:11)

from this:

public addGuardrail(guardrail: IGuardrail) {
    // Do some checks
    validation.throwIfInvalid(this.validateGuardrail, guardrail);
    // Add it to the construct
    this.guardrail = guardrail;
    // Handle permissions
    guardrail.grantApply(this.role);
  }

@aws-rafams
Copy link
Contributor Author

aws-rafams commented Dec 16, 2024

[FIXED]

Adding a guardrail fails:

// create your agent

const guardrails = new bedrock.Guardrail(this, "bedrockGuardrails", {
      name: "my-BedrockGuardrails",
      description: "Legal ethical guardrails.",
    });

    guardrails.addDeniedTopicFilter(bedrock.Topic.FINANCIAL_ADVICE);

    agent.addGuardrail(guardrails);

synth fails with:

validation-helpers.ts:98
    throw new Error(errors.join('\n'));
          ^
Error: The field version with value "${Token[TOKEN.1058]}" does not match the required pattern /^(([0-9]{1,8})|(DRAFT))$/
    at Object.throwIfInvalid (.../src/common/helpers/validation-helpers.ts:98:11)

from this:

public addGuardrail(guardrail: IGuardrail) {
    // Do some checks
    validation.throwIfInvalid(this.validateGuardrail, guardrail);
    // Add it to the construct
    this.guardrail = guardrail;
    // Handle permissions
    guardrail.grantApply(this.role);
  }

I see, validation occurs even when tokens are unresolved. Will modify and add the !cdk.Token.isUnresolved(guardrailName) part missing

@dineshSajwan
Copy link
Contributor

Tested Python samples with the changes and it worked all fine.
Screenshot 2024-12-19 at 12 09 04 PM

@krokoko
Copy link
Collaborator

krokoko commented Jan 7, 2025

Some issues were fixed in Cfn and the bedrock agent sample is now deploying correctly with the changes above
image

@krokoko
Copy link
Collaborator

krokoko commented Jan 7, 2025

Creating an agent alias and attaching it to an agent works:
image

creating 2 aliases, pointing to a specific version:
image

@krokoko
Copy link
Collaborator

krokoko commented Jan 7, 2025

CRIS works also as expected:
image

const cris = bedrock.CrossRegionInferenceProfile.fromConfig({
      geoRegion: bedrock.CrossRegionInferenceProfileRegion.US,
      model: bedrock.BedrockFoundationModel.ANTHROPIC_CLAUDE_3_5_SONNET_V1_0,
    });

    const agent = new bedrock.Agent(this, 'Agent', {
      foundationModel: cris,
      instruction: 'You are a helpful and friendly agent that answers questions about literature.',
      shouldPrepareAgent:true
    });

@krokoko
Copy link
Collaborator

krokoko commented Jan 8, 2025

Issue #747 is fixed with these changes. Following code snippets deploys and runs successfully:

const agent = new bedrock.Agent(this, "Agent", {
      foundationModel: bedrock.BedrockFoundationModel.ANTHROPIC_CLAUDE_HAIKU_V1_0,
      instruction: "You are a helpful and friendly agent that answers questions about literature.",
    });

    const agent2 = new bedrock.Agent(this, "Agent2", {
      foundationModel: bedrock.BedrockFoundationModel.ANTHROPIC_CLAUDE_HAIKU_V1_0,
      instruction: "You are a helpful and friendly agent that answers questions about literature.",
    });

    const actionGroupFunction = new lambda_python.PythonFunction(this, "ActionGroupFunction", {
      runtime: lambda.Runtime.PYTHON_3_12,
      entry: path.join(__dirname, "../lambda/action-group"),
    });
    
    const actionGroup = new bedrock.AgentActionGroup({
      name: "query-library",
      description: "Use these functions to get information about the books in the library.",
      executor: bedrock.ActionGroupExecutor.fromlambdaFunction(actionGroupFunction),
      enabled: true,
      apiSchema: bedrock.ApiSchema.fromLocalAsset(path.join(__dirname, "action-group.yaml")),
    });

    agent.addActionGroup(actionGroup);
    agent2.addActionGroup(actionGroup);

@krokoko
Copy link
Collaborator

krokoko commented Jan 8, 2025

Agent with Guardrails works as expected:
image

@krokoko krokoko marked this pull request as ready for review January 9, 2025 17:28
@krokoko krokoko enabled auto-merge (squash) January 9, 2025 17:32
@krokoko krokoko mentioned this pull request Jan 9, 2025
@krokoko krokoko merged commit 87617a4 into awslabs:main Jan 9, 2025
17 of 18 checks passed
@krokoko krokoko deleted the agent-refactoring branch February 10, 2025 18:00
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

(bedrock): agent module refactoring to follow best practices from CDK
4 participants