Skip to content

Commit 71604bb

Browse files
committed
fix MR comments:
- improve documentations - remove AgentPattern from exports - add system prompt
1 parent e77fb9f commit 71604bb

File tree

6 files changed

+23
-77
lines changed

6 files changed

+23
-77
lines changed

docs/STREAMING.md

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,10 @@ Your agent sends streaming events in SSE format. This guide explains how to inte
77
## Integration Steps
88

99
1. **Your agent sends streaming events** (SSE format)
10-
2. **Update `agentCoreService.js`** to parse your agent's events
10+
2. **Update the appropriate parser file** to handle your agent's events:
11+
- For **Strands agents**: Modify `frontend/src/services/strandsParser.js`
12+
- For **LangGraph agents**: Modify `frontend/src/services/langgraphParser.js`
13+
- For **other agent frameworks**: Create a new parser file and import it in `agentCoreService.js`
1114
3. **Update `ChatInterface.tsx`** (optional) to display additional info like tool usage
1215
4. **UI displays the parsed text** in real-time
1316

frontend/src/services/agentCoreService.js

Lines changed: 12 additions & 66 deletions
Original file line numberDiff line numberDiff line change
@@ -5,74 +5,20 @@
55
* AgentCore Service - Streaming Response Handler
66
*
77
* Handles streaming responses from AgentCore agents using Server-Sent Events (SSE).
8-
* Dynamically loads the appropriate parser based on the agent pattern in aws-exports.json.
98
*
10-
* CUSTOMIZATION GUIDE
11-
* See strandsParser.js and langgraphParser.js for sample implementation of parsers for Strands and Langgraph.
12-
* Modify strandsParser.js or langgraphParser.js when You need to handle additional event types (e.g., tool calls, images).
13-
* Create a new parser file to support other agent frameworks (not Strands or LangGraph), and replace the parser
14-
* with your agent's specific event parsing logic.
9+
* CUSTOMIZATION FOR OTHER AGENT TYPES:
10+
* This service uses separate parser files for Strands and LangGraph agents.
11+
* Both parsers try each streaming event, each processes its format and ignores others.
12+
* To support other agent frameworks, create a new parser file and add a call in the streaming loop.
13+
* See strandsParser.js and langgraphParser.js for examples.
1514
*/
1615

1716
import * as strandsParser from './strandsParser.js';
1817
import * as langgraphParser from './langgraphParser.js';
1918

20-
// Parser selection based on agent pattern
21-
let activeParser = null;
22-
23-
/**
24-
* Load and select the appropriate parser based on agent pattern
25-
*/
26-
const loadParser = async () => {
27-
if (activeParser) {
28-
return activeParser;
29-
}
30-
31-
try {
32-
const response = await fetch("/aws-exports.json");
33-
const config = await response.json();
34-
const pattern = config.agentPattern || "strands-single-agent";
35-
36-
// Select parser based on exact pattern match
37-
if (pattern === 'strands-single-agent') {
38-
activeParser = strandsParser;
39-
console.log(`Using Strands parser for pattern: ${pattern}`);
40-
} else if (pattern === 'langgraph-single-agent') {
41-
activeParser = langgraphParser;
42-
console.log(`Using LangGraph parser for pattern: ${pattern}`);
43-
} else {
44-
throw new Error(
45-
`Unsupported agent pattern: "${pattern}". ` +
46-
`Supported patterns: "strands-single-agent", "langgraph-single-agent". ` +
47-
`To add support for this pattern, create a parser file and update loadParser() in agentCoreService.js.`
48-
);
49-
}
50-
51-
return activeParser;
52-
} catch (error) {
53-
console.error("Failed to load agent pattern:", error);
54-
// Default to Strands parser as fallback
55-
console.warn("Defaulting to Strands parser");
56-
activeParser = strandsParser;
57-
return activeParser;
58-
}
59-
};
60-
61-
// Generate a UUID-like string that meets AgentCore requirements (min 33 chars)
19+
// Generate a UUID
6220
const generateId = () => {
63-
const timestamp = Date.now().toString(36)
64-
65-
// Use cryptographically secure random number generation
66-
const getSecureRandom = () => {
67-
const array = new Uint32Array(1)
68-
crypto.getRandomValues(array)
69-
return array[0].toString(36)
70-
}
71-
72-
const random1 = getSecureRandom()
73-
const random2 = getSecureRandom()
74-
const random3 = getSecureRandom()
75-
return `${timestamp}-${random1}-${random2}-${random3}`
21+
return crypto.randomUUID();
7622
}
7723

