-
Notifications
You must be signed in to change notification settings - Fork 44
/
Copy pathbedrock_agent_helper.py
2138 lines (1877 loc) · 92 KB
/
bedrock_agent_helper.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2024 Amazon.com and its affiliates; all rights reserved.
# This file is AWS Content and may not be duplicated or distributed without permission
"""
This module contains a helper class for building and using Agents for Amazon Bedrock.
The AgentsForAmazonBedrock class provides a convenient interface for working with Agents.
It includes methods for creating, updating, and invoking Agents, as well as managing
IAM roles and Lambda functions for action groups.
"""
import boto3
import json
import time
import uuid
import zipfile
from dateutil.tz import tzutc
import os
import datetime
from io import BytesIO
from typing import List, Dict, Tuple
import re
from boto3.session import Session
from botocore.config import Config
from boto3.dynamodb.conditions import Key
# import matplotlib.pyplot as plt
# import matplotlib.image as mpimg
# from IPython.display import display, Markdown
from termcolor import colored
from rich.console import Console
from rich.markdown import Markdown
PYTHON_TIMEOUT = 180
PYTHON_RUNTIME = "python3.12"
DEFAULT_ALIAS = "TSTALIASID"
DEFAULT_CI_ACTION_GROUP_NAME = "CodeInterpreterAction"
UNDECIDABLE_CLASSIFICATION = "undecidable"
ROUTER_MODEL = "us.anthropic.claude-3-haiku-20240307-v1:0"
TRACE_TRUNCATION_LENGTH = 300
# TODO: Take advantage of a default execution role so that we do not need to have lengthy
# waiting times when creating a new Agent or new Lambda to give time for the IAM role to
# take effect. When this is supported, need to change the default "delete_role_flag" to False
# to avoid deleting the default. And add logic to create the default role if it is not found.
# That way it should only need to be created once.
DEFAULT_AGENT_IAM_ROLE_NAME = "DEFAULT_AgentExecutionRole"
DEFAULT_AGENT_IAM_ASSUME_ROLE_POLICY = {
"Version": "2012-10-17",
"Statement": [
{
"Sid": "AllowBedrock",
"Effect": "Allow",
"Principal": {"Service": "bedrock.amazonaws.com"},
"Action": "sts:AssumeRole",
}
],
}
DEFAULT_AGENT_IAM_POLICY = {
"Version": "2012-10-17",
"Statement": [
{
"Sid": "AmazonBedrockAgentInferencProfilePolicy1",
"Effect": "Allow",
"Action": ["bedrock:InvokeModel*", "bedrock:CreateInferenceProfile"],
"Resource": [
"arn:aws:bedrock:*::foundation-model/*",
"arn:aws:bedrock:*:*:inference-profile/*",
"arn:aws:bedrock:*:*:application-inference-profile/*",
],
},
{
"Sid": "AmazonBedrockAgentInferencProfilePolicy2",
"Effect": "Allow",
"Action": [
"bedrock:GetInferenceProfile",
"bedrock:ListInferenceProfiles",
"bedrock:DeleteInferenceProfile",
"bedrock:TagResource",
"bedrock:UntagResource",
"bedrock:ListTagsForResource",
],
"Resource": [
"arn:aws:bedrock:*:*:inference-profile/*",
"arn:aws:bedrock:*:*:application-inference-profile/*",
],
},
{
"Sid": "AmazonBedrockAgentBedrockFoundationModelPolicy",
"Effect": "Allow",
"Action": ["bedrock:GetAgentAlias", "bedrock:InvokeAgent"],
"Resource": [
"arn:aws:bedrock:*:*:agent/*",
"arn:aws:bedrock:*:*:agent-alias/*",
],
},
{
"Sid": "AmazonBedrockAgentBedrockInvokeGuardrailModelPolicy",
"Effect": "Allow",
"Action": [
"bedrock:InvokeModel",
"bedrock:GetGuardrail",
"bedrock:ApplyGuardrail",
],
"Resource": "arn:aws:bedrock:*:*:guardrail/*",
},
{
"Sid": "QueryKB",
"Effect": "Allow",
"Action": ["bedrock:Retrieve", "bedrock:RetrieveAndGenerate"],
"Resource": "arn:aws:bedrock:*:*:knowledge-base/*",
},
],
}
# # setting logger
# logging.basicConfig(format='[%(asctime)s] p%(process)s {%(filename)s:%(lineno)d} %(levelname)s - %(message)s', level=logging.INFO)
# logger = logging.getLogger(__name__)
class AgentsForAmazonBedrock:
"""Provides an easy to use wrapper for Agents for Amazon Bedrock."""
def __init__(self):
"""Constructs an instance."""
self._boto_session = Session()
self._region = self._boto_session.region_name
self._account_id = boto3.client("sts").get_caller_identity()["Account"]
self._bedrock_agent_client = boto3.client("bedrock-agent")
long_invoke_time_config = Config(read_timeout=600)
self._bedrock_agent_runtime_client = boto3.client(
"bedrock-agent-runtime", config=long_invoke_time_config
)
self._sts_client = boto3.client("sts")
self._iam_client = boto3.client("iam")
self._lambda_client = boto3.client("lambda")
self._s3_client = boto3.client("s3", region_name=self._region)
self._dynamodb_client = boto3.client("dynamodb", region_name=self._region)
self._dynamodb_resource = boto3.resource("dynamodb", region_name=self._region)
self._suffix = f"{self._region}-{self._account_id}"
def get_region(self) -> str:
"""Returns the region for this instance."""
return self._region
def _create_lambda_iam_role(
self,
agent_name: str,
additional_function_iam_policy: Dict = None,
sub_agent_arns: List[str] = None,
dynamodb_table_name: str = None,
enable_trace: bool = False,
) -> object:
"""Creates an IAM role for a Lambda function built to implement an Action Group for an Agent.
Args:
agent_name (str): Name of the agent for which this Lambda supports, will be used as part of the role name
additional_function_iam_policy (Dict, optional): Additional IAM policy to be attached to the role. Defaults to None.
sub_agent_arns (List[str], optional): List of sub-agent ARNs to allow this Lambda to invoke. Defaults to [].
dynamodb_table_name (str, optional): Name of the DynamoDB table to that can be accessed by this Lambda. Defaults to None.
enable_trace (bool, optional): Whether to print out the ARN of the new role. Defaults to False.
Returns:
str: ARN of the new IAM role, to be used when creating a Lambda function
"""
_lambda_function_role_name = f"{agent_name}-lambda-role-{self._suffix}"
_dynamodb_access_policy_name = f"{agent_name}-dynamodb-policy"
# Create IAM Role for the Lambda function
try:
_assume_role_policy_document = {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {"Service": "lambda.amazonaws.com"},
"Action": "sts:AssumeRole",
}
],
}
_assume_role_policy_document_json = json.dumps(_assume_role_policy_document)
_lambda_iam_role = self._iam_client.create_role(
RoleName=_lambda_function_role_name,
AssumeRolePolicyDocument=_assume_role_policy_document_json,
)
# Pause to make sure role is created
time.sleep(10)
except:
_lambda_iam_role = self._iam_client.get_role(
RoleName=_lambda_function_role_name
)
# attach Lambda basic execution policy to the role
self._iam_client.attach_role_policy(
RoleName=_lambda_function_role_name,
PolicyArn="arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole",
)
# If an additional IAM policy has been provided, attach it to the role as well.
if additional_function_iam_policy is not None:
if enable_trace:
print(
f"Attaching additional IAM policy to Lambda role:\n{additional_function_iam_policy}"
)
self._iam_client.put_role_policy(
PolicyDocument=additional_function_iam_policy,
PolicyName="additional_function_policy",
RoleName=_lambda_function_role_name,
)
# create a policy to allow Lambda to invoke sub-agents and look up info about each sub-agent.
# include the ability to invoke the agent based on its ID, and allow use of any Agent Alias.
if sub_agent_arns is not None:
_tmp_resources = [
_sub_agent_arn.replace(":agent/", ":agent*/") + "*"
for _sub_agent_arn in sub_agent_arns
]
_sub_agent_policy_document = {
"Version": "2012-10-17",
"Statement": [
{
"Sid": "AmazonBedrockAgentInvokeSubAgentPolicy",
"Effect": "Allow",
"Action": ["bedrock:InvokeAgent", "bedrock:GetAgentAlias"],
"Resource": _tmp_resources,
},
{
"Sid": "AmazonBedrockAgentGetAgentPolicy",
"Effect": "Allow",
"Action": "bedrock:GetAgent",
"Resource": [
_sub_agent_arn for _sub_agent_arn in sub_agent_arns
],
},
],
}
# Attach the inline policy to the Lambda function's role
sub_agent_policy_json = json.dumps(_sub_agent_policy_document)
self._iam_client.put_role_policy(
PolicyDocument=sub_agent_policy_json,
PolicyName="sub_agent_policy",
RoleName=_lambda_function_role_name,
)
# Create a policy to grant access to the DynamoDB table
if dynamodb_table_name:
_dynamodb_access_policy = {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"dynamodb:GetItem",
"dynamodb:PutItem",
"dynamodb:DeleteItem",
"dynamodb:Query",
"dynamodb:UpdateItem",
],
"Resource": "arn:aws:dynamodb:{}:{}:table/{}".format(
self._region, self._account_id, dynamodb_table_name
),
}
],
}
# Attach the inline policy to the Lambda function's role
_dynamodb_access_policy_json = json.dumps(_dynamodb_access_policy)
self._iam_client.put_role_policy(
PolicyDocument=_dynamodb_access_policy_json,
PolicyName=_dynamodb_access_policy_name,
RoleName=_lambda_function_role_name,
)
return _lambda_iam_role["Role"]["Arn"]
def get_agent_latest_alias_id(self, agent_id: str, verbose: bool = False) -> str:
"""Gets the latest alias ID for the specified Agent.
Args:
agent_id (str): Id of the agent for which to get the latest alias ID
Returns:
str: Latest alias ID
"""
_agent_aliases = self._bedrock_agent_client.list_agent_aliases(
agentId=agent_id, maxResults=100
)
_latest_alias_id = ""
_latest_update = datetime.datetime(1970, 1, 1, 0, 0, 0, tzinfo=tzutc())
for _summary in _agent_aliases["agentAliasSummaries"]:
# print(_summary)
_curr_update = _summary["updatedAt"]
if _curr_update > _latest_update:
_latest_alias_id = _summary["agentAliasId"]
self.wait_agent_alias_status_update(
agent_id, _latest_alias_id, verbose=False
)
_latest_update = _curr_update
_alias_name = _summary["agentAliasName"]
# skip routing config since issue w/ version being blank
# print(f"agent id: {agent_id}, routing config: {_summary['routingConfiguration']}")
# _alias_version = _summary['routingConfiguration'][0]['agentVersion']
if verbose:
print(f"for id: {agent_id}, picked latest alias: {_latest_alias_id}")
print(f" updated at: {_latest_update}")
print(f" alias name: {_alias_name}\n") # , version: {_alias_version}\n")
return _latest_alias_id
def get_agent_alias_arn(
self, agent_id: str, agent_alias_id: str, verbose: bool = False
) -> str:
"""Gets the ARN of the specified Agent Alias.
Args:
agent_alias_id (str): Id of the agent alias for which to get the ARN
Returns:
str: ARN of the specified Agent Alias
"""
_agent_alias = self._bedrock_agent_client.get_agent_alias(
agentId=agent_id, agentAliasId=agent_alias_id
)
_alias_arn = _agent_alias["agentAlias"]["agentAliasArn"]
return _alias_arn
def get_agent_id_by_name(self, agent_name: str) -> str:
"""Gets the Agent ID for the specified Agent.
Args:
agent_name (str): Name of the agent whose ID is to be returned
Returns:
str: Agent ID, or None if not found
"""
_get_agents_resp = self._bedrock_agent_client.list_agents(maxResults=100)
_agents_json = _get_agents_resp["agentSummaries"]
_target_agent = next(
(agent for agent in _agents_json if agent["agentName"] == agent_name), None
)
if _target_agent is None:
return None
else:
return _target_agent["agentId"]
def associate_kb_with_agent(self, agent_id, description, kb_id):
"""Associates a Knowledge Base with an Agent, and prepares the agent.
Args:
agent_id (str): Id of the agent
description (str): Description of the KB
kb_id (str): Id of the KB
"""
_resp = self._bedrock_agent_client.associate_agent_knowledge_base(
agentId=agent_id,
agentVersion="DRAFT",
description=description,
knowledgeBaseId=kb_id,
knowledgeBaseState="ENABLED",
)
_resp = self._bedrock_agent_client.prepare_agent(agentId=agent_id)
def get_agent_arn_by_name(self, agent_name: str) -> str:
"""Gets the Agent ARN for the specified Agent.
Args:
agent_name (str): Name of the agent whose ARN is to be returned
Returns:
str: Agent ARN, or None if not found
"""
_agent_id = self.get_agent_id_by_name(agent_name)
if _agent_id is None:
raise ValueError(f"Agent {agent_name} not found")
_get_agent_resp = self._bedrock_agent_client.get_agent(agentId=_agent_id)
return _get_agent_resp["agent"]["agentArn"]
def get_agent_instructions_by_name(self, agent_name: str) -> str:
"""Gets the current Agent Instructions that are used by the specified Agent.
Args:
agent_name (str): Name of the agent whose Instructions are to be returned
Returns:
str: Agent ARN, or None if not found
"""
_agent_id = self.get_agent_id_by_name(agent_name)
if _agent_id is None:
raise ValueError(f"Agent {agent_name} not found")
_get_agent_resp = self._bedrock_agent_client.get_agent(agentId=_agent_id)
# extract the instructions from the response
_instructions = _get_agent_resp["agent"]["instruction"]
return _instructions
def _allow_agent_lambda(self, agent_id: str, lambda_function_name: str) -> None:
"""Allows the specified Agent to invoke the specified Lambda function by adding the appropriate permission.
Args:
agent_id (str): Id of the agent
lambda_function_name (str): Name of the Lambda function
"""
# Create allow invoke permission on lambda
_permission_resp = self._lambda_client.add_permission(
FunctionName=lambda_function_name,
StatementId=f"allow_bedrock_{agent_id}",
Action="lambda:InvokeFunction",
Principal="bedrock.amazonaws.com",
SourceArn=f"arn:aws:bedrock:{self._region}:{self._account_id}:agent/{agent_id}",
)
def _make_agent_string(self, agent_arns: List[str] = None) -> str:
"""Makes a comma separated string of agent ids from a list of agent ARNs.
Args:
agent_arns (List[str]): List of agent ARNs
"""
if agent_arns is None:
return ""
else:
_agent_string = ""
for _agent_arn in agent_arns:
_agent_string += _agent_arn.split("/")[1] + ","
return _agent_string.strip()[:-1]
def create_lambda(
self,
agent_name: str,
lambda_function_name: str,
source_code_file: str,
additional_function_iam_policy: Dict = None,
sub_agent_arns: List[str] = None,
dynamo_args: List[str] = None,
) -> str:
"""Creates a new Lambda function that implements a set of actions for an Agent Action Group.
Args:
agent_name (str): Name of the existing Agent that this Lambda will support.
lambda_function_name (str): Name of the Lambda function to create.
source_code_file (str): Name of the file containing the Lambda source code.
Must be a local file, and use underscores, not hyphens.
additional_function_iam_policy (Dict, Optional): Additional IAM policy to attach to the Lambda function. Defaults to None.
sub_agent_arns (List[str], Optional): List of ARNs of the sub-agents that this Lambda is allowed to invoke.
Returns:
str: ARN of the new Lambda function
"""
_agent_id = self.get_agent_id_by_name(agent_name)
if _agent_id is None:
return "Agent not found"
_base_filename = source_code_file.split(".py")[0]
# Package up the lambda function code
s = BytesIO()
z = zipfile.ZipFile(s, "w")
z.write(f"{source_code_file}")
z.close()
zip_content = s.getvalue()
# TODO: make this an optional keyword arg. only supply it when sub-agent-arns are provided or DynamoDB variables are provided
if sub_agent_arns:
env_variables = {
"Variables": {"SUB_AGENT_IDS": self._make_agent_string(sub_agent_arns)}
}
else:
env_variables = {"Variables": {}}
if dynamo_args:
# add DynamoDB Table permissions to the Lambda Function
lambda_role = self._create_lambda_iam_role(
agent_name, sub_agent_arns, dynamodb_table_name=dynamo_args[0]
)
# create DynamoDB Table to be used on Lambda Code
self.create_dynamodb(dynamo_args[0], dynamo_args[1], dynamo_args[2])
env_variables["Variables"]["dynamodb_table"] = dynamo_args[0]
env_variables["Variables"]["dynamodb_pk"] = dynamo_args[1]
env_variables["Variables"]["dynamodb_sk"] = dynamo_args[2]
else:
lambda_role = self._create_lambda_iam_role(agent_name, sub_agent_arns)
# Create Lambda Function
_lambda_function = self._lambda_client.create_function(
FunctionName=lambda_function_name,
Runtime=PYTHON_RUNTIME,
Timeout=PYTHON_TIMEOUT,
Role=lambda_role,
Code={"ZipFile": zip_content},
Handler=f"{_base_filename}.lambda_handler",
Environment=env_variables,
)
self._allow_agent_lambda(_agent_id, lambda_function_name)
return _lambda_function["FunctionArn"]
def delete_lambda(
self, lambda_function_name: str, delete_role_flag: bool = True
) -> None:
"""Deletes the specified Lambda function.
Optionally, deletes the IAM role that was created for the Lambda function.
Optionally, deletes the policy that was created for the Lambda function.
Args:
lambda_function_name (str): Name of the Lambda function to delete.
delete_role_flag (bool, Optional): Flag indicating whether to delete the IAM role that was
created for the Lambda function. Defaults to True.
"""
# Detach and delete the role
if delete_role_flag:
try:
_function_resp = self._lambda_client.get_function(
FunctionName=lambda_function_name
)
_role_arn = _function_resp["Configuration"]["Role"]
_role_name = _role_arn.split("/")[1]
self._iam_client.detach_role_policy(
RoleName=_role_name,
PolicyArn="arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole",
)
self._iam_client.delete_role(RoleName=_role_name)
except:
pass
# Delete Lambda function
try:
self._lambda_client.delete_function(FunctionName=lambda_function_name)
except:
pass
def get_agent_role(self, agent_name: str) -> str:
"""Gets the ARN of the IAM role that is associated with the specified Agent.
Args:
agent_name (str): Name of the Agent
Returns:
str: ARN of the IAM role, or None if not found
"""
_get_agents_resp = self._bedrock_agent_client.list_agents(maxResults=100)
_agents_json = _get_agents_resp["agentSummaries"]
_target_agent = next(
(agent for agent in _agents_json if agent["agentName"] == agent_name), None
)
if _target_agent is not None:
# pprint.pp(_target_agent)
_agent_id = _target_agent["agentId"]
_get_agent_resp = self._bedrock_agent_client.get_agent(agentId=_agent_id)
return _get_agent_resp["agent"]["agentResourceRoleArn"]
else:
return "Agent not found"
def delete_agent(
self, agent_name: str, delete_role_flag: bool = True, verbose: bool = False
) -> None:
"""Deletes an existing agent. Optionally, deletes the IAM role associated with the agent.
Args:
agent_name (str): Name of the agent to delete.
delete_role_flag (bool, Optional): Flag indicating whether to delete the IAM role associated with the agent.
Defaults to True.
"""
# first find the agent ID from the agent Name
_get_agents_resp = self._bedrock_agent_client.list_agents(maxResults=100)
_agents_json = _get_agents_resp["agentSummaries"]
_target_agent = next(
(agent for agent in _agents_json if agent["agentName"] == agent_name), None
)
if _target_agent is None:
print(f"Agent {agent_name} not found")
return
if _target_agent is not None and verbose:
print(
f"Found target agent, name: {agent_name}, id: {_target_agent['agentId']}"
)
# Delete the agent aliases
if _target_agent is not None:
_agent_id = _target_agent["agentId"]
if verbose:
print(f"Deleting aliases for agent {_agent_id}...")
try:
_agent_aliases = self._bedrock_agent_client.list_agent_aliases(
agentId=_agent_id, maxResults=100
)
for alias in _agent_aliases["agentAliasSummaries"]:
alias_id = alias["agentAliasId"]
print(f"Deleting alias {alias_id} from agent {_agent_id}")
response = self._bedrock_agent_client.delete_agent_alias(
agentAliasId=alias_id, agentId=_agent_id
)
except Exception as e:
print(f"Error deleting aliases: {e}")
pass
# if the agent exists, delete the agent
if _target_agent is not None:
_agent_id = _target_agent["agentId"]
if verbose:
print(f"Deleting agent: {_agent_id}...")
time.sleep(5)
self._bedrock_agent_client.delete_agent(agentId=_agent_id)
time.sleep(5)
# TODO: add delete_lambda_flag parameter to optionall take care of
# deleting the lambda function associated with the agent.
# delete Agent IAM role if desired
if delete_role_flag:
_agent_role_name = f"AmazonBedrockExecutionRoleForAgents_{agent_name}"
if verbose:
print(f"Deleting IAM role: {_agent_role_name}...")
try:
self._iam_client.delete_role_policy(
PolicyName="bedrock_gr_allow_policy", RoleName=_agent_role_name
)
except Exception as e:
pass
try:
self._iam_client.delete_role_policy(
PolicyName="bedrock_allow_policy", RoleName=_agent_role_name
)
except Exception as e:
pass
try:
self._iam_client.delete_role_policy(
PolicyName="bedrock_kb_allow_policy", RoleName=_agent_role_name
)
except Exception as e:
pass
try:
self._iam_client.delete_role(RoleName=_agent_role_name)
except Exception as e:
pass
return
def _create_agent_role(
self,
agent_name: str,
agent_foundation_models: List[str],
kb_arns: List[str] = None,
reuse_default: bool = True,
verbose: bool = True,
) -> str:
"""Creates an IAM role for an agent.
Args:
agent_name (str): name of the agent for this new role
agent_foundation_models (List[str]): List of IDs or Arn's of the Bedrock foundation model(s) this agent is allowed to use
kb_arns (List[str], Optional): List of ARNs of the Knowledge Base(s) this agent is allowed to use
Returns:
str: the Arn for the new role
"""
if verbose:
print(f"Creating IAM role for agent: {agent_name}")
if reuse_default:
_agent_role_name = DEFAULT_AGENT_IAM_ROLE_NAME
# try creating the default role, which may already exist
try:
# create the default role w/ the proper assume role policy
_assume_role_policy_document_json = DEFAULT_AGENT_IAM_ASSUME_ROLE_POLICY
_assume_role_policy_document = json.dumps(
_assume_role_policy_document_json
)
_bedrock_agent_bedrock_allow_policy_document_json = (
DEFAULT_AGENT_IAM_POLICY
)
_bedrock_agent_bedrock_allow_policy_document = json.dumps(
_bedrock_agent_bedrock_allow_policy_document_json
)
_agent_role = self._iam_client.create_role(
RoleName=_agent_role_name,
AssumeRolePolicyDocument=_assume_role_policy_document,
)
except Exception as e:
if verbose:
print(
f"Caught exc when creating default role for role: {_agent_role_name}: {e}"
)
print(f"using assume role json: {_assume_role_policy_document}")
else:
self._iam_client.put_role_policy(
PolicyDocument=_bedrock_agent_bedrock_allow_policy_document,
PolicyName="bedrock_allow_policy",
RoleName=_agent_role_name,
)
return f"arn:aws:iam::{self._account_id}:role/{DEFAULT_AGENT_IAM_ROLE_NAME}"
else:
_agent_role_name = f"AmazonBedrockExecutionRoleForAgents_{agent_name}"
# _tmp_resources = [f"arn:aws:bedrock:{self._region}::foundation-model/{_model}" for _model in agent_foundation_models]
# Create IAM policies for agent
_assume_role_policy_document = DEFAULT_AGENT_IAM_ASSUME_ROLE_POLICY
_assume_role_policy_document_json = json.dumps(_assume_role_policy_document)
_agent_role = self._iam_client.create_role(
RoleName=_agent_role_name,
AssumeRolePolicyDocument=_assume_role_policy_document_json,
)
# Pause to make sure role is created
time.sleep(10)
if verbose:
print(
f"Role {_agent_role_name} created. ARN: {_agent_role['Role']['Arn']}"
)
print(
f"Adding bedrock_allow_policy to role {_agent_role_name}\n{_bedrock_policy_json}..."
)
_bedrock_agent_bedrock_allow_policy_statement = DEFAULT_AGENT_IAM_POLICY
_bedrock_policy_json = json.dumps(
_bedrock_agent_bedrock_allow_policy_statement
)
self._iam_client.put_role_policy(
PolicyDocument=_bedrock_policy_json,
PolicyName="bedrock_allow_policy",
RoleName=_agent_role_name,
)
# add Knowledge Base retrieve and retrieve and generate permissions if agent has KB attached to it
if kb_arns is not None:
_kb_policy_doc = {
"Version": "2012-10-17",
"Statement": [
{
"Sid": "QueryKB",
"Effect": "Allow",
"Action": [
"bedrock:Retrieve",
"bedrock:RetrieveAndGenerate",
],
"Resource": kb_arns,
}
],
}
_kb_policy_json = json.dumps(_kb_policy_doc)
self._iam_client.put_role_policy(
PolicyDocument=_kb_policy_json,
PolicyName="bedrock_kb_allow_policy",
RoleName=_agent_role_name,
)
# Pause to make sure role is updated
time.sleep(10)
# TODO: scope down GR access to a single GR passed as param
# # Support Guardrail access
# _gr_policy_doc = {
# "Version": "2012-10-17",
# "Statement": [{
# "Sid": "AmazonBedrockAgentBedrockInvokeGuardrailModelPolicy",
# "Effect": "Allow",
# "Action": [
# "bedrock:InvokeModel",
# "bedrock:GetGuardrail",
# "bedrock:ApplyGuardrail"
# ],
# "Resource": f"arn:aws:bedrock:*:{self._account_id}:guardrail/*"
# }]
# }
# _gr_policy_json = json.dumps(_gr_policy_doc)
# self._iam_client.put_role_policy(
# PolicyDocument=_gr_policy_json,
# PolicyName="bedrock_gr_allow_policy",
# RoleName=_agent_role_name
# )
return _agent_role["Role"]["Arn"]
def wait_agent_status_update(self, agent_id):
response = self._bedrock_agent_client.get_agent(agentId=agent_id)
agent_status = response["agent"]["agentStatus"]
_waited_at_least_once = False
while agent_status.endswith("ING"):
print(f"Waiting for agent status to change. Current status {agent_status}")
time.sleep(5)
_waited_at_least_once = True
try:
response = self._bedrock_agent_client.get_agent(agentId=agent_id)
agent_status = response["agent"]["agentStatus"]
except self._bedrock_agent_client.exceptions.ResourceNotFoundException:
agent_status = "DELETED"
if _waited_at_least_once:
print(f"Agent id {agent_id} current status: {agent_status}")
def wait_agent_alias_status_update(self, agent_id, agent_alias_id, verbose=False):
response = self._bedrock_agent_client.get_agent_alias(
agentId=agent_id, agentAliasId=agent_alias_id
)
agent_alias_status = response["agentAlias"]["agentAliasStatus"]
while agent_alias_status.endswith("ING"):
if verbose:
print(
f"Waiting for agent ALIAS status to change. Current status {agent_alias_status}"
)
time.sleep(5)
try:
response = self._bedrock_agent_client.get_agent_alias(
agentId=agent_id, agentAliasId=agent_alias_id
)
agent_alias_status = response["agentAlias"]["agentAliasStatus"]
except self._bedrock_agent_client.exceptions.ResourceNotFoundException:
agent_status = "DELETED"
if verbose:
print(
f"Agent id {agent_id}, Alias {agent_alias_id} current status: {agent_alias_status}"
)
def associate_sub_agents(self, supervisor_agent_id, sub_agents_list):
for sub_agent in sub_agents_list:
self.wait_agent_status_update(
supervisor_agent_id
) # Be sure agent is not still in CREATING state
association_response = (
self._bedrock_agent_client.associate_agent_collaborator(
agentId=supervisor_agent_id,
agentVersion="DRAFT",
agentDescriptor={"aliasArn": sub_agent["sub_agent_alias_arn"]},
collaboratorName=sub_agent["sub_agent_association_name"],
collaborationInstruction=sub_agent["sub_agent_instruction"],
relayConversationHistory=sub_agent["relay_conversation_history"],
)
)
self.wait_agent_status_update(supervisor_agent_id)
self._bedrock_agent_client.prepare_agent(agentId=supervisor_agent_id)
self.wait_agent_status_update(supervisor_agent_id)
supervisor_agent_alias = self._bedrock_agent_client.create_agent_alias(
agentAliasName="multi-agent", agentId=supervisor_agent_id
)
supervisor_agent_alias_id = supervisor_agent_alias["agentAlias"]["agentAliasId"]
supervisor_agent_alias_arn = supervisor_agent_alias["agentAlias"][
"agentAliasArn"
]
return supervisor_agent_alias_id, supervisor_agent_alias_arn
def build_sub_agent_list(self, sub_agent_names: List[str]) -> List:
_sub_agent_list = []
for _agent_name in sub_agent_names:
_agent_id = self.get_agent_id_by_name(_agent_name)
_agent_details = self._bedrock_agent_client.get_agent(agentId=_agent_id)[
"agent"
]
_sub_agent_list.append(
{
"sub_agent_alias_arn": _agent_details["agentArn"],
"sub_agent_instruction": _agent_details["instruction"],
"sub_agent_association_name": _agent_details["agentName"],
"relay_conversation_history": "DISABLED", #'TO_COLLABORATOR'
}
)
return _sub_agent_list
def create_agent(
self,
agent_name: str,
agent_description: str,
agent_instructions: str,
model_ids: List[str],
kb_arns: List[str] = None,
agent_collaboration: str = "DISABLED",
routing_classifier_model: str = None,
code_interpretation: bool = False,
guardrail_id: str = None,
kb_id: str = None,
verbose: bool = False,
) -> Tuple[str, str, str]:
"""Creates an agent given a name, instructions, model, description, and optionally
a set of knowledge bases. Action groups are added to the agent as a separate
step once you have created the agent itself.
Args:
agent_name (str): name of the agent
agent_description (str): description of the agent
agent_instructions (str): instructions for the agent
model_ids (List[str]): IDs of the foundation models this agent is allowed to use, the first one will be used
to create the agent, and the others will also be captured in the agent IAM role for future use
kb_arns (List[str], Optional): ARNs of the Knowledge Base(s) this agent is allowed to use
agent_collaboration (str, Optional): collaboration type for the agent, defaults to 'SUPERVISOR_ROUTER'
code_interpretation (bool, Optional): whether to enable code interpretation for the agent, defaults to False
verbose (bool, Optional): whether to print verbose output, defaults to False
Returns:
str: agent ID
"""
if verbose:
print(f"Creating agent: {agent_name}...")
_role_arn = self._create_agent_role(
agent_name, model_ids, kb_arns, reuse_default=True, verbose=False
)
_model_id = model_ids[0]
if verbose:
print(f"Created agent IAM role: {_role_arn}...")
print(f"Creating agent: {agent_name} with model: {_model_id}...")
_num_tries = 0
_agent_created = False
_create_agent_response = None
_agent_id = None
_kwargs = {}
if routing_classifier_model is not None:
_kwargs["promptOverrideConfiguration"] = {
"promptConfigurations": [
{
"promptType": "ROUTING_CLASSIFIER",
"promptCreationMode": "DEFAULT",
"foundationModel": routing_classifier_model,
"parserMode": "DEFAULT",
"promptState": "ENABLED",
}
]
}
if guardrail_id is not None:
_kwargs["guardrailConfiguration"] = {
"guardrailIdentifier": guardrail_id,
"guardrailVersion": "DRAFT",
}
while not _agent_created and _num_tries <= 2:
try:
if verbose:
print(f"kwargs: {_kwargs}")
_create_agent_response = self._bedrock_agent_client.create_agent(
agentName=agent_name,
agentResourceRoleArn=_role_arn,
description=agent_description.replace(
"\n", ""
), # console doesn't like newlines for subsequent editing
idleSessionTTLInSeconds=1800,
foundationModel=_model_id,
instruction=agent_instructions,
agentCollaboration=agent_collaboration,
**_kwargs,
)
_agent_id = _create_agent_response["agent"]["agentId"]
if verbose:
print(f"Created agent, resulting id: {_agent_id}")
_get_resp = self._bedrock_agent_client.get_agent(agentId=_agent_id)
print(_get_resp)
_agent_created = True
except Exception as e:
if verbose:
print(
f"Error creating agent: {e}\n. Retrying in case it was just waiting to be deleted."
)
_num_tries += 1
if _num_tries <= 2:
time.sleep(4)
pass
else:
if verbose:
print(f"Giving up on agent creation after 2 tries.")
raise e
if code_interpretation:
# possible time.sleep(15) needed here
self.add_code_interpreter(agent_name)