agentsml-impl 0.2.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.
Files changed (129) hide show
  1. agentsml_impl/__init__.py +3 -0
  2. agentsml_impl/cli.py +472 -0
  3. agentsml_impl/compiler/__init__.py +1 -0
  4. agentsml_impl/compiler/capabilities.py +330 -0
  5. agentsml_impl/compiler/conditions.py +177 -0
  6. agentsml_impl/compiler/diagnostics.py +112 -0
  7. agentsml_impl/compiler/durations.py +31 -0
  8. agentsml_impl/compiler/expressions.py +123 -0
  9. agentsml_impl/compiler/identifiers.py +60 -0
  10. agentsml_impl/compiler/ir.py +391 -0
  11. agentsml_impl/compiler/limits.py +28 -0
  12. agentsml_impl/compiler/loader.py +83 -0
  13. agentsml_impl/compiler/naming.py +87 -0
  14. agentsml_impl/compiler/planner.py +79 -0
  15. agentsml_impl/compiler/render.py +90 -0
  16. agentsml_impl/compiler/schema_validation.py +121 -0
  17. agentsml_impl/compiler/semantic_validation.py +424 -0
  18. agentsml_impl/protocols/__init__.py +1 -0
  19. agentsml_impl/runtime/__init__.py +1 -0
  20. agentsml_impl/runtime/events.py +59 -0
  21. agentsml_impl/runtime/json_schema.py +138 -0
  22. agentsml_impl/runtime/tools.py +145 -0
  23. agentsml_impl/schemas/agentsml.schema.json +406 -0
  24. agentsml_impl/schemas/v0.1/agentsml.schema.json +628 -0
  25. agentsml_impl/schemas/v0.2/agentsml.schema.json +363 -0
  26. agentsml_impl/schemas/v0.3/agentsml.schema.json +406 -0
  27. agentsml_impl/targets/__init__.py +1 -0
  28. agentsml_impl/targets/a2a/__init__.py +0 -0
  29. agentsml_impl/targets/a2a/adapter.py +94 -0
  30. agentsml_impl/targets/a2a/capabilities.yaml +25 -0
  31. agentsml_impl/targets/ag2/__init__.py +0 -0
  32. agentsml_impl/targets/ag2/adapter.py +655 -0
  33. agentsml_impl/targets/ag2/capabilities.yaml +37 -0
  34. agentsml_impl/targets/ag_ui/__init__.py +0 -0
  35. agentsml_impl/targets/ag_ui/adapter.py +123 -0
  36. agentsml_impl/targets/ag_ui/capabilities.yaml +25 -0
  37. agentsml_impl/targets/agno/__init__.py +0 -0
  38. agentsml_impl/targets/agno/adapter.py +191 -0
  39. agentsml_impl/targets/agno/capabilities.yaml +26 -0
  40. agentsml_impl/targets/ap2/__init__.py +0 -0
  41. agentsml_impl/targets/ap2/adapter.py +84 -0
  42. agentsml_impl/targets/ap2/capabilities.yaml +25 -0
  43. agentsml_impl/targets/base.py +157 -0
  44. agentsml_impl/targets/bedrock_agentcore/__init__.py +0 -0
  45. agentsml_impl/targets/bedrock_agentcore/adapter.py +592 -0
  46. agentsml_impl/targets/bedrock_agentcore/capabilities.yaml +26 -0
  47. agentsml_impl/targets/claude_agent_sdk/__init__.py +0 -0
  48. agentsml_impl/targets/claude_agent_sdk/adapter.py +178 -0
  49. agentsml_impl/targets/claude_agent_sdk/capabilities.yaml +26 -0
  50. agentsml_impl/targets/crewai/__init__.py +0 -0
  51. agentsml_impl/targets/crewai/adapter.py +441 -0
  52. agentsml_impl/targets/crewai/capabilities.yaml +30 -0
  53. agentsml_impl/targets/databricks/__init__.py +0 -0
  54. agentsml_impl/targets/databricks/adapter.py +427 -0
  55. agentsml_impl/targets/databricks/capabilities.yaml +26 -0
  56. agentsml_impl/targets/flowise/__init__.py +0 -0
  57. agentsml_impl/targets/flowise/adapter.py +71 -0
  58. agentsml_impl/targets/flowise/capabilities.yaml +26 -0
  59. agentsml_impl/targets/google_adk/__init__.py +0 -0
  60. agentsml_impl/targets/google_adk/adapter.py +589 -0
  61. agentsml_impl/targets/google_adk/capabilities.yaml +36 -0
  62. agentsml_impl/targets/langchain/__init__.py +1 -0
  63. agentsml_impl/targets/langchain/adapter.py +351 -0
  64. agentsml_impl/targets/langchain/capabilities.yaml +30 -0
  65. agentsml_impl/targets/langflow/__init__.py +0 -0
  66. agentsml_impl/targets/langflow/adapter.py +147 -0
  67. agentsml_impl/targets/langflow/capabilities.yaml +26 -0
  68. agentsml_impl/targets/langgraph/__init__.py +0 -0
  69. agentsml_impl/targets/langgraph/adapter.py +911 -0
  70. agentsml_impl/targets/langgraph/capabilities.yaml +33 -0
  71. agentsml_impl/targets/llamaindex/__init__.py +1 -0
  72. agentsml_impl/targets/llamaindex/adapter.py +406 -0
  73. agentsml_impl/targets/llamaindex/capabilities.yaml +31 -0
  74. agentsml_impl/targets/lyzr/__init__.py +0 -0
  75. agentsml_impl/targets/lyzr/adapter.py +146 -0
  76. agentsml_impl/targets/lyzr/capabilities.yaml +26 -0
  77. agentsml_impl/targets/mastra/__init__.py +0 -0
  78. agentsml_impl/targets/mastra/adapter.py +635 -0
  79. agentsml_impl/targets/mastra/capabilities.yaml +32 -0
  80. agentsml_impl/targets/mcp_server/__init__.py +0 -0
  81. agentsml_impl/targets/mcp_server/adapter.py +141 -0
  82. agentsml_impl/targets/mcp_server/capabilities.yaml +25 -0
  83. agentsml_impl/targets/microsoft_agent_framework/__init__.py +0 -0
  84. agentsml_impl/targets/microsoft_agent_framework/adapter.py +563 -0
  85. agentsml_impl/targets/microsoft_agent_framework/capabilities.yaml +26 -0
  86. agentsml_impl/targets/n8n/__init__.py +0 -0
  87. agentsml_impl/targets/n8n/adapter.py +139 -0
  88. agentsml_impl/targets/n8n/capabilities.yaml +26 -0
  89. agentsml_impl/targets/openai_agents/__init__.py +0 -0
  90. agentsml_impl/targets/openai_agents/adapter.py +175 -0
  91. agentsml_impl/targets/openai_agents/capabilities.yaml +27 -0
  92. agentsml_impl/targets/pydantic_ai/__init__.py +0 -0
  93. agentsml_impl/targets/pydantic_ai/adapter.py +922 -0
  94. agentsml_impl/targets/pydantic_ai/capabilities.yaml +37 -0
  95. agentsml_impl/targets/registry.py +290 -0
  96. agentsml_impl/targets/relevance_ai/__init__.py +0 -0
  97. agentsml_impl/targets/relevance_ai/adapter.py +66 -0
  98. agentsml_impl/targets/relevance_ai/capabilities.yaml +26 -0
  99. agentsml_impl/targets/smolagents/__init__.py +0 -0
  100. agentsml_impl/targets/smolagents/adapter.py +210 -0
  101. agentsml_impl/targets/smolagents/capabilities.yaml +27 -0
  102. agentsml_impl/targets/snowflake_cortex/__init__.py +0 -0
  103. agentsml_impl/targets/snowflake_cortex/adapter.py +167 -0
  104. agentsml_impl/targets/snowflake_cortex/capabilities.yaml +26 -0
  105. agentsml_impl/targets/spring_ai/__init__.py +1 -0
  106. agentsml_impl/targets/spring_ai/adapter.py +626 -0
  107. agentsml_impl/targets/spring_ai/capabilities.yaml +31 -0
  108. agentsml_impl/targets/strands_agents/__init__.py +1 -0
  109. agentsml_impl/targets/strands_agents/adapter.py +309 -0
  110. agentsml_impl/targets/strands_agents/capabilities.yaml +29 -0
  111. agentsml_impl/targets/support_matrix.py +91 -0
  112. agentsml_impl/targets/ucp/__init__.py +0 -0
  113. agentsml_impl/targets/ucp/adapter.py +86 -0
  114. agentsml_impl/targets/ucp/capabilities.yaml +25 -0
  115. agentsml_impl/targets/vercel_ai/__init__.py +1 -0
  116. agentsml_impl/targets/vercel_ai/adapter.py +349 -0
  117. agentsml_impl/targets/vercel_ai/capabilities.yaml +30 -0
  118. agentsml_impl/targets/vertex_agent_engine/__init__.py +0 -0
  119. agentsml_impl/targets/vertex_agent_engine/adapter.py +407 -0
  120. agentsml_impl/targets/vertex_agent_engine/capabilities.yaml +26 -0
  121. agentsml_impl/targets/zapier_agents/__init__.py +0 -0
  122. agentsml_impl/targets/zapier_agents/adapter.py +106 -0
  123. agentsml_impl/targets/zapier_agents/capabilities.yaml +26 -0
  124. agentsml_impl-0.2.0.dist-info/METADATA +109 -0
  125. agentsml_impl-0.2.0.dist-info/RECORD +129 -0
  126. agentsml_impl-0.2.0.dist-info/WHEEL +5 -0
  127. agentsml_impl-0.2.0.dist-info/entry_points.txt +3 -0
  128. agentsml_impl-0.2.0.dist-info/licenses/LICENSE +28 -0
  129. agentsml_impl-0.2.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,592 @@
