Skip to content

Commit 30d609d

Browse files
authored
Added the option to specify the maximum number of agent loops. (#1309)
1 parent c075b60 commit 30d609d

File tree

3 files changed

+31
-3
lines changed

3 files changed

+31
-3
lines changed

packages/cdk/lambda-python/generic-agent-core-runtime/src/agent.py

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,24 +9,40 @@
99
from strands import Agent as StrandsAgent
1010
from strands.models import BedrockModel
1111

12-
from .config import extract_model_info, get_system_prompt
12+
from .config import extract_model_info, get_max_iterations, get_system_prompt
1313
from .tools import ToolManager
1414
from .types import Message, ModelInfo
1515
from .utils import process_messages, process_prompt
1616

1717
logger = logging.getLogger(__name__)
1818

1919

20+
class IterationLimitExceededError(Exception):
21+
"""Exception raised when iteration limit is exceeded"""
22+
23+
pass
24+
25+
2026
class AgentManager:
2127
"""Manages Strands agent creation and execution."""
2228

2329
def __init__(self):
2430
self.tool_manager = ToolManager()
31+
self.max_iterations = get_max_iterations()
32+
self.iteration_count = 0
2533

2634
def set_session_info(self, session_id: str, trace_id: str):
2735
"""Set session and trace IDs"""
2836
self.tool_manager.set_session_info(session_id, trace_id)
2937

38+
def iteration_limit_handler(self, **ev):
39+
if ev.get("init_event_loop"):
40+
self.iteration_count = 0
41+
if ev.get("start_event_loop"):
42+
self.iteration_count += 1
43+
if self.iteration_count > self.max_iterations:
44+
raise IterationLimitExceededError(f"Event loop reached maximum iteration count ({self.max_iterations}). Please contact the administrator.")
45+
3046
async def process_request_streaming(
3147
self,
3248
messages: list[Message] | list[dict[str, Any]],
@@ -64,6 +80,7 @@ async def process_request_streaming(
6480
messages=processed_messages,
6581
model=bedrock_model,
6682
tools=tools,
83+
callback_handler=self.iteration_limit_handler,
6784
)
6885

6986
async for event in agent.stream_async(processed_prompt):

packages/cdk/lambda-python/generic-agent-core-runtime/src/config.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,8 @@
1313

1414
WORKSPACE_DIR = "/tmp/ws"
1515

16+
DEFAULT_MAX_ITERATIONS = 20
17+
1618
FIXED_SYSTEM_PROMPT = f"""## About File Output
1719
- You are running on AWS Bedrock AgentCore. Therefore, when writing files, always write them under `{WORKSPACE_DIR}`.
1820
- Similarly, if you need a workspace, please use the `{WORKSPACE_DIR}` directory. Do not ask the user about their current workspace. It's always `{WORKSPACE_DIR}`.
@@ -71,3 +73,12 @@ def extract_model_info(model_info: Any) -> tuple[str, str]:
7173
region = model_info.get("region", aws_creds.get("AWS_REGION", "us-east-1"))
7274

7375
return model_id, region
76+
77+
78+
def get_max_iterations() -> int:
79+
"""Get maximum iterations from environment or default to {DEFAULT_MAX_ITERATIONS}"""
80+
try:
81+
return int(os.environ.get("MAX_ITERATIONS", DEFAULT_MAX_ITERATIONS))
82+
except ValueError:
83+
logger.warning(f"Invalid MAX_ITERATIONS value. Defaulting to {DEFAULT_MAX_ITERATIONS}.")
84+
return DEFAULT_MAX_ITERATIONS

packages/cdk/test/__snapshots__/generative-ai-use-cases.test.ts.snap

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4992,7 +4992,7 @@ exports[`GenerativeAiUseCases matches the snapshot (closed network mode) 4`] = `
49924992
"AgentCoreRuntimeName": "GenericAgentCoreRuntime",
49934993
"CustomConfig": {
49944994
"containerImageUri": {
4995-
"Fn::Sub": "123456890123.dkr.ecr.us-east-1.\${AWS::URLSuffix}/cdk-hnb659fds-container-assets-123456890123-us-east-1:736d91ac33c9bb64c93f49d1258dbf8aff8d6ec20441291f20f42076efb65f00",
4995+
"Fn::Sub": "123456890123.dkr.ecr.us-east-1.\${AWS::URLSuffix}/cdk-hnb659fds-container-assets-123456890123-us-east-1:89f9ea87f3ee318598f0b63b57f12a3762e5abe60ad4c925b317d2cf2c737d0d",
49964996
},
49974997
"environmentVariables": {
49984998
"FILE_BUCKET": {
@@ -26205,7 +26205,7 @@ exports[`GenerativeAiUseCases matches the snapshot 4`] = `
2620526205
"AgentCoreRuntimeName": "GenericAgentCoreRuntime",
2620626206
"CustomConfig": {
2620726207
"containerImageUri": {
26208-
"Fn::Sub": "123456890123.dkr.ecr.us-east-1.\${AWS::URLSuffix}/cdk-hnb659fds-container-assets-123456890123-us-east-1:736d91ac33c9bb64c93f49d1258dbf8aff8d6ec20441291f20f42076efb65f00",
26208+
"Fn::Sub": "123456890123.dkr.ecr.us-east-1.\${AWS::URLSuffix}/cdk-hnb659fds-container-assets-123456890123-us-east-1:89f9ea87f3ee318598f0b63b57f12a3762e5abe60ad4c925b317d2cf2c737d0d",
2620926209
},
2621026210
"environmentVariables": {
2621126211
"FILE_BUCKET": {

0 commit comments

Comments
 (0)