gatewaysdk 0.3.2__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 (376) hide show
  1. gatewaysdk/__init__.py +540 -0
  2. gatewaysdk/adapter/__init__.py +15 -0
  3. gatewaysdk/adapter/base.py +94 -0
  4. gatewaysdk/adapter/messages.py +270 -0
  5. gatewaysdk/adapter/triplet.py +1026 -0
  6. gatewaysdk/algorithm/__init__.py +39 -0
  7. gatewaysdk/algorithm/apo/__init__.py +5 -0
  8. gatewaysdk/algorithm/apo/apo.py +898 -0
  9. gatewaysdk/algorithm/apo/prompts/apply_edit_variant01.poml +22 -0
  10. gatewaysdk/algorithm/apo/prompts/apply_edit_variant02.poml +18 -0
  11. gatewaysdk/algorithm/apo/prompts/text_gradient_variant01.poml +18 -0
  12. gatewaysdk/algorithm/apo/prompts/text_gradient_variant02.poml +16 -0
  13. gatewaysdk/algorithm/apo/prompts/text_gradient_variant03.poml +107 -0
  14. gatewaysdk/algorithm/base.py +262 -0
  15. gatewaysdk/algorithm/decorator.py +264 -0
  16. gatewaysdk/algorithm/evals/__init__.py +7 -0
  17. gatewaysdk/algorithm/evals/evals.py +217 -0
  18. gatewaysdk/algorithm/fast.py +250 -0
  19. gatewaysdk/algorithm/gepa/__init__.py +61 -0
  20. gatewaysdk/algorithm/gepa/adapter.py +495 -0
  21. gatewaysdk/algorithm/gepa/gepa.py +570 -0
  22. gatewaysdk/algorithm/gepa/lib/__init__.py +18 -0
  23. gatewaysdk/algorithm/gepa/lib/adapters/README.md +12 -0
  24. gatewaysdk/algorithm/gepa/lib/adapters/__init__.py +0 -0
  25. gatewaysdk/algorithm/gepa/lib/adapters/anymaths_adapter/README.md +341 -0
  26. gatewaysdk/algorithm/gepa/lib/adapters/anymaths_adapter/__init__.py +1 -0
  27. gatewaysdk/algorithm/gepa/lib/adapters/anymaths_adapter/anymaths_adapter.py +174 -0
  28. gatewaysdk/algorithm/gepa/lib/adapters/anymaths_adapter/requirements.txt +1 -0
  29. gatewaysdk/algorithm/gepa/lib/adapters/default_adapter/README.md +0 -0
  30. gatewaysdk/algorithm/gepa/lib/adapters/default_adapter/__init__.py +0 -0
  31. gatewaysdk/algorithm/gepa/lib/adapters/default_adapter/default_adapter.py +209 -0
  32. gatewaysdk/algorithm/gepa/lib/adapters/dspy_adapter/README.md +7 -0
  33. gatewaysdk/algorithm/gepa/lib/adapters/dspy_adapter/__init__.py +0 -0
  34. gatewaysdk/algorithm/gepa/lib/adapters/dspy_adapter/dspy_adapter.py +307 -0
  35. gatewaysdk/algorithm/gepa/lib/adapters/dspy_full_program_adapter/README.md +99 -0
  36. gatewaysdk/algorithm/gepa/lib/adapters/dspy_full_program_adapter/dspy_program_proposal_signature.py +137 -0
  37. gatewaysdk/algorithm/gepa/lib/adapters/dspy_full_program_adapter/full_program_adapter.py +268 -0
  38. gatewaysdk/algorithm/gepa/lib/adapters/generic_rag_adapter/GEPA_RAG.md +621 -0
  39. gatewaysdk/algorithm/gepa/lib/adapters/generic_rag_adapter/__init__.py +56 -0
  40. gatewaysdk/algorithm/gepa/lib/adapters/generic_rag_adapter/evaluation_metrics.py +226 -0
  41. gatewaysdk/algorithm/gepa/lib/adapters/generic_rag_adapter/generic_rag_adapter.py +496 -0
  42. gatewaysdk/algorithm/gepa/lib/adapters/generic_rag_adapter/rag_pipeline.py +238 -0
  43. gatewaysdk/algorithm/gepa/lib/adapters/generic_rag_adapter/vector_store_interface.py +212 -0
  44. gatewaysdk/algorithm/gepa/lib/adapters/generic_rag_adapter/vector_stores/__init__.py +2 -0
  45. gatewaysdk/algorithm/gepa/lib/adapters/generic_rag_adapter/vector_stores/chroma_store.py +196 -0
  46. gatewaysdk/algorithm/gepa/lib/adapters/generic_rag_adapter/vector_stores/lancedb_store.py +422 -0
  47. gatewaysdk/algorithm/gepa/lib/adapters/generic_rag_adapter/vector_stores/milvus_store.py +409 -0
  48. gatewaysdk/algorithm/gepa/lib/adapters/generic_rag_adapter/vector_stores/qdrant_store.py +368 -0
  49. gatewaysdk/algorithm/gepa/lib/adapters/generic_rag_adapter/vector_stores/weaviate_store.py +418 -0
  50. gatewaysdk/algorithm/gepa/lib/adapters/mcp_adapter/README.md +552 -0
  51. gatewaysdk/algorithm/gepa/lib/adapters/mcp_adapter/__init__.py +37 -0
  52. gatewaysdk/algorithm/gepa/lib/adapters/mcp_adapter/mcp_adapter.py +699 -0
  53. gatewaysdk/algorithm/gepa/lib/adapters/mcp_adapter/mcp_client.py +364 -0
  54. gatewaysdk/algorithm/gepa/lib/adapters/terminal_bench_adapter/README.md +9 -0
  55. gatewaysdk/algorithm/gepa/lib/adapters/terminal_bench_adapter/__init__.py +0 -0
  56. gatewaysdk/algorithm/gepa/lib/adapters/terminal_bench_adapter/terminal_bench_adapter.py +217 -0
  57. gatewaysdk/algorithm/gepa/lib/api.py +382 -0
  58. gatewaysdk/algorithm/gepa/lib/core/__init__.py +0 -0
  59. gatewaysdk/algorithm/gepa/lib/core/adapter.py +180 -0
  60. gatewaysdk/algorithm/gepa/lib/core/data_loader.py +74 -0
  61. gatewaysdk/algorithm/gepa/lib/core/engine.py +379 -0
  62. gatewaysdk/algorithm/gepa/lib/core/result.py +233 -0
  63. gatewaysdk/algorithm/gepa/lib/core/state.py +636 -0
  64. gatewaysdk/algorithm/gepa/lib/examples/__init__.py +0 -0
  65. gatewaysdk/algorithm/gepa/lib/examples/aime.py +24 -0
  66. gatewaysdk/algorithm/gepa/lib/examples/anymaths-bench/eval_default.py +111 -0
  67. gatewaysdk/algorithm/gepa/lib/examples/anymaths-bench/prompt-templates/instruction_prompt.txt +9 -0
  68. gatewaysdk/algorithm/gepa/lib/examples/anymaths-bench/prompt-templates/optimal_prompt.txt +24 -0
  69. gatewaysdk/algorithm/gepa/lib/examples/anymaths-bench/train_anymaths.py +177 -0
  70. gatewaysdk/algorithm/gepa/lib/examples/dspy_full_program_evolution/arc_agi.ipynb +25705 -0
  71. gatewaysdk/algorithm/gepa/lib/examples/dspy_full_program_evolution/example.ipynb +348 -0
  72. gatewaysdk/algorithm/gepa/lib/examples/mcp_adapter/__init__.py +4 -0
  73. gatewaysdk/algorithm/gepa/lib/examples/mcp_adapter/mcp_optimization_example.py +456 -0
  74. gatewaysdk/algorithm/gepa/lib/examples/rag_adapter/RAG_GUIDE.md +613 -0
  75. gatewaysdk/algorithm/gepa/lib/examples/rag_adapter/__init__.py +9 -0
  76. gatewaysdk/algorithm/gepa/lib/examples/rag_adapter/rag_optimization.py +820 -0
  77. gatewaysdk/algorithm/gepa/lib/examples/rag_adapter/requirements-rag.txt +29 -0
  78. gatewaysdk/algorithm/gepa/lib/examples/terminal-bench/prompt-templates/instruction_prompt.txt +16 -0
  79. gatewaysdk/algorithm/gepa/lib/examples/terminal-bench/prompt-templates/terminus.txt +9 -0
  80. gatewaysdk/algorithm/gepa/lib/examples/terminal-bench/train_terminus.py +161 -0
  81. gatewaysdk/algorithm/gepa/lib/gepa_utils.py +117 -0
  82. gatewaysdk/algorithm/gepa/lib/logging/__init__.py +0 -0
  83. gatewaysdk/algorithm/gepa/lib/logging/experiment_tracker.py +187 -0
  84. gatewaysdk/algorithm/gepa/lib/logging/logger.py +75 -0
  85. gatewaysdk/algorithm/gepa/lib/logging/utils.py +103 -0
  86. gatewaysdk/algorithm/gepa/lib/proposer/__init__.py +0 -0
  87. gatewaysdk/algorithm/gepa/lib/proposer/base.py +31 -0
  88. gatewaysdk/algorithm/gepa/lib/proposer/merge.py +357 -0
  89. gatewaysdk/algorithm/gepa/lib/proposer/reflective_mutation/__init__.py +0 -0
  90. gatewaysdk/algorithm/gepa/lib/proposer/reflective_mutation/base.py +49 -0
  91. gatewaysdk/algorithm/gepa/lib/proposer/reflective_mutation/reflective_mutation.py +176 -0
  92. gatewaysdk/algorithm/gepa/lib/py.typed +0 -0
  93. gatewaysdk/algorithm/gepa/lib/strategies/__init__.py +0 -0
  94. gatewaysdk/algorithm/gepa/lib/strategies/batch_sampler.py +77 -0
  95. gatewaysdk/algorithm/gepa/lib/strategies/candidate_selector.py +50 -0
  96. gatewaysdk/algorithm/gepa/lib/strategies/component_selector.py +36 -0
  97. gatewaysdk/algorithm/gepa/lib/strategies/eval_policy.py +64 -0
  98. gatewaysdk/algorithm/gepa/lib/strategies/instruction_proposal.py +126 -0
  99. gatewaysdk/algorithm/gepa/lib/utils/__init__.py +10 -0
  100. gatewaysdk/algorithm/gepa/lib/utils/stop_condition.py +196 -0
  101. gatewaysdk/algorithm/gepa/tracing.py +105 -0
  102. gatewaysdk/algorithm/utils.py +177 -0
  103. gatewaysdk/algorithm/verl/__init__.py +5 -0
  104. gatewaysdk/algorithm/verl/interface.py +202 -0
  105. gatewaysdk/automations.py +111 -0
  106. gatewaysdk/benchmark_hub/README.md +88 -0
  107. gatewaysdk/benchmark_hub/__init__.py +119 -0
  108. gatewaysdk/benchmark_hub/_archive.py +189 -0
  109. gatewaysdk/benchmark_hub/_tar.py +6 -0
  110. gatewaysdk/benchmark_hub/client.py +992 -0
  111. gatewaysdk/benchmark_hub/dispatch_shard.py +34 -0
  112. gatewaysdk/benchmark_hub/eval_config.py +20 -0
  113. gatewaysdk/benchmark_hub/evals.py +351 -0
  114. gatewaysdk/benchmark_hub/harbor_adapter.py +673 -0
  115. gatewaysdk/benchmark_hub/path_utils.py +81 -0
  116. gatewaysdk/benchmark_hub/save_utils.py +101 -0
  117. gatewaysdk/benchmark_hub/verifiers_adapter.py +327 -0
  118. gatewaysdk/benchmark_hub/versioning.py +72 -0
  119. gatewaysdk/build.py +515 -0
  120. gatewaysdk/cli/__init__.py +58 -0
  121. gatewaysdk/cli/agent_runner.py +132 -0
  122. gatewaysdk/cli/http_client.py +115 -0
  123. gatewaysdk/cli/platform.py +4086 -0
  124. gatewaysdk/cli/prometheus.py +115 -0
  125. gatewaysdk/cli/release_gate.py +215 -0
  126. gatewaysdk/cli/store.py +131 -0
  127. gatewaysdk/cli/vllm.py +29 -0
  128. gatewaysdk/client.py +406 -0
  129. gatewaysdk/config.py +348 -0
  130. gatewaysdk/connectors/__init__.py +25 -0
  131. gatewaysdk/connectors/client.py +203 -0
  132. gatewaysdk/connectors/skill.py +25 -0
  133. gatewaysdk/connectors/template.py +106 -0
  134. gatewaysdk/context.py +606 -0
  135. gatewaysdk/emitter/__init__.py +43 -0
  136. gatewaysdk/emitter/annotation.py +370 -0
  137. gatewaysdk/emitter/exception.py +54 -0
  138. gatewaysdk/emitter/message.py +61 -0
  139. gatewaysdk/emitter/object.py +117 -0
  140. gatewaysdk/emitter/reward.py +320 -0
  141. gatewaysdk/env_var.py +156 -0
  142. gatewaysdk/environment/__init__.py +108 -0
  143. gatewaysdk/environment/_bundle.py +281 -0
  144. gatewaysdk/environment/_harbor.py +276 -0
  145. gatewaysdk/environment/_materialize.py +97 -0
  146. gatewaysdk/environment/_tar.py +33 -0
  147. gatewaysdk/environment/_world.py +346 -0
  148. gatewaysdk/environment/core.py +527 -0
  149. gatewaysdk/environment/errors.py +58 -0
  150. gatewaysdk/environment/runtime.py +150 -0
  151. gatewaysdk/environment/schema/__init__.py +35 -0
  152. gatewaysdk/environment/schema/__main__.py +225 -0
  153. gatewaysdk/environment/schema/_slack_fidelity.py +116 -0
  154. gatewaysdk/environment/schema/_slack_scenario.py +183 -0
  155. gatewaysdk/environment/schema/api.py +1628 -0
  156. gatewaysdk/environment/schema/batch.py +755 -0
  157. gatewaysdk/environment/schema/compiler.py +615 -0
  158. gatewaysdk/environment/schema/conform.py +428 -0
  159. gatewaysdk/environment/schema/connector.py +777 -0
  160. gatewaysdk/environment/schema/connectors/apple-business-manager/handlers.py +17 -0
  161. gatewaysdk/environment/schema/connectors/apple-business-manager/parity.json +28 -0
  162. gatewaysdk/environment/schema/connectors/apple-business-manager/provenance.json +233 -0
  163. gatewaysdk/environment/schema/connectors/apple-business-manager/scope.toml +112 -0
  164. gatewaysdk/environment/schema/connectors/apple-business-manager/world.json +1380 -0
  165. gatewaysdk/environment/schema/connectors/base.json +28 -0
  166. gatewaysdk/environment/schema/connectors/custom/handlers.py +18 -0
  167. gatewaysdk/environment/schema/connectors/custom/world.json +123 -0
  168. gatewaysdk/environment/schema/connectors/github/handlers.py +81 -0
  169. gatewaysdk/environment/schema/connectors/github/parity.json +37 -0
  170. gatewaysdk/environment/schema/connectors/github/provenance.json +134 -0
  171. gatewaysdk/environment/schema/connectors/github/scope.toml +158 -0
  172. gatewaysdk/environment/schema/connectors/github/world.json +5869 -0
  173. gatewaysdk/environment/schema/connectors/google-calendar/handlers.py +23 -0
  174. gatewaysdk/environment/schema/connectors/google-calendar/world.json +209 -0
  175. gatewaysdk/environment/schema/connectors/google-drive/handlers.py +18 -0
  176. gatewaysdk/environment/schema/connectors/google-drive/world.json +286 -0
  177. gatewaysdk/environment/schema/connectors/jamf/handlers.py +34 -0
  178. gatewaysdk/environment/schema/connectors/jamf/parity.json +49 -0
  179. gatewaysdk/environment/schema/connectors/jamf/provenance.json +181 -0
  180. gatewaysdk/environment/schema/connectors/jamf/scope.toml +128 -0
  181. gatewaysdk/environment/schema/connectors/jamf/world.json +2218 -0
  182. gatewaysdk/environment/schema/connectors/jira/handlers.py +28 -0
  183. gatewaysdk/environment/schema/connectors/jira/world.json +389 -0
  184. gatewaysdk/environment/schema/connectors/kandji/handlers.py +38 -0
  185. gatewaysdk/environment/schema/connectors/kandji/parity.json +29 -0
  186. gatewaysdk/environment/schema/connectors/kandji/provenance.json +152 -0
  187. gatewaysdk/environment/schema/connectors/kandji/scope.toml +120 -0
  188. gatewaysdk/environment/schema/connectors/kandji/world.json +765 -0
  189. gatewaysdk/environment/schema/connectors/linear/handlers.py +20 -0
  190. gatewaysdk/environment/schema/connectors/linear/world.json +363 -0
  191. gatewaysdk/environment/schema/connectors/microsoft-teams/fidelity.json +45 -0
  192. gatewaysdk/environment/schema/connectors/microsoft-teams/handlers.py +1 -0
  193. gatewaysdk/environment/schema/connectors/microsoft-teams/provenance.json +851 -0
  194. gatewaysdk/environment/schema/connectors/microsoft-teams/scope.md +231 -0
  195. gatewaysdk/environment/schema/connectors/microsoft-teams/teams-types.json +1710 -0
  196. gatewaysdk/environment/schema/connectors/microsoft-teams/world.json +858 -0
  197. gatewaysdk/environment/schema/connectors/netsuite/handlers.py +32 -0
  198. gatewaysdk/environment/schema/connectors/netsuite/parity.json +50 -0
  199. gatewaysdk/environment/schema/connectors/netsuite/provenance.json +137 -0
  200. gatewaysdk/environment/schema/connectors/netsuite/scope.toml +78 -0
  201. gatewaysdk/environment/schema/connectors/netsuite/world.json +16243 -0
  202. gatewaysdk/environment/schema/connectors/salesforce/handlers.py +806 -0
  203. gatewaysdk/environment/schema/connectors/salesforce/parity.json +46 -0
  204. gatewaysdk/environment/schema/connectors/salesforce/provenance.json +143 -0
  205. gatewaysdk/environment/schema/connectors/salesforce/scope.toml +174 -0
  206. gatewaysdk/environment/schema/connectors/salesforce/world.json +4695 -0
  207. gatewaysdk/environment/schema/connectors/slack/MODEL.md +236 -0
  208. gatewaysdk/environment/schema/connectors/slack/capabilities.json +1039 -0
  209. gatewaysdk/environment/schema/connectors/slack/handlers.py +762 -0
  210. gatewaysdk/environment/schema/connectors/slack/parity.json +65 -0
  211. gatewaysdk/environment/schema/connectors/slack/provenance.json +294 -0
  212. gatewaysdk/environment/schema/connectors/slack/scope.toml +44 -0
  213. gatewaysdk/environment/schema/connectors/slack/world.json +4993 -0
  214. gatewaysdk/environment/schema/connectors/workday/handlers.py +75 -0
  215. gatewaysdk/environment/schema/connectors/workday/parity.json +36 -0
  216. gatewaysdk/environment/schema/connectors/workday/provenance.json +179 -0
  217. gatewaysdk/environment/schema/connectors/workday/scope.toml +180 -0
  218. gatewaysdk/environment/schema/connectors/workday/world.json +806 -0
  219. gatewaysdk/environment/schema/data.py +593 -0
  220. gatewaysdk/environment/schema/extract.py +263 -0
  221. gatewaysdk/environment/schema/host.py +2437 -0
  222. gatewaysdk/environment/schema/host_surfaces.py +275 -0
  223. gatewaysdk/environment/schema/platform.py +1272 -0
  224. gatewaysdk/environment/schema/scaffold.py +250 -0
  225. gatewaysdk/environment/schema/skill.py +118 -0
  226. gatewaysdk/environment/schema/skills/agents/connector-template-author.md +202 -0
  227. gatewaysdk/environment/schema/skills/connector-schema-authoring/CONNECTORS.md +331 -0
  228. gatewaysdk/environment/schema/skills/connector-schema-authoring/CONVENTIONS.md +100 -0
  229. gatewaysdk/environment/schema/skills/connector-schema-authoring/SKILL.md +313 -0
  230. gatewaysdk/environment/schema/skills/world-data-ingestion/ROWS.md +223 -0
  231. gatewaysdk/environment/schema/skills/world-data-ingestion/SKILL.md +293 -0
  232. gatewaysdk/environment/schema/skills/worlds-getting-started/SKILL.md +390 -0
  233. gatewaysdk/environment/schema/slack.py +757 -0
  234. gatewaysdk/environment/schema/snapshot.py +479 -0
  235. gatewaysdk/environment/schema/store.py +904 -0
  236. gatewaysdk/environment/schema/tasks.py +525 -0
  237. gatewaysdk/environment/schema/tools_world.py +322 -0
  238. gatewaysdk/environment/schema/validation.py +577 -0
  239. gatewaysdk/environment/schema/worker.py +78 -0
  240. gatewaysdk/environment/schema/workers.py +500 -0
  241. gatewaysdk/environment/schema/world_tests.py +336 -0
  242. gatewaysdk/environments/__init__.py +24 -0
  243. gatewaysdk/environments/client.py +486 -0
  244. gatewaysdk/environments/types.py +318 -0
  245. gatewaysdk/execution/__init__.py +15 -0
  246. gatewaysdk/execution/base.py +64 -0
  247. gatewaysdk/execution/client_server.py +443 -0
  248. gatewaysdk/execution/events.py +69 -0
  249. gatewaysdk/execution/inter_process.py +16 -0
  250. gatewaysdk/execution/shared_memory.py +282 -0
  251. gatewaysdk/experiments/__init__.py +90 -0
  252. gatewaysdk/experiments/assignment.py +177 -0
  253. gatewaysdk/experiments/client.py +877 -0
  254. gatewaysdk/experiments/exposure.py +222 -0
  255. gatewaysdk/experiments/types.py +81 -0
  256. gatewaysdk/importers/__init__.py +49 -0
  257. gatewaysdk/importers/_normalize.py +91 -0
  258. gatewaysdk/importers/builder.py +173 -0
  259. gatewaysdk/importers/client.py +95 -0
  260. gatewaysdk/importers/langsmith.py +196 -0
  261. gatewaysdk/importers/recipes.py +249 -0
  262. gatewaysdk/instrumentation/__init__.py +300 -0
  263. gatewaysdk/instrumentation/agentops.py +314 -0
  264. gatewaysdk/instrumentation/agentops_langchain.py +45 -0
  265. gatewaysdk/instrumentation/base.py +119 -0
  266. gatewaysdk/instrumentation/litellm.py +83 -0
  267. gatewaysdk/instrumentation/registry.py +273 -0
  268. gatewaysdk/instrumentation/vllm.py +81 -0
  269. gatewaysdk/instrumentation/weave.py +500 -0
  270. gatewaysdk/integrations/__init__.py +15 -0
  271. gatewaysdk/integrations/gateway/__init__.py +11 -0
  272. gatewaysdk/integrations/gateway/client.py +171 -0
  273. gatewaysdk/integrations/tool_access.py +549 -0
  274. gatewaysdk/litagent/__init__.py +11 -0
  275. gatewaysdk/litagent/decorator.py +536 -0
  276. gatewaysdk/litagent/litagent.py +252 -0
  277. gatewaysdk/llm_proxy.py +1742 -0
  278. gatewaysdk/logging.py +370 -0
  279. gatewaysdk/memory.py +278 -0
  280. gatewaysdk/personas.py +186 -0
  281. gatewaysdk/platform/__init__.py +17 -0
  282. gatewaysdk/platform/builder.py +221 -0
  283. gatewaysdk/platform/compatibility.py +67 -0
  284. gatewaysdk/platform/manifest.py +185 -0
  285. gatewaysdk/platform/orchestrator.py +901 -0
  286. gatewaysdk/platform/registry.py +122 -0
  287. gatewaysdk/platform/worker.py +864 -0
  288. gatewaysdk/replay/__init__.py +1032 -0
  289. gatewaysdk/replay/pytest.py +56 -0
  290. gatewaysdk/reward.py +7 -0
  291. gatewaysdk/run.py +1781 -0
  292. gatewaysdk/runner/__init__.py +11 -0
  293. gatewaysdk/runner/agent.py +878 -0
  294. gatewaysdk/runner/base.py +182 -0
  295. gatewaysdk/runner/legacy.py +309 -0
  296. gatewaysdk/security.py +700 -0
  297. gatewaysdk/semconv.py +170 -0
  298. gatewaysdk/server.py +399 -0
  299. gatewaysdk/sessions.py +282 -0
  300. gatewaysdk/store/__init__.py +45 -0
  301. gatewaysdk/store/base.py +908 -0
  302. gatewaysdk/store/client_server.py +2093 -0
  303. gatewaysdk/store/collection/__init__.py +30 -0
  304. gatewaysdk/store/collection/base.py +587 -0
  305. gatewaysdk/store/collection/memory.py +970 -0
  306. gatewaysdk/store/collection/mongo.py +1412 -0
  307. gatewaysdk/store/collection_based.py +1823 -0
  308. gatewaysdk/store/gateway.py +983 -0
  309. gatewaysdk/store/gateway_listener.py +465 -0
  310. gatewaysdk/store/listener.py +58 -0
  311. gatewaysdk/store/memory.py +396 -0
  312. gatewaysdk/store/mongo.py +165 -0
  313. gatewaysdk/store/redis_stream.py +517 -0
  314. gatewaysdk/store/sqlite.py +3 -0
  315. gatewaysdk/store/threading.py +370 -0
  316. gatewaysdk/store/utils.py +142 -0
  317. gatewaysdk/tracer/__init__.py +14 -0
  318. gatewaysdk/tracer/base.py +286 -0
  319. gatewaysdk/tracer/dummy.py +106 -0
  320. gatewaysdk/tracer/otel.py +559 -0
  321. gatewaysdk/tracing/__init__.py +110 -0
  322. gatewaysdk/tracing/api.py +808 -0
  323. gatewaysdk/tracing/attributes.py +9 -0
  324. gatewaysdk/tracing/context.py +272 -0
  325. gatewaysdk/tracing/exporters/__init__.py +10 -0
  326. gatewaysdk/tracing/exporters/gateway.py +228 -0
  327. gatewaysdk/tracing/identity.py +288 -0
  328. gatewaysdk/tracing/init.py +620 -0
  329. gatewaysdk/tracing/instrumentors/__init__.py +15 -0
  330. gatewaysdk/tracing/instrumentors/claude_agent_sdk.py +766 -0
  331. gatewaysdk/tracing/instrumentors/instrumentation_principles.md +294 -0
  332. gatewaysdk/tracing/instrumentors/registry.py +352 -0
  333. gatewaysdk/tracing/mapping.py +729 -0
  334. gatewaysdk/tracing/processors.py +393 -0
  335. gatewaysdk/tracing/push.py +617 -0
  336. gatewaysdk/tracing/push_models.py +247 -0
  337. gatewaysdk/tracing/semconv.py +294 -0
  338. gatewaysdk/tracing/span_builder.py +356 -0
  339. gatewaysdk/trainer/__init__.py +6 -0
  340. gatewaysdk/trainer/init_utils.py +263 -0
  341. gatewaysdk/trainer/legacy.py +359 -0
  342. gatewaysdk/trainer/registry.py +12 -0
  343. gatewaysdk/trainer/trainer.py +638 -0
  344. gatewaysdk/types/__init__.py +63 -0
  345. gatewaysdk/types/core.py +556 -0
  346. gatewaysdk/types/resources.py +204 -0
  347. gatewaysdk/types/tracer.py +515 -0
  348. gatewaysdk/types/tracing.py +162 -0
  349. gatewaysdk/users.py +251 -0
  350. gatewaysdk/utils/__init__.py +1 -0
  351. gatewaysdk/utils/id.py +18 -0
  352. gatewaysdk/utils/metrics.py +1025 -0
  353. gatewaysdk/utils/otel.py +550 -0
  354. gatewaysdk/utils/otlp.py +556 -0
  355. gatewaysdk/utils/redact.py +22 -0
  356. gatewaysdk/utils/server_launcher.py +1045 -0
  357. gatewaysdk/utils/system_snapshot.py +90 -0
  358. gatewaysdk/verl/__init__.py +8 -0
  359. gatewaysdk/verl/__main__.py +6 -0
  360. gatewaysdk/verl/async_server.py +46 -0
  361. gatewaysdk/verl/config.yaml +27 -0
  362. gatewaysdk/verl/daemon.py +1154 -0
  363. gatewaysdk/verl/dataset.py +44 -0
  364. gatewaysdk/verl/entrypoint.py +248 -0
  365. gatewaysdk/verl/trainer.py +549 -0
  366. gatewaysdk/world_browser.py +748 -0
  367. gatewaysdk/world_data.py +453 -0
  368. gatewaysdk/world_sessions.py +978 -0
  369. gatewaysdk/world_tasks.py +285 -0
  370. gatewaysdk/world_tools.py +115 -0
  371. gatewaysdk/worlds.py +639 -0
  372. gatewaysdk-0.3.2.dist-info/METADATA +236 -0
  373. gatewaysdk-0.3.2.dist-info/RECORD +376 -0
  374. gatewaysdk-0.3.2.dist-info/WHEEL +4 -0
  375. gatewaysdk-0.3.2.dist-info/entry_points.txt +5 -0
  376. gatewaysdk-0.3.2.dist-info/licenses/LICENSE +19 -0
