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,626 @@
1
+ """Spring AI target adapter — Level 1 code generation (Java/Maven).
2
+
3
+ Generates a Spring Boot 3 + Spring AI application:
4
+ - ChatClient for LLM interactions.
5
+ - @Tool-annotated methods in per-agent @Component classes for tools.
6
+ - VectorStore + QuestionAnswerAdvisor for RAG/knowledge.
7
+ - Spring AI model adapters (OpenAI, Vertex, Bedrock, Anthropic).
8
+ - pom.xml with Spring Boot parent + Spring AI BOM.
9
+ """
10
+
11
+ from __future__ import annotations
12
+ from pathlib import Path
13
+
14
+ from agentsml_impl.compiler.ir import AgentSystemIR, ModelIR
15
+ from agentsml_impl.compiler.diagnostics import DiagCode, DiagnosticSet
16
+ from agentsml_impl.compiler.planner import GenerationPlan
17
+ from agentsml_impl.compiler.render import write_file
18
+ from agentsml_impl.compiler.naming import camel_identifier, pascal_identifier, unique_identifiers
19
+ from agentsml_impl.targets.base import TargetAdapter, GenerationResult
20
+
21
+
22
+ class Adapter(TargetAdapter):
23
+ @property
24
+ def name(self) -> str:
25
+ return "spring-ai"
26
+
27
+ def analyze(self, ir: AgentSystemIR, diagnostics: DiagnosticSet) -> None:
28
+ from agentsml_impl.compiler.capabilities import analyze_capabilities
29
+ analyze_capabilities(ir, self.name, diagnostics)
30
+ diagnostics.add_info(
31
+ DiagCode.REQUIRES_ADAPTER,
32
+ "Spring AI target generates Java/Maven project. Requires Java 21+ and Maven 3.9+.",
33
+ path="target"
34
+ )
35
+
36
+ def generate(self, ir: AgentSystemIR, plan: GenerationPlan,
37
+ out_dir: Path, diagnostics: DiagnosticSet) -> GenerationResult:
38
+ out_dir.mkdir(parents=True, exist_ok=True)
39
+
40
+ group_id = "com.agentsml"
41
+ artifact_id = plan.package_name.replace("_", "-")
42
+ pkg_path = f"src/main/java/{group_id.replace('.', '/')}/{artifact_id.replace('-', '')}"
43
+
44
+ java_dir = out_dir / pkg_path
45
+ java_dir.mkdir(parents=True, exist_ok=True)
46
+ resources_dir = out_dir / "src" / "main" / "resources"
47
+ resources_dir.mkdir(parents=True, exist_ok=True)
48
+ test_dir = out_dir / "src" / "test" / "java" / group_id.replace(".", "/") / artifact_id.replace("-", "")
49
+ test_dir.mkdir(parents=True, exist_ok=True)
50
+
51
+ java_pkg = f"{group_id}.{artifact_id.replace('-', '')}"
52
+
53
+ files: list[str] = []
54
+ files += _write_pom(ir, plan, out_dir, group_id, artifact_id)
55
+ files += _write_application_properties(ir, out_dir, resources_dir)
56
+ files += _write_application_class(ir, plan, out_dir, java_dir, java_pkg, artifact_id)
57
+ files += _write_tools_class(ir, plan, out_dir, java_dir, java_pkg, diagnostics)
58
+ files += _write_output_records(ir, out_dir, java_pkg)
59
+ files += _write_agent_service(ir, plan, out_dir, java_dir, java_pkg, diagnostics)
60
+ files += _write_readme(ir, plan, out_dir)
61
+ return GenerationResult(target=self.name, out_dir=out_dir,
62
+ files_written=files, success=True)
63
+
64
+
65
+ # ---------------------------------------------------------------------------
66
+ # Model → Spring AI dependency helpers
67
+ # ---------------------------------------------------------------------------
68
+
69
+ def _spring_ai_model_info(model: ModelIR) -> dict:
70
+ """Return Spring AI dependency + config property info for a model provider."""
71
+ p = model.provider.lower()
72
+ n = model.name
73
+ if p == "openai":
74
+ return {
75
+ "dep_artifact": "spring-ai-starter-model-openai",
76
+ "prop_prefix": "spring.ai.openai",
77
+ "model_prop": f"spring.ai.openai.chat.options.model={n}",
78
+ "api_key_prop": "spring.ai.openai.api-key=${OPENAI_API_KEY}",
79
+ "chat_model_class": "OpenAiChatModel",
80
+ "import": "import org.springframework.ai.openai.OpenAiChatModel;",
81
+ }
82
+ if p == "anthropic":
83
+ return {
84
+ "dep_artifact": "spring-ai-starter-model-anthropic",
85
+ "prop_prefix": "spring.ai.anthropic",
86
+ "model_prop": f"spring.ai.anthropic.chat.options.model={n}",
87
+ "api_key_prop": "spring.ai.anthropic.api-key=${ANTHROPIC_API_KEY}",
88
+ "chat_model_class": "AnthropicChatModel",
89
+ "import": "import org.springframework.ai.anthropic.AnthropicChatModel;",
90
+ }
91
+ if p in ("google", "gemini", "google-cloud", "google_cloud"):
92
+ return {
93
+ "dep_artifact": "spring-ai-starter-model-vertex-ai-gemini",
94
+ "prop_prefix": "spring.ai.vertex.ai.gemini",
95
+ "model_prop": f"spring.ai.vertex.ai.gemini.chat.options.model={n}",
96
+ "api_key_prop": "spring.ai.vertex.ai.gemini.project-id=${GOOGLE_CLOUD_PROJECT}",
97
+ "chat_model_class": "VertexAiGeminiChatModel",
98
+ "import": "import org.springframework.ai.vertexai.gemini.VertexAiGeminiChatModel;",
99
+ }
100
+ if p in ("bedrock", "amazon", "aws"):
101
+ return {
102
+ "dep_artifact": "spring-ai-starter-model-bedrock-converse",
103
+ "prop_prefix": "spring.ai.bedrock",
104
+ "model_prop": f"spring.ai.bedrock.converse.chat.options.model={n}",
105
+ "api_key_prop": "spring.ai.bedrock.aws.region=${AWS_DEFAULT_REGION:us-east-1}",
106
+ "chat_model_class": "BedrockProxyChatModel",
107
+ "import": "import org.springframework.ai.bedrock.proxychat.BedrockProxyChatModel;",
108
+ }
109
+ # Fallback: OpenAI
110
+ return {
111
+ "dep_artifact": "spring-ai-starter-model-openai",
112
+ "prop_prefix": "spring.ai.openai",
113
+ "model_prop": f"spring.ai.openai.chat.options.model={n}",
114
+ "api_key_prop": "spring.ai.openai.api-key=${OPENAI_API_KEY}",
115
+ "chat_model_class": "OpenAiChatModel",
116
+ "import": "import org.springframework.ai.openai.OpenAiChatModel;",
117
+ }
118
+
119
+
120
+ # ---------------------------------------------------------------------------
121
+ # File generators
122
+ # ---------------------------------------------------------------------------
123
+
124
+ def _write_pom(ir: AgentSystemIR, plan: GenerationPlan, out_dir: Path,
125
+ group_id: str, artifact_id: str) -> list[str]:
126
+ # Collect unique model deps
127
+ model_deps: set[str] = set()
128
+ for model in ir.models.values():
129
+ info = _spring_ai_model_info(model)
130
+ model_deps.add(info["dep_artifact"])
131
+
132
+ if not model_deps:
133
+ model_deps.add("spring-ai-starter-model-openai")
134
+
135
+ has_knowledge = any(a.knowledge for a in ir.agents.values())
136
+
137
+ dep_blocks = "\n".join(f'''\
138
+ <dependency>
139
+ <groupId>org.springframework.ai</groupId>
140
+ <artifactId>{dep}</artifactId>
141
+ </dependency>''' for dep in sorted(model_deps))
142
+
143
+ rag_deps = ""
144
+ if has_knowledge:
145
+ rag_deps = """
146
+ <dependency>
147
+ <groupId>org.springframework.ai</groupId>
148
+ <artifactId>spring-ai-starter-vector-store-pgvector</artifactId>
149
+ </dependency>
150
+ <dependency>
151
+ <groupId>org.springframework.ai</groupId>
152
+ <artifactId>spring-ai-advisors-vector-store</artifactId>
153
+ </dependency>"""
154
+
155
+ c = f'''<?xml version="1.0" encoding="UTF-8"?>
156
+ <project xmlns="http://maven.apache.org/POM/4.0.0"
157
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
158
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
159
+ <modelVersion>4.0.0</modelVersion>
160
+
161
+ <parent>
162
+ <groupId>org.springframework.boot</groupId>
163
+ <artifactId>spring-boot-starter-parent</artifactId>
164
+ <version>3.4.5</version>
165
+ <relativePath/>
166
+ </parent>
167
+
168
+ <groupId>{group_id}</groupId>
169
+ <artifactId>{artifact_id}</artifactId>
170
+ <version>{ir.metadata.version or '0.1.0'}</version>
171
+ <name>{plan.project_name}</name>
172
+ <description>{ir.metadata.description or plan.project_name} — auto-generated by agentsml-impl</description>
173
+ <packaging>jar</packaging>
174
+
175
+ <properties>
176
+ <java.version>21</java.version>
177
+ <spring-ai.version>1.0.0</spring-ai.version>
178
+ </properties>
179
+
180
+ <dependencyManagement>
181
+ <dependencies>
182
+ <dependency>
183
+ <groupId>org.springframework.ai</groupId>
184
+ <artifactId>spring-ai-bom</artifactId>
185
+ <version>${{spring-ai.version}}</version>
186
+ <type>pom</type>
187
+ <scope>import</scope>
188
+ </dependency>
189
+ </dependencies>
190
+ </dependencyManagement>
191
+
192
+ <dependencies>
193
+ <dependency>
194
+ <groupId>org.springframework.boot</groupId>
195
+ <artifactId>spring-boot-starter-web</artifactId>
196
+ </dependency>
197
+ <dependency>
198
+ <groupId>org.springframework.boot</groupId>
199
+ <artifactId>spring-boot-starter</artifactId>
200
+ </dependency>
201
+ {dep_blocks}{rag_deps}
202
+
203
+ <dependency>
204
+ <groupId>org.springframework.boot</groupId>
205
+ <artifactId>spring-boot-starter-test</artifactId>
206
+ <scope>test</scope>
207
+ </dependency>
208
+ </dependencies>
209
+
210
+ <build>
211
+ <plugins>
212
+ <plugin>
213
+ <groupId>org.springframework.boot</groupId>
214
+ <artifactId>spring-boot-maven-plugin</artifactId>
215
+ </plugin>
216
+ </plugins>
217
+ </build>
218
+ </project>
219
+ '''
220
+ write_file(out_dir, "pom.xml", c)
221
+ return ["pom.xml"]
222
+
223
+
224
+ def _write_application_properties(ir: AgentSystemIR, out_dir: Path, resources_dir: Path) -> list[str]:
225
+ prop_lines: list[str] = ["# Auto-generated by agentsml-impl"]
226
+ model_info_set: list[dict] = []
227
+ for model in ir.models.values():
228
+ info = _spring_ai_model_info(model)
229
+ if info not in model_info_set:
230
+ model_info_set.append(info)
231
+
232
+ for info in model_info_set:
233
+ prop_lines.append(f"# {info['chat_model_class']} configuration")
234
+ prop_lines.append(info["model_prop"])
235
+ prop_lines.append(info["api_key_prop"])
236
+ prop_lines.append("")
237
+
238
+ prop_lines.append("spring.application.name=" + out_dir.name)
239
+
240
+ content = "\n".join(prop_lines)
241
+ rel = "src/main/resources/application.properties"
242
+ write_file(out_dir, rel, content)
243
+ return [rel]
244
+
245
+
246
+ def _write_application_class(ir: AgentSystemIR, plan: GenerationPlan, out_dir: Path,
247
+ java_dir: Path, java_pkg: str, artifact_id: str) -> list[str]:
248
+ class_name = pascal_identifier(artifact_id, prefix="Agentsml") + "Application"
249
+
250
+ c = f'''\
251
+ package {java_pkg};
252
+
253
+ import org.springframework.boot.SpringApplication;
254
+ import org.springframework.boot.autoconfigure.SpringBootApplication;
255
+
256
+ /**
257
+ * Spring Boot application — auto-generated by agentsml-impl.
258
+ * Project: {plan.project_name}
259
+ */
260
+ @SpringBootApplication
261
+ public class {class_name} {{
262
+
263
+ public static void main(String[] args) {{
264
+ SpringApplication.run({class_name}.class, args);
265
+ }}
266
+ }}
267
+ '''
268
+ rel = f"src/main/java/{java_pkg.replace('.', '/')}/{class_name}.java"
269
+ write_file(out_dir, rel, c)
270
+ return [rel]
271
+
272
+
273
+ _JAVA_TYPES = {"string": "String", "number": "Double", "boolean": "Boolean", "integer": "Integer"}
274
+
275
+
276
+ def _jstr(value: str) -> str:
277
+ return (value.replace("\\", "\\\\").replace('"', '\\"')
278
+ .replace("\r", " ").replace("\n", "\\n"))
279
+
280
+
281
+ _RECORD_RESERVED = {"hashCode", "toString", "getClass", "notify", "notifyAll", "wait",
282
+ "clone", "finalize", "equals"}
283
+
284
+
285
+ def _schema_type(schema: dict) -> str:
286
+ t = schema.get("type")
287
+ if isinstance(t, list):
288
+ t = next((x for x in t if x != "null"), None)
289
+ return str(t) if t else ""
290
+
291
+
292
+ def _java_type(schema, hint: str, taken: set[str], nested: list[str], indent: str) -> str:
293
+ """Java type for a JSON Schema fragment; nested object records are appended to ``nested``."""
294
+ schema = schema if isinstance(schema, dict) else {}
295
+ t = _schema_type(schema)
296
+ if t == "string":
297
+ return "String"
298
+ if t == "integer":
299
+ return "Long"
300
+ if t == "number":
301
+ return "Double"
302
+ if t == "boolean":
303
+ return "Boolean"
304
+ if t == "array":
305
+ inner = _java_type(schema.get("items"), hint + "Item", taken, nested, indent)
306
+ return f"java.util.List<{inner}>"
307
+ if t == "object":
308
+ if not isinstance(schema.get("properties"), dict) or not schema["properties"]:
309
+ return "java.util.Map<String, Object>"
310
+ name = pascal_identifier(hint, prefix="Nested")
311
+ while name in taken:
312
+ name += "_"
313
+ taken.add(name)
314
+ nested.append(_record_source(name, schema, taken, indent))
315
+ return name
316
+ if "enum" in schema:
317
+ return "String"
318
+ return "Object"
319
+
320
+
321
+ def _record_source(name: str, schema: dict, taken: set[str], indent: str,
322
+ top: bool = False) -> str:
323
+ props = schema.get("properties") or {}
324
+ cnames = unique_identifiers(
325
+ props.keys(), lambda v: camel_identifier(v, prefix="field", language="java"))
326
+ inner = indent + " "
327
+ nested: list[str] = []
328
+ comps: list[str] = []
329
+ for key, pschema in props.items():
330
+ pschema = pschema if isinstance(pschema, dict) else {}
331
+ jtype = _java_type(pschema, key, taken, nested, inner)
332
+ cname = cnames[key]
333
+ while cname in _RECORD_RESERVED:
334
+ cname += "_"
335
+ ann = ""
336
+ if pschema.get("description"):
337
+ ann += f'@JsonPropertyDescription("{_jstr(str(pschema["description"]))}") '
338
+ ann += f'@JsonProperty("{_jstr(key)}") '
339
+ comps.append(f"{inner}{ann}{jtype} {cname}")
340
+ head = "public record" if top else "record"
341
+ body = ""
342
+ if nested:
343
+ body = "\n" + "\n\n".join(nested) + "\n" + indent
344
+ comp_src = ",\n".join(comps)
345
+ if comps:
346
+ return f"{indent}{head} {name}(\n{comp_src}) {{{body}}}"
347
+ return f"{indent}{head} {name}() {{{body}}}"
348
+
349
+
350
+ def _output_record_names(ir: AgentSystemIR) -> dict[str, str]:
351
+ """Agent key -> collision-free ``<Agent>Output`` record name (agents with output_schema only)."""
352
+ keys = [k for k, a in ir.agents.items() if isinstance(a.output_schema, dict)]
353
+ names = unique_identifiers(
354
+ keys, lambda v: pascal_identifier(v, prefix="Agent") + "Output")
355
+ taken = {"AgentService", "SharedTools"} | set(_agent_class_names(ir).values())
356
+ out: dict[str, str] = {}
357
+ for ak in keys:
358
+ n = names[ak]
359
+ while n in taken:
360
+ n += "_2"
361
+ taken.add(n)
362
+ out[ak] = n
363
+ return out
364
+
365
+
366
+ def _write_output_records(ir: AgentSystemIR, out_dir: Path, java_pkg: str) -> list[str]:
367
+ files: list[str] = []
368
+ for ak, rname in _output_record_names(ir).items():
369
+ schema = ir.agents[ak].output_schema
370
+ taken = {rname}
371
+ src = _record_source(rname, schema, taken, "", top=True)
372
+ c = f'''\
373
+ package {java_pkg};
374
+
375
+ import com.fasterxml.jackson.annotation.JsonProperty;
376
+ import com.fasterxml.jackson.annotation.JsonPropertyDescription;
377
+
378
+ /**
379
+ * Structured output (AgentsML output_schema) for agent '{ak.replace('*/', '* /')}' — auto-generated by agentsml-impl.
380
+ */
381
+ {src}
382
+ '''
383
+ rel = f"src/main/java/{java_pkg.replace('.', '/')}/{rname}.java"
384
+ write_file(out_dir, rel, c)
385
+ files.append(rel)
386
+ return files
387
+
388
+
389
+
390
+ def _tool_method(k: str, tool_ir, java_name: str) -> str:
391
+ desc = _jstr(tool_ir.description or k)
392
+ props = ((tool_ir.input_schema or {}).get("properties") or {})
393
+ params: list[str] = []
394
+ pnames = unique_identifiers(
395
+ props.keys(), lambda v: camel_identifier(v, prefix="arg", language="java"))
396
+ for pname, pschema in props.items():
397
+ pschema = pschema if isinstance(pschema, dict) else {}
398
+ jtype = _JAVA_TYPES.get(str(pschema.get("type", "string")), "String")
399
+ jname = pnames[pname]
400
+ pdesc = _jstr(pschema.get("description") or pname)
401
+ params.append(f'@ToolParam(description = "{pdesc}") {jtype} {jname}')
402
+ sig = ",\n ".join(params)
403
+ return f'''\
404
+ /**
405
+ * {tool_ir.description or k}
406
+ */
407
+ @Tool(name = "{_jstr(k)}", description = "{desc}")
408
+ public String {java_name}({sig}) {{
409
+ // TODO: implement business logic for {_jstr(k)}
410
+ return "TODO: {_jstr(k)} is not implemented";
411
+ }}'''
412
+
413
+
414
+ def _agent_class_names(ir: AgentSystemIR) -> dict[str, str]:
415
+ """Agent key -> collision-free ``<Agent>Tools`` class name (never ``SharedTools``)."""
416
+ names = unique_identifiers(
417
+ ir.agents.keys(), lambda v: pascal_identifier(v, prefix="Agent") + "Tools")
418
+ taken = {"SharedTools"}
419
+ out: dict[str, str] = {}
420
+ for ak, cls in names.items():
421
+ while cls in taken:
422
+ cls += "_2"
423
+ taken.add(cls)
424
+ out[ak] = cls
425
+ return out
426
+
427
+
428
+ def _tools_classes(ir: AgentSystemIR) -> dict[str, tuple[str, list[str]]]:
429
+ """Map class name -> (agent key or '', tool keys). Agent classes first, then shared."""
430
+ out: dict[str, tuple[str, list[str]]] = {}
431
+ referenced: set[str] = set()
432
+ class_names = _agent_class_names(ir)
433
+ for ak, agent in ir.agents.items():
434
+ keys = [t for t in agent.tools if t in ir.tools and not ir.tools[t].is_mcp()]
435
+ referenced.update(keys)
436
+ if keys:
437
+ out[class_names[ak]] = (ak, keys)
438
+ rest = [k for k, t in ir.tools.items() if k not in referenced and not t.is_mcp()]
439
+ if rest:
440
+ out["SharedTools"] = ("", rest)
441
+ return out
442
+
443
+
444
+ def _write_tools_class(ir: AgentSystemIR, plan: GenerationPlan, out_dir: Path,
445
+ java_dir: Path, java_pkg: str, ds: DiagnosticSet) -> list[str]:
446
+ files: list[str] = []
447
+ for cls, (_ak, keys) in _tools_classes(ir).items():
448
+ mnames = unique_identifiers(
449
+ keys, lambda v: camel_identifier(v, prefix="tool", language="java"))
450
+ methods = "\n\n".join(_tool_method(k, ir.tools[k], mnames[k]) for k in keys)
451
+ c = f'''\
452
+ package {java_pkg};
453
+
454
+ import org.springframework.ai.tool.annotation.Tool;
455
+ import org.springframework.ai.tool.annotation.ToolParam;
456
+ import org.springframework.stereotype.Component;
457
+
458
+ /**
459
+ * Tool definitions — auto-generated by agentsml-impl.
460
+ */
461
+ @Component
462
+ public class {cls} {{
463
+
464
+ {methods}
465
+ }}
466
+ '''
467
+ rel = f"src/main/java/{java_pkg.replace('.', '/')}/{cls}.java"
468
+ write_file(out_dir, rel, c)
469
+ files.append(rel)
470
+ return files
471
+
472
+
473
+ def _write_agent_service(ir: AgentSystemIR, plan: GenerationPlan, out_dir: Path,
474
+ java_dir: Path, java_pkg: str, ds: DiagnosticSet) -> list[str]:
475
+ # Build model imports
476
+ model_imports: set[str] = set()
477
+ chat_model_class = "OpenAiChatModel"
478
+ for model in ir.models.values():
479
+ info = _spring_ai_model_info(model)
480
+ model_imports.add(info["import"])
481
+ chat_model_class = info["chat_model_class"]
482
+ break # Use first model for primary ChatClient
483
+
484
+ tool_classes = _tools_classes(ir)
485
+ agent_tool_field = {ak: cls for cls, (ak, _k) in tool_classes.items() if ak}
486
+ has_knowledge = any(a.knowledge for a in ir.agents.values())
487
+
488
+ field_names = unique_identifiers(
489
+ agent_tool_field.values(),
490
+ lambda v: camel_identifier(v, prefix="tools", language="java"))
491
+ reserved_fields = {"chatClient", "chatClientBuilder", "vectorStore", "userMessage"}
492
+ for cls, fname in list(field_names.items()):
493
+ while fname in reserved_fields:
494
+ fname += "_"
495
+ field_names[cls] = fname
496
+ tool_fields = "".join(
497
+ f"\n private final {cls} {field_names[cls]};"
498
+ for cls in agent_tool_field.values())
499
+ tool_ctor = "".join(
500
+ f",\n {cls} {field_names[cls]}"
501
+ for cls in agent_tool_field.values())
502
+ tool_assign = "".join(
503
+ f"\n this.{field_names[cls]} = {field_names[cls]};"
504
+ for cls in agent_tool_field.values())
505
+ method_names = unique_identifiers(
506
+ ir.agents.keys(), lambda v: "call" + pascal_identifier(v, prefix="Agent"))
507
+
508
+ rag_imports = ""
509
+ rag_field = ""
510
+ rag_advisor = ""
511
+ if has_knowledge:
512
+ ds.add_info(DiagCode.REQUIRES_ADAPTER,
513
+ "Knowledge config detected. Generated QuestionAnswerAdvisor stub. "
514
+ "Populate the VectorStore with your documents.",
515
+ path="agents")
516
+ rag_imports = """import org.springframework.ai.chat.client.advisor.vectorstore.QuestionAnswerAdvisor;
517
+ import org.springframework.ai.vectorstore.VectorStore;"""
518
+ rag_field = "\n private final VectorStore vectorStore;"
519
+ rag_advisor = "\n .defaultAdvisors(QuestionAnswerAdvisor.builder(vectorStore).build())"
520
+
521
+ out_records = _output_record_names(ir)
522
+
523
+ # Build call method for each agent
524
+ agent_methods: list[str] = []
525
+ for ak, agent in ir.agents.items():
526
+ sys_prompt = agent.instructions.replace('"', '\\"').replace('\n', '\\n')
527
+ method_name = method_names[ak]
528
+ tools_line = ""
529
+ if ak in agent_tool_field:
530
+ tools_line = f"\n .tools({field_names[agent_tool_field[ak]]})"
531
+ rtype = out_records.get(ak, "String")
532
+ terminal = f".entity({rtype}.class)" if ak in out_records else ".content()"
533
+ agent_methods.append(f'''\
534
+ /**
535
+ * Invoke agent '{ak.replace('*/', '* /')}'.
536
+ */
537
+ public {rtype} {method_name}(String userMessage) {{
538
+ return chatClient.prompt()
539
+ .system("{sys_prompt}"){tools_line}
540
+ .user(userMessage)
541
+ .call()
542
+ {terminal};
543
+ }}''')
544
+
545
+ vector_store_constructor = ",\n VectorStore vectorStore" if has_knowledge else ""
546
+
547
+ c = f'''\
548
+ package {java_pkg};
549
+
550
+ import org.springframework.ai.chat.client.ChatClient;
551
+ import org.springframework.stereotype.Service;
552
+ {chr(10).join(sorted(model_imports))}
553
+ {rag_imports}
554
+
555
+ /**
556
+ * Agent service — auto-generated by agentsml-impl.
557
+ * Project: {plan.project_name}
558
+ */
559
+ @Service
560
+ public class AgentService {{
561
+
562
+ private final ChatClient chatClient;{tool_fields}{rag_field}
563
+
564
+ public AgentService(ChatClient.Builder chatClientBuilder{tool_ctor}{vector_store_constructor}) {{
565
+ this.chatClient = chatClientBuilder{rag_advisor}
566
+ .build();{tool_assign}
567
+ {"this.vectorStore = vectorStore;" if has_knowledge else ""}
568
+ }}
569
+
570
+ {chr(10).join(agent_methods)}
571
+ }}
572
+ '''
573
+ rel = f"src/main/java/{java_pkg.replace('.', '/')}/AgentService.java"
574
+ write_file(out_dir, rel, c)
575
+ return [rel]
576
+
577
+
578
+ def _write_readme(ir: AgentSystemIR, plan: GenerationPlan, out_dir: Path) -> list[str]:
579
+ agents_md = "\n".join(f"- `{k}`: {v.description or ''}" for k, v in ir.agents.items())
580
+ c = f"""\
581
+ # {plan.project_name} — Spring AI (Java)
582
+
583
+ > Auto-generated by `agentsml-impl`.
584
+
585
+ ## Agents
586
+ {agents_md or "None"}
587
+
588
+ ## Architecture
589
+
590
+ Spring Boot 3 + Spring AI 1.0:
591
+ - `AgentService.java` — `ChatClient` with auto-wired tools and RAG advisors.
592
+ - `<Agent>Tools.java` — `@Component` classes whose `@Tool` methods are passed to `ChatClient` via `.tools(...)`.
593
+ - `application.properties` — model and API key configuration.
594
+
595
+ ## Quickstart
596
+ ```bash
597
+ # Requires Java 21+ and Maven 3.9+
598
+ export OPENAI_API_KEY="your-key" # or appropriate provider key
599
+ mvn spring-boot:run -Dspring-boot.run.arguments="Your question here"
600
+ ```
601
+
602
+ ## Models
603
+
604
+ Configure the model in `application.properties`:
605
+ ```properties
606
+ spring.ai.openai.chat.options.model=gpt-4o
607
+ spring.ai.openai.api-key=${{OPENAI_API_KEY}}
608
+ ```
609
+
610
+ ## RAG (if applicable)
611
+
612
+ Populate the vector store in a `@PostConstruct` method or `CommandLineRunner`:
613
+ ```java
614
+ @Autowired VectorStore vectorStore;
615
+ vectorStore.add(List.of(new Document("Your document content here")));
616
+ ```
617
+
618
+ > See `diagnostics.yaml` for portability warnings.
619
+ """
620
+ write_file(out_dir, "README.md", c)
621
+ return ["README.md"]
622
+
623
+
624
+ # ---------------------------------------------------------------------------
625
+ # Helpers
626
+ # ---------------------------------------------------------------------------
@@ -0,0 +1,31 @@
1
+ target: spring_ai
2
+ kind: code
3
+ language: java
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: unsupported
16
+ mcp: unsupported
17
+ a2a: unsupported
18
+ ag_ui: unsupported
19
+ structured_output: native
20
+ observability: unsupported
21
+ artifacts:
22
+ - java_project
23
+ - diagnostics
24
+ - readme
25
+ notes: >
26
+ Spring AI maps cleanly to ChatClient and ToolCallback-based services, with
27
+ RAG is generated through a QuestionAnswerAdvisor stub. Workflow orchestration
28
+ is not preserved as an executable graph, and MCP/A2A/AG-UI, approval, and
29
+ observability wiring are not claimed here.
30
+ profiles:
31
+ agentsml-rag: adapter
@@ -0,0 +1 @@
1
+ """Target: strands_agents."""