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,563 @@
1
+ """Microsoft Agent Framework (Semantic Kernel) target adapter — Level 1 code generation.
2
+
3
+ Fixes (2026-06-09):
4
+ - Replace ad-hoc Python class wrappers with proper SK ChatCompletionAgent API.
5
+ - Multi-agent: generate AgentGroupChat with selection/termination strategies.
6
+ - Add function-invocation filters for guardrail policies.
7
+ - Use OpenAIChatCompletion service on the kernel.
8
+
9
+ Fixes (2026-11-16, verified against semantic-kernel 1.47.0):
10
+ - ChatCompletionAgent has no ``service_id``; the service is resolved from the kernel.
11
+ ``agent.invoke(messages=...)`` is an async generator of AgentResponseItem.
12
+ - Tools are ``@kernel_function(name=..., description=...)`` methods registered through
13
+ ``kernel.add_plugin(Plugin(), plugin_name=...)``.
14
+ - AgentGroupChat is deprecated; multi-agent uses GroupChatOrchestration with
15
+ RoundRobinGroupChatManager on an InProcessRuntime (needs ``protobuf``).
16
+ """
17
+
18
+ from __future__ import annotations
19
+ from pathlib import Path
20
+
21
+ from agentsml_impl.compiler.identifiers import python_identifier_ir
22
+ from agentsml_impl.compiler.naming import snake_identifier, unique_identifiers
23
+ from agentsml_impl.compiler.ir import AgentSystemIR, ModelIR
24
+ from agentsml_impl.compiler.diagnostics import DiagCode, DiagnosticSet
25
+ from agentsml_impl.compiler.planner import GenerationPlan
26
+ from agentsml_impl.compiler.render import toml_string, write_file
27
+ from agentsml_impl.runtime.tools import generate_tools_module
28
+ from agentsml_impl.targets.base import TargetAdapter, GenerationResult
29
+
30
+
31
+ class Adapter(TargetAdapter):
32
+ @property
33
+ def name(self) -> str:
34
+ return "microsoft-agent-framework"
35
+
36
+ def analyze(self, ir: AgentSystemIR, diagnostics: DiagnosticSet) -> None:
37
+ from agentsml_impl.compiler.capabilities import analyze_capabilities
38
+ analyze_capabilities(ir, "microsoft_agent_framework", diagnostics)
39
+
40
+ def generate(self, ir: AgentSystemIR, plan: GenerationPlan,
41
+ out_dir: Path, diagnostics: DiagnosticSet) -> GenerationResult:
42
+ ir = python_identifier_ir(ir)
43
+ out_dir.mkdir(parents=True, exist_ok=True)
44
+ pkg = plan.package_name
45
+ src = out_dir / "src" / pkg
46
+ src.mkdir(parents=True, exist_ok=True)
47
+
48
+ files: list[str] = []
49
+ files += _write_pyproject(ir, plan, out_dir)
50
+ files += _write_tools(ir, src, out_dir, diagnostics)
51
+ files += _write_filters(ir, src, out_dir, diagnostics)
52
+ files += _write_agent(ir, plan, src, out_dir, diagnostics)
53
+ files += _write_run(plan, src, out_dir, len(ir.agents) > 1)
54
+ files += _write_init(src, out_dir)
55
+ files += _write_readme(ir, plan, out_dir)
56
+
57
+ return GenerationResult(
58
+ target=self.name, out_dir=out_dir, files_written=files, success=True
59
+ )
60
+
61
+
62
+ # ---------------------------------------------------------------------------
63
+ # Model string helpers
64
+ # ---------------------------------------------------------------------------
65
+
66
+ def _sk_model_service(model: ModelIR) -> tuple[str, str, str]:
67
+ """Return (service_import, service_id, service_init) for a SK model.
68
+
69
+ Returns:
70
+ service_import: import line
71
+ service_id: string ID for the service
72
+ service_init: kernel.add_service(...) call
73
+ """
74
+ p = model.provider.lower()
75
+ n = model.name
76
+ sid = "openai"
77
+
78
+ if p in ("openai",):
79
+ imp = "from semantic_kernel.connectors.ai.open_ai import OpenAIChatCompletion"
80
+ init = f'kernel.add_service(OpenAIChatCompletion(service_id="{sid}", ai_model_id="{n}"))'
81
+ elif p in ("azure", "azure-openai"):
82
+ imp = "from semantic_kernel.connectors.ai.open_ai import AzureChatCompletion"
83
+ sid = "azure"
84
+ init = f'kernel.add_service(AzureChatCompletion(service_id="{sid}", deployment_name="{n}"))'
85
+ elif p in ("google", "gemini", "google-cloud", "google_cloud"):
86
+ imp = "from semantic_kernel.connectors.ai.google.google_ai import GoogleAIChatCompletion"
87
+ sid = "google"
88
+ init = f'kernel.add_service(GoogleAIChatCompletion(gemini_model_id="{n}", service_id="{sid}"))'
89
+ elif p == "anthropic":
90
+ imp = "from semantic_kernel.connectors.ai.anthropic import AnthropicChatCompletion"
91
+ sid = "anthropic"
92
+ init = f'kernel.add_service(AnthropicChatCompletion(ai_model_id="{n}", service_id="{sid}"))'
93
+ else:
94
+ imp = "from semantic_kernel.connectors.ai.open_ai import OpenAIChatCompletion"
95
+ init = f'kernel.add_service(OpenAIChatCompletion(service_id="{sid}", ai_model_id="{n}")) # TODO: check provider'
96
+ return imp, sid, init
97
+
98
+
99
+ def _write_pyproject(ir: AgentSystemIR, plan: GenerationPlan, out_dir: Path) -> list[str]:
100
+ c = f'''\
101
+ [build-system]
102
+ requires = ["setuptools>=68"]
103
+ build-backend = "setuptools.build_meta"
104
+
105
+ [project]
106
+ name = "{plan.package_name}"
107
+ version = "{ir.metadata.version or '0.1.0'}"
108
+ description = {toml_string(ir.metadata.description or plan.project_name)}
109
+ requires-python = ">=3.11"
110
+ dependencies = [
111
+ "semantic-kernel>=1.30.0",
112
+ "protobuf",
113
+ "pydantic>=2.7",
114
+ "python-dotenv"
115
+ ]
116
+
117
+ [tool.setuptools.packages.find]
118
+ where = ["src"]
119
+ '''
120
+ write_file(out_dir, "pyproject.toml", c)
121
+ return ["pyproject.toml"]
122
+
123
+
124
+ def _write_tools(ir: AgentSystemIR, src: Path, out_dir: Path, ds: DiagnosticSet) -> list[str]:
125
+ if not ir.tools:
126
+ return []
127
+ c = generate_tools_module(ir.tools, ds, framework="microsoft", decorator="kernel_function")
128
+ c = c.replace("from typing import Any", "from typing import Any\nfrom semantic_kernel.functions import kernel_function")
129
+ # SK exposes ``**kwargs`` as a *required* parameter named "kwargs"; make it optional.
130
+ c = c.replace("(**kwargs: Any)", '(arguments: str = "")')
131
+ names = unique_identifiers(ir.tools, lambda v: snake_identifier(v, prefix="tool"))
132
+ for tool in ir.tools.values():
133
+ fn = names[tool.key]
134
+ deco = f"@kernel_function(name={fn!r}, description={(tool.description or fn)!r})"
135
+ c = c.replace(f"@kernel_function\ndef {fn}(", f"{deco}\ndef {fn}(", 1)
136
+ rel = f"src/{src.name}/tools.py"
137
+ write_file(out_dir, rel, c)
138
+ return [rel]
139
+
140
+
141
+ def _write_filters(ir: AgentSystemIR, src: Path, out_dir: Path, ds: DiagnosticSet) -> list[str]:
142
+ """Generate semantic-kernel 1.x function-invocation filters for guardrail policies.
143
+
144
+ In semantic-kernel 1.x there is no ``IFunctionInvocationFilter`` interface: a filter is an
145
+ ``async def fn(context: FunctionInvocationContext, next)`` registered with
146
+ ``kernel.add_filter(FilterTypes.FUNCTION_INVOCATION, fn)``. A denied call sets
147
+ ``context.result`` to an error ``FunctionResult`` and does not call ``next``, so the tool
148
+ body never runs and the model receives the denial text as the tool result.
149
+ """
150
+ guardrail_policies = [p for p in ir.policies.values() if p.guardrails]
151
+ if not guardrail_policies:
152
+ return []
153
+
154
+ filter_fns: list[str] = []
155
+ global_fns: list[str] = []
156
+ agent_fns: dict[str, list[str]] = {}
157
+ for pol in guardrail_policies:
158
+ g = pol.guardrails or {}
159
+ allowlist = g.get("tools", {}).get("allowed", [])
160
+ denylist = g.get("tools", {}).get("denied", [])
161
+ fn_name = _filter_fn_name(pol.key)
162
+ scope_agents = sorted({n for n in pol.applies_to if n in ir.agents})
163
+ scope_tools = sorted({n for n in pol.applies_to if n in ir.tools})
164
+ if scope_agents:
165
+ for an in scope_agents:
166
+ agent_fns.setdefault(an, []).append(fn_name)
167
+ else:
168
+ global_fns.append(fn_name)
169
+ scope = ""
170
+ if scope_tools:
171
+ scope = f"""
172
+ if name not in {scope_tools!r}:
173
+ await next(context) # policy is scoped to other tools
174
+ return"""
175
+ checks = ""
176
+ if denylist:
177
+ checks += f"""
178
+ if name in {sorted(denylist)!r}:
179
+ return _deny(context, f"Tool '{{name}}' is denied by policy {pol.key!r}.")"""
180
+ if allowlist:
181
+ checks += f"""
182
+ if name not in {sorted(allowlist)!r}:
183
+ return _deny(context, f"Tool '{{name}}' is not in the allowlist of policy {pol.key!r}.")"""
184
+ filter_fns.append(f'''\
185
+ async def {fn_name}(context: FunctionInvocationContext, next: _Next) -> None:
186
+ """Guardrail filter generated from policy {pol.key!r}."""
187
+ name = context.function.name{scope}{checks}
188
+ logger.info("guardrail %s allowed tool %s", {pol.key!r}, name)
189
+ await next(context)
190
+ ''')
191
+
192
+ agent_map = "".join(f" {k!r}: [{', '.join(v)}],\n" for k, v in sorted(agent_fns.items()))
193
+ c = f'''\
194
+ """Semantic Kernel guardrail filters - auto-generated from AgentsML policies."""
195
+ from __future__ import annotations
196
+ import logging
197
+ from typing import Awaitable, Callable
198
+
199
+ from semantic_kernel.filters import FilterTypes, FunctionInvocationContext
200
+ from semantic_kernel.functions import FunctionResult
201
+
202
+ logger = logging.getLogger(__name__)
203
+ _Next = Callable[[FunctionInvocationContext], Awaitable[None]]
204
+
205
+
206
+ def _deny(context: FunctionInvocationContext, message: str) -> None:
207
+ """Short-circuit the call: the tool body is skipped and the model sees the denial text."""
208
+ logger.warning(message)
209
+ context.result = FunctionResult(function=context.function.metadata, value=message)
210
+
211
+
212
+ {chr(10).join(filter_fns)}
213
+ # Policies without agent scoping guard every kernel; tool-scoped ones still only act on their tools.
214
+ GLOBAL_GUARDRAIL_FILTERS = [{", ".join(global_fns)}]
215
+ # Policies whose applies_to names agents are registered only on those agents' kernels.
216
+ AGENT_GUARDRAIL_FILTERS = {{
217
+ {agent_map}}}
218
+
219
+
220
+ def register_guardrails(kernel) -> None:
221
+ """Register the global (not agent-scoped) guardrail filters via ``kernel.add_filter``."""
222
+ for fn in GLOBAL_GUARDRAIL_FILTERS:
223
+ kernel.add_filter(FilterTypes.FUNCTION_INVOCATION, fn)
224
+
225
+
226
+ def register_agent_guardrails(kernel, agent_key: str) -> None:
227
+ """Additionally register the filters of policies that name ``agent_key`` in applies_to."""
228
+ for fn in AGENT_GUARDRAIL_FILTERS.get(agent_key, []):
229
+ kernel.add_filter(FilterTypes.FUNCTION_INVOCATION, fn)
230
+ '''
231
+ rel = f"src/{src.name}/filters.py"
232
+ write_file(out_dir, rel, c)
233
+ ds.add_info(DiagCode.REQUIRES_ADAPTER,
234
+ f"Generated function-invocation filters for {len(guardrail_policies)} policy(s); "
235
+ "build_kernel() registers them with kernel.add_filter(FilterTypes.FUNCTION_INVOCATION, fn).",
236
+ path="policies")
237
+ return [rel]
238
+
239
+
240
+ def _filter_fn_name(key: str) -> str:
241
+ return f"{snake_identifier(key)}_guardrail_filter"
242
+
243
+
244
+ def _write_agent(ir: AgentSystemIR, plan: GenerationPlan, src: Path, out_dir: Path, ds: DiagnosticSet) -> list[str]:
245
+ is_multi = len(ir.agents) > 1
246
+ tools_import = f"from .tools import {', '.join(ir.tools.keys())}" if ir.tools else ""
247
+
248
+ # Collect service info for all models referenced
249
+ service_imports: set[str] = set()
250
+ service_inits: list[str] = []
251
+ primary_service_id = "openai"
252
+ for agent in ir.agents.values():
253
+ model = ir.models.get(agent.model)
254
+ if model:
255
+ imp, sid, init = _sk_model_service(model)
256
+ service_imports.add(imp)
257
+ if init not in service_inits:
258
+ service_inits.append(init)
259
+ primary_service_id = sid
260
+ break # One kernel service for all agents (SK pattern)
261
+
262
+ service_import_str = "\n".join(service_imports) if service_imports else \
263
+ "from semantic_kernel.connectors.ai.open_ai import OpenAIChatCompletion"
264
+ service_init_str = "\n ".join(service_inits) if service_inits else \
265
+ f'kernel.add_service(OpenAIChatCompletion(service_id="openai", ai_model_id="gpt-4o"))'
266
+
267
+ if is_multi:
268
+ return _write_agent_group_chat(
269
+ ir, plan, src, out_dir, ds,
270
+ tools_import, service_import_str, service_init_str, primary_service_id
271
+ )
272
+ else:
273
+ return _write_agent_single(
274
+ ir, plan, src, out_dir, ds,
275
+ tools_import, service_import_str, service_init_str, primary_service_id
276
+ )
277
+
278
+
279
+ def _write_agent_single(
280
+ ir: AgentSystemIR, plan: GenerationPlan, src: Path, out_dir: Path, ds: DiagnosticSet,
281
+ tools_import: str, service_import_str: str, service_init_str: str, service_id: str,
282
+ ) -> list[str]:
283
+ has_guardrails = bool([p for p in ir.policies.values() if p.guardrails])
284
+ _guardrail_policies = [p for p in ir.policies.values() if p.guardrails]
285
+ filters_import = ("from .filters import register_agent_guardrails, register_guardrails"
286
+ if has_guardrails else "")
287
+ filter_regs = (" register_guardrails(kernel)\n"
288
+ f" register_agent_guardrails(kernel, {list(ir.agents)[0]!r})\n"
289
+ if has_guardrails else "")
290
+ fcb_import = ("from semantic_kernel.connectors.ai import FunctionChoiceBehavior\n"
291
+ if (ir.tools and list(ir.agents.values())[0].tools) else "")
292
+
293
+ agents_list = list(ir.agents.items())
294
+ ak, agent = agents_list[0]
295
+ inst = agent.instructions.replace('"""', "'''")
296
+
297
+ # Plugin registration for tools
298
+ plugin_init = ""
299
+ plugin_cls = ""
300
+ if ir.tools and agent.tools:
301
+ plugin_cls_name, plugin_cls = _plugin_class_source(ak, list(agent.tools))
302
+ plugin_init = f'\n kernel.add_plugin({plugin_cls_name}(), plugin_name="{ak}_tools")'
303
+
304
+ c = f'''\
305
+ """Semantic Kernel agent for {plan.project_name}.
306
+
307
+ Auto-generated by agentsml-impl. Re-run to regenerate.
308
+ """
309
+ from __future__ import annotations
310
+ import asyncio
311
+ import semantic_kernel as sk
312
+ {service_import_str}
313
+ from semantic_kernel.agents import ChatCompletionAgent
314
+ {fcb_import}{tools_import}
315
+ {filters_import}
316
+ {plugin_cls}
317
+
318
+ def build_kernel() -> sk.Kernel:
319
+ kernel = sk.Kernel()
320
+ {service_init_str}{plugin_init}
321
+ {filter_regs} return kernel
322
+
323
+
324
+ def build_agent(kernel: sk.Kernel | None = None) -> ChatCompletionAgent:
325
+ kernel = kernel or build_kernel()
326
+ agent = ChatCompletionAgent(
327
+ kernel=kernel,
328
+ name="{ak}",
329
+ instructions="""{inst}""",{_fcb_kwarg(bool(plugin_init))}
330
+ )
331
+ return agent
332
+
333
+
334
+ async def invoke_agent(question: str) -> str:
335
+ agent = build_agent()
336
+ parts: list[str] = []
337
+ async for response in agent.invoke(messages=question):
338
+ parts.append(str(response.content))
339
+ return "\\n".join(parts)
340
+ '''
341
+ rel = f"src/{src.name}/agent.py"
342
+ write_file(out_dir, rel, c)
343
+ return [rel]
344
+
345
+
346
+ def _plugin_class_source(ak: str, tools: list[str]) -> tuple[str, str]:
347
+ """Return (class name, source) for a plugin exposing ``tools`` of agent ``ak``."""
348
+ name = "".join(part.capitalize() for part in ak.split("_")) + "Plugin"
349
+ members = "\n".join(f" {t} = staticmethod({t})" for t in tools)
350
+ src = (f"\n\nclass {name}:\n \"\"\"Semantic Kernel plugin exposing the tools declared "
351
+ f"for '{ak}'.\"\"\"\n{members}\n")
352
+ return name, src
353
+
354
+
355
+ def _write_agent_group_chat(
356
+ ir: AgentSystemIR, plan: GenerationPlan, src: Path, out_dir: Path, ds: DiagnosticSet,
357
+ tools_import: str, service_import_str: str, service_init_str: str, service_id: str,
358
+ ) -> list[str]:
359
+ """Generate AgentGroupChat for multi-agent scenarios."""
360
+ ds.add_info(DiagCode.REQUIRES_ADAPTER,
361
+ "Multi-agent workflow detected. Generating GroupChatOrchestration with "
362
+ "RoundRobinGroupChatManager on an InProcessRuntime (AgentGroupChat is deprecated).",
363
+ path="agents")
364
+
365
+ agent_defs: list[str] = []
366
+ plugin_classes = ""
367
+ plugin_map: list[str] = []
368
+ any_tools = False
369
+ for ak, agent in ir.agents.items():
370
+ inst = agent.instructions.replace('"""', "'''")
371
+ has_tools = bool(ir.tools and agent.tools)
372
+ fcb = ""
373
+ if has_tools:
374
+ any_tools = True
375
+ cls_name, cls_src = _plugin_class_source(ak, list(agent.tools))
376
+ plugin_classes += cls_src
377
+ plugin_map.append(f' "{ak}": ({cls_name}, "{ak}_tools"),')
378
+ fcb = "\n function_choice_behavior=FunctionChoiceBehavior.Auto(),"
379
+ agent_defs.append(f'''\
380
+ {ak}_agent = ChatCompletionAgent(
381
+ kernel=build_agent_kernel("{ak}"),
382
+ name="{ak}",
383
+ description={(agent.description or ak)!r},
384
+ instructions="""{inst}""",{fcb}
385
+ )''')
386
+ fcb_import = ("from semantic_kernel.connectors.ai import FunctionChoiceBehavior\n"
387
+ if any_tools else "")
388
+ plugin_map_str = "{\n" + "\n".join(plugin_map) + "\n}" if plugin_map else "{}"
389
+ if any_tools:
390
+ ds.add_info(DiagCode.REQUIRES_ADAPTER,
391
+ "Each tool-bearing group-chat member gets its own Kernel with only its "
392
+ "declared tools registered as a plugin, so tools are not shared across members.",
393
+ path="agents")
394
+
395
+ has_guardrails = bool([p for p in ir.policies.values() if p.guardrails])
396
+ filters_import = ("from .filters import register_agent_guardrails, register_guardrails"
397
+ if has_guardrails else "")
398
+ filter_regs = " register_guardrails(kernel)\n" if has_guardrails else ""
399
+ agent_guard = " register_agent_guardrails(kernel, agent_key)\n" if has_guardrails else ""
400
+ agent_names = list(ir.agents.keys())
401
+ agents_list_str = ", ".join(f"{ak}_agent" for ak in agent_names)
402
+
403
+ wf = ir.workflows.get(plan.main_workflow_key)
404
+ max_iters = 10
405
+ if wf and wf.error_policy:
406
+ max_iters = wf.error_policy.get("max_iterations", 10)
407
+
408
+ c = f'''\
409
+ """Semantic Kernel GroupChatOrchestration for {plan.project_name}.
410
+
411
+ Auto-generated by agentsml-impl. Re-run to regenerate.
412
+ """
413
+ from __future__ import annotations
414
+ import asyncio
415
+ import semantic_kernel as sk
416
+ {service_import_str}
417
+ from semantic_kernel.agents import (
418
+ ChatCompletionAgent,
419
+ GroupChatOrchestration,
420
+ RoundRobinGroupChatManager,
421
+ )
422
+ from semantic_kernel.agents.runtime import InProcessRuntime
423
+ {fcb_import}{tools_import}
424
+ {filters_import}
425
+ {plugin_classes}
426
+ # agent key -> (plugin class, plugin name); each member only sees its own tools
427
+ AGENT_PLUGINS = {plugin_map_str}
428
+
429
+
430
+ def build_kernel() -> sk.Kernel:
431
+ kernel = sk.Kernel()
432
+ {service_init_str}
433
+ {filter_regs} return kernel
434
+
435
+
436
+ def build_agent_kernel(agent_key: str) -> sk.Kernel:
437
+ """Build a dedicated kernel for one member, registering only its declared tools."""
438
+ kernel = build_kernel()
439
+ if agent_key in AGENT_PLUGINS:
440
+ plugin_cls, plugin_name = AGENT_PLUGINS[agent_key]
441
+ kernel.add_plugin(plugin_cls(), plugin_name=plugin_name)
442
+ {agent_guard} return kernel
443
+
444
+
445
+ def build_group_chat(response_callback=None) -> GroupChatOrchestration:
446
+ {chr(10).join(agent_defs)}
447
+
448
+ return GroupChatOrchestration(
449
+ members=[{agents_list_str}],
450
+ manager=RoundRobinGroupChatManager(max_rounds={max_iters}),
451
+ agent_response_callback=response_callback,
452
+ )
453
+
454
+
455
+ async def invoke_group_chat(question: str) -> str:
456
+ transcript: list[str] = []
457
+
458
+ def record(message) -> None:
459
+ transcript.append(f"[{{message.name}}]: {{message.content}}")
460
+
461
+ orchestration = build_group_chat(response_callback=record)
462
+ runtime = InProcessRuntime()
463
+ runtime.start()
464
+ result = await orchestration.invoke(task=question, runtime=runtime)
465
+ await result.get()
466
+ await runtime.stop_when_idle()
467
+ return "\\n".join(transcript)
468
+ '''
469
+ rel = f"src/{src.name}/agent.py"
470
+ write_file(out_dir, rel, c)
471
+ return [rel]
472
+
473
+
474
+ def _fcb_kwarg(has_tools: bool) -> str:
475
+ if not has_tools:
476
+ return ""
477
+ return "\n function_choice_behavior=FunctionChoiceBehavior.Auto(),"
478
+
479
+
480
+ def _write_run(plan: GenerationPlan, src: Path, out_dir: Path, is_multi: bool = False) -> list[str]:
481
+ if is_multi:
482
+ run_import = "from .agent import invoke_group_chat"
483
+ run_body = " res = await invoke_group_chat(q)"
484
+ else:
485
+ run_import = "from .agent import invoke_agent"
486
+ run_body = " res = await invoke_agent(q)"
487
+ c = f'''\
488
+ """Runner for {plan.project_name} (Microsoft Agent Framework / Semantic Kernel)."""
489
+ from __future__ import annotations
490
+ import sys
491
+ import asyncio
492
+ {run_import}
493
+
494
+
495
+ async def main():
496
+ q = " ".join(sys.argv[1:]) or "Hello"
497
+ {run_body}
498
+ print("Result:", res)
499
+
500
+
501
+ if __name__ == "__main__":
502
+ asyncio.run(main())
503
+ '''
504
+ rel = f"src/{src.name}/run.py"
505
+ write_file(out_dir, rel, c)
506
+ return [rel]
507
+
508
+
509
+ def _write_init(src: Path, out_dir: Path) -> list[str]:
510
+ c = f'"""Package: {src.name}."""\n'
511
+ rel = f"src/{src.name}/__init__.py"
512
+ write_file(out_dir, rel, c)
513
+ return [rel]
514
+
515
+
516
+ def _write_readme(ir: AgentSystemIR, plan: GenerationPlan, out_dir: Path) -> list[str]:
517
+ is_multi = len(ir.agents) > 1
518
+ multi_note = ""
519
+ if is_multi:
520
+ multi_note = f"""
521
+ ## Multi-agent (GroupChatOrchestration)
522
+
523
+ This project uses `GroupChatOrchestration` with `RoundRobinGroupChatManager`
524
+ on an `InProcessRuntime`. Agents take turns until `max_rounds` is reached.
525
+
526
+ Each member that declares tools gets its own `Kernel` (via `build_agent_kernel`) with only
527
+ those tools registered as a plugin and `FunctionChoiceBehavior.Auto()`, so tools are not
528
+ shared across members.
529
+
530
+ To customize selection, subclass `GroupChatManager` (for example an LLM-driven manager).
531
+ """
532
+
533
+ agents_md = "\n".join(f"- `{k}`: {v.description or ''}" for k, v in ir.agents.items())
534
+ c = f"""\
535
+ # {plan.project_name} — Microsoft Agent Framework (Semantic Kernel)
536
+
537
+ > Auto-generated by `agentsml-impl`.
538
+
539
+ ## Agents
540
+ {agents_md or "None"}
541
+ {multi_note}
542
+ ## Quickstart
543
+ ```bash
544
+ pip install -e .
545
+ export OPENAI_API_KEY="your-key"
546
+ python -m {plan.package_name}.run
547
+ ```
548
+
549
+ ## SK Filters (Guardrails)
550
+
551
+ If guardrail policies are defined, `filters.py` contains async function-invocation filters
552
+ (`async def fn(context, next)`), registered through
553
+ `kernel.add_filter(FilterTypes.FUNCTION_INVOCATION, fn)`. Scoping follows the policy's `applies_to`:
554
+ a policy naming no agents is registered by `build_kernel()` on every kernel; a policy naming agents is
555
+ registered only on those agents' kernels (`build_agent_kernel(agent_key)` / the single-agent kernel);
556
+ a policy naming tools only acts on calls to those tools and passes other tools through untouched
557
+ (mixed lists apply both rules). A denied tool call is short-circuited
558
+ (the tool body never runs) and the model receives the denial text as the tool result.
559
+
560
+ > See `diagnostics.yaml` for portability warnings.
561
+ """
562
+ write_file(out_dir, "README.md", c)
563
+ return ["README.md"]
@@ -0,0 +1,26 @@
1
+ target: microsoft_agent_framework
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: adapter
20
+ observability: native
21
+ artifacts:
22
+ - python_project
23
+ - diagnostics
24
+ - readme
25
+ notes: >
26
+ Maps to Microsoft Agent Framework (Semantic Kernel / Magentic-One).
File without changes