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,178 @@
1
+ """Claude Agent SDK target adapter — Level 1 code generation."""
2
+
3
+ from __future__ import annotations
4
+ from pathlib import Path
5
+
6
+ from agentsml_impl.compiler.identifiers import python_identifier_ir
7
+ from agentsml_impl.compiler.ir import AgentSystemIR, ModelIR
8
+ from agentsml_impl.compiler.diagnostics import DiagCode, DiagnosticSet
9
+ from agentsml_impl.compiler.planner import GenerationPlan
10
+ from agentsml_impl.compiler.render import toml_string, write_file
11
+ from agentsml_impl.runtime.tools import generate_tools_module
12
+ from agentsml_impl.targets.base import TargetAdapter, GenerationResult
13
+
14
+
15
+ class Adapter(TargetAdapter):
16
+ @property
17
+ def name(self) -> str:
18
+ return "claude-agent-sdk"
19
+
20
+ def analyze(self, ir: AgentSystemIR, diagnostics: DiagnosticSet) -> None:
21
+ from agentsml_impl.compiler.capabilities import analyze_capabilities
22
+ analyze_capabilities(ir, "claude_agent_sdk", diagnostics)
23
+
24
+ def generate(self, ir: AgentSystemIR, plan: GenerationPlan,
25
+ out_dir: Path, diagnostics: DiagnosticSet) -> GenerationResult:
26
+ ir = python_identifier_ir(ir)
27
+ out_dir.mkdir(parents=True, exist_ok=True)
28
+ pkg = plan.package_name
29
+ src = out_dir / "src" / pkg
30
+ src.mkdir(parents=True, exist_ok=True)
31
+
32
+ files: list[str] = []
33
+ files += _write_pyproject(ir, plan, out_dir)
34
+ files += _write_tools(ir, src, out_dir, diagnostics)
35
+ files += _write_agent(ir, plan, src, out_dir, diagnostics)
36
+ files += _write_run(plan, src, out_dir)
37
+ files += _write_init(src, out_dir)
38
+ files += _write_readme(ir, plan, out_dir)
39
+
40
+ return GenerationResult(
41
+ target=self.name, out_dir=out_dir, files_written=files, success=True
42
+ )
43
+
44
+
45
+ def _write_pyproject(ir: AgentSystemIR, plan: GenerationPlan, out_dir: Path) -> list[str]:
46
+ c = f'''\
47
+ [build-system]
48
+ requires = ["setuptools>=68"]
49
+ build-backend = "setuptools.build_meta"
50
+
51
+ [project]
52
+ name = "{plan.package_name}"
53
+ version = "{ir.metadata.version or '0.1.0'}"
54
+ description = {toml_string(ir.metadata.description or plan.project_name)}
55
+ requires-python = ">=3.11"
56
+ dependencies = [
57
+ "anthropic",
58
+ "python-dotenv"
59
+ ]
60
+
61
+ [tool.setuptools.packages.find]
62
+ where = ["src"]
63
+ '''
64
+ write_file(out_dir, "pyproject.toml", c)
65
+ return ["pyproject.toml"]
66
+
67
+
68
+ def _write_tools(ir: AgentSystemIR, src: Path, out_dir: Path, ds: DiagnosticSet) -> list[str]:
69
+ if not ir.tools:
70
+ return []
71
+ c = generate_tools_module(ir.tools, ds, framework="claude-agent-sdk")
72
+ rel = f"src/{src.name}/tools.py"
73
+ write_file(out_dir, rel, c)
74
+ return [rel]
75
+
76
+
77
+ def _write_agent(ir: AgentSystemIR, plan: GenerationPlan, src: Path, out_dir: Path, ds: DiagnosticSet) -> list[str]:
78
+ agent_blocks: list[str] = []
79
+
80
+ tools_import = f"from .tools import {', '.join(ir.tools.keys())}" if ir.tools else ""
81
+
82
+ for ak, agent in ir.agents.items():
83
+ m = ir.models.get(agent.model)
84
+ mstr = m.name if m else 'claude-3-5-sonnet-latest'
85
+ inst = agent.instructions.replace('"""', "'''")
86
+ tools_list = ", ".join(agent.tools) if agent.tools else ""
87
+
88
+ agent_blocks.append(f'''\
89
+ class {ak.capitalize()}Agent:
90
+ def __init__(self, client):
91
+ self.client = client
92
+ self.model = "{mstr}"
93
+ self.system = """{inst}"""
94
+ self.tools = [{tools_list}]
95
+
96
+ def run(self, prompt: str):
97
+ response = self.client.messages.create(
98
+ model=self.model,
99
+ system=self.system,
100
+ messages=[{{"role": "user", "content": prompt}}],
101
+ max_tokens=1024
102
+ )
103
+ return response
104
+ ''')
105
+
106
+ wf = ir.workflows.get(plan.main_workflow_key)
107
+ if wf and wf.edges:
108
+ ds.add_warning(
109
+ DiagCode.LOSSY_MAPPING,
110
+ "Workflow edges are mapped as manual logic.",
111
+ path=f"workflows.{plan.main_workflow_key}.edges"
112
+ )
113
+
114
+ c = f'''\
115
+ """Claude Agent definitions for {plan.project_name}."""
116
+ from __future__ import annotations
117
+ import anthropic
118
+ {tools_import}
119
+
120
+ {chr(10).join(agent_blocks)}
121
+ '''
122
+ rel = f"src/{src.name}/agent.py"
123
+ write_file(out_dir, rel, c)
124
+ return [rel]
125
+
126
+
127
+ def _write_run(plan: GenerationPlan, src: Path, out_dir: Path) -> list[str]:
128
+ c = f'''\
129
+ """Runner for {plan.project_name} (Claude)."""
130
+ from __future__ import annotations
131
+ import sys
132
+ import anthropic
133
+ from .agent import *
134
+
135
+ def main():
136
+ q = " ".join(sys.argv[1:]) or "Hello"
137
+ client = anthropic.Anthropic()
138
+
139
+ # Pick the first agent class
140
+ agent_classes = [v for k, v in globals().items() if k.endswith("Agent") and isinstance(v, type)]
141
+ start_agent_cls = agent_classes[0] if agent_classes else None
142
+
143
+ if not start_agent_cls:
144
+ print("No agents found.")
145
+ return
146
+
147
+ agent = start_agent_cls(client)
148
+ response = agent.run(q)
149
+ print("Result:", response.content[0].text)
150
+
151
+ if __name__ == "__main__":
152
+ main()
153
+ '''
154
+ rel = f"src/{src.name}/run.py"
155
+ write_file(out_dir, rel, c)
156
+ return [rel]
157
+
158
+ def _write_init(src: Path, out_dir: Path) -> list[str]:
159
+ c = f'"""Package: {src.name}."""\n'
160
+ rel = f"src/{src.name}/__init__.py"
161
+ write_file(out_dir, rel, c)
162
+ return [rel]
163
+
164
+ def _write_readme(ir: AgentSystemIR, plan: GenerationPlan, out_dir: Path) -> list[str]:
165
+ c = f"""\
166
+ # {plan.project_name} — Claude Agent SDK
167
+
168
+ Generated by `agentsml-impl`.
169
+
170
+ ## Quickstart
171
+ ```bash
172
+ pip install -e .
173
+ export ANTHROPIC_API_KEY="your-key"
174
+ python -m {plan.package_name}.run
175
+ ```
176
+ """
177
+ write_file(out_dir, "README.md", c)
178
+ return ["README.md"]
@@ -0,0 +1,26 @@
1
+ target: claude_agent_sdk
2
+ kind: code
3
+ language: python
4
+ status: implemented
5
+ level: 1
6
+ version_tested: "0.1.0"
7
+ supports:
8
+ agents: native
9
+ tools: native
10
+ workflows: lossy
11
+ graph_edges: lossy
12
+ graph_conditions: manual
13
+ cycles: lossy
14
+ parallel: unsupported
15
+ human_approval: manual
16
+ mcp: native
17
+ a2a: manual
18
+ ag_ui: unsupported
19
+ structured_output: manual
20
+ observability: adapter
21
+ artifacts:
22
+ - python_project
23
+ - diagnostics
24
+ - readme
25
+ notes: >
26
+ Maps to Anthropic's typical agent scaffolding.
File without changes
@@ -0,0 +1,441 @@
1
+ """CrewAI target adapter — Level 1 code generation.
2
+
3
+ Fixes (2026-06-09):
4
+ - Conditional edges → Flow + @router decorated method.
5
+ - Inter-task context passing via context=[prev_task].
6
+ - output_pydantic on tasks with output schemas.
7
+ - Process.hierarchical when a supervisor role is detected.
8
+ - kickoff_async variant for parallel execution.
9
+ - LiteLLM provider string table expanded.
10
+ """
11
+
12
+ from __future__ import annotations
13
+ from pathlib import Path
14
+
15
+ from agentsml_impl.compiler.identifiers import python_identifier_ir
16
+ from agentsml_impl.compiler.naming import snake_identifier, unique_identifiers
17
+ from agentsml_impl.compiler.ir import AgentSystemIR, ModelIR
18
+ from agentsml_impl.compiler.diagnostics import DiagCode, DiagnosticSet
19
+ from agentsml_impl.compiler.planner import GenerationPlan
20
+ from agentsml_impl.compiler.render import toml_string, write_file
21
+ from agentsml_impl.runtime.tools import generate_tools_module
22
+ from agentsml_impl.runtime.json_schema import generate_models_source
23
+ from agentsml_impl.targets.base import TargetAdapter, GenerationResult
24
+
25
+
26
+ class Adapter(TargetAdapter):
27
+ @property
28
+ def name(self) -> str:
29
+ return "crewai"
30
+
31
+ def analyze(self, ir: AgentSystemIR, diagnostics: DiagnosticSet) -> None:
32
+ from agentsml_impl.compiler.capabilities import analyze_capabilities
33
+ analyze_capabilities(ir, self.name, diagnostics)
34
+
35
+ def generate(self, ir: AgentSystemIR, plan: GenerationPlan,
36
+ out_dir: Path, diagnostics: DiagnosticSet) -> GenerationResult:
37
+ ir = python_identifier_ir(ir)
38
+ out_dir.mkdir(parents=True, exist_ok=True)
39
+ pkg = plan.package_name
40
+ src = out_dir / "src" / pkg
41
+ src.mkdir(parents=True, exist_ok=True)
42
+
43
+ files: list[str] = []
44
+ files += _write_pyproject(ir, plan, out_dir)
45
+ files += _write_schemas(ir, plan, src, out_dir, diagnostics)
46
+ files += _write_tools(ir, plan, src, out_dir, diagnostics)
47
+ files += _write_crew(ir, plan, src, out_dir, diagnostics)
48
+ files += _write_run(plan, src, out_dir)
49
+ files += _write_init(src, out_dir)
50
+ files += _write_readme(ir, plan, out_dir)
51
+
52
+ return GenerationResult(
53
+ target=self.name, out_dir=out_dir, files_written=files, success=True
54
+ )
55
+
56
+
57
+ # ---------------------------------------------------------------------------
58
+ # LiteLLM model string table (expanded)
59
+ # ---------------------------------------------------------------------------
60
+
61
+ def _model_str(model: ModelIR) -> str:
62
+ """Return LiteLLM-format model string for CrewAI."""
63
+ p = model.provider.lower()
64
+ n = model.name
65
+ litellm_prefix = {
66
+ "openai": "openai",
67
+ "anthropic": "anthropic",
68
+ "google": "gemini",
69
+ "gemini": "gemini",
70
+ "google-cloud": "vertex_ai",
71
+ "google_cloud": "vertex_ai",
72
+ "azure": "azure",
73
+ "azure-openai": "azure",
74
+ "cohere": "cohere",
75
+ "huggingface": "huggingface",
76
+ "mistral": "mistral",
77
+ "ollama": "ollama",
78
+ "groq": "groq",
79
+ "bedrock": "bedrock",
80
+ "vertex": "vertex_ai",
81
+ "together": "together_ai",
82
+ "fireworks": "fireworks_ai",
83
+ }.get(p)
84
+ if litellm_prefix:
85
+ return f'"{litellm_prefix}/{n}"'
86
+ # Unknown provider — pass model name through; LiteLLM may still handle it
87
+ return f'"{n}" # TODO: verify LiteLLM prefix for provider {p!r}'
88
+
89
+
90
+ # ---------------------------------------------------------------------------
91
+ # Topology detection
92
+ # ---------------------------------------------------------------------------
93
+
94
+ def _has_conditional_edges(ir: AgentSystemIR, plan: GenerationPlan) -> bool:
95
+ wf = ir.workflows.get(plan.main_workflow_key)
96
+ return bool(wf and any(e.condition for e in wf.edges))
97
+
98
+
99
+ def _detect_supervisor(ir: AgentSystemIR) -> str | None:
100
+ """Return key of agent with role=supervisor, if any."""
101
+ for ak, agent in ir.agents.items():
102
+ if agent.role and "supervisor" in agent.role.lower():
103
+ return ak
104
+ return None
105
+
106
+
107
+ # ---------------------------------------------------------------------------
108
+ # File generators
109
+ # ---------------------------------------------------------------------------
110
+
111
+ def _write_pyproject(ir: AgentSystemIR, plan: GenerationPlan, out_dir: Path) -> list[str]:
112
+ has_flow = _has_conditional_edges(ir, plan)
113
+ flow_dep = '\n "crewai-flows>=0.1.0",' if has_flow else ""
114
+ c = f'''\
115
+ [build-system]
116
+ requires = ["setuptools>=68"]
117
+ build-backend = "setuptools.build_meta"
118
+
119
+ [project]
120
+ name = "{plan.package_name}"
121
+ version = "{ir.metadata.version or '0.1.0'}"
122
+ description = {toml_string(ir.metadata.description or plan.project_name)}
123
+ requires-python = ">=3.11"
124
+ dependencies = [
125
+ "crewai>=0.83.0",
126
+ "python-dotenv",
127
+ "pydantic>=2.0",{flow_dep}
128
+ ]
129
+
130
+ [tool.setuptools.packages.find]
131
+ where = ["src"]
132
+ '''
133
+ write_file(out_dir, "pyproject.toml", c)
134
+ return ["pyproject.toml"]
135
+
136
+
137
+ def _write_schemas(ir: AgentSystemIR, plan: GenerationPlan, src: Path, out_dir: Path, ds: DiagnosticSet) -> list[str]:
138
+ schemas = {f"{k}_output": v.output_schema for k, v in ir.agents.items() if v.output_schema}
139
+ if not schemas:
140
+ return []
141
+ c = generate_models_source(schemas, ds)
142
+ rel = f"src/{src.name}/schemas.py"
143
+ write_file(out_dir, rel, c)
144
+ return [rel]
145
+
146
+
147
+ def _write_tools(ir: AgentSystemIR, plan: GenerationPlan, src: Path, out_dir: Path, ds: DiagnosticSet) -> list[str]:
148
+ if not ir.tools:
149
+ return []
150
+ c = generate_tools_module(ir.tools, ds, framework="crewai", decorator="tool")
151
+ c = c.replace("from typing import Any", "from typing import Any\nfrom crewai.tools import tool")
152
+ rel = f"src/{src.name}/tools.py"
153
+ write_file(out_dir, rel, c)
154
+ return [rel]
155
+
156
+
157
+ def _write_crew(ir: AgentSystemIR, plan: GenerationPlan, src: Path, out_dir: Path, ds: DiagnosticSet) -> list[str]:
158
+ wf = ir.workflows.get(plan.main_workflow_key)
159
+ steps = wf.steps if wf else []
160
+ has_flow = _has_conditional_edges(ir, plan)
161
+ supervisor_key = _detect_supervisor(ir)
162
+
163
+ tools_import = f"from .tools import {', '.join(ir.tools.keys())}" if ir.tools else ""
164
+ has_schemas = any(v.output_schema for v in ir.agents.values())
165
+ schemas_import = ("from .schemas import " +
166
+ ", ".join(f'{k.capitalize()}Output' for k, v in ir.agents.items() if v.output_schema)
167
+ if has_schemas else "")
168
+
169
+ # Build agents
170
+ agent_blocks: list[str] = []
171
+ for ak, agent in ir.agents.items():
172
+ model = ir.models.get(agent.model)
173
+ mstr = _model_str(model) if model else '"openai/gpt-4o"'
174
+ role = agent.role or ak
175
+ goal = agent.description or f"Complete {role} tasks"
176
+ backstory = agent.instructions.replace('"""', "'''")
177
+ tools_list = ", ".join(agent.tools) if agent.tools else ""
178
+ tools_arg = f" tools=[{tools_list}],\n" if tools_list else ""
179
+ allow_deleg = "True" if ak == supervisor_key else "False"
180
+ agent_blocks.append(f'''\
181
+ {ak}_agent = Agent(
182
+ role="""{role}""",
183
+ goal="""{goal}""",
184
+ backstory="""{backstory}""",
185
+ {tools_arg} llm={mstr},
186
+ allow_delegation={allow_deleg},
187
+ verbose=True
188
+ )''')
189
+
190
+ # Build tasks with context + output_pydantic
191
+ task_blocks: list[str] = []
192
+ task_names: list[str] = []
193
+ step_to_task: dict[str, str] = {}
194
+ task_ids = unique_identifiers([s.id for s in steps], lambda v: snake_identifier(v, prefix="task"))
195
+
196
+ for i, step in enumerate(steps):
197
+ agent_ref = step.agent or next(iter(ir.agents.keys()), "unknown")
198
+ task_name = task_ids[step.id]
199
+ task_names.append(task_name)
200
+ step_to_task[step.id] = task_name
201
+
202
+ desc = f"Execute step {step.id}."
203
+ exp_out = "A completed output for this step."
204
+
205
+ # Context from depends_on
206
+ context_arg = ""
207
+ if step.depends_on:
208
+ ctx_tasks = [step_to_task[dep] for dep in step.depends_on if dep in step_to_task]
209
+ if ctx_tasks:
210
+ context_arg = f" context=[{', '.join(ctx_tasks)}],\n"
211
+
212
+ # output_pydantic
213
+ out_pydantic_arg = ""
214
+ agent_ir = ir.agents.get(agent_ref)
215
+ if agent_ir and agent_ir.output_schema:
216
+ out_pydantic_arg = f" output_pydantic={agent_ref.capitalize()}Output,\n"
217
+
218
+ task_blocks.append(f'''\
219
+ {task_name} = Task(
220
+ description="{desc}",
221
+ expected_output="{exp_out}",
222
+ agent={agent_ref}_agent,
223
+ {context_arg}{out_pydantic_arg})''')
224
+
225
+ # Process type
226
+ if supervisor_key:
227
+ process_line = f"process=Process.hierarchical,\n manager_agent={supervisor_key}_agent,"
228
+ else:
229
+ process_line = "process=Process.sequential,"
230
+
231
+ if has_flow:
232
+ # Generate Flow class with @router
233
+ return _write_crew_flow(
234
+ ir, plan, src, out_dir, ds,
235
+ tools_import, schemas_import, agent_blocks, task_blocks, task_names, wf,
236
+ process_line
237
+ )
238
+
239
+ c = f'''\
240
+ """CrewAI definitions for {plan.project_name}."""
241
+ from __future__ import annotations
242
+ from crewai import Agent, Task, Crew, Process
243
+ {tools_import}
244
+ {schemas_import}
245
+
246
+ # ── Agents ────────────────────────────────────────────────────────────────────
247
+ {chr(10).join(agent_blocks)}
248
+
249
+ # ── Tasks ─────────────────────────────────────────────────────────────────────
250
+ {chr(10).join(task_blocks)}
251
+
252
+ # ── Crew ──────────────────────────────────────────────────────────────────────
253
+ main_crew = Crew(
254
+ agents=[{", ".join(f"{k}_agent" for k in ir.agents.keys())}],
255
+ tasks=[{", ".join(task_names)}],
256
+ {process_line}
257
+ verbose=True
258
+ )
259
+ '''
260
+ rel = f"src/{src.name}/crew.py"
261
+ write_file(out_dir, rel, c)
262
+ return [rel]
263
+
264
+
265
+ def _write_crew_flow(
266
+ ir: AgentSystemIR, plan: GenerationPlan, src: Path, out_dir: Path, ds: DiagnosticSet,
267
+ tools_import: str, schemas_import: str,
268
+ agent_blocks: list[str], task_blocks: list[str], task_names: list[str],
269
+ wf, process_line: str,
270
+ ) -> list[str]:
271
+ """Generate CrewAI Flow with @router for conditional edges."""
272
+ ds.add_info(DiagCode.REQUIRES_ADAPTER,
273
+ "Conditional workflow edges detected. Generating CrewAI Flow with @router methods.",
274
+ path=f"workflows.{plan.main_workflow_key}.edges")
275
+
276
+ # Build router branches from conditional edges
277
+ route_cases: list[str] = []
278
+ for edge in wf.edges:
279
+ if edge.condition:
280
+ cond = str(edge.condition)
281
+ # Simple heuristic: condition references a step output key
282
+ route_cases.append(
283
+ f' # Route to {edge.to_step} if: {cond}\n'
284
+ f' # return "{edge.to_step}" # Uncomment and implement condition check'
285
+ )
286
+ route_body = "\n".join(route_cases) if route_cases else ' pass # No conditions matched'
287
+
288
+ c = f'''\
289
+ """CrewAI Flow + Crew definitions for {plan.project_name}."""
290
+ from __future__ import annotations
291
+ from crewai import Agent, Task, Crew, Process
292
+ from crewai.flow.flow import Flow, listen, router, start
293
+ {tools_import}
294
+ {schemas_import}
295
+
296
+ # ── Agents ────────────────────────────────────────────────────────────────────
297
+ {chr(10).join(agent_blocks)}
298
+
299
+ # ── Tasks ─────────────────────────────────────────────────────────────────────
300
+ {chr(10).join(task_blocks)}
301
+
302
+ # ── Crew ──────────────────────────────────────────────────────────────────────
303
+ main_crew = Crew(
304
+ agents=[{", ".join(f"{k}_agent" for k in ir.agents.keys())}],
305
+ tasks=[{", ".join(task_names)}],
306
+ {process_line}
307
+ verbose=True
308
+ )
309
+
310
+
311
+ # ── Flow (conditional routing) ────────────────────────────────────────────────
312
+ class {plan.package_name.capitalize()}Flow(Flow):
313
+
314
+ @start()
315
+ async def run_crew(self) -> str:
316
+ result = main_crew.kickoff(inputs={{"question": self.state.get("question", "")}})
317
+ return str(result)
318
+
319
+ @router(run_crew)
320
+ def route_result(self, result: str) -> str:
321
+ {route_body}
322
+ return "done"
323
+
324
+ @listen("done")
325
+ def on_done(self, result: str) -> str:
326
+ return result
327
+
328
+ @listen(Exception)
329
+ def on_error(self, error: Exception) -> None:
330
+ print(f"Flow error: {{error}}")
331
+ '''
332
+ rel = f"src/{src.name}/crew.py"
333
+ write_file(out_dir, rel, c)
334
+ return [rel]
335
+
336
+
337
+ def _write_run(plan: GenerationPlan, src: Path, out_dir: Path) -> list[str]:
338
+ c = f'''\
339
+ """Runner for {plan.project_name} (CrewAI)."""
340
+ from __future__ import annotations
341
+ import sys
342
+ import asyncio
343
+
344
+
345
+ def main():
346
+ q = " ".join(sys.argv[1:]) or "Start process"
347
+ inputs = {{"question": q}}
348
+
349
+ # Try Flow-based execution (conditional routing)
350
+ try:
351
+ from .crew import {plan.package_name.capitalize()}Flow
352
+ flow = {plan.package_name.capitalize()}Flow()
353
+ flow.state["question"] = q
354
+ result = asyncio.run(flow.kickoff_async())
355
+ print("Result:", result)
356
+ return
357
+ except (ImportError, AttributeError):
358
+ pass
359
+
360
+ # Fallback: simple crew kickoff
361
+ from .crew import main_crew
362
+ result = main_crew.kickoff(inputs=inputs)
363
+ print("Result:", result)
364
+
365
+
366
+ async def main_async():
367
+ """Async entry point using kickoff_async for parallel crews."""
368
+ q = " ".join(sys.argv[1:]) or "Start process"
369
+ inputs = {{"question": q}}
370
+ from .crew import main_crew
371
+ result = await main_crew.kickoff_async(inputs=inputs)
372
+ print("Result:", result)
373
+
374
+
375
+ if __name__ == "__main__":
376
+ main()
377
+ '''
378
+ rel = f"src/{src.name}/run.py"
379
+ write_file(out_dir, rel, c)
380
+ return [rel]
381
+
382
+
383
+ def _write_init(src: Path, out_dir: Path) -> list[str]:
384
+ c = f'"""Package: {src.name}."""\n'
385
+ rel = f"src/{src.name}/__init__.py"
386
+ write_file(out_dir, rel, c)
387
+ return [rel]
388
+
389
+
390
+ def _write_readme(ir: AgentSystemIR, plan: GenerationPlan, out_dir: Path) -> list[str]:
391
+ has_flow = _has_conditional_edges(ir, plan)
392
+ supervisor = _detect_supervisor(ir)
393
+
394
+ flow_note = ""
395
+ if has_flow:
396
+ flow_note = """
397
+ ## Conditional Routing (Flow)
398
+
399
+ This project uses `CrewAI Flow` with `@router` decorator for conditional branching.
400
+ Implement routing logic in `crew.py` inside the `route_result` method.
401
+
402
+ ```python
403
+ @router(run_crew)
404
+ def route_result(self, result: str) -> str:
405
+ if "approved" in result:
406
+ return "approve_branch"
407
+ return "reject_branch"
408
+ ```
409
+ """
410
+
411
+ supervisor_note = ""
412
+ if supervisor:
413
+ supervisor_note = f"""
414
+ ## Hierarchical Process
415
+
416
+ `{supervisor}_agent` is the supervisor. Crew runs in `Process.hierarchical` mode.
417
+ The manager agent delegates tasks to other agents.
418
+ """
419
+
420
+ c = f"""\
421
+ # {plan.project_name} — CrewAI
422
+
423
+ > Auto-generated by `agentsml-impl`.
424
+ {flow_note}{supervisor_note}
425
+ ## Quickstart
426
+ ```bash
427
+ pip install -e .
428
+ python -m {plan.package_name}.run
429
+ ```
430
+
431
+ ## Async execution
432
+ ```python
433
+ from {plan.package_name}.run import main_async
434
+ import asyncio
435
+ asyncio.run(main_async())
436
+ ```
437
+
438
+ > See `diagnostics.yaml` for portability warnings.
439
+ """
440
+ write_file(out_dir, "README.md", c)
441
+ return ["README.md"]
@@ -0,0 +1,30 @@
1
+ target: crewai
2
+ kind: code
3
+ language: python
4
+ status: implemented
5
+ level: 1
6
+ version_tested: "0.83.0"
7
+ supports:
8
+ agents: native
9
+ tools: native
10
+ workflows: native
11
+ graph_edges: lossy
12
+ graph_conditions: manual
13
+ cycles: unsupported
14
+ parallel: native
15
+ human_approval: adapter
16
+ mcp: adapter
17
+ a2a: manual
18
+ ag_ui: adapter
19
+ structured_output: native
20
+ observability: native
21
+ artifacts:
22
+ - python_project
23
+ - diagnostics
24
+ - readme
25
+ notes: >
26
+ CrewAI maps AgentsML workflows to Crew processes (Sequential or Hierarchical).
27
+ Workflow edges are ignored; steps map to CrewAI Tasks running sequentially.
28
+ Conditional edges generate a Flow with an @router scaffold whose branches are
29
+ left as comments, so the routing has to be implemented by hand.
30
+ Cycles are not supported. Human approval requires custom tool/step.
File without changes