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,922 @@
1
+ """PydanticAI target adapter — Level 1 code generation.
2
+
3
+ Fixes (2026-06-09):
4
+ - Multi-agent workflows now use pydantic_graph Graph + BaseNode API (V2).
5
+ - ModelRetry → retry_policy mapping added.
6
+ - agent.as_tool() delegation pattern documented in multi-agent README.
7
+ """
8
+
9
+ from __future__ import annotations
10
+ from pathlib import Path
11
+
12
+ from agentsml_impl.compiler.conditions import ConditionError, compile_condition
13
+ from agentsml_impl.compiler.identifiers import python_identifier_ir
14
+ from agentsml_impl.compiler.ir import AgentSystemIR, ModelIR
15
+ from agentsml_impl.compiler.diagnostics import DiagCode, DiagnosticSet
16
+ from agentsml_impl.compiler.durations import parse_duration_seconds
17
+ from agentsml_impl.compiler.naming import pascal_identifier, snake_identifier, unique_identifiers
18
+ from agentsml_impl.compiler.planner import GenerationPlan
19
+ from agentsml_impl.compiler.render import toml_string, write_file
20
+ from agentsml_impl.runtime.tools import generate_tool_stub
21
+ from agentsml_impl.runtime.json_schema import generate_models_source
22
+ from agentsml_impl.targets.base import TargetAdapter, GenerationResult
23
+
24
+
25
+ class Adapter(TargetAdapter):
26
+ @property
27
+ def name(self) -> str:
28
+ return "pydantic-ai"
29
+
30
+ def analyze(self, ir: AgentSystemIR, diagnostics: DiagnosticSet) -> None:
31
+ from agentsml_impl.compiler.capabilities import analyze_capabilities
32
+ analyze_capabilities(ir, "pydantic_ai", diagnostics)
33
+
34
+ def generate(self, ir: AgentSystemIR, plan: GenerationPlan,
35
+ out_dir: Path, diagnostics: DiagnosticSet) -> GenerationResult:
36
+ ir = python_identifier_ir(ir)
37
+ out_dir.mkdir(parents=True, exist_ok=True)
38
+ write_file(out_dir, "__init__.py", '"""Generated PydanticAI agent package."""\n')
39
+ files: list[str] = ["__init__.py"]
40
+ files += _write_models(ir, out_dir, diagnostics)
41
+ files += _write_tools(ir, out_dir, diagnostics)
42
+ files += _write_agent(ir, plan, out_dir, diagnostics)
43
+ files += _write_run(ir, plan, out_dir)
44
+ files += _write_pyproject(ir, plan, out_dir)
45
+ files += _write_readme(ir, plan, out_dir)
46
+ return GenerationResult(target=self.name, out_dir=out_dir,
47
+ files_written=files, success=True)
48
+
49
+
50
+ def _agent_extra_args(ak: str, agent, steps, ds: DiagnosticSet) -> str:
51
+ """Draft 0.3 mapping: step `retry` -> Agent(retries=) and agent `reasoning` -> model_settings.
52
+
53
+ `retries` counts re-attempts after the first try, so retries = max_attempts - 1.
54
+ Reasoning effort maps to the unified ModelSettings `thinking` field (off -> False).
55
+ """
56
+ out = ""
57
+ for step in steps:
58
+ r = step.retry
59
+ if step.agent == ak and r is not None:
60
+ if r.valid_max_attempts() is not None:
61
+ out += (f"\n retries={r.valid_max_attempts() - 1},"
62
+ f" # retry.max_attempts={r.max_attempts} (attempts after the first)")
63
+ if r.backoff not in (None, "none") or r.initial_interval is not None or r.max_interval is not None:
64
+ ds.add_warning(
65
+ DiagCode.LOSSY_MAPPING,
66
+ f"Step '{step.id}' retry backoff/interval settings are not applied: PydanticAI "
67
+ "retries (validation and ModelRetry) do not support backoff intervals.",
68
+ target="pydantic_ai", path=f"steps.{step.id}.retry",
69
+ )
70
+ break
71
+ rc = agent.reasoning
72
+ if rc is not None:
73
+ settings: list[str] = []
74
+ if rc.effort == "off":
75
+ settings.append('"thinking": False')
76
+ elif rc.effort in ("low", "medium", "high"):
77
+ settings.append(f'"thinking": {rc.effort!r}')
78
+ elif rc.budget_tokens or rc.expose_trace:
79
+ settings.append('"thinking": True')
80
+ if rc.budget_tokens is not None or rc.expose_trace is not None:
81
+ ds.add_warning(
82
+ DiagCode.LOSSY_MAPPING,
83
+ f"Agent '{ak}' reasoning.budget_tokens/expose_trace have no unified PydanticAI "
84
+ "setting; only effort is applied.",
85
+ target="pydantic_ai", path=f"agents.{ak}.reasoning",
86
+ )
87
+ if settings:
88
+ out += "\n model_settings={" + ", ".join(settings) + "}, # reasoning (AgentsML 0.3)"
89
+ return out
90
+
91
+
92
+ def _pai_model_str(model: ModelIR) -> str:
93
+ """Return PydanticAI model string (provider:name format)."""
94
+ p = model.provider.lower()
95
+ n = model.name
96
+ if p == "openai":
97
+ return f"openai:{n}"
98
+ if p in ("google", "gemini", "google-cloud", "google_cloud"):
99
+ return f"google-gla:{n}"
100
+ if p == "anthropic":
101
+ return f"anthropic:{n}"
102
+ if p in ("azure", "azure-openai"):
103
+ return f"openai:{n}" # via Azure env vars
104
+ return f"openai:{n} # TODO: check provider {p!r}"
105
+
106
+
107
+ # ---------------------------------------------------------------------------
108
+ # Detect multi-agent graph scenarios
109
+ # ---------------------------------------------------------------------------
110
+
111
+ def _is_multi_agent_workflow(ir: AgentSystemIR, plan: GenerationPlan) -> bool:
112
+ """Return True when the workflow has multiple distinct agent steps."""
113
+ wf = ir.workflows.get(plan.main_workflow_key)
114
+ if not wf:
115
+ return False
116
+ agent_steps = [s for s in wf.steps if s.agent and s.agent in ir.agents]
117
+ return len(agent_steps) > 1
118
+
119
+
120
+ def _name_maps(ir: AgentSystemIR, plan: GenerationPlan | None) -> dict[str, object]:
121
+ wf = ir.workflows.get(plan.main_workflow_key) if plan else None
122
+ steps = wf.steps if wf else []
123
+ agent_steps = [s for s in steps if s.agent and s.agent in ir.agents]
124
+ mcp_servers = ir.extras.get("mcp_servers", {}) or {}
125
+ output_agents = [ak for ak, agent in ir.agents.items() if agent.output_schema]
126
+
127
+ agent_ids = unique_identifiers(
128
+ ir.agents.keys(),
129
+ lambda value: snake_identifier(value, prefix="agent"),
130
+ )
131
+ tool_ids = unique_identifiers(
132
+ ir.tools.keys(),
133
+ lambda value: snake_identifier(value, prefix="tool"),
134
+ )
135
+ mcp_server_ids = unique_identifiers(
136
+ mcp_servers.keys(),
137
+ lambda value: snake_identifier(value, prefix="mcp_server"),
138
+ )
139
+ step_ids = unique_identifiers(
140
+ [step.id for step in agent_steps],
141
+ lambda value: snake_identifier(value, prefix="step"),
142
+ )
143
+ return {
144
+ "wf": wf,
145
+ "steps": steps,
146
+ "agent_steps": agent_steps,
147
+ "agent_vars": {key: f"{value}_agent" for key, value in agent_ids.items()},
148
+ "tool_vars": tool_ids,
149
+ "mcp_server_vars": {key: f"{value}_mcp" for key, value in mcp_server_ids.items()},
150
+ "step_node_classes": unique_identifiers(
151
+ [step.id for step in agent_steps],
152
+ lambda value: f"{pascal_identifier(value, prefix='Step')}Node",
153
+ ),
154
+ "step_result_fields": {key: f"{value}_result" for key, value in step_ids.items()},
155
+ "output_classes": unique_identifiers(
156
+ output_agents,
157
+ lambda value: f"{pascal_identifier(value, prefix='Agent')}Output",
158
+ ),
159
+ }
160
+
161
+
162
+ def _output_model_schemas(ir: AgentSystemIR) -> dict[str, dict]:
163
+ names = _name_maps(ir, None)
164
+ return {
165
+ names["output_classes"][ak]: agent.output_schema
166
+ for ak, agent in ir.agents.items()
167
+ if agent.output_schema
168
+ }
169
+
170
+
171
+ # Helpers the generated graph uses to evaluate compiled edge conditions.
172
+ # They mirror the LangGraph target's helpers so a condition behaves the same
173
+ # way in both targets.
174
+ _CONDITION_HELPERS = '''
175
+
176
+ _OPERATORS: dict[str, Any] = {
177
+ "==": lambda a, b: a == b,
178
+ "!=": lambda a, b: a != b,
179
+ "<": lambda a, b: a < b,
180
+ "<=": lambda a, b: a <= b,
181
+ ">": lambda a, b: a > b,
182
+ ">=": lambda a, b: a >= b,
183
+ }
184
+
185
+
186
+ def compare(left: Any, op: str, right: Any) -> bool:
187
+ """Evaluate a compiled comparison, treating incompatible types as false."""
188
+ try:
189
+ return bool(_OPERATORS[op](left, right))
190
+ except (KeyError, TypeError):
191
+ return False
192
+
193
+
194
+ def lookup(ctx: dict[str, Any], path: str) -> Any:
195
+ """Read a dotted path out of the condition context."""
196
+ value: Any = ctx
197
+ for part in path.split("."):
198
+ if isinstance(value, dict):
199
+ value = value.get(part)
200
+ elif isinstance(value, list) and part.isdigit() and int(part) < len(value):
201
+ value = value[int(part)]
202
+ else:
203
+ return None
204
+ return value
205
+
206
+
207
+ def parse_step_output(text: Any) -> dict[str, Any]:
208
+ """Read a step result as an object so conditions can address its fields."""
209
+ import json
210
+
211
+ try:
212
+ value = json.loads(text)
213
+ except (TypeError, ValueError):
214
+ return {"text": text}
215
+ return value if isinstance(value, dict) else {"value": value}
216
+
217
+
218
+ def _condition_context(state: "WorkflowState") -> dict[str, Any]:
219
+ """Build the input/state/steps context that edge conditions read."""
220
+ return {
221
+ "input": {"question": state.question},
222
+ "state": {},
223
+ "steps": {
224
+ step_id: {"output": parse_step_output(getattr(state, field, ""))}
225
+ for step_id, field in _STEP_OUTPUT_FIELDS.items()
226
+ },
227
+ }
228
+ '''
229
+
230
+
231
+ # ---------------------------------------------------------------------------
232
+ # Pydantic models / output schemas
233
+ # ---------------------------------------------------------------------------
234
+
235
+ def _write_models(ir: AgentSystemIR, out_dir: Path, ds: DiagnosticSet) -> list[str]:
236
+ schemas = _output_model_schemas(ir)
237
+ if not schemas:
238
+ return []
239
+ c = generate_models_source(schemas, ds)
240
+ write_file(out_dir, "models.py", c)
241
+ return ["models.py"]
242
+
243
+
244
+ # ---------------------------------------------------------------------------
245
+ # Tools
246
+ # ---------------------------------------------------------------------------
247
+
248
+ def _write_tools(ir: AgentSystemIR, out_dir: Path, ds: DiagnosticSet) -> list[str]:
249
+ if not ir.tools:
250
+ return []
251
+ names = _name_maps(ir, None)
252
+ lines = [
253
+ '"""PydanticAI tool stubs — auto-generated by agentsml-impl."""',
254
+ "from __future__ import annotations",
255
+ "from typing import Any",
256
+ "from pydantic_ai import RunContext",
257
+ "",
258
+ "# Note: these stubs are attached to agents via @agent.tool decorator in agent.py.",
259
+ "# Implement the bodies below.",
260
+ "",
261
+ ]
262
+ for tool in ir.tools.values():
263
+ stub = generate_tool_stub(tool, ds, "pydantic-ai", names["tool_vars"][tool.key])
264
+ lines.append(stub)
265
+ lines.append("")
266
+
267
+ write_file(out_dir, "tools.py", "\n".join(lines))
268
+ return ["tools.py"]
269
+
270
+
271
+ # ---------------------------------------------------------------------------
272
+ # Agent definitions — single-agent OR Graph-based multi-agent
273
+ # ---------------------------------------------------------------------------
274
+
275
+ def _warn_step_timeouts(ir: AgentSystemIR, plan: GenerationPlan, ds: DiagnosticSet) -> None:
276
+ """Draft 0.3 step `timeout` is not enforced by the generated PydanticAI runner."""
277
+ wf = ir.workflows.get(plan.main_workflow_key)
278
+ for step in (wf.steps if wf else []):
279
+ if step.timeout is None:
280
+ continue
281
+ detail = ("" if parse_duration_seconds(step.timeout) is not None
282
+ else f" (value {step.timeout!r} is also unparseable)")
283
+ ds.add_warning(
284
+ DiagCode.LOSSY_MAPPING,
285
+ f"Step '{step.id}' step timeout not enforced by generated PydanticAI runner{detail}.",
286
+ target="pydantic_ai", path=f"workflows.{plan.main_workflow_key}.steps.{step.id}.timeout",
287
+ )
288
+
289
+
290
+ def _write_agent(ir: AgentSystemIR, plan: GenerationPlan,
291
+ out_dir: Path, ds: DiagnosticSet) -> list[str]:
292
+ _warn_step_timeouts(ir, plan, ds)
293
+ is_multi = _is_multi_agent_workflow(ir, plan)
294
+ if is_multi:
295
+ return _write_agent_graph(ir, plan, out_dir, ds)
296
+ return _write_agent_single(ir, plan, out_dir, ds)
297
+
298
+
299
+ def _write_agent_single(ir: AgentSystemIR, plan: GenerationPlan,
300
+ out_dir: Path, ds: DiagnosticSet) -> list[str]:
301
+ names = _name_maps(ir, plan)
302
+ agent_blocks: list[str] = []
303
+ tool_reg_blocks: list[str] = []
304
+
305
+ wf = names["wf"]
306
+ has_approvals = wf and any(s.approval for s in wf.steps)
307
+ if has_approvals:
308
+ ds.add_info(DiagCode.REQUIRES_ADAPTER,
309
+ "Human approval steps are mapped to deferred tools in PydanticAI. "
310
+ "Implement defer=True tools for approval gates.",
311
+ path=f"workflows.{plan.main_workflow_key}")
312
+
313
+ # MCP servers
314
+ mcp_servers_raw = ir.extras.get("mcp_servers", {}) or {}
315
+ mcp_imports: list[str] = []
316
+ mcp_server_vars: list[str] = []
317
+ for srv_key, srv in mcp_servers_raw.items():
318
+ srv_var = names["mcp_server_vars"][srv_key]
319
+ transport = srv.get("transport", "stdio")
320
+ if transport == "stdio":
321
+ cmd = srv.get("command", "npx")
322
+ args = srv.get("args", [])
323
+ mcp_imports.append("from pydantic_ai.mcp import MCPServerStdio")
324
+ mcp_server_vars.append(f'{srv_var} = MCPServerStdio("{cmd}", args={args!r})')
325
+ else:
326
+ url = srv.get("url", "")
327
+ mcp_imports.append("from pydantic_ai.mcp import MCPServerHTTP")
328
+ mcp_server_vars.append(f'{srv_var} = MCPServerHTTP("{url}")')
329
+
330
+ for ak, agent in ir.agents.items():
331
+ agent_var = names["agent_vars"][ak]
332
+ model = ir.models.get(agent.model)
333
+ mstr = _pai_model_str(model) if model else "openai:gpt-4o"
334
+
335
+ has_output = bool(agent.output_schema)
336
+ result_type_line = (
337
+ f" result_type={names['output_classes'][ak]},"
338
+ if has_output else ""
339
+ )
340
+
341
+ inst = agent.instructions.replace('"""', "'''")
342
+
343
+ mcp_tools = [t for t in agent.tools if ir.tools.get(t) and ir.tools[t].is_mcp()]
344
+ mcp_srv_names = []
345
+ for mt in mcp_tools:
346
+ srv_ref = ir.tools[mt].mcp_server
347
+ if srv_ref and srv_ref in mcp_servers_raw:
348
+ mcp_srv_names.append(names["mcp_server_vars"][srv_ref])
349
+ mcp_servers_arg = (f"\n mcp_servers=[{', '.join(mcp_srv_names)}],"
350
+ if mcp_srv_names else "")
351
+
352
+ extra_args = _agent_extra_args(ak, agent, wf.steps if wf else [], ds)
353
+
354
+ agent_blocks.append(f'''\
355
+ {agent_var} = Agent(
356
+ "{mstr}",
357
+ name={(agent.display_name or ak)!r},
358
+ system_prompt="""{inst}""",
359
+ defer_model_check=True,{result_type_line}{mcp_servers_arg}{extra_args}
360
+ )''')
361
+
362
+ local_tools = [t for t in agent.tools if ir.tools.get(t) and not ir.tools[t].is_mcp()]
363
+ for tool_key in local_tools:
364
+ tool_name = names["tool_vars"][tool_key]
365
+ tool = ir.tools[tool_key]
366
+ params = _tool_params(tool.input_schema)
367
+ ret = _tool_ret(tool.output_schema)
368
+ tool_reg_blocks.append(f'''\
369
+ @{agent_var}.tool
370
+ async def {tool_name}(ctx: RunContext[None]{", " + params if params else ""}) -> {ret}:
371
+ """{tool.description}"""
372
+ # TODO: implement — raise ModelRetry("reason") to trigger retry
373
+ raise NotImplementedError
374
+ ''')
375
+
376
+ models_import = ""
377
+ if any(v.output_schema for v in ir.agents.values()):
378
+ models_import = "from .models import " + ", ".join(names["output_classes"][k] for k, v in ir.agents.items() if v.output_schema)
379
+
380
+ mcp_import_str = "\n".join(sorted(set(mcp_imports)))
381
+ mcp_vars_str = "\n".join(mcp_server_vars)
382
+ agents_str = "\n\n".join(agent_blocks)
383
+ tools_str = "\n".join(tool_reg_blocks)
384
+
385
+ c = f'''\
386
+ """PydanticAI agents for {plan.project_name}.
387
+
388
+ Auto-generated by agentsml-impl. Re-run to regenerate.
389
+ """
390
+ from __future__ import annotations
391
+ from typing import Any, Optional
392
+ from pydantic_ai import Agent, RunContext
393
+ {mcp_import_str}
394
+ {models_import}
395
+
396
+ # MCP server bindings
397
+ {mcp_vars_str or "# No MCP servers"}
398
+
399
+ # Agent definitions
400
+ {agents_str}
401
+
402
+ # Tool registrations
403
+ {tools_str or "# No local tools registered"}
404
+ '''
405
+ write_file(out_dir, "agent.py", c)
406
+ return ["agent.py"]
407
+
408
+
409
+ def _graph_plan(
410
+ wf, agent_steps: list, ds: DiagnosticSet, plan: GenerationPlan
411
+ ) -> dict[str, object]:
412
+ """Compute the successor/condition routing of the generated graph.
413
+
414
+ The generated graph is a ``pydantic_graph`` decision graph: every node
415
+ declares its possible successors in its return type and the node body
416
+ picks the successor at runtime. Workflow edges therefore drive the graph
417
+ shape; when a workflow declares no edges the steps stay chained in
418
+ declaration order.
419
+ """
420
+ agent_step_ids = {s.id for s in agent_steps}
421
+ step_ids = [s.id for s in agent_steps]
422
+
423
+ successors: dict[str, list[str]] = {sid: [] for sid in step_ids}
424
+ conditions: dict[str, list[tuple[str, str]]] = {sid: [] for sid in step_ids}
425
+ predecessors: dict[str, list[str]] = {sid: [] for sid in step_ids}
426
+
427
+ edge_path = f"workflows.{plan.main_workflow_key}.edges"
428
+
429
+ def _warn_unusable(edge, reason: str) -> None:
430
+ ds.add_warning(
431
+ DiagCode.LOSSY_MAPPING,
432
+ f"Edge {edge.from_step} -> {edge.to_step} is not generated ({reason}).",
433
+ path=edge_path,
434
+ recommendation=(
435
+ "Use a target with full DAG support, or express the step as an agent step."
436
+ ),
437
+ )
438
+
439
+ if wf.edges:
440
+ for edge in wf.edges:
441
+ if edge.from_step not in agent_step_ids or edge.to_step not in agent_step_ids:
442
+ unknown = (
443
+ edge.from_step if edge.from_step not in agent_step_ids else edge.to_step
444
+ )
445
+ if unknown in {s.id for s in wf.steps}:
446
+ _warn_unusable(
447
+ edge,
448
+ f"step '{unknown}' is not an agent step and is not part of the graph",
449
+ )
450
+ else:
451
+ ds.add_warning(
452
+ DiagCode.AMBIGUOUS_REFERENCE,
453
+ f"Edge {edge.from_step} -> {edge.to_step} references an undeclared step.",
454
+ path=edge_path,
455
+ recommendation="Declare both steps in the workflow.",
456
+ )
457
+ continue
458
+ if edge.condition:
459
+ try:
460
+ predicate = compile_condition(str(edge.condition))
461
+ except ConditionError as exc:
462
+ ds.add_warning(
463
+ DiagCode.NONPORTABLE_EXPRESSION,
464
+ f"Condition on edge {edge.from_step} -> {edge.to_step} was not compiled "
465
+ f"({exc}); the edge is never taken.",
466
+ path=edge_path,
467
+ recommendation=(
468
+ "Use comparisons, &&, ||, ! and input/state/steps references."
469
+ ),
470
+ )
471
+ continue
472
+ conditions[edge.from_step].append((predicate, edge.to_step))
473
+ predecessors[edge.to_step].append(edge.from_step)
474
+ else:
475
+ successors[edge.from_step].append(edge.to_step)
476
+ predecessors[edge.to_step].append(edge.from_step)
477
+ else:
478
+ for src, dst in zip(step_ids, step_ids[1:]):
479
+ successors[src].append(dst)
480
+ predecessors[dst].append(src)
481
+
482
+ # A decision graph hands control to exactly one successor, so fan-out and
483
+ # joins are reported rather than silently reshaped.
484
+ for sid, targets in successors.items():
485
+ if len(targets) > 1:
486
+ ds.add_warning(
487
+ DiagCode.LOSSY_MAPPING,
488
+ f"Step '{sid}' has {len(targets)} unconditional successors. The generated "
489
+ "PydanticAI graph routes to one successor only, so the extra branches are not run.",
490
+ path=edge_path,
491
+ recommendation=(
492
+ "Use a target with parallel fan-out support, or chain the branches."
493
+ ),
494
+ )
495
+ for sid, sources in predecessors.items():
496
+ if len(sources) > 1:
497
+ ds.add_warning(
498
+ DiagCode.LOSSY_MAPPING,
499
+ f"Step '{sid}' joins {len(sources)} branches. The generated PydanticAI graph "
500
+ "does not wait for all of them.",
501
+ path=edge_path,
502
+ recommendation=(
503
+ "Use a target with join support, or merge the branches upstream."
504
+ ),
505
+ )
506
+
507
+ roots = [sid for sid in step_ids if not predecessors[sid]]
508
+ if len(roots) > 1:
509
+ ds.add_warning(
510
+ DiagCode.LOSSY_MAPPING,
511
+ f"The workflow has {len(roots)} entry steps. The generated PydanticAI graph starts "
512
+ f"at '{roots[0]}'.",
513
+ path=edge_path,
514
+ recommendation="Add a single entry step that fans out to the other roots.",
515
+ )
516
+
517
+ if wf.has_cycles():
518
+ ds.add_warning(
519
+ DiagCode.LOSSY_MAPPING,
520
+ "The workflow contains cycles. The generated PydanticAI graph runs every step once.",
521
+ path=edge_path,
522
+ recommendation="Model iteration with an explicit loop step.",
523
+ )
524
+
525
+ return {
526
+ "successors": successors,
527
+ "conditions": conditions,
528
+ "predecessors": predecessors,
529
+ "roots": roots,
530
+ }
531
+
532
+
533
+ def _write_agent_graph(ir: AgentSystemIR, plan: GenerationPlan,
534
+ out_dir: Path, ds: DiagnosticSet) -> list[str]:
535
+ """Generate a pydantic_graph decision graph for multi-agent workflows."""
536
+ names = _name_maps(ir, plan)
537
+ ds.add_info(DiagCode.REQUIRES_ADAPTER,
538
+ "Multi-agent workflow detected. Generating a pydantic_graph decision graph "
539
+ "whose edges follow the workflow edges. Requires pydantic-graph>=1.107.0.",
540
+ path=f"workflows.{plan.main_workflow_key}")
541
+
542
+ wf = names["wf"]
543
+ agent_steps = names["agent_steps"]
544
+ _emit_multi_agent_step_diagnostics(wf, plan, ds)
545
+
546
+ plan_data = _graph_plan(wf, agent_steps, ds, plan)
547
+ successors = plan_data["successors"]
548
+ conditions = plan_data["conditions"]
549
+ predecessors = plan_data["predecessors"]
550
+
551
+ ordered_steps = agent_steps
552
+
553
+ # State fields
554
+ state_fields = [" question: str"]
555
+ for s in ordered_steps:
556
+ state_fields.append(f" {names['step_result_fields'][s.id]}: str = \"\"")
557
+
558
+ # Generate individual agents
559
+ agent_defs: list[str] = []
560
+ for ak, agent in ir.agents.items():
561
+ agent_var = names["agent_vars"][ak]
562
+ model = ir.models.get(agent.model)
563
+ mstr = _pai_model_str(model) if model else "openai:gpt-4o"
564
+ inst = agent.instructions.replace('"""', "'''")
565
+ agent_defs.append(f'''\
566
+ {agent_var} = Agent(
567
+ "{mstr}",
568
+ name={(agent.display_name or ak)!r},
569
+ system_prompt="""{inst}""",
570
+ defer_model_check=True,{_agent_extra_args(ak, agent, ordered_steps, ds)}
571
+ )''')
572
+
573
+ # Generate node classes
574
+ node_classes: list[str] = []
575
+ for step in ordered_steps:
576
+ ak = step.agent
577
+ step_cls = names["step_node_classes"][step.id]
578
+ uncond = successors.get(step.id, [])
579
+ conds = conditions.get(step.id, [])
580
+ targets: list[str] = []
581
+ for _, target in conds:
582
+ if target not in targets:
583
+ targets.append(target)
584
+ for target in uncond:
585
+ if target not in targets:
586
+ targets.append(target)
587
+
588
+ if targets:
589
+ hint = " | ".join([names["step_node_classes"][t] for t in targets])
590
+ next_return = f'"{hint} | End[str]"'
591
+ else:
592
+ next_return = '"End[str]"'
593
+
594
+ preds = predecessors.get(step.id, [])
595
+ if len(preds) == 1:
596
+ input_expr = f"run_ctx.state.{names['step_result_fields'][preds[0]]}"
597
+ else:
598
+ input_expr = "run_ctx.state.question"
599
+
600
+ body: list[str] = [
601
+ f" result = await {names['agent_vars'][ak]}.run({input_expr})",
602
+ f" run_ctx.state.{names['step_result_fields'][step.id]} = str(result.output)",
603
+ ]
604
+ if conds:
605
+ body.append(" ctx = _condition_context(run_ctx.state)")
606
+ for predicate, target in conds:
607
+ body.append(f" if {predicate}:")
608
+ body.append(f" return {names['step_node_classes'][target]}()")
609
+ if uncond:
610
+ body.append(f" return {names['step_node_classes'][uncond[0]]}()")
611
+ elif not conds:
612
+ body.append(
613
+ " return End(run_ctx.state."
614
+ f"{names['step_result_fields'][step.id]})"
615
+ )
616
+
617
+ node_classes.append(
618
+ "@dataclass\n"
619
+ f"class {step_cls}(BaseNode[WorkflowState]):\n"
620
+ f" async def run(self, run_ctx: GraphRunContext[WorkflowState]) -> {next_return}:\n"
621
+ + "\n".join(body)
622
+ )
623
+
624
+ # Node list for the graph builder
625
+ node_list = ", ".join(
626
+ f"_graph_builder.node({names['step_node_classes'][s.id]})" for s in ordered_steps
627
+ )
628
+ first_node = names["step_node_classes"][ordered_steps[0].id] if ordered_steps else None
629
+
630
+ models_import = ""
631
+ if any(v.output_schema for v in ir.agents.values()):
632
+ models_import = "from .models import " + ", ".join(names["output_classes"][k] for k, v in ir.agents.items() if v.output_schema)
633
+
634
+ condition_helpers = _CONDITION_HELPERS
635
+ step_output_fields = "\n".join(
636
+ f' "{s.id}": "{names["step_result_fields"][s.id]}",' for s in ordered_steps
637
+ )
638
+
639
+ c = f'''\
640
+ """PydanticAI multi-agent Graph for {plan.project_name}.
641
+
642
+ Auto-generated by agentsml-impl. Uses pydantic_graph for multi-step coordination.
643
+ Re-run to regenerate.
644
+ """
645
+ from __future__ import annotations
646
+ from dataclasses import dataclass, field
647
+ from typing import Any
648
+ from pydantic_ai import Agent, RunContext
649
+ from pydantic_graph import BaseNode, End, GraphBuilder, GraphRunContext
650
+ {models_import}
651
+
652
+ # ── Workflow state ─────────────────────────────────────────────────────────────
653
+
654
+ @dataclass
655
+ class WorkflowState:
656
+ {chr(10).join(state_fields)}
657
+
658
+ # Step id -> state field holding that step's result.
659
+ _STEP_OUTPUT_FIELDS: dict[str, str] = {{
660
+ {step_output_fields}
661
+ }}
662
+
663
+ # ── Agent definitions ─────────────────────────────────────────────────────────
664
+
665
+ {chr(10).join(agent_defs)}
666
+ {condition_helpers}
667
+ # ── Graph nodes ───────────────────────────────────────────────────────────────
668
+
669
+ {chr(10).join(node_classes)}
670
+
671
+ # ── Graph definition ──────────────────────────────────────────────────────────
672
+
673
+ _graph_builder = GraphBuilder(
674
+ name="{plan.package_name}",
675
+ state_type=WorkflowState,
676
+ input_type={first_node},
677
+ output_type=str,
678
+ )
679
+ _graph_builder.add(
680
+ _graph_builder.edge_from(_graph_builder.start_node).to({first_node}),
681
+ {node_list},
682
+ )
683
+ {plan.package_name}_graph = _graph_builder.build()
684
+ '''
685
+ write_file(out_dir, "agent.py", c)
686
+ return ["agent.py"]
687
+
688
+
689
+ def _emit_multi_agent_step_diagnostics(wf, plan: GenerationPlan, ds: DiagnosticSet) -> None:
690
+ """Report per-step omissions from the generated multi-agent graph."""
691
+ if not wf:
692
+ return
693
+
694
+ base_path = f"workflows.{plan.main_workflow_key}.steps"
695
+ for step in wf.steps:
696
+ step_path = f"{base_path}.{step.id}"
697
+ if step.a2a_agent is not None:
698
+ ds.add_warning(
699
+ DiagCode.REQUIRES_ADAPTER,
700
+ (
701
+ f"Step '{step.id}' delegates to A2A agent '{step.a2a_agent}' and is "
702
+ "omitted from the generated PydanticAI graph."
703
+ ),
704
+ path=f"{step_path}.a2a_agent",
705
+ recommendation="Wrap the remote agent in a local adapter step or use a target with native A2A graph support.",
706
+ )
707
+ elif step.workflow is not None:
708
+ ds.add_warning(
709
+ DiagCode.LOSSY_MAPPING,
710
+ (
711
+ f"Step '{step.id}' delegates to nested workflow '{step.workflow}' and is "
712
+ "omitted from the generated PydanticAI graph."
713
+ ),
714
+ path=f"{step_path}.workflow",
715
+ recommendation="Flatten the nested workflow into agent steps or use an orchestrator that supports sub-workflows.",
716
+ )
717
+ elif step.tool is not None:
718
+ ds.add_warning(
719
+ DiagCode.LOSSY_MAPPING,
720
+ (
721
+ f"Step '{step.id}' targets tool '{step.tool}' and is omitted from the "
722
+ "generated PydanticAI graph."
723
+ ),
724
+ path=f"{step_path}.tool",
725
+ recommendation="Move the tool invocation into an agent step or use a target with native tool-step orchestration.",
726
+ )
727
+ elif step.is_approval_only():
728
+ ds.add_warning(
729
+ DiagCode.REQUIRES_ADAPTER,
730
+ f"Approval-only step '{step.id}' is omitted from the generated PydanticAI graph.",
731
+ path=f"{step_path}.approval",
732
+ recommendation="Model the approval gate with a deferred tool or external approval callback.",
733
+ )
734
+
735
+
736
+ # ---------------------------------------------------------------------------
737
+ # Run entrypoint
738
+ # ---------------------------------------------------------------------------
739
+
740
+ def _write_run(ir: AgentSystemIR, plan: GenerationPlan, out_dir: Path) -> list[str]:
741
+ names = _name_maps(ir, plan)
742
+ primary = next(iter(ir.agents.keys()), None)
743
+
744
+ is_multi = _is_multi_agent_workflow(ir, plan)
745
+
746
+ if is_multi:
747
+ agent_steps = names["agent_steps"]
748
+ first_node = (
749
+ names["step_node_classes"][agent_steps[0].id]
750
+ if agent_steps else "None"
751
+ )
752
+
753
+ c = f'''\
754
+ """Runner for {plan.project_name} (PydanticAI Graph). Auto-generated."""
755
+ from __future__ import annotations
756
+ import asyncio
757
+ import sys
758
+ from .agent import {plan.package_name}_graph, WorkflowState, {", ".join(names["step_node_classes"][s.id] for s in agent_steps)}
759
+
760
+
761
+ async def run_async(question: str) -> str:
762
+ state = WorkflowState(question=question)
763
+ result = await {plan.package_name}_graph.run(state=state, inputs={first_node}())
764
+ return str(result)
765
+
766
+
767
+ def main() -> None:
768
+ q = " ".join(sys.argv[1:]) or "Hello!"
769
+ print(asyncio.run(run_async(q)))
770
+
771
+
772
+ if __name__ == "__main__":
773
+ main()
774
+ '''
775
+ else:
776
+ agent_ref = names["agent_vars"][primary] if primary else "agent"
777
+ c = f'''\
778
+ """Runner for {plan.project_name} (PydanticAI). Auto-generated."""
779
+ from __future__ import annotations
780
+ import asyncio
781
+ import sys
782
+ from .agent import {agent_ref}
783
+
784
+
785
+ async def run_async(question: str) -> str:
786
+ result = await {agent_ref}.run(question)
787
+ return str(result.output)
788
+
789
+
790
+ def main() -> None:
791
+ q = " ".join(sys.argv[1:]) or "Hello!"
792
+ print(asyncio.run(run_async(q)))
793
+
794
+
795
+ if __name__ == "__main__":
796
+ main()
797
+ '''
798
+ write_file(out_dir, "run.py", c)
799
+ return ["run.py"]
800
+
801
+
802
+ # ---------------------------------------------------------------------------
803
+ # pyproject.toml
804
+ # ---------------------------------------------------------------------------
805
+
806
+ def _write_pyproject(ir: AgentSystemIR, plan: GenerationPlan, out_dir: Path) -> list[str]:
807
+ is_multi = _is_multi_agent_workflow(ir, plan)
808
+ graph_dep = '\n "pydantic-graph>=1.107.0",' if is_multi else ""
809
+ c = f'''\
810
+ [build-system]
811
+ requires = ["setuptools>=68"]
812
+ build-backend = "setuptools.build_meta"
813
+
814
+ [project]
815
+ name = "{plan.package_name}"
816
+ version = "{ir.metadata.version or '0.1.0'}"
817
+ description = {toml_string(ir.metadata.description or plan.project_name)}
818
+ requires-python = ">=3.11"
819
+ dependencies = [
820
+ "pydantic-ai>=1.0",
821
+ "pydantic>=2.7",
822
+ "python-dotenv",{graph_dep}
823
+ ]
824
+
825
+ [tool.setuptools.packages.find]
826
+ where = ["."]
827
+ '''
828
+ write_file(out_dir, "pyproject.toml", c)
829
+ return ["pyproject.toml"]
830
+
831
+
832
+ # ---------------------------------------------------------------------------
833
+ # README
834
+ # ---------------------------------------------------------------------------
835
+
836
+ def _write_readme(ir: AgentSystemIR, plan: GenerationPlan, out_dir: Path) -> list[str]:
837
+ names = _name_maps(ir, plan)
838
+ primary = next(iter(ir.agents.keys()), "agent")
839
+ is_multi = _is_multi_agent_workflow(ir, plan)
840
+ agents_md = "\n".join(f"- `{k}`: {v.description or ''}" for k, v in ir.agents.items())
841
+ tools_md = "\n".join(f"- `{k}`: {v.description[:70]}" for k, v in ir.tools.items())
842
+ multi_note = ""
843
+ if is_multi:
844
+ multi_note = """
845
+ ## Multi-agent Architecture
846
+
847
+ This project uses `pydantic_graph` for multi-agent coordination.
848
+ Each workflow step is a `BaseNode` that calls a PydanticAI `Agent`.
849
+ State is shared via `WorkflowState`.
850
+
851
+ To use a sub-agent as a tool in another agent, use `agent.as_tool()`:
852
+ ```python
853
+ from .agent import sub_agent
854
+ parent_agent = Agent("openai:gpt-4o", tools=[sub_agent.as_tool()])
855
+ ```
856
+ """
857
+ c = f"""\
858
+ # {plan.project_name} — PydanticAI
859
+
860
+ > Auto-generated by `agentsml-impl`.
861
+
862
+ ## Agents
863
+ {agents_md or "None"}
864
+
865
+ ## Tools
866
+ {tools_md or "None"}
867
+ {multi_note}
868
+ ## Quickstart
869
+ ```bash
870
+ pip install -e .
871
+ # Set OPENAI_API_KEY / GOOGLE_API_KEY / ANTHROPIC_API_KEY
872
+ python run.py "Your question here"
873
+ ```
874
+
875
+ ## Smoke test
876
+ ```bash
877
+ python -c "from agent import {names['agent_vars'].get(primary, 'agent')}; print(type({names['agent_vars'].get(primary, 'agent')}))"
878
+ ```
879
+
880
+ ## Observability
881
+ ```python
882
+ import logfire
883
+ logfire.configure()
884
+ logfire.instrument_pydantic_ai()
885
+ ```
886
+
887
+ > See `diagnostics.yaml` for portability warnings.
888
+ """
889
+ write_file(out_dir, "README.md", c)
890
+ return ["README.md"]
891
+
892
+
893
+ # ── helpers ──────────────────────────────────────────────────────────────────
894
+
895
+ def _tool_params(schema: dict | None) -> str:
896
+ if not schema or schema.get("type") != "object":
897
+ return ""
898
+ props = schema.get("properties", {})
899
+ required = set(schema.get("required", []))
900
+ param_names = unique_identifiers(
901
+ props,
902
+ lambda value: snake_identifier(value, prefix="arg"),
903
+ )
904
+ req_parts = []
905
+ opt_parts = []
906
+ for name, prop in props.items():
907
+ t = prop.get("type", "Any")
908
+ py = {"string": "str", "integer": "int", "number": "float",
909
+ "boolean": "bool"}.get(t, "Any")
910
+ safe_name = param_names[name]
911
+ if name in required:
912
+ req_parts.append(f"{safe_name}: {py}")
913
+ else:
914
+ opt_parts.append(f"{safe_name}: {py} = None")
915
+ return ", ".join(req_parts + opt_parts)
916
+
917
+ def _tool_ret(schema: dict | None) -> str:
918
+ if not schema:
919
+ return "Any"
920
+ t = schema.get("type")
921
+ return {"object": "dict[str, Any]", "array": "list[Any]", "string": "str",
922
+ "integer": "int", "number": "float", "boolean": "bool"}.get(t, "Any")