agentcore-rl-toolkit 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- agentcore_rl_toolkit/__init__.py +6 -0
- agentcore_rl_toolkit/app.py +252 -0
- agentcore_rl_toolkit/frameworks/strands/__init__.py +3 -0
- agentcore_rl_toolkit/frameworks/strands/app.py +30 -0
- agentcore_rl_toolkit/frameworks/strands/rollout_collector.py +58 -0
- agentcore_rl_toolkit/reward_function.py +39 -0
- agentcore_rl_toolkit-0.1.0.dist-info/METADATA +125 -0
- agentcore_rl_toolkit-0.1.0.dist-info/RECORD +11 -0
- agentcore_rl_toolkit-0.1.0.dist-info/WHEEL +4 -0
- agentcore_rl_toolkit-0.1.0.dist-info/licenses/LICENSE +175 -0
- agentcore_rl_toolkit-0.1.0.dist-info/licenses/NOTICE +1 -0
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
from .app import AgentCoreRLApp
|
|
2
|
+
from .frameworks.strands import StrandsAgentCoreRLApp
|
|
3
|
+
from .frameworks.strands.rollout_collector import RolloutCollector as StrandsRolloutCollector
|
|
4
|
+
from .reward_function import RewardFunction
|
|
5
|
+
|
|
6
|
+
__all__ = ["AgentCoreRLApp", "StrandsAgentCoreRLApp", "StrandsRolloutCollector", "RewardFunction"]
|
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
import asyncio
|
|
2
|
+
import json
|
|
3
|
+
import logging
|
|
4
|
+
import os
|
|
5
|
+
from abc import ABC, abstractmethod
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from datetime import datetime, timezone
|
|
8
|
+
from functools import wraps
|
|
9
|
+
|
|
10
|
+
import boto3
|
|
11
|
+
from bedrock_agentcore.runtime import BedrockAgentCoreApp
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@dataclass
|
|
15
|
+
class TrainingConfig:
|
|
16
|
+
"""Training configuration for rollout collection and storage."""
|
|
17
|
+
|
|
18
|
+
exp_id: str
|
|
19
|
+
session_id: str
|
|
20
|
+
input_id: str
|
|
21
|
+
sqs_url: str
|
|
22
|
+
s3_bucket: str
|
|
23
|
+
|
|
24
|
+
@classmethod
|
|
25
|
+
def from_dict(cls, data: dict) -> "TrainingConfig":
|
|
26
|
+
"""Create TrainingConfig from dictionary with validation."""
|
|
27
|
+
try:
|
|
28
|
+
return cls(
|
|
29
|
+
exp_id=data["exp_id"],
|
|
30
|
+
session_id=data["session_id"],
|
|
31
|
+
input_id=data["input_id"],
|
|
32
|
+
sqs_url=data["sqs_url"],
|
|
33
|
+
s3_bucket=data["s3_bucket"],
|
|
34
|
+
)
|
|
35
|
+
except KeyError as e:
|
|
36
|
+
raise ValueError(f"Missing required training config field: {e}") from e
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class AgentCoreRLApp(BedrockAgentCoreApp, ABC):
|
|
40
|
+
def __init__(self):
|
|
41
|
+
super().__init__()
|
|
42
|
+
self.s3_client = boto3.client("s3")
|
|
43
|
+
self.sqs_client = boto3.client("sqs")
|
|
44
|
+
|
|
45
|
+
@abstractmethod
|
|
46
|
+
def create_openai_compatible_model(self, **kwargs):
|
|
47
|
+
"""Create an OpenAI-compatible model for this framework.
|
|
48
|
+
|
|
49
|
+
Must be implemented by framework-specific subclasses.
|
|
50
|
+
|
|
51
|
+
Args:
|
|
52
|
+
**kwargs: Framework-specific model parameters
|
|
53
|
+
|
|
54
|
+
Returns:
|
|
55
|
+
Framework-specific model instance configured for vLLM server
|
|
56
|
+
"""
|
|
57
|
+
pass
|
|
58
|
+
|
|
59
|
+
def _get_model_config(self):
|
|
60
|
+
"""Get and validate model configuration from environment."""
|
|
61
|
+
base_url = os.getenv("BASE_URL")
|
|
62
|
+
model_id = os.getenv("MODEL_ID")
|
|
63
|
+
|
|
64
|
+
if not base_url or not model_id:
|
|
65
|
+
raise ValueError(
|
|
66
|
+
"Missing required environment variables: BASE_URL, MODEL_ID. " "Make sure to call load_dotenv()."
|
|
67
|
+
)
|
|
68
|
+
|
|
69
|
+
return base_url, model_id
|
|
70
|
+
|
|
71
|
+
def _validate_and_normalize_rollout(self, rollout_dict: dict) -> dict:
|
|
72
|
+
"""
|
|
73
|
+
Validate and normalize rollout data structure.
|
|
74
|
+
|
|
75
|
+
Ensures the return value from user functions has the expected format:
|
|
76
|
+
{"rollout_data": [...], "rewards": [...]}
|
|
77
|
+
|
|
78
|
+
Args:
|
|
79
|
+
rollout_dict: Dictionary returned from user function
|
|
80
|
+
|
|
81
|
+
Returns:
|
|
82
|
+
Normalized rollout dictionary with validated structure
|
|
83
|
+
|
|
84
|
+
Raises:
|
|
85
|
+
ValueError: If structure is invalid or rewards don't match rollout length
|
|
86
|
+
"""
|
|
87
|
+
# Require both fields to exist
|
|
88
|
+
if "rollout_data" not in rollout_dict:
|
|
89
|
+
raise ValueError("Return value must include 'rollout_data' field")
|
|
90
|
+
if "rewards" not in rollout_dict:
|
|
91
|
+
raise ValueError("Return value must include 'rewards' field")
|
|
92
|
+
|
|
93
|
+
rollout_data = rollout_dict["rollout_data"]
|
|
94
|
+
rewards = rollout_dict["rewards"]
|
|
95
|
+
|
|
96
|
+
# Validate rollout_data
|
|
97
|
+
if not isinstance(rollout_data, list) or len(rollout_data) == 0:
|
|
98
|
+
raise ValueError("rollout_data must be a list with length >= 1")
|
|
99
|
+
|
|
100
|
+
# Normalize rewards to list if not already
|
|
101
|
+
if not isinstance(rewards, list):
|
|
102
|
+
rewards = [rewards]
|
|
103
|
+
|
|
104
|
+
# Validate rewards length
|
|
105
|
+
if len(rewards) != 1 and len(rewards) != len(rollout_data):
|
|
106
|
+
raise ValueError(
|
|
107
|
+
f"rewards must be length 1 (outcome reward) or "
|
|
108
|
+
f"match rollout_data length {len(rollout_data)} (per-step reward)"
|
|
109
|
+
)
|
|
110
|
+
|
|
111
|
+
# Update with normalized rewards
|
|
112
|
+
rollout_dict["rewards"] = rewards
|
|
113
|
+
return rollout_dict
|
|
114
|
+
|
|
115
|
+
def save_rollout_and_notify(self, rollout_data: dict, training_config: dict):
|
|
116
|
+
"""
|
|
117
|
+
Save rollout data to S3 and notify SQS queue.
|
|
118
|
+
|
|
119
|
+
Args:
|
|
120
|
+
rollout_data: The prepared rollout data
|
|
121
|
+
training_config: Training configuration dict containing:
|
|
122
|
+
- s3_bucket: S3 bucket name
|
|
123
|
+
- sqs_url: SQS queue URL for notifications
|
|
124
|
+
- exp_id: Experiment ID for organizing data
|
|
125
|
+
- session_id: Session id for the current task
|
|
126
|
+
- input_id: id for discriminating different input data examples
|
|
127
|
+
"""
|
|
128
|
+
# Validate and extract training configuration
|
|
129
|
+
try:
|
|
130
|
+
config = TrainingConfig.from_dict(training_config)
|
|
131
|
+
except ValueError as e:
|
|
132
|
+
logging.error(f"Invalid training configuration: {e}")
|
|
133
|
+
raise
|
|
134
|
+
|
|
135
|
+
result_key = f"{config.exp_id}/{config.input_id}_{config.session_id}.json"
|
|
136
|
+
|
|
137
|
+
if "status_code" not in rollout_data:
|
|
138
|
+
rollout_data["status_code"] = 200
|
|
139
|
+
|
|
140
|
+
if "stop_reason" not in rollout_data:
|
|
141
|
+
rollout_data["stop_reason"] = "end_turn"
|
|
142
|
+
|
|
143
|
+
# Return the input id identifying rollouts of the same input data (prompt) example
|
|
144
|
+
# for advantage computation.
|
|
145
|
+
rollout_data["input_id"] = config.input_id
|
|
146
|
+
|
|
147
|
+
# Save to S3
|
|
148
|
+
try:
|
|
149
|
+
self.s3_client.put_object(
|
|
150
|
+
Bucket=config.s3_bucket,
|
|
151
|
+
Key=result_key,
|
|
152
|
+
Body=json.dumps(rollout_data, indent=2),
|
|
153
|
+
ContentType="application/json",
|
|
154
|
+
)
|
|
155
|
+
logging.info(f"Stored complete results at {result_key}")
|
|
156
|
+
except Exception as e:
|
|
157
|
+
logging.error(f"Failed to store results in S3: {e}")
|
|
158
|
+
raise
|
|
159
|
+
|
|
160
|
+
# Send SQS notification (mimic S3 notification format)
|
|
161
|
+
try:
|
|
162
|
+
sqs_message = {
|
|
163
|
+
"Records": [
|
|
164
|
+
{
|
|
165
|
+
"eventSource": "rollout:collector",
|
|
166
|
+
"eventName": "ObjectCreated:Put",
|
|
167
|
+
"eventTime": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%fZ"),
|
|
168
|
+
"s3": {"bucket": {"name": config.s3_bucket}, "object": {"key": result_key}},
|
|
169
|
+
}
|
|
170
|
+
]
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
self.sqs_client.send_message(QueueUrl=config.sqs_url, MessageBody=json.dumps(sqs_message))
|
|
174
|
+
logging.info(f"Sent SQS notification for {result_key}")
|
|
175
|
+
except Exception as e:
|
|
176
|
+
logging.error(f"Failed to send SQS notification for {result_key}: {e}")
|
|
177
|
+
raise
|
|
178
|
+
|
|
179
|
+
def rollout_entrypoint(self, func):
|
|
180
|
+
"""
|
|
181
|
+
Decorator for RL training that handles asyncio.create_task and rollout saving automatically.
|
|
182
|
+
|
|
183
|
+
This decorator:
|
|
184
|
+
1. Handles both sync and async user functions using BedrockAgentCoreApp's infrastructure
|
|
185
|
+
2. Automatically saves rollout data when user returns it
|
|
186
|
+
3. Handles errors and saves error rollouts for client notification
|
|
187
|
+
4. Returns immediately with {"status": "processing"} for non-blocking behavior
|
|
188
|
+
|
|
189
|
+
Usage:
|
|
190
|
+
@app.rollout_entrypoint
|
|
191
|
+
def invoke_agent(payload, context): # Can be sync or async
|
|
192
|
+
# Framework-specific rollout collection
|
|
193
|
+
rollout_data = collect_rollout(...)
|
|
194
|
+
return rollout_data # Automatically saved!
|
|
195
|
+
|
|
196
|
+
Args:
|
|
197
|
+
func: The user function that handles agent logic and rollout collection
|
|
198
|
+
|
|
199
|
+
Returns:
|
|
200
|
+
Decorated function registered as entrypoint
|
|
201
|
+
"""
|
|
202
|
+
|
|
203
|
+
async def rollout_background_task(payload, context):
|
|
204
|
+
"""Background task that does the actual agent work and rollout saving."""
|
|
205
|
+
training_config = payload.get("_training")
|
|
206
|
+
|
|
207
|
+
# Register with async task tracking system for logging and ping status
|
|
208
|
+
task_id = self.add_async_task(f"{func.__name__}")
|
|
209
|
+
|
|
210
|
+
try:
|
|
211
|
+
# Use BedrockAgentCoreApp's _invoke_handler for sync/async compatibility
|
|
212
|
+
# This automatically runs sync functions in thread pool to avoid blocking
|
|
213
|
+
result = await self._invoke_handler(func, context, self._takes_context(func), payload)
|
|
214
|
+
|
|
215
|
+
# If this is an RL training run, validate and normalize the rollout structure
|
|
216
|
+
if training_config:
|
|
217
|
+
if not isinstance(result, dict):
|
|
218
|
+
raise ValueError("RL training runs must return a dictionary")
|
|
219
|
+
result = self._validate_and_normalize_rollout(result)
|
|
220
|
+
|
|
221
|
+
# Save rollout data if we have training config
|
|
222
|
+
if isinstance(result, dict) and training_config:
|
|
223
|
+
self.save_rollout_and_notify(rollout_data=result, training_config=training_config)
|
|
224
|
+
logging.info(f"Rollout data saved for function: {func.__name__}")
|
|
225
|
+
|
|
226
|
+
return result
|
|
227
|
+
|
|
228
|
+
except Exception as e:
|
|
229
|
+
# Always save error rollout for client notification
|
|
230
|
+
if training_config:
|
|
231
|
+
error_rollout = {"status_code": 500, "stop_reason": str(e)}
|
|
232
|
+
self.save_rollout_and_notify(rollout_data=error_rollout, training_config=training_config)
|
|
233
|
+
logging.error(f"Error rollout saved for function: {func.__name__}: {e}")
|
|
234
|
+
raise
|
|
235
|
+
finally:
|
|
236
|
+
# Complete the async task for logging and ping status
|
|
237
|
+
self.complete_async_task(task_id)
|
|
238
|
+
|
|
239
|
+
@wraps(func)
|
|
240
|
+
async def rollout_entrypoint_wrapper(payload, context):
|
|
241
|
+
"""Entrypoint that starts background task and returns immediately."""
|
|
242
|
+
# Start background task without waiting
|
|
243
|
+
asyncio.create_task(rollout_background_task(payload, context))
|
|
244
|
+
return {"status": "processing"}
|
|
245
|
+
|
|
246
|
+
# Remove __wrapped__ so inspect.signature() sees the wrapper's actual signature
|
|
247
|
+
# (payload, context) instead of the user function's signature. This ensures
|
|
248
|
+
# BedrockAgentCoreApp._takes_context() correctly passes context to this wrapper.
|
|
249
|
+
del rollout_entrypoint_wrapper.__wrapped__
|
|
250
|
+
|
|
251
|
+
# Register using existing BedrockAgentCoreApp entrypoint infrastructure
|
|
252
|
+
return self.entrypoint(rollout_entrypoint_wrapper)
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
from ...app import AgentCoreRLApp
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class StrandsAgentCoreRLApp(AgentCoreRLApp):
|
|
5
|
+
def create_openai_compatible_model(self, provider_model_id=None, **kwargs):
|
|
6
|
+
"""
|
|
7
|
+
Create Strands model that's compatible with the OpenAI format. When provider_model_id
|
|
8
|
+
is provided, LiteLLM model will be used. Otherwise, an OpenAI compatible model with
|
|
9
|
+
base_url and model_id will be used.
|
|
10
|
+
|
|
11
|
+
:param provider_model_id: Provide this parameter when using cloud providers (bedrock,
|
|
12
|
+
anthropic, openai, etc.) that does not use a base_url. Example: Otherwise, leave it to None.
|
|
13
|
+
"""
|
|
14
|
+
try:
|
|
15
|
+
from strands.models.openai import OpenAIModel
|
|
16
|
+
except ImportError:
|
|
17
|
+
raise ImportError("Strands not installed. Install with: " "uv pip install strands-agents[openai]") from None
|
|
18
|
+
|
|
19
|
+
if not provider_model_id:
|
|
20
|
+
base_url, model_id = self._get_model_config()
|
|
21
|
+
return OpenAIModel(client_args={"api_key": "dummy", "base_url": base_url}, model_id=model_id, **kwargs)
|
|
22
|
+
|
|
23
|
+
try:
|
|
24
|
+
from strands.models.litellm import LiteLLMModel
|
|
25
|
+
except ImportError:
|
|
26
|
+
raise ImportError(
|
|
27
|
+
"Strands not installed. Install with: " "uv pip install strands-agents[litellm]"
|
|
28
|
+
) from None
|
|
29
|
+
|
|
30
|
+
return LiteLLMModel(model_id=provider_model_id, **kwargs)
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
"""Base rollout collector for Strands framework with hooks-based data collection."""
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class RolloutCollector:
|
|
5
|
+
"""Base rollout collector using Strands hooks to collect conversation data and compute rewards."""
|
|
6
|
+
|
|
7
|
+
def __init__(self):
|
|
8
|
+
self.turns = []
|
|
9
|
+
|
|
10
|
+
def register_hooks(self, registry):
|
|
11
|
+
"""Register hooks for rollout collection with Strands HookRegistry."""
|
|
12
|
+
try:
|
|
13
|
+
from strands.experimental.hooks import BeforeModelInvocationEvent
|
|
14
|
+
from strands.hooks import AfterInvocationEvent
|
|
15
|
+
except ImportError:
|
|
16
|
+
raise ImportError("Strands not installed. Install with: " "uv pip install strands-agents[openai]") from None
|
|
17
|
+
|
|
18
|
+
registry.add_callback(BeforeModelInvocationEvent, self.collect_messages)
|
|
19
|
+
registry.add_callback(AfterInvocationEvent, self.prepare_rollout)
|
|
20
|
+
|
|
21
|
+
def collect_messages(self, event: "BeforeModelInvocationEvent"): # noqa: F821
|
|
22
|
+
"""Collect messages before model invocation."""
|
|
23
|
+
|
|
24
|
+
agent = event.agent
|
|
25
|
+
tool_specs = agent.tool_registry.get_all_tool_specs()
|
|
26
|
+
formatted_request = agent.model.format_request(agent.messages, tool_specs, agent.system_prompt)
|
|
27
|
+
|
|
28
|
+
# Store the complete formatted messages for this turn
|
|
29
|
+
self.turns.append(
|
|
30
|
+
{
|
|
31
|
+
"turn_id": len(self.turns),
|
|
32
|
+
"formatted_request": formatted_request,
|
|
33
|
+
}
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
def prepare_rollout(self, event: "AfterInvocationEvent"): # noqa: F821
|
|
37
|
+
if len(self.turns) == 0:
|
|
38
|
+
return
|
|
39
|
+
|
|
40
|
+
# Since hook is triggered before model invocation, all turns end with the user message
|
|
41
|
+
# This loop turns [[u1], [u1, a1, u2], [u1, a1, u2, a2, u3], ..., [u1, ...a(n-1), u(n)]] into
|
|
42
|
+
# [[u1, a1], [u1, a1, u2, a2], [u1, a1, u2, a2, u3, a3], ..., [u1, ...a(n-1), u(n)]]
|
|
43
|
+
for i in range(1, len(self.turns)):
|
|
44
|
+
self.turns[i - 1]["formatted_request"]["messages"].append(
|
|
45
|
+
self.turns[i]["formatted_request"]["messages"][-2], # second to last is assistant message
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
# Gather final response
|
|
49
|
+
agent = event.agent
|
|
50
|
+
if agent.messages[-1]["role"] == "assistant": # successful invocation
|
|
51
|
+
tool_specs = agent.tool_registry.get_all_tool_specs()
|
|
52
|
+
formatted_request = agent.model.format_request(agent.messages, tool_specs, agent.system_prompt)
|
|
53
|
+
final_response = formatted_request["messages"][-1]
|
|
54
|
+
self.turns[-1]["formatted_request"]["messages"].append(final_response)
|
|
55
|
+
|
|
56
|
+
def get_rollout_data(self) -> list:
|
|
57
|
+
"""Return collected rollout data without computing rewards."""
|
|
58
|
+
return self.turns
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Base reward function interface for pure reward computation in RL training.
|
|
3
|
+
|
|
4
|
+
Reward functions only compute rewards - the app framework handles all validation and formatting.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from abc import ABC, abstractmethod
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class RewardFunction(ABC):
|
|
11
|
+
"""
|
|
12
|
+
Base class for reward functions focused purely on reward computation.
|
|
13
|
+
|
|
14
|
+
Users implement compute_reward() and can return:
|
|
15
|
+
- float: Single reward value
|
|
16
|
+
- list of floats: Per-turn rewards or single-element list for outcome rewards
|
|
17
|
+
|
|
18
|
+
The app framework handles all validation, normalization, and formatting automatically.
|
|
19
|
+
Right now, this class mostly defines a contract, but we might add some more shared utilities
|
|
20
|
+
in the future.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
@abstractmethod
|
|
24
|
+
def __call__(self, **kwargs):
|
|
25
|
+
"""
|
|
26
|
+
Compute reward(s) for the rollout.
|
|
27
|
+
|
|
28
|
+
Args:
|
|
29
|
+
**kwargs: Flexible arguments for reward computation, such as:
|
|
30
|
+
- response_text: Agent's response text
|
|
31
|
+
- ground_truth: Correct answer
|
|
32
|
+
- user_input: Original user input
|
|
33
|
+
- Any other context needed for reward computation
|
|
34
|
+
|
|
35
|
+
Returns:
|
|
36
|
+
float: Single reward value, or
|
|
37
|
+
list[float]: Per-turn rewards or single-element list for outcome rewards
|
|
38
|
+
"""
|
|
39
|
+
pass
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: agentcore-rl-toolkit
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Toolkit for Seamlessly Enabling RL Training with Bedrock AgentCore.
|
|
5
|
+
Project-URL: Homepage, https://github.com/awslabs/agentcore-rl-toolkit
|
|
6
|
+
Author-email: Amazon Web Services - Labs <opensource@amazon.com>
|
|
7
|
+
License-Expression: Apache-2.0
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
License-File: NOTICE
|
|
10
|
+
Classifier: Development Status :: 3 - Alpha
|
|
11
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
17
|
+
Requires-Python: >=3.10
|
|
18
|
+
Requires-Dist: bedrock-agentcore-starter-toolkit<=0.2.0
|
|
19
|
+
Requires-Dist: bedrock-agentcore>=1.0.3
|
|
20
|
+
Requires-Dist: boto3>=1.40.55
|
|
21
|
+
Requires-Dist: python-dotenv>=1.0.0
|
|
22
|
+
Provides-Extra: dev
|
|
23
|
+
Requires-Dist: mypy>=1.0; extra == 'dev'
|
|
24
|
+
Requires-Dist: pre-commit>=3.0; extra == 'dev'
|
|
25
|
+
Requires-Dist: pytest>=7.0; extra == 'dev'
|
|
26
|
+
Description-Content-Type: text/markdown
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
# AgentCore RL Toolkit (ART)
|
|
30
|
+
|
|
31
|
+
Toolkit for Seamlessly Enabling RL Training on Any Agent with Bedrock AgentCore.
|
|
32
|
+
|
|
33
|
+
## Repo Structure
|
|
34
|
+
|
|
35
|
+
- **Main package**: `agentcore-rl-toolkit` is a thin wrapper around of [bedrock-agentcore-sdk-python](https://github.com/aws/bedrock-agentcore-sdk-python/tree/main) that allows developers to start RL training their production agent with only a few lines of code change.
|
|
36
|
+
- **Examples**: Located in `examples/` directory, each with their own `pyproject.toml` and dependencies. Their corresponding docker files are located in `.bedrock_agentcore`, most of which have been generated automatically (see [instructions below](#prepare-docker-file)).
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
## Start Training on Example Agents
|
|
40
|
+
AgentCore runtime is currently supported by the following training library.
|
|
41
|
+
- [verl](https://github.com/volcengine/verl): related [PR](https://github.com/volcengine/verl/pull/4216).
|
|
42
|
+
|
|
43
|
+
Before training, build the docker for the RL-ready application and upload to ECR. To do this, follow the steps below:
|
|
44
|
+
|
|
45
|
+
### Setup Credentials and Environment Variables
|
|
46
|
+
|
|
47
|
+
First, make sure `aws sts get-caller-identity` returns the right identity. If not, follow the [developer guide](https://docs.aws.amazon.com/en_us/serverless-application-model/latest/developerguide/serverless-getting-started-set-up-credentials.html) to set up AWS Credentials. After setup, run `aws sts get-caller-identity` again to verify.
|
|
48
|
+
|
|
49
|
+
Next, the build script requires info related to your AWS account. Create a `.env` file from the example:
|
|
50
|
+
|
|
51
|
+
```bash
|
|
52
|
+
cp .env.example .env
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
Then edit `.env` and fill in your values:
|
|
56
|
+
- `AWS_REGION`: Your AWS region (e.g., `us-west-2`)
|
|
57
|
+
- `AWS_ACCOUNT`: Your AWS account ID
|
|
58
|
+
- `ECR_REPO_NAME`: Your ECR repository name
|
|
59
|
+
|
|
60
|
+
### Build and Push Docker Image
|
|
61
|
+
|
|
62
|
+
```bash
|
|
63
|
+
# Use examples/strands_math_agent as an example
|
|
64
|
+
chmod +x scripts/build_docker_image_and_push_to_ecr.sh
|
|
65
|
+
bash ./scripts/build_docker_image_and_push_to_ecr.sh --dockerfile=.bedrock_agentcore/examples_strands_math_agent_rl_app/Dockerfile --tag=dev
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
Then, go to the training library of your choice and simply provide agentcore specific config args to start training.
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
## Development
|
|
72
|
+
|
|
73
|
+
### Installation
|
|
74
|
+
|
|
75
|
+
This project uses [uv](https://docs.astral.sh/uv/) for dependency management. Install uv if you haven't already, follow the installation [guide](https://docs.astral.sh/uv/getting-started/installation/#standalone-installer) here.
|
|
76
|
+
|
|
77
|
+
### For Package Development
|
|
78
|
+
|
|
79
|
+
If you're developing or contributing to the `agentcore-rl-toolkit` package itself:
|
|
80
|
+
|
|
81
|
+
```bash
|
|
82
|
+
# Enter the repository
|
|
83
|
+
cd agentcore-rl-toolkit
|
|
84
|
+
|
|
85
|
+
# Create and activate uv environment
|
|
86
|
+
uv venv --python 3.13
|
|
87
|
+
source .venv/bin/activate
|
|
88
|
+
|
|
89
|
+
# Install with development dependencies
|
|
90
|
+
uv sync --frozen --extra dev
|
|
91
|
+
|
|
92
|
+
# Install pre-commit hooks
|
|
93
|
+
pre-commit install
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
Additionally, when co-developing the toolkit together with examples, add the following to the example app's docker file so that changes to the toolkit is reflected in the container.
|
|
97
|
+
|
|
98
|
+
```bash
|
|
99
|
+
COPY . .
|
|
100
|
+
RUN uv pip install --force-reinstall --no-deps .
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
### For Running Examples
|
|
104
|
+
|
|
105
|
+
Each example has its own dependencies and can be installed independently. Follow the README for specific examples there (e.g., `examples/strands_math_agent/README.md`).
|
|
106
|
+
|
|
107
|
+
## Appendix
|
|
108
|
+
|
|
109
|
+
### Prepare Docker file
|
|
110
|
+
|
|
111
|
+
Docker file for most examples can be automatically generated with the `agentcore` CLI. Use `examples/strands_math_agent` as an example:
|
|
112
|
+
|
|
113
|
+
```bash
|
|
114
|
+
agentcore configure --entrypoint examples/strands_math_agent/rl_app.py --requirements-file examples/strands_math_agent/pyproject.toml --deployment-type container --disable-memory --non-interactive
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
Make sure to run the command in project root.
|
|
118
|
+
|
|
119
|
+
## Security
|
|
120
|
+
|
|
121
|
+
See [CONTRIBUTING](CONTRIBUTING.md#security-issue-notifications) for more information.
|
|
122
|
+
|
|
123
|
+
## License
|
|
124
|
+
|
|
125
|
+
This project is licensed under the Apache-2.0 License.
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
agentcore_rl_toolkit/__init__.py,sha256=H41JfKfhc_C8CQTS-PNiY-ddNzOAE7N7qbloRSXxrvs,324
|
|
2
|
+
agentcore_rl_toolkit/app.py,sha256=sefL9oSK_KO3wODYfk7zIq4cvzPdlNhwXN4x4J3Cnzk,9916
|
|
3
|
+
agentcore_rl_toolkit/reward_function.py,sha256=MVuuAYbIWryTues_sguxFKrRwzJ7KU7Bc8IBRoLZaTk,1322
|
|
4
|
+
agentcore_rl_toolkit/frameworks/strands/__init__.py,sha256=OSnoqf7KoIr9OL9M7tU4b6-3L-TkpmhASFNDpcjQ6ZI,76
|
|
5
|
+
agentcore_rl_toolkit/frameworks/strands/app.py,sha256=OHq9DyaxzfqLhxcJRYJeLlJqHmCO5fbKfZ5xr55hdck,1361
|
|
6
|
+
agentcore_rl_toolkit/frameworks/strands/rollout_collector.py,sha256=2aNxOYIG9ZL75EnEdZHbzUJ_OX4J90pB6Kl4Fafn-to,2655
|
|
7
|
+
agentcore_rl_toolkit-0.1.0.dist-info/METADATA,sha256=7f7kHeYiq7geKshSOYxi8uPuc-3VDQYlv_-iPlsEBng,4908
|
|
8
|
+
agentcore_rl_toolkit-0.1.0.dist-info/WHEEL,sha256=WLgqFyCfm_KASv4WHyYy0P3pM_m7J5L9k2skdKLirC8,87
|
|
9
|
+
agentcore_rl_toolkit-0.1.0.dist-info/licenses/LICENSE,sha256=CeipvOyAZxBGUsFoaFqwkx54aPnIKEtm9a5u2uXxEws,10142
|
|
10
|
+
agentcore_rl_toolkit-0.1.0.dist-info/licenses/NOTICE,sha256=1CkO1kwu3Q_OHYTj-d-yiBJA_lNN73a4zSntavaD4oc,67
|
|
11
|
+
agentcore_rl_toolkit-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
|