Skip to content

Commit dbe1662

Browse files
fix(event_handler): clear Bedrock Agent function context when a tool raises (#8874)
* fix(event_handler): clear Bedrock Agent function context when a tool raises BedrockAgentFunctionResolver only cleared the context after a tool returned. When the tool raised, the error response was built without clearing it, so data added with append_context carried over to the next invocation on the same warm container. An event missing a required field had the same problem. Clear the context in a finally block in resolve(), as ApiGatewayResolver and AppSyncResolver already do. * test(event_handler): pass a plain dict as context in the invalid event test --------- Co-authored-by: Leandro Damascena <lcdama@amazon.pt>
1 parent a1f97bd commit dbe1662

2 files changed

Lines changed: 46 additions & 2 deletions

File tree

‎aws_lambda_powertools/event_handler/bedrock_agent_function.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -192,6 +192,8 @@ def resolve(self, event: dict[str, Any], context: Any) -> dict[str, Any]:
192192
return self._resolve()
193193
except KeyError as e:
194194
raise ValueError(f"Missing required field: {str(e)}") from e
195+
finally:
196+
self.clear_context()
195197

196198
def _resolve(self) -> dict[str, Any]:
197199
"""Internal resolution logic"""
@@ -235,8 +237,6 @@ def _resolve(self) -> dict[str, Any]:
235237
# Call the function with the filtered parameters
236238
result = func(**valid_params)
237239

238-
self.clear_context()
239-
240240
# Build and return the response
241241
return BedrockFunctionsResponseBuilder(result).build(self.current_event, serializer=self.serializer)
242242
except Exception as error:

‎tests/functional/event_handler/required_dependencies/test_bedrock_agent_functions.py‎

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -350,6 +350,50 @@ def second_function():
350350
assert not hasattr(app.context, "new_key")
351351

352352

353+
def test_bedrock_agent_function_clears_context_when_tool_raises():
354+
# GIVEN a Bedrock Agent Function resolver with a tool that appends context and then raises
355+
app = BedrockAgentFunctionResolver()
356+
357+
@app.tool()
358+
def failing_function():
359+
app.append_context(user_id="12345")
360+
raise ValueError("Something went wrong")
361+
362+
@app.tool()
363+
def context_function():
364+
return dict(app.context)
365+
366+
# WHEN the failing tool is invoked
367+
raw_event = load_event("bedrockAgentFunctionEvent.json")
368+
raw_event["function"] = "failing_function"
369+
failed_result = app.resolve(raw_event, LambdaContext())
370+
371+
# THEN the error is returned to the agent and the context is cleared
372+
failed_body = failed_result["response"]["functionResponse"]["responseBody"]["TEXT"]["body"]
373+
assert failed_body == json.dumps("Error: ValueError: Something went wrong")
374+
assert app.context == {}
375+
376+
# WHEN the next invocation runs in the same execution environment
377+
raw_event["function"] = "context_function"
378+
next_result = app.resolve(raw_event, LambdaContext())
379+
380+
# THEN it does not see the context from the failed invocation
381+
assert next_result["response"]["functionResponse"]["responseBody"]["TEXT"]["body"] == json.dumps({})
382+
383+
384+
def test_bedrock_agent_function_clears_context_when_event_is_invalid():
385+
# GIVEN a Bedrock Agent Function resolver with context appended before resolving
386+
app = BedrockAgentFunctionResolver()
387+
app.append_context(user_id="12345")
388+
389+
# WHEN resolving an event without the required fields
390+
with pytest.raises(ValueError, match="Missing required field"):
391+
app.resolve({}, {})
392+
393+
# THEN the context is cleared
394+
assert app.context == {}
395+
396+
353397
def test_resolve_with_no_current_event():
354398
"""Test that _resolve() raises ValueError when current_event is None"""
355399
# GIVEN a Bedrock Agent Function resolver with no current event

0 commit comments

Comments
 (0)