Skip to content

Commit 539441e

Browse files
committed
Added the option to specify the maximum number of agent loops.
1 parent d19fb4a commit 539441e

File tree

2 files changed

+26
-2
lines changed

2 files changed

+26
-2
lines changed

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

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,24 +9,37 @@
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_system_prompt, get_max_iterations
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

19+
class IterationLimitExceededError(Exception):
20+
"""Exception raised when iteration limit is exceeded"""
21+
pass
1922

2023
class AgentManager:
2124
"""Manages Strands agent creation and execution."""
2225

2326
def __init__(self):
2427
self.tool_manager = ToolManager()
28+
self.max_iterations = get_max_iterations()
29+
self.iteration_count = 0
2530

2631
def set_session_info(self, session_id: str, trace_id: str):
2732
"""Set session and trace IDs"""
2833
self.tool_manager.set_session_info(session_id, trace_id)
29-
34+
self.iteration_count = 0
35+
36+
def iteration_limit_handler(self, **ev):
37+
if ev.get("start_event_loop"):
38+
self.iteration_count += 1
39+
if self.iteration_count > self.max_iterations:
40+
raise IterationLimitExceededError(
41+
f"Event loop reached maximum iteration count ({self.max_iterations}). Please contact the administrator."
42+
)
3043
async def process_request_streaming(
3144
self,
3245
messages: list[Message] | list[dict[str, Any]],
@@ -64,6 +77,7 @@ async def process_request_streaming(
6477
messages=processed_messages,
6578
model=bedrock_model,
6679
tools=tools,
80+
callback_handler=self.iteration_limit_handler,
6781
)
6882

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

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

Lines changed: 10 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,11 @@ 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+
def get_max_iterations() -> int:
78+
"""Get maximum iterations from environment or default to {DEFAULT_MAX_ITERATIONS}"""
79+
try:
80+
return int(os.environ.get("MAX_ITERATIONS", DEFAULT_MAX_ITERATIONS))
81+
except ValueError:
82+
logger.warning(f"Invalid MAX_ITERATIONS value. Defaulting to {DEFAULT_MAX_ITERATIONS}.")
83+
return DEFAULT_MAX_ITERATIONS

0 commit comments

Comments
 (0)