-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path19_deploy_agent.py
More file actions
245 lines (204 loc) · 8.6 KB
/
Copy path19_deploy_agent.py
File metadata and controls
245 lines (204 loc) · 8.6 KB
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
#!/usr/bin/env python3
"""
Script to deploy agent to AgentCore Runtime.
This script:
1. Loads all configuration files
2. Configures runtime deployment settings
3. Sets environment variables
4. Deploys to AgentCore Runtime
5. Saves agent ARN to runtime_config.json
"""
import json
import os
from bedrock_agentcore_starter_toolkit import Runtime
print("="*80)
print("AGENTCORE RUNTIME DEPLOYMENT")
print("="*80)
# ============================================================================
# STEP 1: Load all configuration files
# ============================================================================
print("\n1. Loading configuration files...")
config_files = {}
# Load memory configuration
try:
with open('memory_config.json') as f:
config_files['memory'] = json.load(f)
print(f" ✓ Memory config loaded: {config_files['memory']['memory_id']}")
except FileNotFoundError:
print(" ⚠️ memory_config.json not found - agent will run without memory")
# Load gateway configuration
try:
with open('gateway_config.json') as f:
config_files['gateway'] = json.load(f)
print(f" ✓ Gateway config loaded: {config_files['gateway']['gateway_id']}")
except FileNotFoundError:
print(" ⚠️ gateway_config.json not found - agent will run without gateway")
# Load Cognito configuration (required)
try:
with open('cognito_config.json') as f:
config_files['cognito'] = json.load(f)
print(f" ✓ Cognito config loaded: {config_files['cognito']['client_id']}")
except FileNotFoundError:
print(" ❌ Error: cognito_config.json not found (required)")
exit(1)
# Load runtime execution role (required)
try:
with open('runtime_execution_role_config.json') as f:
config_files['role'] = json.load(f)
print(f" ✓ Runtime role loaded: {config_files['role']['role_name']}")
except FileNotFoundError:
print(" ❌ Error: runtime_execution_role_config.json not found (required)")
exit(1)
# Load knowledge base configuration
try:
with open('kb_config.json') as f:
config_files['kb'] = json.load(f)
print(f" ✓ Knowledge Base config loaded: {config_files['kb']['knowledge_base_id']}")
except FileNotFoundError:
print(" ⚠️ kb_config.json not found - agent will run without knowledge base")
# ============================================================================
# STEP 2: Configure runtime deployment settings
# ============================================================================
print("\n2. Configuring AgentCore Runtime deployment...")
# Initialize Runtime
runtime = Runtime()
# Build authorizer configuration for Cognito JWT
auth_config = {
"customJWTAuthorizer": {
"allowedClients": [config_files['cognito']["client_id"]],
"discoveryUrl": config_files['cognito']["discovery_url"]
}
}
# Configure runtime deployment
try:
runtime.configure(
entrypoint="17_runtime_agent.py",
agent_name="returns_refunds_agent",
execution_role=config_files['role']["role_arn"],
auto_create_ecr=True,
memory_mode="NO_MEMORY", # Memory is handled via environment variables
requirements_file="requirements.txt",
region="us-west-2",
authorizer_configuration=auth_config
)
print(" ✓ Runtime configured successfully")
print(" ✓ Configuration saved to .bedrock_agentcore.yaml")
except Exception as e:
print(f" ❌ Error configuring runtime: {e}")
exit(1)
# ============================================================================
# STEP 3: Build environment variables
# ============================================================================
print("\n3. Setting environment variables...")
env_vars = {}
# Add memory ID if available
if 'memory' in config_files:
env_vars["MEMORY_ID"] = config_files['memory']["memory_id"]
print(f" ✓ MEMORY_ID: {env_vars['MEMORY_ID']}")
else:
print(" ⚠️ MEMORY_ID not set (memory config not found)")
# Add knowledge base ID if available
if 'kb' in config_files:
env_vars["KNOWLEDGE_BASE_ID"] = config_files['kb']["knowledge_base_id"]
print(f" ✓ KNOWLEDGE_BASE_ID: {env_vars['KNOWLEDGE_BASE_ID']}")
else:
print(" ⚠️ KNOWLEDGE_BASE_ID not set (kb config not found)")
# Add gateway info if available
if 'gateway' in config_files:
env_vars["GATEWAY_URL"] = config_files['gateway']["gateway_url"]
print(f" ✓ GATEWAY_URL: {env_vars['GATEWAY_URL']}")
else:
print(" ⚠️ GATEWAY_URL not set (gateway config not found)")
# Add Cognito credentials (required)
env_vars["COGNITO_CLIENT_ID"] = config_files['cognito']["client_id"]
env_vars["COGNITO_CLIENT_SECRET"] = config_files['cognito']["client_secret"]
env_vars["COGNITO_DISCOVERY_URL"] = config_files['cognito']["discovery_url"]
print(f" ✓ COGNITO_CLIENT_ID: {env_vars['COGNITO_CLIENT_ID']}")
print(f" ✓ COGNITO_CLIENT_SECRET: ***")
print(f" ✓ COGNITO_DISCOVERY_URL: {env_vars['COGNITO_DISCOVERY_URL']}")
# Add OAuth scopes for gateway
env_vars["OAUTH_SCOPES"] = "gateway-api/read gateway-api/write"
print(f" ✓ OAUTH_SCOPES: {env_vars['OAUTH_SCOPES']}")
# ============================================================================
# STEP 4: Deploy to AgentCore Runtime
# ============================================================================
print("\n" + "="*80)
print("LAUNCHING AGENT TO AGENTCORE RUNTIME")
print("="*80)
print("\nThis process will:")
print(" 1. Create CodeBuild project")
print(" 2. Build Docker container from your agent code")
print(" 3. Push container to Amazon ECR")
print(" 4. Deploy to AgentCore Runtime")
print("\n⏱️ Expected time: 5-10 minutes")
print("\n☕ Grab a coffee while the deployment runs...")
print("="*80)
try:
launch_result = runtime.launch(
env_vars=env_vars,
auto_update_on_conflict=True
)
agent_arn = launch_result.agent_arn
print("\n" + "="*80)
print("✓ DEPLOYMENT INITIATED SUCCESSFULLY!")
print("="*80)
print(f"\nAgent ARN: {agent_arn}")
except Exception as e:
print("\n" + "="*80)
print("❌ DEPLOYMENT FAILED")
print("="*80)
print(f"\nError: {e}")
print("\nTroubleshooting:")
print(" 1. Verify all config files exist")
print(" 2. Check IAM role has correct permissions")
print(" 3. Ensure Docker is running (if using local build)")
print(" 4. Check AWS credentials are configured")
exit(1)
# ============================================================================
# STEP 5: Save agent ARN to runtime_config.json
# ============================================================================
print("\n5. Saving deployment configuration...")
runtime_output_config = {
"agent_arn": agent_arn,
"agent_name": "returns_refunds_agent",
"region": "us-west-2",
"entrypoint": "17_runtime_agent.py"
}
# Add optional configurations
if 'memory' in config_files:
runtime_output_config["memory_id"] = config_files['memory']["memory_id"]
if 'gateway' in config_files:
runtime_output_config["gateway_url"] = config_files['gateway']["gateway_url"]
runtime_output_config["gateway_id"] = config_files['gateway']["gateway_id"]
if 'kb' in config_files:
runtime_output_config["knowledge_base_id"] = config_files['kb']["knowledge_base_id"]
runtime_output_config["cognito_client_id"] = config_files['cognito']["client_id"]
runtime_output_config["cognito_discovery_url"] = config_files['cognito']["discovery_url"]
with open('runtime_config.json', 'w') as f:
json.dump(runtime_output_config, f, indent=2)
print(" ✓ Configuration saved to runtime_config.json")
# ============================================================================
# NEXT STEPS
# ============================================================================
print("\n" + "="*80)
print("NEXT STEPS")
print("="*80)
print("\n1. Monitor deployment status:")
print(" The agent is being built and deployed in the background.")
print(" This may take 5-10 minutes to complete.")
print("\n2. Check status:")
print(" Create a script to check runtime status using:")
print(" - MCP tool: agentcore_runtime_status")
print(" - Or use AWS Console to view AgentCore Runtime")
print("\n3. Wait for status 'READY':")
print(" The agent must be in READY state before you can invoke it.")
print("\n4. Test your deployed agent:")
print(" Once READY, create an invoke script using:")
print(" - MCP tool: agentcore_runtime_invoke")
print(" - Pass your test prompt and actor_id")
print("\n5. Monitor with CloudWatch:")
print(" View logs and traces in CloudWatch for debugging")
print("="*80)
print("\n✅ Deployment script completed successfully!")
print(f"Agent ARN: {agent_arn}")
print("="*80)