@@ -0,0 +1,898 @@
1
+ # Copyright (c) Microsoft. All rights reserved.
2
+
3
+ """
4
+ APO with textual gradients that read rollout spans and outputs to modify the prompt.
5
+
6
+ - algo: beam search with span-aware textual gradients -> apply_edit via LLM
7
+ - rollout: same pattern as your example, but task is a dict (T_task)
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import asyncio
13
+ import logging
14
+ import random
15
+ import time
16
+ from dataclasses import dataclass
17
+ from pathlib import Path
18
+ from typing import (
19
+ TYPE_CHECKING,
20
+ Any,
21
+ ClassVar,
22
+ Counter,
23
+ Dict,
24
+ Generic,
25
+ Iterator,
26
+ List,
27
+ Optional,
28
+ Sequence,
29
+ Set,
30
+ Tuple,
31
+ TypedDict,
32
+ TypeVar,
33
+ cast,
34
+ )
35
+
36
+ import poml
37
+ from openai import AsyncOpenAI
38
+
39
+ from gatewaysdk.adapter.messages import TraceToMessages
40
+ from gatewaysdk.algorithm.base import Algorithm
41
+ from gatewaysdk.algorithm.utils import batch_iter_over_dataset, with_llm_proxy, with_store
42
+ from gatewaysdk.emitter import find_final_reward
43
+ from gatewaysdk.types import Dataset, NamedResources, PromptTemplate, Rollout, RolloutMode, RolloutStatus
44
+
45
+ if TYPE_CHECKING:
46
+ from gatewaysdk.llm_proxy import LLMProxy
47
+ from gatewaysdk.store.base import LightningStore
48
+
49
+ logger = logging.getLogger(__name__)
50
+
51
+ T_task = TypeVar("T_task")
52
+
53
+
54
+ class RolloutResultForAPO(TypedDict):
55
+ """This must be all JSON serializable to be processable by POML."""
56
+
57
+ status: RolloutStatus
58
+ final_reward: Optional[float]
59
+ spans: List[Dict[str, Any]]
60
+ messages: List[Any]
61
+
62
+
63
+ @dataclass
64
+ class VersionedPromptTemplate:
65
+ version: str
66
+ prompt_template: PromptTemplate
67
+ score: Optional[float] = None
68
+
69
+
70
+ GRADIENT_PROMPT_FILES = [
71
+ Path(__file__).parent / "prompts" / "text_gradient_variant01.poml",
72
+ Path(__file__).parent / "prompts" / "text_gradient_variant02.poml",
73
+ Path(__file__).parent / "prompts" / "text_gradient_variant03.poml",
74
+ ]
75
+
76
+ APPLY_EDIT_PROMPT_FILES = [
77
+ Path(__file__).parent / "prompts" / "apply_edit_variant01.poml",
78
+ Path(__file__).parent / "prompts" / "apply_edit_variant02.poml",
79
+ ]
80
+
81
+
82
+ class APO(Algorithm, Generic[T_task]):
83
+ """Automatic Prompt Optimization (APO) algorithm using textual gradients and beam search.
84
+
85
+ APO is an iterative prompt optimization algorithm that uses LLM-generated textual gradients
86
+ to improve prompts through a beam search process. It evaluates prompts on rollouts,
87
+ computes critiques based on the results, and applies edits to generate improved prompts.
88
+
89
+ The algorithm operates in rounds, where each round:
90
+
91
+ 1. Samples parent prompts from the current beam
92
+ 2. Generates new prompts by computing textual gradients and applying edits
93
+ 3. Evaluates all candidates on a validation set
94
+ 4. Selects the top-k prompts for the next round
95
+
96
+ Based on the ideas from:
97
+
98
+ - [ProTeGi](https://aclanthology.org/2023.emnlp-main.494.pdf)
99
+ - [TextGrad](https://github.com/zou-group/textgrad)
100
+ """
101
+
102
+ # Platform metadata
103
+ name: ClassVar[str] = "apo"
104
+ display_name: ClassVar[str] = "APO"
105
+ description: ClassVar[str] = "Async Prompt Optimization with textual gradients"
106
+ requirements: ClassVar[Dict[str, Any]] = {"gpu": False, "min_runners": 1}
107
+
108
+ def __init__(
109
+ self,
110
+ async_openai_client: AsyncOpenAI,
111
+ *,
112
+ gradient_model: str = "gpt-5-mini",
113
+ apply_edit_model: str = "gpt-4.1-mini",
114
+ diversity_temperature: float = 1.0,
115
+ gradient_batch_size: int = 4,
116
+ val_batch_size: int = 16,
117
+ beam_width: int = 4,
118
+ branch_factor: int = 4,
119
+ beam_rounds: int = 3,
120
+ rollout_batch_timeout: float = 3600.0,
121
+ run_initial_validation: bool = True,
122
+ # Internal flags for debugging
123
+ _poml_trace: bool = False,
124
+ ):
125
+ """
126
+ Initialize the APO algorithm with configuration parameters.
127
+
128
+ Args:
129
+ async_openai_client: AsyncOpenAI client for making LLM API calls.
130
+ gradient_model: Model name for computing textual gradients (critiques).
131
+ apply_edit_model: Model name for applying edits based on critiques.
132
+ diversity_temperature: Temperature parameter for LLM calls to control diversity.
133
+ gradient_batch_size: Number of rollout results to sample for gradient computation.
134
+ val_batch_size: Number of validation examples to use for evaluation.
135
+ beam_width: Number of top-scoring prompts to keep in the beam at each round.
136
+ branch_factor: Number of new prompt candidates to generate from each parent prompt
137
+ by applying textual gradient edits. This controls the expansion of the search tree.
138
+ beam_rounds: Number of beam search rounds to perform.
139
+ rollout_batch_timeout: Maximum time in seconds to wait for rollout batch completion.
140
+ run_initial_validation: If True, runs validation on the seed prompt before starting
141
+ optimization to establish a baseline score. Defaults to True.
142
+ """
143
+ self.async_openai_client = async_openai_client
144
+ self.gradient_model = gradient_model
145
+ self.apply_edit_model = apply_edit_model
146
+ self.diversity_temperature = diversity_temperature
147
+ self.gradient_batch_size = gradient_batch_size
148
+ self.val_batch_size = val_batch_size
149
+ self.beam_width = beam_width
150
+ self.branch_factor = branch_factor
151
+ self.beam_rounds = beam_rounds
152
+ self.rollout_batch_timeout = rollout_batch_timeout
153
+ self.run_initial_validation = run_initial_validation
154
+
155
+ self._history_best_prompt: Optional[PromptTemplate] = None
156
+ self._history_best_score: float = float("-inf")
157
+ self._history_best_version: Optional[str] = None
158
+
159
+ self._version_counter: int = 0
160
+
161
+ self._poml_trace = _poml_trace
162
+
163
+ def _create_versioned_prompt(
164
+ self,
165
+ prompt_template: PromptTemplate,
166
+ *,
167
+ score: Optional[float] = None,
168
+ ) -> VersionedPromptTemplate:
169
+ """
170
+ Wrap a prompt template with a new monotonically increasing version identifier.
171
+ """
172
+ version = f"v{self._version_counter}"
173
+ self._version_counter += 1
174
+ return VersionedPromptTemplate(version=version, prompt_template=prompt_template, score=score)
175
+
176
+ def _format_log_prefix(
177
+ self,
178
+ *,
179
+ round_num: Optional[int] = None,
180
+ beam_idx: Optional[int] = None,
181
+ branch_idx: Optional[int] = None,
182
+ prompt_version: Optional[str] = None,
183
+ ) -> str:
184
+ """
185
+ Construct the standardized log prefix.
186
+ """
187
+ parts: List[str] = []
188
+ if round_num is not None:
189
+ parts.append(f"Round {round_num:02d}")
190
+ if beam_idx is not None:
191
+ parts.append(f"Beam {beam_idx:02d}")
192
+ if branch_idx is not None:
193
+ parts.append(f"Branch {branch_idx:02d}")
194
+ if prompt_version is not None:
195
+ parts.append(f"Prompt {prompt_version}")
196
+ if not parts:
197
+ return ""
198
+ return f"[{' | '.join(parts)}]"
199
+
200
+ def _log(self, level: int, message: str, *, prefix: Optional[str] = None) -> None:
201
+ """
202
+ Log a message with an optional standardized prefix.
203
+ """
204
+ effective_prefix = prefix
205
+ if effective_prefix:
206
+ logger.log(level, f"{effective_prefix} {message}")
207
+ else:
208
+ logger.log(level, message)
209
+
210
+ def get_seed_prompt_template(self) -> Tuple[str, PromptTemplate]:
211
+ """
212
+ Extract the initial prompt template from the algorithm's resources.
213
+
214
+ Returns:
215
+ A tuple of (resource_name, prompt_template) representing the seed prompt.
216
+
217
+ Raises:
218
+ ValueError: If initial_resources is not set or no PromptTemplate is found.
219
+ """
220
+ initial_resources = self.get_initial_resources()
221
+ if initial_resources is None:
222
+ raise ValueError(
223
+ "initial_resources are not set for APO algorithm. "
224
+ "Use algorithm.set_initial_resources() to set initial resources or set it in Trainer()"
225
+ )
226
+ for name, resource in initial_resources.items():
227
+ if isinstance(resource, PromptTemplate):
228
+ return name, resource
229
+ raise ValueError("No prompt template resource found in initial_resources")
230
+
231
+ def get_adapter(self) -> TraceToMessages:
232
+ """
233
+ Get the adapter for converting spans to messages.
234
+
235
+ Returns:
236
+ The TraceToMessages instance for this algorithm.
237
+
238
+ Raises:
239
+ ValueError: If the adapter is not a TraceToMessages.
240
+ """
241
+ adapter = super().get_adapter()
242
+ if not isinstance(adapter, TraceToMessages):
243
+ raise ValueError("Adapter must be a TraceToMessages for APO algorithm")
244
+ return adapter
245
+
246
+ def get_best_prompt(self) -> PromptTemplate:
247
+ """
248
+ Retrieve the best prompt discovered during optimization.
249
+
250
+ Returns:
251
+ The prompt template with the highest validation score found so far.
252
+
253
+ Raises:
254
+ ValueError: If no best prompt has been found yet (run() not called).
255
+ """
256
+ if self._history_best_prompt is None:
257
+ raise ValueError("No best prompt found")
258
+ return self._history_best_prompt
259
+
260
+ async def compute_textual_gradient(
261
+ self,
262
+ current_prompt: VersionedPromptTemplate,
263
+ rollout_results: List[RolloutResultForAPO],
264
+ *,
265
+ prefix: Optional[str] = None,
266
+ ) -> Optional[str]:
267
+ """
268
+ Compute a textual gradient (critique) for the current prompt based on rollout results.
269
+
270
+ This method samples rollout results, sends them to an LLM along with the current prompt,
271
+ and generates a critique describing how the prompt could be improved.
272
+
273
+ Args:
274
+ current_prompt: The prompt template to critique.
275
+ rollout_results: List of rollout results containing spans, messages, and rewards.
276
+
277
+ Returns:
278
+ A textual critique generated by the LLM, or None if generation fails.
279
+ """
280
+ tg_template = random.choice(GRADIENT_PROMPT_FILES)
281
+
282
+ if len(rollout_results) < self.gradient_batch_size:
283
+ self._log(
284
+ logging.WARNING,
285
+ f"Only {len(rollout_results)} rollouts available, but {self.gradient_batch_size} are needed. Using all rollouts.",
286
+ prefix=prefix,
287
+ )
288
+ sampled_rollout_results = rollout_results
289
+ else:
290
+ sampled_rollout_results = random.sample(rollout_results, self.gradient_batch_size)
291
+
292
+ self._log(
293
+ logging.INFO,
294
+ f"Gradient will be computed with {self.gradient_model} for {len(sampled_rollout_results)} rollouts with template: {tg_template.name}",
295
+ prefix=prefix,
296
+ )
297
+
298
+ tg_msg = poml.poml( # type: ignore
299
+ tg_template,
300
+ context={
301
+ "experiments": sampled_rollout_results,
302
+ "prompt_template": current_prompt.prompt_template.template,
303
+ },
304
+ format="openai_chat",
305
+ )
306
+ self._log(
307
+ logging.DEBUG,
308
+ f"Gradient computed with {self.gradient_model} prompt: {tg_msg}",
309
+ prefix=prefix,
310
+ )
311
+ critique_response = await self.async_openai_client.chat.completions.create(
312
+ model=self.gradient_model,
313
+ messages=tg_msg["messages"], # type: ignore
314
+ temperature=self.diversity_temperature,
315
+ )
316
+ critique_text = critique_response.choices[0].message.content
317
+ self._log(
318
+ logging.INFO,
319
+ f"Gradient computed with {self.gradient_model} has result: {critique_text}",
320
+ prefix=prefix,
321
+ )
322
+
323
+ return critique_text
324
+
325
+ async def textual_gradient_and_apply_edit(
326
+ self,
327
+ current_prompt: VersionedPromptTemplate,
328
+ rollout: List[RolloutResultForAPO],
329
+ *,
330
+ prefix: Optional[str] = None,
331
+ ) -> Optional[str]:
332
+ """
333
+ Generate an improved prompt by computing a textual gradient and applying an edit.
334
+
335
+ This is the main optimization step that:
336
+
337
+ 1. Computes a critique (textual gradient) based on rollout performance
338
+ 2. Uses another LLM to apply the critique and generate an improved prompt
339
+
340
+ Args:
341
+ current_prompt: The current prompt template to improve.
342
+ rollout: List of rollout results to base the critique on.
343
+
344
+ Returns:
345
+ The improved prompt text, or the original prompt if gradient computation fails.
346
+ """
347
+ # 1) Critique
348
+ critique_text = await self.compute_textual_gradient(
349
+ current_prompt,
350
+ rollout,
351
+ prefix=prefix,
352
+ )
353
+ if not critique_text:
354
+ self._log(
355
+ logging.ERROR,
356
+ "Failed to compute critique for prompt.",
357
+ prefix=prefix,
358
+ )
359
+ return current_prompt.prompt_template.template
360
+
361
+ # 2) Apply edit
362
+ ae_template = random.choice(APPLY_EDIT_PROMPT_FILES)
363
+ self._log(
364
+ logging.INFO,
365
+ f"Edit will be generated by {self.apply_edit_model} with template: {ae_template.name}",
366
+ prefix=prefix,
367
+ )
368
+ ae_msg = poml.poml( # type: ignore
369
+ ae_template,
370
+ context={
371
+ "prompt_template": current_prompt.prompt_template.template,
372
+ "critique": critique_text,
373
+ },
374
+ format="openai_chat",
375
+ )
376
+
377
+ ae_response = await self.async_openai_client.chat.completions.create(
378
+ model=self.apply_edit_model,
379
+ messages=ae_msg["messages"], # type: ignore
380
+ temperature=self.diversity_temperature,
381
+ )
382
+ new_prompt = ae_response.choices[0].message.content
383
+ if new_prompt:
384
+ self._log(
385
+ logging.INFO,
386
+ f"Edit generated by {self.apply_edit_model}: {new_prompt[:50]}...",
387
+ prefix=prefix,
388
+ )
389
+ return new_prompt
390
+
391
+ @with_store
392
+ async def get_rollout_results(
393
+ self,
394
+ store: LightningStore,
395
+ rollout: List[Rollout],
396
+ *,
397
+ prefix: Optional[str] = None,
398
+ ) -> List[RolloutResultForAPO]:
399
+ """
400
+ Convert completed rollouts to APO-compatible result format.
401
+
402
+ Fetches spans for each rollout, adapts them to messages, and packages them
403
+ with rewards and status information for gradient computation.
404
+
405
+ Args:
406
+ rollout: List of completed rollout metadata.
407
+
408
+ Returns:
409
+ List of rollout results formatted for APO processing.
410
+ """
411
+ rollout_results: List[RolloutResultForAPO] = []
412
+ adapter = self.get_adapter()
413
+ for r in rollout:
414
+ spans = await store.query_spans(r.rollout_id)
415
+ messages = adapter.adapt(spans)
416
+ rollout_result = RolloutResultForAPO(
417
+ status=r.status,
418
+ final_reward=find_final_reward(spans),
419
+ spans=[span.model_dump() for span in spans],
420
+ messages=messages,
421
+ )
422
+ self._log(
423
+ logging.DEBUG,
424
+ f"Rollout result for {r.rollout_id}: status {rollout_result['status']} with final reward {rollout_result['final_reward']}. "
425
+ f"{len(rollout_result['spans'])} spans and {len(rollout_result['messages'])} messages.",
426
+ prefix=prefix,
427
+ )
428
+ rollout_results.append(rollout_result)
429
+ return rollout_results
430
+
431
+ async def evaluate_prompt_on_batch(
432
+ self,
433
+ prompt: VersionedPromptTemplate,
434
+ resource_name: str,
435
+ dataset: Sequence[T_task],
436
+ mode: RolloutMode,
437
+ *,
438
+ prefix: Optional[str] = None,
439
+ ) -> Tuple[List[RolloutResultForAPO], float]:
440
+ """
441
+ Evaluate a prompt on a batch of tasks by running rollouts and computing average reward.
442
+
443
+ This method:
444
+
445
+ 1. Adds the prompt as a named resource to the store
446
+ 2. Enqueues rollouts for each task in the dataset
447
+ 3. Waits for rollouts to complete (with timeout)
448
+ 4. Computes and returns the average reward
449
+
450
+ Args:
451
+ prompt: The prompt template string to evaluate.
452
+ resource_name: The name to register the prompt under in the store.
453
+ dataset: Sequence of tasks to evaluate the prompt on.
454
+ mode: Rollout mode ("train" or "val") for logging/tracking.
455
+
456
+ Returns:
457
+ A tuple of (rollout_results, average_reward) where rollout_results contains
458
+ detailed information for each rollout and average_reward is the mean final reward.
459
+ """
460
+ store = self.get_store()
461
+ preview = prompt.prompt_template.template[:50]
462
+ self._log(
463
+ logging.INFO,
464
+ f'Evaluating prompt "{preview}..." on {len(dataset)} tasks in {mode} mode',
465
+ prefix=prefix,
466
+ )
467
+
468
+ # Install prompt as named resource
469
+ resources: NamedResources = {resource_name: prompt.prompt_template}
470
+ resource_update = await store.update_resources(prompt.version, resources)
471
+
472
+ rollout_ids: List[str] = []
473
+ for t in dataset:
474
+ r = await store.enqueue_rollout(input=t, mode=mode, resources_id=resource_update.resources_id)
475
+ rollout_ids.append(r.rollout_id)
476
+
477
+ deadline = time.time() + self.rollout_batch_timeout
478
+ finished: List[Rollout] = []
479
+ while time.time() < deadline:
480
+ finished = await store.wait_for_rollouts(rollout_ids=rollout_ids, timeout=0.0)
481
+ if len(finished) >= len(rollout_ids):
482
+ self._log(
483
+ logging.INFO,
484
+ f"All {len(rollout_ids)} rollouts finished within timeout.",
485
+ prefix=prefix,
486
+ )
487
+ break
488
+ else:
489
+ self._log(
490
+ logging.DEBUG,
491
+ f"Only {len(finished)} rollouts finished within timeout. Waiting for remaining {len(rollout_ids) - len(finished)} rollouts.",
492
+ prefix=prefix,
493
+ )
494
+ # Sleep to avoid busy-waiting
495
+ await asyncio.sleep(2.0)
496
+
497
+ rollout_results = await self.get_rollout_results(
498
+ finished,
499
+ prefix=prefix,
500
+ )
501
+ final_rewards = [rr["final_reward"] for rr in rollout_results]
502
+
503
+ avg = float(sum([r or 0.0 for r in final_rewards]) / max(1, len(final_rewards)))
504
+ status_counter = Counter([rr["status"] for rr in rollout_results])
505
+
506
+ self._log(
507
+ logging.INFO,
508
+ f"Evaluated {len(rollout_results)} rollouts. Statuses: {status_counter}. Rewards: {final_rewards}, average is {avg}",
509
+ prefix=prefix,
510
+ )
511
+ return rollout_results, avg
512
+
513
+ def _initialize_beam(
514
+ self,
515
+ train_dataset: Optional[Dataset[T_task]],
516
+ val_dataset: Optional[Dataset[T_task]],
517
+ ) -> Tuple[str, PromptTemplate, Iterator[Sequence[T_task]], Iterator[Sequence[T_task]]]:
518
+ """
519
+ Initialize the beam search with seed prompt and dataset iterators.
520
+
521
+ Args:
522
+ train_dataset: Dataset for computing gradients.
523
+ val_dataset: Dataset for evaluating prompts.
524
+
525
+ Returns:
526
+ Tuple of (resource_name, seed_prompt, grad_iterator, val_iterator).
527
+
528
+ Raises:
529
+ ValueError: If either dataset is None.
530
+ """
531
+ resource_name, seed_prompt = self.get_seed_prompt_template()
532
+
533
+ if train_dataset is None:
534
+ raise ValueError("train_dataset is required for APO algorithm")
535
+ if val_dataset is None:
536
+ raise ValueError("val_dataset is required for APO algorithm")
537
+
538
+ grad_dataset_iterator = batch_iter_over_dataset(train_dataset, self.gradient_batch_size)
539
+ val_dataset_iterator = batch_iter_over_dataset(val_dataset, self.val_batch_size)
540
+
541
+ # Initialize history tracking
542
+ self._history_best_prompt = seed_prompt
543
+ self._history_best_score = float("-inf")
544
+
545
+ return resource_name, seed_prompt, grad_dataset_iterator, val_dataset_iterator
546
+
547
+ def _sample_parent_prompts(
548
+ self,
549
+ beam: List[VersionedPromptTemplate],
550
+ round_num: int,
551
+ ) -> List[Tuple[int, VersionedPromptTemplate]]:
552
+ """
553
+ Sample parent prompts from the current beam for generating new candidates.
554
+
555
+ If the beam has fewer prompts than beam_width, replicates existing prompts.
556
+ Otherwise, randomly samples beam_width prompts.
557
+
558
+ Args:
559
+ beam: Current list of prompt templates in the beam.
560
+ round_num: Current round number (for logging, 0-indexed).
561
+
562
+ Returns:
563
+ List of parent prompts to generate children from.
564
+ """
565
+ display_round = round_num + 1
566
+ if len(beam) < self.beam_width:
567
+ prefix = self._format_log_prefix(round_num=display_round)
568
+ self._log(
569
+ logging.WARNING,
570
+ f"Beam width is currently {self.beam_width}, but only {len(beam)} prompts in beam. Replicating all prompts.",
571
+ prefix=prefix,
572
+ )
573
+ return [(i % len(beam), beam[i % len(beam)]) for i in range(self.beam_width)]
574
+
575
+ selected_indices = random.sample(range(len(beam)), self.beam_width)
576
+ return [(idx, beam[idx]) for idx in selected_indices]
577
+
578
+ async def _generate_candidate_prompts(
579
+ self,
580
+ parent_prompts: List[Tuple[int, VersionedPromptTemplate]],
581
+ resource_name: str,
582
+ grad_dataset_iterator: Iterator[Sequence[T_task]],
583
+ round_num: int,
584
+ ) -> List[VersionedPromptTemplate]:
585
+ """
586
+ Generate new candidate prompts from parents using textual gradients.
587
+
588
+ For each parent prompt, generates branch_factor new candidates by:
589
+
590
+ 1. Evaluating the parent on a training batch
591
+ 2. Computing textual gradient
592
+ 3. Applying edit to generate improved prompt
593
+
594
+ Args:
595
+ parent_prompts: List of parent prompts to generate children from.
596
+ resource_name: Name to register prompts under in the store.
597
+ grad_dataset_iterator: Iterator over training data batches.
598
+ round_num: Current round number (for logging, 0-indexed).
599
+
600
+ Returns:
601
+ List of newly generated prompt templates.
602
+ """
603
+ display_round = round_num + 1
604
+ round_prefix = self._format_log_prefix(round_num=display_round)
605
+ self._log(
606
+ logging.INFO,
607
+ f"Applying {self.branch_factor} edits to each of the {len(parent_prompts)} parents based on "
608
+ "gradients computed on training dataset",
609
+ prefix=round_prefix,
610
+ )
611
+
612
+ parent_prompts_str = [
613
+ f"{p.version}:{p.score:.3f}" if p.score is not None else p.version for _, p in parent_prompts
614
+ ]
615
+ self._log(
616
+ logging.INFO,
617
+ f"Parent prompts: {', '.join(parent_prompts_str)}",
618
+ prefix=round_prefix,
619
+ )
620
+
621
+ candidates: List[VersionedPromptTemplate] = []
622
+ used_beam_indices: Set[int] = set()
623
+ for real_beam_idx, (beam_idx, prompt) in enumerate(parent_prompts):
624
+ if beam_idx in used_beam_indices:
625
+ beam_prefix = self._format_log_prefix(
626
+ round_num=display_round,
627
+ beam_idx=beam_idx + 1,
628
+ prompt_version=prompt.version,
629
+ )
630
+ self._log(
631
+ logging.WARNING,
632
+ "Duplicated beam index found. Might be caused by beam_width too high. "
633
+ + f"The real index of this beam is {real_beam_idx + 1}.",
634
+ prefix=beam_prefix,
635
+ )
636
+ else:
637
+ used_beam_indices.add(beam_idx)
638
+ for branch_idx in range(self.branch_factor):
639
+ parent_prefix = self._format_log_prefix(
640
+ round_num=display_round,
641
+ beam_idx=beam_idx + 1,
642
+ branch_idx=branch_idx + 1,
643
+ prompt_version=prompt.version,
644
+ )
645
+ baseline_score = f"{prompt.score:.3f}" if prompt.score is not None else "N/A"
646
+ self._log(
647
+ logging.INFO,
648
+ f"Use parent prompt {prompt.version} as a baseline to generate a new prompt. Baseline score: {baseline_score}",
649
+ prefix=parent_prefix,
650
+ )
651
+ grad_samples = next(grad_dataset_iterator)
652
+ rollout_results, _ = await self.evaluate_prompt_on_batch(
653
+ prompt,
654
+ resource_name,
655
+ grad_samples,
656
+ mode="train",
657
+ prefix=parent_prefix,
658
+ )
659
+ new_prompt = await self.textual_gradient_and_apply_edit(
660
+ prompt,
661
+ rollout_results,
662
+ prefix=parent_prefix,
663
+ )
664
+ if not new_prompt:
665
+ self._log(
666
+ logging.ERROR,
667
+ f"Failed to compute edit for prompt: {prompt.prompt_template.template}",
668
+ prefix=parent_prefix,
669
+ )
670
+ continue
671
+ new_prompt_template = PromptTemplate(template=new_prompt, engine="f-string")
672
+ versioned_candidate = self._create_versioned_prompt(new_prompt_template)
673
+ self._log(
674
+ logging.INFO,
675
+ f"New prompt template created from parent {prompt.version}: {versioned_candidate.version}",
676
+ prefix=parent_prefix,
677
+ )
678
+ candidate_prefix = self._format_log_prefix(
679
+ round_num=display_round, prompt_version=versioned_candidate.version
680
+ )
681
+ self._log(
682
+ logging.INFO,
683
+ f"New prompt template created from parent {prompt.version}:\n```\n{new_prompt}\n```",
684
+ prefix=candidate_prefix,
685
+ )
686
+ candidates.append(versioned_candidate)
687
+
688
+ return candidates
689
+
690
+ async def _evaluate_and_select_beam(
691
+ self,
692
+ candidates: List[VersionedPromptTemplate],
693
+ resource_name: str,
694
+ val_dataset_iterator: Iterator[Sequence[T_task]],
695
+ round_num: int,
696
+ ) -> List[VersionedPromptTemplate]:
697
+ """
698
+ Evaluate all candidate prompts on validation data and select top-k for the beam.
699
+
700
+ Args:
701
+ candidates: List of candidate prompts to evaluate.
702
+ resource_name: Name to register prompts under in the store.
703
+ val_dataset_iterator: Iterator over validation data batches.
704
+ round_num: Current round number (for logging, 0-indexed).
705
+
706
+ Returns:
707
+ List of top beam_width prompts sorted by validation score (best first).
708
+
709
+ Raises:
710
+ ValueError: If no candidates remain after evaluation.
711
+ """
712
+ display_round = round_num + 1
713
+ round_prefix = self._format_log_prefix(round_num=display_round)
714
+ self._log(
715
+ logging.INFO,
716
+ f"Evaluating {len(candidates)} candidates on validation dataset",
717
+ prefix=round_prefix,
718
+ )
719
+
720
+ val_batch = next(val_dataset_iterator)
721
+
722
+ for prompt in candidates:
723
+ candidate_prefix = self._format_log_prefix(
724
+ round_num=display_round,
725
+ prompt_version=prompt.version,
726
+ )
727
+ _, score = await self.evaluate_prompt_on_batch(
728
+ prompt,
729
+ resource_name,
730
+ val_batch,
731
+ mode="val",
732
+ prefix=candidate_prefix,
733
+ )
734
+ prompt.score = score
735
+ self._log(
736
+ logging.INFO,
737
+ f"Candidate score: {score:.3f}",
738
+ prefix=candidate_prefix,
739
+ )
740
+
741
+ # Sort by score (descending) and select top beam_width
742
+ sorted_prompts = [
743
+ p for p in sorted(candidates, key=lambda x: x.score if x.score is not None else float("-inf"), reverse=True)
744
+ ]
745
+ selected_prompts = sorted_prompts[: self.beam_width]
746
+ selected_versions = [
747
+ f"{prompt.version}:{prompt.score:.3f}" if prompt.score is not None else prompt.version
748
+ for prompt in selected_prompts
749
+ ]
750
+ self._log(
751
+ logging.INFO,
752
+ f"Top {len(selected_prompts)} candidates on validation dataset: {selected_versions}",
753
+ prefix=round_prefix,
754
+ )
755
+
756
+ if len(selected_prompts) == 0:
757
+ raise ValueError("No beam candidates any more")
758
+
759
+ return selected_prompts
760
+
761
+ async def _update_best_prompt(
762
+ self,
763
+ beam: List[VersionedPromptTemplate],
764
+ resource_name: str,
765
+ val_dataset: Dataset[T_task],
766
+ round_num: int,
767
+ ) -> None:
768
+ """
769
+ Evaluate the best prompt in the beam on the full validation set and update history.
770
+
771
+ Args:
772
+ beam: Current beam of prompts (sorted, best first).
773
+ resource_name: Name to register prompts under in the store.
774
+ val_dataset: Full validation dataset.
775
+ round_num: Current round number (for logging, 0-indexed).
776
+ """
777
+ display_round = round_num + 1
778
+ best_prompt = beam[0]
779
+ prefix = self._format_log_prefix(round_num=display_round, prompt_version=best_prompt.version)
780
+ _, best_score = await self.evaluate_prompt_on_batch(
781
+ best_prompt,
782
+ resource_name,
783
+ cast(Sequence[T_task], val_dataset),
784
+ mode="val",
785
+ prefix=prefix,
786
+ )
787
+ self._log(
788
+ logging.INFO,
789
+ f"Beam leader score: {best_score:.3f}",
790
+ prefix=prefix,
791
+ )
792
+
793
+ if best_score > self._history_best_score:
794
+ prev = self._history_best_score
795
+ self._log(
796
+ logging.INFO,
797
+ f"Best prompt updated. New best score: {best_score:.3f} (prev: {prev:.3f})",
798
+ prefix=prefix,
799
+ )
800
+ self._history_best_prompt = best_prompt.prompt_template
801
+ self._history_best_score = best_score
802
+ self._history_best_version = best_prompt.version
803
+ else:
804
+ self._log(
805
+ logging.WARNING,
806
+ f"Best prompt not updated. Current score: {best_score:.3f} vs. history best: {self._history_best_score:.3f})",
807
+ prefix=prefix,
808
+ )
809
+
810
+ @with_llm_proxy()
811
+ @with_store
812
+ async def run(
813
+ self,
814
+ store: LightningStore, # Injected by decorator - callers should not provide this parameter
815
+ llm_proxy: Optional[LLMProxy], # Injected by decorator - callers should not provide this parameter
816
+ train_dataset: Optional[Dataset[T_task]] = None,
817
+ val_dataset: Optional[Dataset[T_task]] = None,
818
+ ) -> None:
819
+ """
820
+ Execute the APO algorithm to optimize prompts through beam search with textual gradients.
821
+
822
+ The algorithm performs iterative prompt optimization over multiple rounds:
823
+
824
+ - Each round: samples parent prompts, generates new candidates via textual gradients,
825
+ evaluates all candidates on validation data, and keeps the top performers
826
+ - Tracks the historically best prompt across all rounds
827
+ - Uses different training data samples for each gradient computation to ensure diversity
828
+
829
+ Args:
830
+ train_dataset: Dataset of tasks for computing textual gradients. Required.
831
+ val_dataset: Dataset of tasks for evaluating and selecting prompts. Required.
832
+
833
+ Raises:
834
+ ValueError: If train_dataset or val_dataset is None, or if resources are not set.
835
+ """
836
+ # Initialize beam search
837
+ resource_name, seed_prompt, grad_iterator, val_iterator = self._initialize_beam(train_dataset, val_dataset)
838
+
839
+ if self._poml_trace:
840
+ poml.set_trace(trace_dir="pomltrace")
841
+
842
+ # Validation datasets are guaranteed to be non-None after initialization
843
+ assert val_dataset is not None
844
+
845
+ # Start with seed prompt in the beam
846
+ seed_versioned = self._create_versioned_prompt(seed_prompt)
847
+ beam: List[VersionedPromptTemplate] = [seed_versioned]
848
+ self._history_best_prompt = seed_prompt
849
+ self._history_best_version = seed_versioned.version
850
+
851
+ # Optionally evaluate seed prompt on validation set to establish baseline
852
+ if self.run_initial_validation:
853
+ seed_prefix = self._format_log_prefix(round_num=0, prompt_version=seed_versioned.version)
854
+ self._log(
855
+ logging.INFO,
856
+ "Evaluating seed prompt on validation dataset before optimization...",
857
+ prefix=seed_prefix,
858
+ )
859
+ _, seed_score = await self.evaluate_prompt_on_batch(
860
+ seed_versioned,
861
+ resource_name,
862
+ cast(Sequence[T_task], val_dataset),
863
+ mode="val",
864
+ prefix=seed_prefix,
865
+ )
866
+ self._log(
867
+ logging.INFO,
868
+ f"Seed prompt baseline score: {seed_score:.3f}",
869
+ prefix=seed_prefix,
870
+ )
871
+ self._history_best_prompt = seed_prompt
872
+ self._history_best_score = seed_score
873
+ self._history_best_version = seed_versioned.version
874
+
875
+ # Run beam search for specified number of rounds
876
+ for rnd in range(self.beam_rounds):
877
+ display_round = rnd + 1
878
+ round_prefix = self._format_log_prefix(round_num=display_round)
879
+ self._log(
880
+ logging.INFO,
881
+ f"Round {display_round}/{self.beam_rounds}...",
882
+ prefix=round_prefix,
883
+ )
884
+
885
+ # Sample parent prompts from current beam
886
+ parent_prompts = self._sample_parent_prompts(beam, rnd)
887
+
888
+ # Generate new candidate prompts from parents
889
+ new_candidates = await self._generate_candidate_prompts(parent_prompts, resource_name, grad_iterator, rnd)
890
+
891
+ # Combine existing beam with new candidates
892
+ all_candidates = [*beam, *new_candidates]
893
+
894
+ # Evaluate and select top-k prompts for next beam
895
+ beam = await self._evaluate_and_select_beam(all_candidates, resource_name, val_iterator, rnd)
896
+
897
+ # Update historically best prompt if improved
898
+ await self._update_best_prompt(beam, resource_name, val_dataset, rnd)