-
Notifications
You must be signed in to change notification settings - Fork 421
/
Copy pathtest_bedrock_agent.py
313 lines (244 loc) · 11.3 KB
/
test_bedrock_agent.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
import json
from typing import Any, Dict, Optional
import pytest
from typing_extensions import Annotated
from aws_lambda_powertools.event_handler import BedrockAgentResolver, BedrockResponse, Response, content_types
from aws_lambda_powertools.event_handler.openapi.params import Body
from aws_lambda_powertools.utilities.data_classes import BedrockAgentEvent
from tests.functional.utils import load_event
claims_response = "You have 3 claims"
def test_bedrock_agent_event():
# GIVEN a Bedrock Agent event
app = BedrockAgentResolver()
@app.get("/claims", description="Gets claims")
def claims() -> Dict[str, Any]:
assert isinstance(app.current_event, BedrockAgentEvent)
assert app.lambda_context == {}
return {"output": claims_response}
# WHEN calling the event handler
result = app(load_event("bedrockAgentEvent.json"), {})
# THEN process event correctly
# AND set the current_event type as BedrockAgentEvent
assert result["messageVersion"] == "1.0"
assert result["response"]["apiPath"] == "/claims"
assert result["response"]["actionGroup"] == "ClaimManagementActionGroup"
assert result["response"]["httpMethod"] == "GET"
assert result["response"]["httpStatusCode"] == 200
body = result["response"]["responseBody"]["application/json"]["body"]
assert json.loads(body) == {"output": claims_response}
def test_bedrock_agent_with_path_params():
# GIVEN a Bedrock Agent event
app = BedrockAgentResolver()
@app.get("/claims/<claim_id>", description="Gets claims by ID")
def claims(claim_id: str):
assert isinstance(app.current_event, BedrockAgentEvent)
assert app.lambda_context == {}
assert claim_id == "123"
# WHEN calling the event handler
result = app(load_event("bedrockAgentEventWithPathParams.json"), {})
# THEN process event correctly
# AND set the current_event type as BedrockAgentEvent
assert result["messageVersion"] == "1.0"
assert result["response"]["apiPath"] == "/claims/<claim_id>"
assert result["response"]["actionGroup"] == "ClaimManagementActionGroup"
assert result["response"]["httpMethod"] == "GET"
assert result["response"]["httpStatusCode"] == 200
def test_bedrock_agent_event_with_response():
# GIVEN a Bedrock Agent event
app = BedrockAgentResolver()
output = {"output": claims_response}
@app.get("/claims", description="Gets claims")
def claims():
assert isinstance(app.current_event, BedrockAgentEvent)
assert app.lambda_context == {}
return Response(200, content_types.APPLICATION_JSON, output)
# WHEN calling the event handler
result = app(load_event("bedrockAgentEvent.json"), {})
# THEN process event correctly
# AND set the current_event type as BedrockAgentEvent
assert result["messageVersion"] == "1.0"
assert result["response"]["apiPath"] == "/claims"
assert result["response"]["actionGroup"] == "ClaimManagementActionGroup"
assert result["response"]["httpMethod"] == "GET"
assert result["response"]["httpStatusCode"] == 200
body = result["response"]["responseBody"]["application/json"]["body"]
assert json.loads(body) == output
def test_bedrock_agent_event_with_no_matches():
# GIVEN a Bedrock Agent event
app = BedrockAgentResolver()
@app.get("/no_match", description="Matches nothing")
def claims():
raise RuntimeError()
# WHEN calling the event handler
result = app(load_event("bedrockAgentEvent.json"), {})
# THEN process event correctly
# AND return 404 because the event doesn't match any known rule
assert result["messageVersion"] == "1.0"
assert result["response"]["apiPath"] == "/claims"
assert result["response"]["actionGroup"] == "ClaimManagementActionGroup"
assert result["response"]["httpMethod"] == "GET"
assert result["response"]["httpStatusCode"] == 404
def test_bedrock_agent_event_with_validation_error():
# GIVEN a Bedrock Agent event
app = BedrockAgentResolver()
@app.get("/claims", description="Gets claims")
def claims() -> Dict[str, Any]:
return "oh no, this is not a dict" # type: ignore
# WHEN calling the event handler
result = app(load_event("bedrockAgentEvent.json"), {})
# THEN process event correctly
# AND set the current_event type as BedrockAgentEvent
assert result["messageVersion"] == "1.0"
assert result["response"]["apiPath"] == "/claims"
assert result["response"]["actionGroup"] == "ClaimManagementActionGroup"
assert result["response"]["httpMethod"] == "GET"
assert result["response"]["httpStatusCode"] == 422
body = json.loads(result["response"]["responseBody"]["application/json"]["body"])
assert body["detail"][0]["type"] == "dict_type"
def test_bedrock_agent_event_with_exception():
# GIVEN a Bedrock Agent event
app = BedrockAgentResolver()
@app.exception_handler(RuntimeError)
def handle_runtime_error(ex: RuntimeError):
return Response(
status_code=500,
content_type=content_types.TEXT_PLAIN,
body="Something went wrong",
)
@app.get("/claims", description="Gets claims")
def claims():
raise RuntimeError()
# WHEN calling the event handler
result = app(load_event("bedrockAgentEvent.json"), {})
# THEN process the exception correctly
# AND return 500 because of the internal server error
assert result["messageVersion"] == "1.0"
assert result["response"]["apiPath"] == "/claims"
assert result["response"]["actionGroup"] == "ClaimManagementActionGroup"
assert result["response"]["httpMethod"] == "GET"
assert result["response"]["httpStatusCode"] == 500
body = result["response"]["responseBody"]["text/plain"]["body"]
assert body == "Something went wrong"
def test_bedrock_agent_with_post():
# GIVEN a Bedrock Agent resolver with a POST method
app = BedrockAgentResolver()
@app.post("/send-reminders", description="Sends reminders")
def send_reminders(
_claim_id: Annotated[int, Body(description="Claim ID", alias="claimId")],
_pending_documents: Annotated[str, Body(description="Social number and VAT", alias="pendingDocuments")],
) -> Annotated[bool, Body(description="returns true if I like the email")]:
return True
# WHEN calling the event handler
result = app(load_event("bedrockAgentPostEvent.json"), {})
# THEN process the event correctly
assert result["messageVersion"] == "1.0"
assert result["response"]["apiPath"] == "/send-reminders"
assert result["response"]["httpMethod"] == "POST"
assert result["response"]["httpStatusCode"] == 200
# THEN return the correct result
body = result["response"]["responseBody"]["application/json"]["body"]
assert json.loads(body) is True
@pytest.mark.usefixtures("pydanticv2_only")
def test_openapi_schema_for_pydanticv2(openapi30_schema):
# GIVEN BedrockAgentResolver is initialized with enable_validation=True
app = BedrockAgentResolver(enable_validation=True)
# WHEN we have a simple handler
@app.get("/", description="Testing")
def handler() -> Optional[Dict]:
pass
# WHEN we get the schema
schema = json.loads(app.get_openapi_json_schema())
# THEN the schema must be a valid 3.0.3 version
assert openapi30_schema(schema)
assert schema.get("openapi") == "3.0.3"
def test_bedrock_agent_with_bedrock_response():
# GIVEN a Bedrock Agent event
app = BedrockAgentResolver()
# WHEN using BedrockResponse
@app.get("/claims", description="Gets claims")
def claims():
assert isinstance(app.current_event, BedrockAgentEvent)
assert app.lambda_context == {}
return BedrockResponse(
session_attributes={"user_id": "123"},
prompt_session_attributes={"context": "testing"},
knowledge_bases_configuration=[
{
"knowledgeBaseId": "kb-123",
"retrievalConfiguration": {
"vectorSearchConfiguration": {"numberOfResults": 3, "overrideSearchType": "HYBRID"},
},
},
],
)
result = app(load_event("bedrockAgentEvent.json"), {})
assert result["messageVersion"] == "1.0"
assert result["response"]["apiPath"] == "/claims"
assert result["response"]["actionGroup"] == "ClaimManagementActionGroup"
assert result["response"]["httpMethod"] == "GET"
assert result["sessionAttributes"] == {"user_id": "123"}
assert result["promptSessionAttributes"] == {"context": "testing"}
assert result["knowledgeBasesConfiguration"] == [
{
"knowledgeBaseId": "kb-123",
"retrievalConfiguration": {
"vectorSearchConfiguration": {"numberOfResults": 3, "overrideSearchType": "HYBRID"},
},
},
]
def test_bedrock_agent_with_empty_bedrock_response():
# GIVEN a Bedrock Agent event
app = BedrockAgentResolver()
@app.get("/claims", description="Gets claims")
def claims():
return BedrockResponse(body={"message": "test"})
# WHEN calling the event handler
result = app(load_event("bedrockAgentEvent.json"), {})
# THEN process event correctly without optional attributes
assert result["messageVersion"] == "1.0"
assert result["response"]["httpStatusCode"] == 200
assert "sessionAttributes" not in result
assert "promptSessionAttributes" not in result
assert "knowledgeBasesConfiguration" not in result
def test_bedrock_agent_with_partial_bedrock_response():
# GIVEN a Bedrock Agent event
app = BedrockAgentResolver()
@app.get("/claims", description="Gets claims")
def claims():
return BedrockResponse(
body={"message": "test"},
session_attributes={"user_id": "123"},
# Only include session_attributes to test partial response
)
# WHEN calling the event handler
result = app(load_event("bedrockAgentEvent.json"), {})
# THEN process event correctly with only session_attributes
assert result["messageVersion"] == "1.0"
assert result["response"]["httpStatusCode"] == 200
assert result["sessionAttributes"] == {"user_id": "123"}
assert "promptSessionAttributes" not in result
assert "knowledgeBasesConfiguration" not in result
def test_bedrock_agent_with_different_attributes_combination():
# GIVEN a Bedrock Agent event
app = BedrockAgentResolver()
@app.get("/claims", description="Gets claims")
def claims():
return BedrockResponse(
body={"message": "test"},
prompt_session_attributes={"context": "testing"},
knowledge_bases_configuration=[
{
"knowledgeBaseId": "kb-123",
"retrievalConfiguration": {"vectorSearchConfiguration": {"numberOfResults": 3}},
},
],
# Omit session_attributes to test different combination
)
# WHEN calling the event handler
result = app(load_event("bedrockAgentEvent.json"), {})
# THEN process event correctly with specific attributes
assert result["messageVersion"] == "1.0"
assert result["response"]["httpStatusCode"] == 200
assert "sessionAttributes" not in result
assert result["promptSessionAttributes"] == {"context": "testing"}
assert result["knowledgeBasesConfiguration"][0]["knowledgeBaseId"] == "kb-123"