-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path21_invoke_agent.py
More file actions
251 lines (205 loc) · 7.57 KB
/
Copy path21_invoke_agent.py
File metadata and controls
251 lines (205 loc) · 7.57 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
246
247
248
249
250
251
#!/usr/bin/env python3
"""
Script to invoke deployed AgentCore Runtime agent.
This script:
1. Loads Cognito credentials
2. Gets OAuth token for authentication
3. Invokes the agent with a test query
4. Displays the full response
"""
import json
import base64
import os
import requests
from bedrock_agentcore_starter_toolkit import Runtime
print("="*80)
print("AGENTCORE RUNTIME AGENT INVOCATION")
print("="*80)
# Check if runtime config exists
if not os.path.exists('runtime_config.json'):
print("\n❌ Error: Agent not deployed yet")
print("Please run 19_deploy_agent.py first")
exit(1)
# Load runtime config
with open('runtime_config.json') as f:
runtime_deployed_config = json.load(f)
agent_arn = runtime_deployed_config.get('agent_arn')
print(f"\nAgent ARN: {agent_arn}")
# Load configuration files
try:
with open('cognito_config.json') as f:
cognito_config = json.load(f)
with open('runtime_execution_role_config.json') as f:
role_config = json.load(f)
except FileNotFoundError as e:
print(f"\n❌ Error: Required config file not found: {e}")
exit(1)
# Load .bedrock_agentcore.yaml to get agent name and entrypoint
if not os.path.exists('.bedrock_agentcore.yaml'):
print("\n❌ Error: .bedrock_agentcore.yaml not found")
print("Please run 19_deploy_agent.py first")
exit(1)
import yaml
with open('.bedrock_agentcore.yaml') as f:
runtime_config = yaml.safe_load(f)
default_agent = runtime_config.get('default_agent')
agent_config = runtime_config.get('agents', {}).get(default_agent, {})
agent_name = agent_config.get('name')
entrypoint = agent_config.get('entrypoint')
print(f"Agent Name: {agent_name}")
# ============================================================================
# STEP 1: Generate OAuth Bearer Token
# ============================================================================
print("\n" + "="*80)
print("STEP 1: GENERATING OAUTH TOKEN")
print("="*80)
try:
# Use token endpoint from config
token_endpoint = cognito_config["token_endpoint"]
# Prepare credentials for Basic Auth
credentials = f"{cognito_config['client_id']}:{cognito_config['client_secret']}"
encoded_credentials = base64.b64encode(credentials.encode()).decode()
# Get OAuth scopes - use gateway-api scopes
oauth_scopes = "gateway-api/read gateway-api/write"
print(f"Token Endpoint: {token_endpoint}")
print(f"Client ID: {cognito_config['client_id']}")
print(f"Scopes: {oauth_scopes}")
# Request token
response = requests.post(
token_endpoint,
headers={
"Authorization": f"Basic {encoded_credentials}",
"Content-Type": "application/x-www-form-urlencoded"
},
data={
"grant_type": "client_credentials",
"scope": oauth_scopes
},
timeout=10
)
if response.status_code != 200:
print(f"\n❌ Failed to get OAuth token")
print(f"Status Code: {response.status_code}")
print(f"Response: {response.text}")
exit(1)
bearer_token = response.json()["access_token"]
print("\n✓ OAuth token obtained successfully")
except Exception as e:
print(f"\n❌ Error getting OAuth token: {e}")
import traceback
traceback.print_exc()
exit(1)
# ============================================================================
# STEP 2: Configure Runtime
# ============================================================================
print("\n" + "="*80)
print("STEP 2: CONFIGURING RUNTIME")
print("="*80)
# Initialize Runtime
runtime = Runtime()
# Build authorizer configuration for Cognito JWT
auth_config = {
"customJWTAuthorizer": {
"allowedClients": [cognito_config["client_id"]],
"discoveryUrl": cognito_config["discovery_url"]
}
}
# Configure runtime (to load existing configuration)
try:
runtime.configure(
entrypoint=entrypoint,
agent_name=agent_name,
execution_role=role_config["role_arn"],
auto_create_ecr=True,
memory_mode="NO_MEMORY",
requirements_file="requirements.txt",
region="us-west-2",
authorizer_configuration=auth_config
)
print("✓ Runtime configured successfully")
except Exception as e:
print(f"❌ Error configuring runtime: {e}")
exit(1)
# ============================================================================
# STEP 3: Invoke Agent
# ============================================================================
print("\n" + "="*80)
print("STEP 3: INVOKING AGENT")
print("="*80)
# Test query
test_query = "Can you look up my order ORD-001 and help me with a return?"
actor_id = "user_001"
print(f"\nActor ID: {actor_id}")
print(f"Query: {test_query}")
payload = {
"prompt": test_query,
"actor_id": actor_id
}
print("\nSending request to agent...")
try:
response = runtime.invoke(
payload,
bearer_token=bearer_token
)
print("\n" + "="*80)
print("✅ AGENT RESPONSE")
print("="*80)
# Parse response if it's a dict with 'result' key
if isinstance(response, dict):
if 'result' in response:
print(response['result'])
elif 'error' in response:
print(f"❌ Agent returned error: {response['error']}")
if 'traceback' in response:
print("\nTraceback:")
print(response['traceback'])
else:
print(json.dumps(response, indent=2))
else:
print(response)
print("="*80)
# Display verification checklist
print("\n" + "="*80)
print("VERIFICATION CHECKLIST")
print("="*80)
response_text = str(response).lower()
# Check if agent used memory
memory_used = any(word in response_text for word in ['remember', 'preference', 'email', 'previously'])
print(f" {'✓' if memory_used else '✗'} Used memory (customer preferences): {memory_used}")
# Check if agent looked up order
order_lookup = 'ord-001' in response_text or 'laptop' in response_text
print(f" {'✓' if order_lookup else '✗'} Looked up order ORD-001: {order_lookup}")
# Check if agent provided return info
return_info = any(word in response_text for word in ['return', 'eligible', 'refund', 'days'])
print(f" {'✓' if return_info else '✗'} Provided return information: {return_info}")
print("="*80)
if memory_used and order_lookup and return_info:
print("\n✅ SUCCESS: Agent demonstrated full integration!")
print(" - Memory: Recalled customer preferences")
print(" - Gateway: Looked up order via Lambda")
print(" - Knowledge Base: Accessed return policies")
print(" - Custom Tools: Processed return eligibility")
else:
print("\n⚠️ PARTIAL: Some capabilities may not have been demonstrated")
print(" This could be normal depending on the agent's response strategy")
print("="*80)
except Exception as e:
print("\n" + "="*80)
print("❌ ERROR INVOKING AGENT")
print("="*80)
print(f"\nError: {e}")
import traceback
traceback.print_exc()
print("\n" + "="*80)
print("TROUBLESHOOTING")
print("="*80)
print("\n1. Check agent status:")
print(" python3 20_check_status.py")
print("\n2. Verify agent is in READY state")
print("\n3. Check CloudWatch logs:")
print(f" aws logs tail /aws/bedrock-agentcore/runtimes/{agent_name.replace('_', '-')}-* --since 10m")
print("\n4. Verify OAuth token is valid")
print("\n5. Check IAM role permissions")
print("="*80)
exit(1)
print("\n✅ Invocation completed successfully!")