|
| 1 | +"""Strands agent with Gateway MCP tools, Memory, Code Interpreter, and Browser.""" |
| 2 | + |
| 3 | +import json |
| 4 | +import logging |
| 5 | +import os |
| 6 | + |
| 7 | +from bedrock_agentcore.memory.integrations.strands.config import ( |
| 8 | + AgentCoreMemoryConfig, |
| 9 | + RetrievalConfig, |
| 10 | +) |
| 11 | +from bedrock_agentcore.memory.integrations.strands.session_manager import ( |
| 12 | + AgentCoreMemorySessionManager, |
| 13 | +) |
| 14 | +from bedrock_agentcore.runtime import BedrockAgentCoreApp, RequestContext |
| 15 | +from strands import Agent |
| 16 | +from strands.models import BedrockModel |
| 17 | +from tools.gateway import create_gateway_mcp_client |
| 18 | +from utils.auth import extract_user_id_from_context |
| 19 | + |
| 20 | +from tools.browser import StrandsBrowserTools |
| 21 | +from tools.code_interpreter import StrandsCodeInterpreterTools |
| 22 | + |
| 23 | +logger = logging.getLogger(__name__) |
| 24 | + |
| 25 | +app = BedrockAgentCoreApp() |
| 26 | + |
| 27 | +SYSTEM_PROMPT = ( |
| 28 | + "You are a helpful assistant with access to tools via the Gateway, " |
| 29 | + "Code Interpreter, and Browser. " |
| 30 | + "When asked about your tools, list them and explain what they do." |
| 31 | +) |
| 32 | + |
| 33 | + |
| 34 | +def _create_session_manager( |
| 35 | + user_id: str, session_id: str |
| 36 | +) -> AgentCoreMemorySessionManager: |
| 37 | + """Create an AgentCore memory session manager, optionally with long-term semantic retrieval. |
| 38 | +
|
| 39 | + When the USE_LONG_TERM_MEMORY environment variable is "true", configures retrieval |
| 40 | + from the /facts/{actorId} namespace so the agent recalls facts across sessions. |
| 41 | + When false (default), only short-term memory (conversation history) is active, |
| 42 | + avoiding the additional storage and retrieval costs of long-term memory. |
| 43 | +
|
| 44 | + Args: |
| 45 | + user_id: Unique identifier for the user (actor), extracted from the JWT sub claim. |
| 46 | + session_id: Unique identifier for the current conversation session. |
| 47 | +
|
| 48 | + Returns: |
| 49 | + An AgentCoreMemorySessionManager bound to the user and session. |
| 50 | + """ |
| 51 | + memory_id = os.environ.get("MEMORY_ID") |
| 52 | + if not memory_id: |
| 53 | + raise ValueError("MEMORY_ID environment variable is required") |
| 54 | + |
| 55 | + use_ltm = os.environ.get("USE_LONG_TERM_MEMORY", "false").lower() == "true" |
| 56 | + |
| 57 | + top_k = int(os.environ.get("LTM_TOP_K", "10")) |
| 58 | + relevance_score = float(os.environ.get("LTM_RELEVANCE_SCORE", "0.3")) |
| 59 | + |
| 60 | + # Only pass retrieval_config when LTM is explicitly enabled. |
| 61 | + # Omitting it means the session manager uses short-term memory only, |
| 62 | + # which avoids the $0.50/1,000 retrieval and $0.75/1,000 storage costs. |
| 63 | + retrieval_config = ( |
| 64 | + { |
| 65 | + "/facts/{actorId}": RetrievalConfig( |
| 66 | + top_k=top_k, |
| 67 | + relevance_score=relevance_score, |
| 68 | + ) |
| 69 | + } |
| 70 | + if use_ltm |
| 71 | + else None |
| 72 | + ) |
| 73 | + |
| 74 | + config = AgentCoreMemoryConfig( |
| 75 | + memory_id=memory_id, |
| 76 | + session_id=session_id, |
| 77 | + actor_id=user_id, |
| 78 | + retrieval_config=retrieval_config, |
| 79 | + ) |
| 80 | + return AgentCoreMemorySessionManager( |
| 81 | + agentcore_memory_config=config, |
| 82 | + region_name=os.environ.get("AWS_DEFAULT_REGION", "us-east-1"), |
| 83 | + ) |
| 84 | + |
| 85 | + |
| 86 | +def create_strands_agent(user_id: str, session_id: str) -> Agent: |
| 87 | + """Create a Strands agent with Gateway tools, memory, Code Interpreter, and Browser.""" |
| 88 | + |
| 89 | + bedrock_model = BedrockModel( |
| 90 | + model_id="us.anthropic.claude-sonnet-4-5-20250929-v1:0", temperature=0.1 |
| 91 | + ) |
| 92 | + |
| 93 | + session_manager = _create_session_manager(user_id, session_id) |
| 94 | + |
| 95 | + region = os.environ.get("AWS_DEFAULT_REGION", "us-east-1") |
| 96 | + code_tools = StrandsCodeInterpreterTools(region) |
| 97 | + browser_tools = StrandsBrowserTools(region) |
| 98 | + |
| 99 | + gateway_client = create_gateway_mcp_client() |
| 100 | + |
| 101 | + return Agent( |
| 102 | + name="strands_agent", |
| 103 | + system_prompt=SYSTEM_PROMPT, |
| 104 | + tools=[ |
| 105 | + gateway_client, |
| 106 | + code_tools.execute_python_securely, |
| 107 | + browser_tools.browser, |
| 108 | + ], |
| 109 | + model=bedrock_model, |
| 110 | + session_manager=session_manager, |
| 111 | + trace_attributes={"user.id": user_id, "session.id": session_id}, |
| 112 | + ) |
| 113 | + |
| 114 | + |
| 115 | +@app.entrypoint |
| 116 | +async def invocations(payload, context: RequestContext): |
| 117 | + """Main entrypoint — called by AgentCore Runtime on each request. |
| 118 | +
|
| 119 | + Extracts user ID from the validated JWT token (not the payload body) |
| 120 | + to prevent impersonation via prompt injection. |
| 121 | + """ |
| 122 | + user_query = payload.get("prompt") |
| 123 | + session_id = payload.get("runtimeSessionId") |
| 124 | + |
| 125 | + if not all([user_query, session_id]): |
| 126 | + yield { |
| 127 | + "status": "error", |
| 128 | + "error": "Missing required fields: prompt or runtimeSessionId", |
| 129 | + } |
| 130 | + return |
| 131 | + |
| 132 | + try: |
| 133 | + user_id = extract_user_id_from_context(context) |
| 134 | + agent = create_strands_agent(user_id, session_id) |
| 135 | + |
| 136 | + async for event in agent.stream_async(user_query): |
| 137 | + yield json.loads(json.dumps(dict(event), default=str)) |
| 138 | + |
| 139 | + except Exception as e: |
| 140 | + logger.exception("Agent run failed") |
| 141 | + yield {"status": "error", "error": str(e)} |
| 142 | + |
| 143 | + |
| 144 | +if __name__ == "__main__": |
| 145 | + app.run() |
0 commit comments