7824
// Configuration - will be populated from aws-exports.json
@@ -104,9 +50,6 @@ export const invokeAgentCore = async (query, sessionId, onStreamUpdate, accessTo
10450
throw new Error("Agent Runtime ARN not configured")
10551
}
10652

107-
// Load the appropriate parser
108-
const parser = await loadParser();
109-
11053
// Bedrock Agent Core endpoint
11154
const endpoint = `https://bedrock-agentcore.${AGENT_CONFIG.AWS_REGION}.amazonaws.com`
11255

@@ -168,8 +111,11 @@ export const invokeAgentCore = async (query, sessionId, onStreamUpdate, accessTo
168111

169112
for (const line of lines) {
170113
if (line.trim()) {
171-
// Use the dynamically loaded parser
172-
completion = parser.parseStreamingChunk(line, completion, onStreamUpdate);
114+
// Both parsers try each event, each processes its format and ignores others
115+
// No overlap between formats, so both can safely run
116+
// Suggestion: Keep only the parser for your agent type to reduce unnecessary processing
117+
completion = strandsParser.parseStreamingChunk(line, completion, onStreamUpdate);
118+
completion = langgraphParser.parseStreamingChunk(line, completion, onStreamUpdate);
173119
}
174120
}
175121
}

infra-cdk/config.yaml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,4 +5,4 @@ stack_name_base: genaiid-agentcore-starter-pack
55
admin_user_email: null # Example: admin@example.com
66

77
backend:
8-
pattern: strands-single-agent # Available patterns: strands-single-agent
8+
pattern: strands-single-agent # Available patterns: strands-single-agent, langgraph-single-agent

infra-cdk/lib/backend-stack.ts

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -231,12 +231,6 @@ export class BackendStack extends cdk.NestedStack {
231231
description: "ARN of the agent memory resource",
232232
value: memoryArn,
233233
})
234-
235-
// Agent pattern output for frontend parser selection
236-
new cdk.CfnOutput(this, "AgentPattern", {
237-
description: "Agent pattern type (e.g., strands-single-agent, langgraph-single-agent)",
238-
value: pattern,
239-
})
240234
}
241235

242236
private createRuntimeSSMParameters(config: AppConfig): void {

patterns/langgraph-single-agent/langgraph_agent.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,9 @@ async def create_langgraph_agent(user_id: str, session_id: str, tools: list):
7979
This function sets up a LangGraph StateGraph that can access tools through
8080
the AgentCore Gateway and maintains conversation memory.
8181
"""
82+
system_prompt = """You are a helpful assistant with access to tools via the Gateway.
83+
When asked about your tools, list them and explain what they do."""
84+
8285
# Create Bedrock model
8386
bedrock_model = ChatBedrock(
8487
model_id="us.anthropic.claude-sonnet-4-5-20250929-v1:0",
@@ -103,7 +106,8 @@ async def create_langgraph_agent(user_id: str, session_id: str, tools: list):
103106
graph = create_react_agent(
104107
model=bedrock_model,
105108
tools=tools,
106-
checkpointer=checkpointer
109+
checkpointer=checkpointer,
110+
prompt=system_prompt
107111
)
108112

109113
print("[AGENT] Agent created successfully with Gateway tools")

scripts/post-deploy.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ def generate_aws_exports(stack_name):
6060
output_map[output['OutputKey']] = output['OutputValue']
6161

6262
# Validate required outputs
63-
required = ["CognitoClientId", "CognitoUserPoolId", "AmplifyUrl", "RuntimeArn", "FeedbackApiUrl", "AgentPattern"]
63+
required = ["CognitoClientId", "CognitoUserPoolId", "AmplifyUrl", "RuntimeArn", "FeedbackApiUrl"]
6464
missing = [key for key in required if key not in output_map]
6565

6666
if missing:
@@ -76,7 +76,6 @@ def generate_aws_exports(stack_name):
7676
"scope": "email openid profile",
7777
"automaticSilentRenew": True,
7878
"agentRuntimeArn": output_map['RuntimeArn'],
79-
"agentPattern": output_map['AgentPattern'],
8079
"awsRegion": region,
8180
"feedbackApiUrl": output_map['FeedbackApiUrl'],
8281
}

0 commit comments

Comments
 (0)