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,655 @@
1
+ """ag2 (AG2) target adapter — Level 1 code generation.
2
+
3
+ Targets the AG2 1.x API (ag2>=1.3.1):
4
+
5
+ - Agents are ``ag2.Agent`` instances whose model is a ``ModelConfig``.
6
+ - A workflow becomes a coordinator agent whose workers are exposed as tools
7
+ with ``Agent.as_tool()``.
8
+ - A step that calls a remote agent is an ``Agent`` configured with
9
+ ``A2AConfig(card_url=...)``, so the A2A client is native to the framework.
10
+
11
+ The earlier 0.x generation (``AssistantAgent``, ``UserProxyAgent``,
12
+ ``llm_config``, ``initiate_swarm_chat``) no longer exists in AG2 1.x.
13
+
14
+ A2A notes (verified against ``ag2==1.3.1``):
15
+
16
+ - ``A2AConfig.card_url`` is the *base URL* of the remote agent. AG2 resolves
17
+ the card from ``{card_url}/.well-known/agent-card.json``. AgentsML declares
18
+ the full card URL, so the adapter normalises it down to the base URL —
19
+ passing the card URL verbatim produces a 404 on
20
+ ``.../agent-card.json/.well-known/agent-card.json``.
21
+ - Bearer credentials are attached through ``A2AConfig(headers=...)``.
22
+ - The server direction uses ``ag2.a2a.server.A2AServer``.
23
+ """
24
+
25
+ from __future__ import annotations
26
+ import json
27
+ from pathlib import Path
28
+
29
+ from agentsml_impl.compiler.identifiers import python_identifier_ir
30
+ from agentsml_impl.compiler.ir import AgentSystemIR, ModelIR, StepIR
31
+ from agentsml_impl.compiler.diagnostics import DiagCode, DiagnosticSet
32
+ from agentsml_impl.compiler.naming import pascal_identifier, snake_identifier
33
+ from agentsml_impl.compiler.planner import GenerationPlan
34
+ from agentsml_impl.compiler.render import toml_string, write_file
35
+ from agentsml_impl.runtime.json_schema import generate_models_source
36
+ from agentsml_impl.runtime.tools import generate_tools_module
37
+ from agentsml_impl.targets.base import TargetAdapter, GenerationResult
38
+
39
+
40
+ # AG2 resolves the agent card from ``{card_url}/.well-known/agent-card.json``,
41
+ # so a declared card URL has to be reduced to the agent's base URL.
42
+ _A2A_WELL_KNOWN_SUFFIXES = (
43
+ "/.well-known/agent-card.json",
44
+ "/.well-known/agent.json",
45
+ "/.well-known/agent-card",
46
+ )
47
+
48
+
49
+ def _a2a_base_url(card_url: str) -> str:
50
+ """Return the AG2 base URL for a declared AgentsML agent card URL."""
51
+ trimmed = card_url.strip().rstrip("/")
52
+ for suffix in _A2A_WELL_KNOWN_SUFFIXES:
53
+ if trimmed.endswith(suffix):
54
+ return trimmed[: -len(suffix)]
55
+ return trimmed
56
+
57
+
58
+ class Adapter(TargetAdapter):
59
+ @property
60
+ def name(self) -> str:
61
+ return "ag2"
62
+
63
+ def analyze(self, ir: AgentSystemIR, diagnostics: DiagnosticSet) -> None:
64
+ from agentsml_impl.compiler.capabilities import analyze_capabilities
65
+ analyze_capabilities(ir, self.name, diagnostics)
66
+
67
+ def generate(self, ir: AgentSystemIR, plan: GenerationPlan,
68
+ out_dir: Path, diagnostics: DiagnosticSet) -> GenerationResult:
69
+ ir = python_identifier_ir(ir)
70
+ out_dir.mkdir(parents=True, exist_ok=True)
71
+ pkg = plan.package_name
72
+ src = out_dir / "src" / pkg
73
+ src.mkdir(parents=True, exist_ok=True)
74
+
75
+ files: list[str] = []
76
+ files += _write_pyproject(ir, plan, out_dir)
77
+ files += _write_tools(ir, src, out_dir, diagnostics)
78
+ files += _write_models(ir, src, out_dir, diagnostics)
79
+ files += _write_agent(ir, plan, src, out_dir, diagnostics)
80
+ files += _write_run(plan, src, out_dir, ir)
81
+ files += _write_init(src, out_dir)
82
+ files += _write_readme(ir, plan, out_dir)
83
+
84
+ return GenerationResult(
85
+ target=self.name, out_dir=out_dir, files_written=files, success=True
86
+ )
87
+
88
+
89
+ # ---------------------------------------------------------------------------
90
+ # Model configuration
91
+ # ---------------------------------------------------------------------------
92
+
93
+ def _model_config_expr(model: ModelIR | None) -> tuple[str, str]:
94
+ """Return (expression, import line) for the AG2 model config of a model."""
95
+ if model is None:
96
+ return 'GeminiConfig(model="gemini-2.0-flash")', "from ag2.config import GeminiConfig"
97
+ provider = model.provider.lower()
98
+ name = model.name
99
+ if provider in ("google", "gemini", "google-cloud", "google_cloud"):
100
+ return f'GeminiConfig(model="{name}")', "from ag2.config import GeminiConfig"
101
+ if provider == "anthropic":
102
+ return f'AnthropicConfig(model="{name}")', "from ag2.config import AnthropicConfig"
103
+ if provider in ("openai", "azure", "azure-openai", "openai-completions", "openai-responses"):
104
+ return f'OpenAIConfig(model="{name}")', "from ag2.config import OpenAIConfig"
105
+ return f'OpenAIConfig(model="{name}")', "from ag2.config import OpenAIConfig"
106
+
107
+
108
+ # ---------------------------------------------------------------------------
109
+ # File generators
110
+ # ---------------------------------------------------------------------------
111
+
112
+ def _provider_extra(provider: str | None) -> str | None:
113
+ """Return the AG2 optional-dependency extra that a model provider needs.
114
+
115
+ AG2 keeps every provider client behind an extra (``ag2[openai]``,
116
+ ``ag2[gemini]``, ...). The generated project must declare the extra for
117
+ the providers it uses, otherwise importing the generated module fails with
118
+ ``ImportError: OpenAIConfig requires optional dependencies``.
119
+ """
120
+ if not provider:
121
+ return None
122
+ mapping = {
123
+ "openai": "openai",
124
+ "azure": "openai",
125
+ "azure-openai": "openai",
126
+ "openai-completions": "openai",
127
+ "openai-responses": "openai",
128
+ "anthropic": "anthropic",
129
+ "google": "gemini",
130
+ "gemini": "gemini",
131
+ "google-cloud": "gemini",
132
+ "google_cloud": "gemini",
133
+ "mistral": "mistral",
134
+ "ollama": "ollama",
135
+ "bedrock": "bedrock",
136
+ "xai": "xai",
137
+ "perplexity": "perplexity",
138
+ "dashscope": "dashscope",
139
+ "zai": "zai",
140
+ }
141
+ return mapping.get(provider.lower())
142
+
143
+
144
+ def _write_pyproject(ir: AgentSystemIR, plan: GenerationPlan, out_dir: Path) -> list[str]:
145
+ extras: set[str] = set()
146
+ for model in ir.models.values():
147
+ extra = _provider_extra(model.provider)
148
+ if extra:
149
+ extras.add(extra)
150
+ if ir.a2a_agents:
151
+ extras.add("a2a")
152
+
153
+ if extras:
154
+ deps = [f' "ag2[{",".join(sorted(extras))}]>=1.3.1"']
155
+ else:
156
+ deps = [' "ag2>=1.3.1"']
157
+ if ir.a2a_server:
158
+ deps.append(' "a2a-sdk[http-server]>=1.3.0"')
159
+ deps.append(' "uvicorn>=0.30"')
160
+ deps.append(' "python-dotenv"')
161
+ deps_block = ",\n".join(deps)
162
+ c = f'''\
163
+ [build-system]
164
+ requires = ["setuptools>=68"]
165
+ build-backend = "setuptools.build_meta"
166
+
167
+ [project]
168
+ name = "{plan.package_name}"
169
+ version = "{ir.metadata.version or '0.1.0'}"
170
+ description = {toml_string(ir.metadata.description or plan.project_name)}
171
+ requires-python = ">=3.11"
172
+ dependencies = [
173
+ {deps_block}
174
+ ]
175
+
176
+ [tool.setuptools.packages.find]
177
+ where = ["src"]
178
+ '''
179
+ write_file(out_dir, "pyproject.toml", c)
180
+ return ["pyproject.toml"]
181
+
182
+
183
+ def _write_tools(ir: AgentSystemIR, src: Path, out_dir: Path, ds: DiagnosticSet) -> list[str]:
184
+ if not ir.tools:
185
+ return []
186
+ c = generate_tools_module(ir.tools, ds, framework="ag2")
187
+ rel = f"src/{src.name}/tools.py"
188
+ write_file(out_dir, rel, c)
189
+ return [rel]
190
+
191
+
192
+ def _write_models(ir: AgentSystemIR, src: Path, out_dir: Path, ds: DiagnosticSet) -> list[str]:
193
+ """Generate Pydantic models for agent output schemas (AG2 response_schema)."""
194
+ schemas: dict[str, dict] = {}
195
+ for ak, agent in ir.agents.items():
196
+ if not agent.output_schema:
197
+ continue
198
+ schemas[f"{pascal_identifier(ak, prefix='Agent')}Output"] = agent.output_schema
199
+ if not schemas:
200
+ return []
201
+ c = generate_models_source(schemas, ds)
202
+ rel = f"src/{src.name}/models.py"
203
+ write_file(out_dir, rel, c)
204
+ return [rel]
205
+
206
+
207
+ def _output_model_name(agent_key: str) -> str:
208
+ return f"{pascal_identifier(agent_key, prefix='Agent')}Output"
209
+
210
+
211
+ def _emit_omitted_step_diagnostics(
212
+ ir: AgentSystemIR, plan: GenerationPlan, ds: DiagnosticSet
213
+ ) -> None:
214
+ """Report workflow steps the AG2 team model cannot express.
215
+
216
+ AG2 1.x models a workflow as a coordinator agent whose workers are tools.
217
+ Steps that are not an agent call (tool calls, nested workflows, approval
218
+ gates) have no representation in that model, so they are reported rather
219
+ than dropped silently.
220
+ """
221
+ wf = ir.workflows.get(plan.main_workflow_key)
222
+ if not wf:
223
+ return
224
+ base_path = f"workflows.{plan.main_workflow_key}.steps"
225
+ for step in wf.steps:
226
+ step_path = f"{base_path}.{step.id}"
227
+ if step.agent or step.a2a_agent:
228
+ continue
229
+ if step.approval:
230
+ ds.add_warning(
231
+ DiagCode.REQUIRES_ADAPTER,
232
+ f"Approval step '{step.id}' is not generated by the AG2 team model. "
233
+ "The coordinator agent calls each worker once, without a human gate.",
234
+ path=f"{step_path}.approval",
235
+ recommendation=(
236
+ "Attach an AG2 hitl_hook to the worker agent, or gate the workflow "
237
+ "outside the generated project."
238
+ ),
239
+ )
240
+ elif step.tool:
241
+ ds.add_warning(
242
+ DiagCode.LOSSY_MAPPING,
243
+ f"Tool step '{step.id}' is not generated by the AG2 team model. "
244
+ "Tools are attached to the agent that declares them.",
245
+ path=f"{step_path}.tool",
246
+ recommendation="Attach the tool to the agent that should call it.",
247
+ )
248
+ elif step.workflow:
249
+ ds.add_warning(
250
+ DiagCode.LOSSY_MAPPING,
251
+ f"Nested workflow step '{step.id}' is not generated by the AG2 team model.",
252
+ path=f"{step_path}.workflow",
253
+ recommendation="Flatten the nested workflow into agent steps.",
254
+ )
255
+
256
+
257
+ def _write_agent(ir: AgentSystemIR, plan: GenerationPlan, src: Path,
258
+ out_dir: Path, ds: DiagnosticSet) -> list[str]:
259
+ wf = ir.workflows.get(plan.main_workflow_key)
260
+ steps = wf.steps if wf else []
261
+
262
+ if wf and any(edge.condition for edge in wf.edges):
263
+ ds.add_warning(
264
+ DiagCode.LOSSY_MAPPING,
265
+ "Conditional workflow edges are not expressible in the AG2 1.x team model. "
266
+ "The workflow is generated as a coordinator agent whose workers are exposed as tools.",
267
+ path=f"workflows.{plan.main_workflow_key}.edges",
268
+ recommendation="Use AG2 middleware or the network API for deterministic conditional routing.",
269
+ )
270
+
271
+ if wf and wf.edges:
272
+ ds.add_warning(
273
+ DiagCode.LOSSY_MAPPING,
274
+ "Workflow edges are not expressible in the AG2 1.x team model. "
275
+ "Steps are exposed to the coordinator agent in declared step order.",
276
+ path=f"workflows.{plan.main_workflow_key}.edges",
277
+ recommendation="Use AG2 middleware or the network API for deterministic routing.",
278
+ )
279
+
280
+ if wf and wf.has_cycles():
281
+ ds.add_warning(
282
+ DiagCode.LOSSY_MAPPING,
283
+ "Cyclic workflows are not expressible in the AG2 1.x team model. "
284
+ "The generated coordinator agent runs each worker once, in declared step order.",
285
+ path=f"workflows.{plan.main_workflow_key}.edges",
286
+ recommendation="Model iteration with AG2 middleware or an explicit loop tool.",
287
+ )
288
+
289
+ for ak, agent in ir.agents.items():
290
+ if agent.memory and agent.memory.get("reasoning"):
291
+ ds.add_warning(
292
+ DiagCode.REQUIRES_ADAPTER,
293
+ f"Agent '{ak}' declares a reasoning configuration. AG2 1.x has no ReasoningAgent, "
294
+ "so the reasoning settings are not generated.",
295
+ path=f"agents.{ak}.memory.reasoning",
296
+ recommendation="Configure reasoning through the model config or AG2 middleware.",
297
+ )
298
+
299
+ _emit_omitted_step_diagnostics(ir, plan, ds)
300
+
301
+ imports: set[str] = set()
302
+ local_blocks: list[str] = []
303
+ a2a_blocks: list[str] = []
304
+ needs_secret_helper = False
305
+
306
+ step_agents: list[tuple[str, str]] = [] # (variable, description)
307
+
308
+ for step in steps:
309
+ if step.a2a_agent:
310
+ spec = ir.a2a_agents.get(step.a2a_agent)
311
+ if spec is None:
312
+ ds.add_error(
313
+ DiagCode.AMBIGUOUS_REFERENCE,
314
+ f"A2A step '{step.id}' references undeclared A2A agent '{step.a2a_agent}'.",
315
+ path=f"workflows.{plan.main_workflow_key}.steps.{step.id}.a2a_agent",
316
+ recommendation=f"Declare '{step.a2a_agent}' in the a2a_agents block.",
317
+ )
318
+ continue
319
+ card = spec.get("agent_card_url") or spec.get("agent_card")
320
+ if not card:
321
+ ds.add_warning(
322
+ DiagCode.MISSING_SCHEMA,
323
+ f"A2A agent '{step.a2a_agent}' declares no agent_card_url, "
324
+ "so the remote agent cannot be generated.",
325
+ path=f"a2a_agents.{step.a2a_agent}",
326
+ recommendation="Add agent_card_url pointing at the remote agent card.",
327
+ )
328
+ continue
329
+ var = f"{snake_identifier(step.id, prefix='step')}_a2a"
330
+ description = spec.get("description") or f"Remote agent {step.a2a_agent}."
331
+ base_url = _a2a_base_url(card)
332
+
333
+ auth = spec.get("auth") or {}
334
+ auth_lines = ""
335
+ if auth.get("type") == "bearer" and auth.get("secret_ref"):
336
+ needs_secret_helper = True
337
+ secret_ref = str(auth["secret_ref"])
338
+ auth_lines = (
339
+ ' headers={"Authorization": f"Bearer {_require_secret('
340
+ + repr(secret_ref)
341
+ + ')}"},\n'
342
+ )
343
+ elif auth:
344
+ ds.add_warning(
345
+ DiagCode.REQUIRES_ADAPTER,
346
+ f"A2A agent '{step.a2a_agent}' declares auth type '{auth.get('type')}', "
347
+ "which the AG2 adapter does not generate.",
348
+ path=f"a2a_agents.{step.a2a_agent}.auth",
349
+ recommendation="Wire the credential for this remote agent manually.",
350
+ )
351
+
352
+ imports.add("from ag2.a2a.config import A2AConfig")
353
+ a2a_blocks.append(
354
+ f"{var} = Agent(\n"
355
+ f' name="{step.id}",\n'
356
+ f" config=A2AConfig(\n"
357
+ f' card_url="{base_url}",\n'
358
+ f"{auth_lines}"
359
+ f" ),\n"
360
+ f")"
361
+ )
362
+ step_agents.append((var, description))
363
+ continue
364
+
365
+ if step.agent and step.agent in ir.agents:
366
+ agent = ir.agents[step.agent]
367
+ var = f"{snake_identifier(step.id, prefix='step')}_agent"
368
+ model_expr, model_import = _model_config_expr(ir.models.get(agent.model))
369
+ imports.add(model_import)
370
+ tool_list = ""
371
+ if agent.tools:
372
+ names = ", ".join(snake_identifier(t, prefix="tool") for t in agent.tools)
373
+ tool_list = f"\n tools=[{names}],"
374
+ prompt = agent.instructions.replace('"""', "'''")
375
+ schema_line = ""
376
+ if agent.output_schema:
377
+ schema_line = f"\n response_schema={_output_model_name(step.agent)},"
378
+ local_blocks.append(f'''\
379
+ {var} = Agent(
380
+ name="{step.id}",
381
+ prompt="""{prompt}""",
382
+ config={model_expr},{tool_list}{schema_line}
383
+ )''')
384
+ step_agents.append((var, agent.description or agent.instructions.splitlines()[0][:70]))
385
+
386
+ # Agents that are declared but not used by a step still get generated.
387
+ used = {step.agent for step in steps if step.agent}
388
+ for ak, agent in ir.agents.items():
389
+ if ak in used:
390
+ continue
391
+ var = f"{snake_identifier(ak, prefix='agent')}_agent"
392
+ model_expr, model_import = _model_config_expr(ir.models.get(agent.model))
393
+ imports.add(model_import)
394
+ prompt = agent.instructions.replace('"""', "'''")
395
+ schema_line = ""
396
+ if agent.output_schema:
397
+ schema_line = f"\n response_schema={_output_model_name(ak)},"
398
+ local_blocks.append(f'''\
399
+ {var} = Agent(
400
+ name="{ak}",
401
+ prompt="""{prompt}""",
402
+ config={model_expr},{schema_line}
403
+ )''')
404
+
405
+ if step_agents:
406
+ if len(step_agents) == 1:
407
+ root_block = f"root_agent = {step_agents[0][0]}"
408
+ else:
409
+ root_model, root_import = _model_config_expr(
410
+ ir.models.get(next(iter(ir.agents.values())).model)
411
+ if ir.agents else None
412
+ )
413
+ imports.add(root_import)
414
+ tool_lines = ",\n".join(
415
+ f' {var}.as_tool(description={json.dumps(desc)}, name="{var}")'
416
+ for var, desc in step_agents
417
+ )
418
+ root_block = f'''\
419
+ root_agent = Agent(
420
+ name="{plan.package_name}",
421
+ prompt="""Coordinate the specialist agents to answer the user's request.""",
422
+ config={root_model},
423
+ tools=[
424
+ {tool_lines},
425
+ ],
426
+ )'''
427
+ else:
428
+ root_model, root_import = _model_config_expr(None)
429
+ imports.add(root_import)
430
+ root_block = f'''\
431
+ root_agent = Agent(
432
+ name="{plan.package_name}",
433
+ prompt="""Agent generated from AgentsML {plan.project_name}.""",
434
+ config={root_model},
435
+ )'''
436
+
437
+ tools_import = (
438
+ f"from .tools import {', '.join(snake_identifier(t, prefix='tool') for t in ir.tools)}"
439
+ if ir.tools else ""
440
+ )
441
+
442
+ models_import = ""
443
+ if any(v.output_schema for v in ir.agents.values()):
444
+ models_import = "from .models import " + ", ".join(
445
+ _output_model_name(k) for k, v in ir.agents.items() if v.output_schema
446
+ )
447
+
448
+ secret_helper = _SECRET_HELPER if needs_secret_helper else ""
449
+
450
+ c = f'''\
451
+ """AG2 definitions for {plan.project_name}.
452
+
453
+ Auto-generated by agentsml-impl. Re-run to regenerate.
454
+ """
455
+ from __future__ import annotations
456
+ import ag2
457
+ from ag2 import Agent
458
+ {chr(10).join(sorted(imports))}
459
+ {tools_import}
460
+ {models_import}
461
+ {secret_helper}
462
+ # ── Agents ───────────────────────────────────────────────────────────────────
463
+ {chr(10).join(local_blocks) or "# No local agents"}
464
+
465
+ # ── Remote A2A agents ────────────────────────────────────────────────────────
466
+ {chr(10).join(a2a_blocks) or "# No remote A2A agents"}
467
+
468
+ # ── Root agent (entry point) ────────────────────────────────────────────────
469
+ {root_block}
470
+ '''
471
+ rel = f"src/{src.name}/agent.py"
472
+ write_file(out_dir, rel, c)
473
+ return [rel]
474
+
475
+
476
+ _SECRET_HELPER = '''
477
+
478
+ def _require_secret(name: str) -> str:
479
+ """Read a required secret from the environment.
480
+
481
+ The credential is resolved when the module is imported, so a missing secret
482
+ fails immediately with a clear message instead of an opaque auth failure.
483
+ """
484
+ import os
485
+
486
+ value = os.environ.get(name)
487
+ if not value:
488
+ raise RuntimeError(f"Missing required secret environment variable {name}")
489
+ return value
490
+ '''
491
+
492
+
493
+ def _a2a_server_block(ir: AgentSystemIR, plan: GenerationPlan) -> tuple[str, str]:
494
+ """Generate the A2A server entrypoint for the ``a2a_server`` block."""
495
+ server = ir.a2a_server or {}
496
+ host = str(server.get("host", "0.0.0.0"))
497
+ port = int(server.get("port", 8000))
498
+ public_url = str(server.get("url") or f"http://localhost:{port}")
499
+ name = server.get("name") or plan.package_name
500
+ description = server.get("description") or f"AgentsML agent {name}."
501
+ version = server.get("version") or ir.metadata.version or "0.1.0"
502
+
503
+ skill_blocks: list[str] = []
504
+ for skill in server.get("skills", []) or []:
505
+ if not isinstance(skill, dict):
506
+ continue
507
+ skill_id = skill.get("id") or skill.get("name") or "skill"
508
+ skill_name = skill.get("name") or skill_id
509
+ skill_desc = skill.get("description") or ""
510
+ tags = list(skill.get("tags") or []) or ["agentsml"]
511
+ skill_blocks.append(
512
+ " AgentSkill(\n"
513
+ f" id={skill_id!r},\n"
514
+ f" name={skill_name!r},\n"
515
+ f" description={skill_desc!r},\n"
516
+ f" tags={tags!r},\n"
517
+ " ),"
518
+ )
519
+
520
+ skills_arg = ""
521
+ if skill_blocks:
522
+ skills_arg = (
523
+ " skills=[\n"
524
+ + "\n".join(skill_blocks)
525
+ + "\n ],\n"
526
+ )
527
+
528
+ block = (
529
+ "\n"
530
+ "# ── A2A service ───────────────────────────────────────────────────────\n"
531
+ "# Exposes the root agent as an A2A service. Serve it with:\n"
532
+ f"# python -m {plan.package_name}.run --serve\n"
533
+ "from ag2.a2a.card import build_card\n"
534
+ "from ag2.a2a.server import A2AServer\n"
535
+ "from a2a.types import AgentSkill\n"
536
+ "\n"
537
+ f'A2A_HOST = "{host}"\n'
538
+ f"A2A_PORT = {port}\n"
539
+ f'A2A_PUBLIC_URL = "{public_url}"\n'
540
+ "\n"
541
+ "A2A_CARD = build_card(\n"
542
+ " root_agent,\n"
543
+ " url=A2A_PUBLIC_URL,\n"
544
+ f" description={description!r},\n"
545
+ f" version={version!r},\n"
546
+ f"{skills_arg}"
547
+ ")\n"
548
+ f"A2A_CARD.name = {name!r}\n"
549
+ "\n"
550
+ "a2a_app = A2AServer(root_agent).build_jsonrpc(\n"
551
+ " url=A2A_PUBLIC_URL,\n"
552
+ " card=A2A_CARD,\n"
553
+ ")\n"
554
+ )
555
+ return block, "a2a_server"
556
+
557
+
558
+ def _write_run(plan: GenerationPlan, src: Path, out_dir: Path, ir: AgentSystemIR) -> list[str]:
559
+ server_block = ""
560
+ serve_entry = ""
561
+ if ir.a2a_server:
562
+ server_block, _ = _a2a_server_block(ir, plan)
563
+ serve_entry = '''
564
+
565
+ def serve() -> None:
566
+ """Serve the generated agent over the A2A JSON-RPC protocol."""
567
+ import uvicorn
568
+
569
+ from .agent import A2A_HOST, A2A_PORT, a2a_app
570
+
571
+ uvicorn.run(a2a_app, host=A2A_HOST, port=A2A_PORT)
572
+ '''
573
+
574
+ c = f'''\
575
+ """Runner for {plan.project_name} (AG2). Auto-generated."""
576
+ from __future__ import annotations
577
+ import asyncio
578
+
579
+ from .agent import root_agent
580
+ {server_block}
581
+
582
+ async def run_async(question: str) -> str:
583
+ """Run one turn against the root agent and return the reply text."""
584
+ async with root_agent.run(question) as run:
585
+ reply = await run.result()
586
+ return await reply.content() or ""
587
+
588
+
589
+ def main() -> None:
590
+ import sys
591
+ if "--serve" in sys.argv:
592
+ serve()
593
+ return
594
+ q = " ".join(a for a in sys.argv[1:] if not a.startswith("--")) or "Hello!"
595
+ print(asyncio.run(run_async(q)))
596
+ {serve_entry}
597
+
598
+ if __name__ == "__main__":
599
+ main()
600
+ '''
601
+ rel = f"src/{src.name}/run.py"
602
+ write_file(out_dir, rel, c)
603
+ return [rel]
604
+
605
+
606
+ def _write_init(src: Path, out_dir: Path) -> list[str]:
607
+ c = f'"""Package: {src.name}."""\n'
608
+ rel = f"src/{src.name}/__init__.py"
609
+ write_file(out_dir, rel, c)
610
+ return [rel]
611
+
612
+
613
+ def _write_readme(ir: AgentSystemIR, plan: GenerationPlan, out_dir: Path) -> list[str]:
614
+ a2a_client_note = """
615
+ ## Remote A2A agents
616
+
617
+ Steps that declare `a2a_agent` become AG2 agents configured with
618
+ `A2AConfig(card_url=...)`. AG2 resolves the agent card from
619
+ `{card_url}/.well-known/agent-card.json`, so a declared
620
+ `agent_card_url` is normalised to the remote agent's base URL.
621
+ Bearer credentials are sent as an `Authorization` header and are read
622
+ from the environment variable named by `auth.secret_ref`.
623
+ """
624
+ a2a_server_note = """
625
+ ## A2A service
626
+
627
+ The `a2a_server` block exposes the root agent over the A2A JSON-RPC protocol:
628
+
629
+ ```bash
630
+ python -m {pkg}.run --serve
631
+ ```
632
+ """.format(pkg=plan.package_name)
633
+
634
+ c = f"""\
635
+ # {plan.project_name} — AG2
636
+
637
+ > Auto-generated by `agentsml-impl`.
638
+
639
+ ## Team model
640
+
641
+ AG2 1.x models a workflow as a coordinator agent whose workers are exposed as tools
642
+ with `Agent.as_tool()`. A step that calls a remote agent is an agent configured with
643
+ `A2AConfig(card_url=...)`, so the A2A client is native to the framework.
644
+ {a2a_client_note if ir.a2a_agents else ""}{a2a_server_note if ir.a2a_server else ""}
645
+ ## Quickstart
646
+ ```bash
647
+ pip install -e .
648
+ export GOOGLE_API_KEY="your-key" # or OPENAI_API_KEY, depending on the model
649
+ python -m {plan.package_name}.run
650
+ ```
651
+
652
+ > See `diagnostics.yaml` for portability warnings.
653
+ """
654
+ write_file(out_dir, "README.md", c)
655
+ return ["README.md"]
@@ -0,0 +1,37 @@
1
+ target: ag2
2
+ kind: code
3
+ language: python
4
+ status: implemented
5
+ level: 1
6
+ version_tested: "1.3.1"
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: manual
16
+ mcp: adapter
17
+ a2a: native
18
+ ag_ui: unsupported
19
+ structured_output: native
20
+ observability: native
21
+ artifacts:
22
+ - python_project
23
+ - diagnostics
24
+ - readme
25
+ notes: >
26
+ Maps to AutoGen 2.0 (ag2) 1.x. A workflow becomes a coordinator agent whose
27
+ workers are exposed as tools, so workflow edges, edge conditions and cycles
28
+ are lossy: they are reported and the steps run in declared order.
29
+ A2A is native in both directions and certified against ag2==1.3.1: a step
30
+ that declares an a2a_agent becomes an Agent configured with
31
+ A2AConfig(card_url=...), and an a2a_server block generates an
32
+ A2AServer-backed JSON-RPC service. AG2 resolves the card from
33
+ {card_url}/.well-known/agent-card.json, so the declared agent_card_url is
34
+ normalised to the remote agent's base URL. Structured output is native via
35
+ Agent(response_schema=...) with generated Pydantic models.
36
+ Human approval is not generated by the team model and needs an AG2 hitl_hook
37
+ or an external gate.
File without changes