1
+ """Bedrock Agent target adapter — Level 1 runnable code generation."""
2
+
3
+ from __future__ import annotations
4
+ import json
5
+ from pathlib import Path
6
+
7
+ from agentsml_impl.compiler.identifiers import python_identifier_ir
8
+ from agentsml_impl.compiler.naming import pascal_identifier, snake_identifier, unique_identifiers
9
+ from agentsml_impl.compiler.ir import AgentSystemIR, ModelIR
10
+ from agentsml_impl.compiler.diagnostics import DiagCode, DiagnosticSet
11
+ from agentsml_impl.compiler.planner import GenerationPlan
12
+ from agentsml_impl.compiler.render import toml_string, write_file
13
+ from agentsml_impl.runtime.tools import generate_tools_module
14
+ from agentsml_impl.targets.base import TargetAdapter, GenerationResult
15
+
16
+
17
+ class Adapter(TargetAdapter):
18
+ @property
19
+ def name(self) -> str:
20
+ return "bedrock-agentcore"
21
+
22
+ def analyze(self, ir: AgentSystemIR, diagnostics: DiagnosticSet) -> None:
23
+ from agentsml_impl.compiler.capabilities import analyze_capabilities
24
+ analyze_capabilities(ir, "bedrock_agentcore", diagnostics)
25
+
26
+ def generate(self, ir: AgentSystemIR, plan: GenerationPlan,
27
+ out_dir: Path, diagnostics: DiagnosticSet) -> GenerationResult:
28
+ ir = python_identifier_ir(ir)
29
+ out_dir.mkdir(parents=True, exist_ok=True)
30
+ pkg = plan.package_name
31
+ src = out_dir / "src" / pkg
32
+ src.mkdir(parents=True, exist_ok=True)
33
+
34
+ files: list[str] = []
35
+ files += _write_pyproject(ir, plan, out_dir)
36
+ files += _write_tools(ir, src, out_dir, diagnostics)
37
+ files += _write_agent(ir, plan, src, out_dir, diagnostics)
38
+ files += _write_run(plan, src, out_dir)
39
+ files += _write_runtime_handler(plan, src, out_dir)
40
+ files += _write_gateway_config(ir, plan, src, out_dir)
41
+ files += _write_init(src, out_dir)
42
+ files += _write_lambda_package(ir, src, out_dir)
43
+ files += _write_cloudformation(ir, plan, out_dir)
44
+ files += _write_env_example(out_dir)
45
+ files += _write_readme(ir, plan, out_dir)
46
+
47
+ return GenerationResult(
48
+ target=self.name, out_dir=out_dir, files_written=files, success=True
49
+ )
50
+
51
+
52
+ def _write_pyproject(ir: AgentSystemIR, plan: GenerationPlan, out_dir: Path) -> list[str]:
53
+ c = f'''\
54
+ [build-system]
55
+ requires = ["setuptools>=68"]
56
+ build-backend = "setuptools.build_meta"
57
+
58
+ [project]
59
+ name = "{plan.package_name}"
60
+ version = "{ir.metadata.version or '0.1.0'}"
61
+ description = {toml_string(ir.metadata.description or plan.project_name)}
62
+ requires-python = ">=3.11"
63
+ dependencies = [
64
+ "boto3>=1.34.0",
65
+ "python-dotenv"
66
+ ]
67
+
68
+ [tool.setuptools.packages.find]
69
+ where = ["src"]
70
+ '''
71
+ write_file(out_dir, "pyproject.toml", c)
72
+ return ["pyproject.toml"]
73
+
74
+
75
+ def _write_tools(ir: AgentSystemIR, src: Path, out_dir: Path, ds: DiagnosticSet) -> list[str]:
76
+ if not ir.tools:
77
+ return []
78
+ c = generate_tools_module(ir.tools, ds, framework="bedrock")
79
+ rel = f"src/{src.name}/tools.py"
80
+ write_file(out_dir, rel, c)
81
+ return [rel]
82
+
83
+
84
+ def _write_agent(ir: AgentSystemIR, plan: GenerationPlan, src: Path, out_dir: Path, ds: DiagnosticSet) -> list[str]:
85
+ agent_blocks: list[str] = []
86
+ class_names: list[str] = []
87
+ tools_import = f"from .tools import {', '.join(ir.tools.keys())}" if ir.tools else ""
88
+
89
+ for ak, agent in ir.agents.items():
90
+ m = ir.models.get(agent.model)
91
+ mstr = m.name if m else 'anthropic.claude-3-sonnet-20240229-v1:0'
92
+ inst = agent.instructions.replace('"""', "'''")
93
+ tools_list = ", ".join(agent.tools) if agent.tools else ""
94
+
95
+ class_name = f"{pascal_identifier(ak, prefix='Agent')}Agent"
96
+ class_names.append(class_name)
97
+ agent_blocks.append(f'''\
98
+ class {class_name}:
99
+ """AWS Bedrock Agent client and runtime adapter for '{ak}'."""
100
+
101
+ def __init__(
102
+ self,
103
+ client: Any | None = None,
104
+ agent_id: str | None = None,
105
+ agent_alias_id: str | None = None,
106
+ region_name: str | None = None,
107
+ ):
108
+ self.region_name = region_name or os.environ.get("AWS_REGION", "us-east-1")
109
+ self.agent_id = agent_id or os.environ.get("BEDROCK_AGENT_ID", "default-agent-id")
110
+ self.agent_alias_id = agent_alias_id or os.environ.get("BEDROCK_AGENT_ALIAS_ID", "TSTALIASID")
111
+ self.model = "{mstr}"
112
+ self.instructions = """{inst}"""
113
+ self.tools = [{tools_list}]
114
+ self.client = client
115
+
116
+ def _get_client(self) -> Any:
117
+ if self.client is None:
118
+ self.client = boto3.client("bedrock-agent-runtime", region_name=self.region_name)
119
+ return self.client
120
+
121
+ def invoke(self, prompt: str, session_id: str | None = None) -> dict[str, Any]:
122
+ """Invoke the Bedrock agent or execute locally with configured tools."""
123
+ session_id = session_id or str(uuid.uuid4())
124
+ if os.environ.get("AWS_ACCESS_KEY_ID") and self.agent_id != "default-agent-id":
125
+ try:
126
+ client = self._get_client()
127
+ response = client.invoke_agent(
128
+ agentId=self.agent_id,
129
+ agentAliasId=self.agent_alias_id,
130
+ sessionId=session_id,
131
+ inputText=prompt,
132
+ )
133
+ output_text = ""
134
+ for event in response.get("completion", []):
135
+ if "chunk" in event:
136
+ output_text += event["chunk"]["bytes"].decode("utf-8")
137
+ return {{"output": output_text, "session_id": session_id, "status": "success"}}
138
+ except Exception as exc: # real API failures must not look like success
139
+ return {{
140
+ "output": "",
141
+ "session_id": session_id,
142
+ "status": "error",
143
+ "error": f"{{type(exc).__name__}}: {{exc}}",
144
+ }}
145
+ return {{
146
+ "output": f"Bedrock agent ({{self.model}}) response to: {{prompt}}",
147
+ "session_id": session_id,
148
+ "status": "success",
149
+ }}
150
+ ''')
151
+
152
+ first_cls = class_names[0] if class_names else "DefaultAgent"
153
+ if not class_names:
154
+ agent_blocks.append('''\
155
+ class DefaultAgent:
156
+ def __init__(self, **kwargs: Any):
157
+ pass
158
+ def invoke(self, prompt: str, session_id: str | None = None) -> dict[str, Any]:
159
+ return {"output": prompt, "status": "success"}
160
+ ''')
161
+
162
+ c = f'''\
163
+ """AWS Bedrock Agent definitions for {plan.project_name}."""
164
+ from __future__ import annotations
165
+ import os
166
+ import uuid
167
+ from typing import Any
168
+ import boto3
169
+ {tools_import}
170
+
171
+ {chr(10).join(agent_blocks)}
172
+
173
+ root_agent = {first_cls}()
174
+ __all__ = [{", ".join(repr(cn) for cn in class_names)}, "root_agent"]
175
+ '''
176
+ rel = f"src/{src.name}/agent.py"
177
+ write_file(out_dir, rel, c)
178
+ return [rel]
179
+
180
+
181
+ def _write_run(plan: GenerationPlan, src: Path, out_dir: Path) -> list[str]:
182
+ c = f'''\
183
+ """Runner for {plan.project_name} (AWS Bedrock)."""
184
+ from __future__ import annotations
185
+ import sys
186
+ from .agent import root_agent
187
+
188
+ def main() -> None:
189
+ q = " ".join(sys.argv[1:]) or "Hello"
190
+ res = root_agent.invoke(q)
191
+ print("Result:", res.get("output", res))
192
+
193
+ if __name__ == "__main__":
194
+ main()
195
+ '''
196
+ rel = f"src/{src.name}/run.py"
197
+ write_file(out_dir, rel, c)
198
+ return [rel]
199
+
200
+
201
+ def _write_runtime_handler(plan: GenerationPlan, src: Path, out_dir: Path) -> list[str]:
202
+ c = f'''\
203
+ """AWS Bedrock AgentCore runtime container web handler for {plan.project_name}.
204
+
205
+ Exposes the container endpoints required by AgentCore Runtime:
206
+ - GET /ping (health check)
207
+ - POST /invocations (agent turn invocation)
208
+ """
209
+ from __future__ import annotations
210
+ import json
211
+ from http.server import HTTPServer, BaseHTTPRequestHandler
212
+ from .agent import root_agent
213
+
214
+
215
+ class AgentCoreHandler(BaseHTTPRequestHandler):
216
+ def do_GET(self) -> None:
217
+ if self.path == "/ping":
218
+ self.send_response(200)
219
+ self.send_header("Content-Type", "application/json")
220
+ self.end_headers()
221
+ self.wfile.write(b'{{"status": "healthy"}}')
222
+ else:
223
+ self.send_response(404)
224
+ self.end_headers()
225
+
226
+ def do_POST(self) -> None:
227
+ if self.path == "/invocations":
228
+ content_length = int(self.headers.get("Content-Length", 0))
229
+ body = self.rfile.read(content_length).decode("utf-8")
230
+ payload = json.loads(body) if body else {{}}
231
+ prompt = payload.get("inputText", payload.get("prompt", ""))
232
+ result = root_agent.invoke(prompt)
233
+ self.send_response(200)
234
+ self.send_header("Content-Type", "application/json")
235
+ self.end_headers()
236
+ self.wfile.write(json.dumps(result).encode("utf-8"))
237
+ else:
238
+ self.send_response(404)
239
+ self.end_headers()
240
+
241
+
242
+ def serve(port: int = 8080) -> None:
243
+ server = HTTPServer(("0.0.0.0", port), AgentCoreHandler)
244
+ print(f"Bedrock AgentCore Runtime listening on port {{port}}")
245
+ server.serve_forever()
246
+
247
+
248
+ if __name__ == "__main__":
249
+ serve()
250
+ '''
251
+ rel = f"src/{src.name}/runtime_handler.py"
252
+ write_file(out_dir, rel, c)
253
+ return [rel]
254
+
255
+
256
+ def _write_gateway_config(ir: AgentSystemIR, plan: GenerationPlan, src: Path, out_dir: Path) -> list[str]:
257
+ tools_list = []
258
+ for tk, tool in ir.tools.items():
259
+ tools_list.append({
260
+ "name": tk,
261
+ "description": tool.description or f"Tool {tk}",
262
+ "source": tool.source or "local",
263
+ })
264
+ data = {
265
+ "gatewayVersion": "1.0",
266
+ "name": f"{plan.project_name}-gateway",
267
+ "tools": tools_list,
268
+ }
269
+ c = json.dumps(data, indent=2) + "\n"
270
+ rel = f"src/{src.name}/gateway_config.json"
271
+ write_file(out_dir, rel, c)
272
+ return [rel]
273
+
274
+
275
+ def _write_init(src: Path, out_dir: Path) -> list[str]:
276
+ c = f'"""Package: {src.name}."""\n'
277
+ rel = f"src/{src.name}/__init__.py"
278
+ write_file(out_dir, rel, c)
279
+ return [rel]
280
+
281
+
282
+ _CFN_TYPES = {"string", "number", "integer", "boolean", "array"}
283
+
284
+
285
+ def _tool_names(ir: AgentSystemIR) -> dict[str, str]:
286
+ """Raw tool key -> sanitized name; mirrors generate_tools_module so handler dispatch matches."""
287
+ return unique_identifiers(ir.tools, lambda v: snake_identifier(v, prefix="tool"))
288
+
289
+
290
+ def _json_type(pdef: object) -> str:
291
+ ptype = pdef.get("type") if isinstance(pdef, dict) else None
292
+ if isinstance(ptype, list):
293
+ ptype = next((t for t in ptype if t != "null"), None)
294
+ return ptype if ptype in _CFN_TYPES else "string"
295
+
296
+
297
+ def _function_defs(ir: AgentSystemIR, tool_keys: list[str]) -> list[dict]:
298
+ names = _tool_names(ir)
299
+ funcs = []
300
+ for tk in tool_keys:
301
+ tool = ir.tools.get(tk)
302
+ if tool is None:
303
+ continue
304
+ schema = tool.input_schema if isinstance(tool.input_schema, dict) else {}
305
+ required = set(schema.get("required") or [])
306
+ params = {}
307
+ for pname, pdef in (schema.get("properties") or {}).items():
308
+ params[pname] = {
309
+ "Type": _json_type(pdef),
310
+ "Description": (pdef.get("description") if isinstance(pdef, dict) else None) or pname,
311
+ "Required": pname in required,
312
+ }
313
+ fn = {"Name": names[tk], "Description": tool.description or f"Tool {tk}"}
314
+ if params:
315
+ fn["Parameters"] = params
316
+ funcs.append(fn)
317
+ return funcs
318
+
319
+
320
+ _HANDLER_TEMPLATE = '''\
321
+ """Bedrock action-group Lambda handler (generated). Package with scripts/package_lambda.sh."""
322
+ import json
323
+
324
+ import tools as _tools
325
+
326
+ # function name -> {bedrock parameter name: (declared JSON type, python argument name)}
327
+ TOOL_PARAMS = json.loads(__PARAMS__)
328
+
329
+
330
+ def _convert(value, json_type):
331
+ if value is None or json_type == "string":
332
+ return value
333
+ if json_type == "integer":
334
+ return int(value)
335
+ if json_type == "number":
336
+ return float(value)
337
+ if json_type == "boolean":
338
+ if isinstance(value, bool):
339
+ return value
340
+ return json.loads(str(value).lower())
341
+ if json_type == "array":
342
+ return json.loads(value) if isinstance(value, str) else value
343
+ return value
344
+
345
+
346
+ def _respond(event, function, body):
347
+ return {
348
+ "messageVersion": "1.0",
349
+ "response": {
350
+ "actionGroup": event.get("actionGroup"),
351
+ "function": function,
352
+ "functionResponse": {"responseBody": {"TEXT": {"body": body}}},
353
+ },
354
+ }
355
+
356
+
357
+ def handler(event, context):
358
+ function = event.get("function")
359
+ if function not in TOOL_PARAMS:
360
+ return _respond(event, function, "Unknown function: " + str(function))
361
+ spec = TOOL_PARAMS[function]
362
+ kwargs = {}
363
+ try:
364
+ for param in event.get("parameters") or []:
365
+ json_type, arg = spec.get(param["name"], ["string", param["name"]])
366
+ kwargs[arg] = _convert(param.get("value"), json_type)
367
+ result = getattr(_tools, function)(**kwargs)
368
+ body = result if isinstance(result, str) else json.dumps(result, default=str)
369
+ except Exception as exc:
370
+ body = "Error: " + type(exc).__name__ + ": " + str(exc)
371
+ return _respond(event, function, body)
372
+ '''
373
+
374
+ _PACKAGE_SCRIPT = """\
375
+ #!/usr/bin/env bash
376
+ # Zip the action-group Lambda (handler.py + tools.py) into tools_lambda.zip.
377
+ set -euo pipefail
378
+ ROOT="$(cd "$(dirname "$0")/.." && pwd)"
379
+ cd "$ROOT/lambda"
380
+ rm -f "$ROOT/tools_lambda.zip"
381
+ zip -r "$ROOT/tools_lambda.zip" handler.py tools.py
382
+ echo "Wrote $ROOT/tools_lambda.zip"
383
+ """
384
+
385
+
386
+ def _write_lambda_package(ir: AgentSystemIR, src: Path, out_dir: Path) -> list[str]:
387
+ """Emit lambda/handler.py, lambda/tools.py and scripts/package_lambda.sh."""
388
+ if not ir.tools:
389
+ return []
390
+ names = _tool_names(ir)
391
+ params: dict[str, dict[str, list[str]]] = {}
392
+ for tk, tool in ir.tools.items():
393
+ schema = tool.input_schema if isinstance(tool.input_schema, dict) else {}
394
+ props = schema.get("properties") or {}
395
+ argnames = unique_identifiers(props, lambda v: snake_identifier(v, prefix="arg"))
396
+ params[names[tk]] = {p: [_json_type(d), argnames[p]] for p, d in props.items()}
397
+ files = []
398
+ handler = _HANDLER_TEMPLATE.replace("__PARAMS__", repr(json.dumps(params, sort_keys=True)))
399
+ write_file(out_dir, "lambda/handler.py", handler)
400
+ files.append("lambda/handler.py")
401
+ tools_src = (out_dir / "src" / src.name / "tools.py").read_text(encoding="utf-8")
402
+ write_file(out_dir, "lambda/tools.py", tools_src)
403
+ files.append("lambda/tools.py")
404
+ write_file(out_dir, "scripts/package_lambda.sh", _PACKAGE_SCRIPT)
405
+ (out_dir / "scripts" / "package_lambda.sh").chmod(0o755)
406
+ files.append("scripts/package_lambda.sh")
407
+ return files
408
+
409
+
410
+ def _tools_resources(ir: AgentSystemIR, first_key: str | None, tool_keys: list[str]) -> tuple[str, str]:
411
+ """Return (action_groups_yaml, extra_resources_yaml) for the declared tools."""
412
+ funcs = _function_defs(ir, tool_keys)
413
+ if not funcs or first_key is None:
414
+ return "", ""
415
+ fn_id = f"{pascal_identifier(first_key, prefix='Agent')}ToolsFunction"
416
+ group_name = snake_identifier(first_key, prefix="agent") + "_tools"
417
+ ag = f"""\
418
+ ActionGroups:
419
+ - ActionGroupName: {group_name}
420
+ Description: Tools for the {first_key} agent
421
+ ActionGroupExecutor:
422
+ Lambda: !GetAtt {fn_id}.Arn
423
+ FunctionSchema:
424
+ Functions: {json.dumps(funcs)}
425
+ """
426
+ res = f"""
427
+ {fn_id}Role:
428
+ Type: AWS::IAM::Role
429
+ Properties:
430
+ AssumeRolePolicyDocument:
431
+ Version: '2012-10-17'
432
+ Statement:
433
+ - Effect: Allow
434
+ Principal:
435
+ Service: lambda.amazonaws.com
436
+ Action: sts:AssumeRole
437
+ ManagedPolicyArns:
438
+ - arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
439
+
440
+ {fn_id}:
441
+ Type: AWS::Lambda::Function
442
+ Properties:
443
+ Runtime: python3.12
444
+ Handler: handler.handler
445
+ Role: !GetAtt {fn_id}Role.Arn
446
+ Code:
447
+ S3Bucket: !Ref ToolsCodeBucket
448
+ S3Key: !Ref ToolsCodeKey
449
+
450
+ {fn_id}InvokePermission:
451
+ Type: AWS::Lambda::Permission
452
+ Properties:
453
+ Action: lambda:InvokeFunction
454
+ FunctionName: !Ref {fn_id}
455
+ Principal: bedrock.amazonaws.com
456
+ """
457
+ return ag, res
458
+
459
+
460
+ def _write_cloudformation(ir: AgentSystemIR, plan: GenerationPlan, out_dir: Path) -> list[str]:
461
+ first_agent = next(iter(ir.agents.values()), None)
462
+ inst = (first_agent.instructions if first_agent else "You are a helpful assistant.").replace("\n", " ")
463
+ mstr = "anthropic.claude-3-sonnet-20240229-v1:0"
464
+ if first_agent and first_agent.model in ir.models:
465
+ mstr = ir.models[first_agent.model].name
466
+
467
+ first_key = next(iter(ir.agents), None)
468
+ action_groups, tool_resources = _tools_resources(ir, first_key, list(dict.fromkeys(t for a in ir.agents.values() for t in a.tools)))
469
+
470
+ tool_params = """\
471
+ ToolsCodeBucket:
472
+ Type: String
473
+ Description: S3 bucket holding tools_lambda.zip (build with scripts/package_lambda.sh)
474
+ ToolsCodeKey:
475
+ Type: String
476
+ Default: tools_lambda.zip
477
+ Description: S3 key of the packaged action-group Lambda
478
+ """ if action_groups else ""
479
+
480
+ c = f"""\
481
+ AWSTemplateFormatVersion: '2010-09-09'
482
+ Description: AWS Bedrock Agent deployment template for {plan.project_name}
483
+
484
+ Parameters:
485
+ AgentName:
486
+ Type: String
487
+ Default: {plan.project_name}-agent
488
+ FoundationModel:
489
+ Type: String
490
+ Default: {mstr}
491
+ {tool_params}
492
+ Resources:
493
+ BedrockAgentRole:
494
+ Type: AWS::IAM::Role
495
+ Properties:
496
+ AssumeRolePolicyDocument:
497
+ Version: '2012-10-17'
498
+ Statement:
499
+ - Effect: Allow
500
+ Principal:
501
+ Service: bedrock.amazonaws.com
502
+ Action: sts:AssumeRole
503
+ Policies:
504
+ - PolicyName: BedrockAgentPolicy
505
+ PolicyDocument:
506
+ Version: '2012-10-17'
507
+ Statement:
508
+ - Effect: Allow
509
+ Action:
510
+ - bedrock:InvokeModel
511
+ Resource: '*'
512
+
513
+ BedrockAgent:
514
+ Type: AWS::Bedrock::Agent
515
+ Properties:
516
+ AgentName: !Ref AgentName
517
+ AgentResourceRoleArn: !GetAtt BedrockAgentRole.Arn
518
+ FoundationModel: !Ref FoundationModel
519
+ Instruction: {json.dumps(inst)}
520
+ IdleSessionTTLInSeconds: 1800
521
+ {action_groups}
522
+ BedrockAgentAlias:
523
+ Type: AWS::Bedrock::AgentAlias
524
+ Properties:
525
+ AgentId: !Ref BedrockAgent
526
+ AgentAliasName: live
527
+ {tool_resources}"""
528
+ write_file(out_dir, "template.yaml", c)
529
+ return ["template.yaml"]
530
+
531
+
532
+ def _write_env_example(out_dir: Path) -> list[str]:
533
+ c = """\
534
+ AWS_REGION=us-east-1
535
+ AWS_ACCESS_KEY_ID=your-access-key-id
536
+ AWS_SECRET_ACCESS_KEY=your-secret-access-key
537
+ BEDROCK_AGENT_ID=your-agent-id
538
+ BEDROCK_AGENT_ALIAS_ID=TSTALIASID
539
+ """
540
+ write_file(out_dir, ".env.example", c)
541
+ return [".env.example"]
542
+
543
+
544
+ def _write_readme(ir: AgentSystemIR, plan: GenerationPlan, out_dir: Path) -> list[str]:
545
+ c = f"""\
546
+ # {plan.project_name} — AWS Bedrock Agents & AgentCore
547
+
548
+ Generated by `agentsml-impl`.
549
+
550
+ This project targets AWS Bedrock Agents and Bedrock AgentCore Runtime.
551
+
552
+ ## Architecture
553
+
554
+ - `src/{plan.package_name}/agent.py`: Bedrock Agent client and runtime adapter.
555
+ - `src/{plan.package_name}/runtime_handler.py`: Container web server implementing `/ping` and `/invocations` for Bedrock AgentCore Runtime.
556
+ - `src/{plan.package_name}/gateway_config.json`: AgentCore Gateway configuration.
557
+ - `template.yaml`: AWS CloudFormation template for deploying the Bedrock Agent and IAM roles.
558
+ - `src/{plan.package_name}/run.py`: Local execution runner.
559
+
560
+ ## Quickstart
561
+
562
+ ```bash
563
+ pip install -e .
564
+ python -m {plan.package_name}.run "Analyze recent transactions"
565
+ ```
566
+
567
+ ## Running as an AgentCore Container
568
+
569
+ ```bash
570
+ python -m {plan.package_name}.runtime_handler
571
+ # Health check: curl http://localhost:8080/ping
572
+ # Invocation: curl -X POST http://localhost:8080/invocations -d '{{"inputText": "hello"}}'
573
+ ```
574
+
575
+ ## CloudFormation Deployment
576
+
577
+ If the agent declares tools, package and upload the action-group Lambda first
578
+ (`lambda/handler.py` + `lambda/tools.py`), then pass its location as parameters.
579
+ `ToolsCodeBucket` has no default and must be supplied; `ToolsCodeKey` defaults to `tools_lambda.zip`.
580
+ ```bash
581
+ ./scripts/package_lambda.sh
582
+ aws s3 cp tools_lambda.zip s3://<your-bucket>/tools_lambda.zip
583
+ aws cloudformation deploy \\
584
+ --template-file template.yaml \\
585
+ --stack-name {plan.project_name}-stack \\
586
+ --capabilities CAPABILITY_IAM \\
587
+ --parameter-overrides ToolsCodeBucket=<your-bucket> ToolsCodeKey=tools_lambda.zip
588
+ ```
589
+ (Omit `--parameter-overrides` when no tools are declared.)
590
+ """
591
+ write_file(out_dir, "README.md", c)
592
+ return ["README.md"]
@@ -0,0 +1,26 @@
1
+ target: bedrock_agentcore
2
+ kind: code
3
+ language: python
4
+ status: implemented
5
+ level: 1
6
+ version_tested: "1.0.0"
7
+ supports:
8
+ agents: native
9
+ tools: native
10
+ workflows: lossy
11
+ graph_edges: lossy
12
+ graph_conditions: lossy
13
+ cycles: lossy
14
+ parallel: unsupported
15
+ human_approval: adapter
16
+ mcp: adapter
17
+ a2a: manual
18
+ ag_ui: unsupported
19
+ structured_output: manual
20
+ observability: native
21
+ artifacts:
22
+ - python_project
23
+ - diagnostics
24
+ - readme
25
+ notes: >
26
+ Maps to AWS Bedrock Agents.
File without changes