-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgepa.py
More file actions
1754 lines (1517 loc) · 66 KB
/
Copy pathgepa.py
File metadata and controls
1754 lines (1517 loc) · 66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import http.client
import json
import os
import tomllib
from collections.abc import Mapping
from contextlib import closing
from dataclasses import dataclass, field
from enum import StrEnum
from pathlib import Path
from typing import Any, ClassVar
from urllib.parse import urlparse
from pydantic import BaseModel, ConfigDict, Field
from synth_containers import ContainerConnection, PromptProgram
from ._synth_optimizers import GepaRun as _NativeGepaRun
from ._synth_optimizers import GepaRunResult
from ._synth_optimizers import default_proposer_best_practices as _default_proposer_best_practices
from .hosted import OptimizerAlgorithmSlug
class PolicyType(StrEnum):
DAG = "dag"
REACT = "react"
CODEX = "codex"
class RolloutTransport(StrEnum):
SYNC = "sync"
ASYNC = "async"
class GepaPipelineMode(StrEnum):
SYNC_SERIAL = "sync_serial"
ASYNC_PIPELINED = "async_pipelined"
FLASH_EVOLVE = "flash_evolve"
class GepaStalenessPolicy(StrEnum):
FULL = "full"
GUARDED = "guarded"
REFLECTIVE = "reflective"
class ContainerTomlSection(BaseModel):
model_config = ConfigDict(extra="ignore")
url: str | None = None
headers: dict[str, str] = Field(default_factory=dict)
auth_bearer_env: str | None = None
pool: "ContainerPoolTomlSection | None" = None
command: list[str] = Field(default_factory=list)
cwd: str | Path | None = None
startup_timeout_seconds: int | None = None
def to_connection(self) -> ContainerConnection:
return ContainerConnection(url=self.resolved_url())
def resolved_url(self) -> str:
if self.pool is None:
url = (self.url or "").strip()
if not url:
raise ValueError("container.url or container.pool.pool_id is required")
return url
return self.pool.resolved_url()
def resolved_headers(self) -> dict[str, str]:
headers = dict(self.headers)
if self.auth_bearer_env:
headers.setdefault("authorization", _bearer_header_from_env(self.auth_bearer_env))
elif self.pool is not None and not _has_authorization_header(headers):
headers["authorization"] = _bearer_header_from_env(self.pool.api_key_env)
return headers
def resolved_auth_bearer_env(self) -> str | None:
if self.auth_bearer_env:
return self.auth_bearer_env
if self.pool is not None and not _has_authorization_header(self.headers):
return self.pool.api_key_env
return None
class ContainerPoolTomlSection(BaseModel):
model_config = ConfigDict(extra="forbid")
pool_id: str = Field(min_length=1)
task_id: str | None = None
backend_base_url: str | None = None
api_key_env: str = "SYNTH_API_KEY"
def resolved_url(self) -> str:
pool_id = _path_segment(self.pool_id, "container.pool.pool_id")
backend_base = _normalize_backend_base_url(
self.backend_base_url or _backend_base_url_from_env() or "https://api.usesynth.ai"
)
if self.task_id:
task_id = _path_segment(self.task_id, "container.pool.task_id")
return f"{backend_base}/v1/pools/{pool_id}/tasks/{task_id}/container"
return f"{backend_base}/v1/pools/{pool_id}/container"
class RunSettingsTomlSection(BaseModel):
model_config = ConfigDict(extra="ignore")
run_id: str = "gepa_sdk_run"
output_dir: str | Path = "runs"
seed: int = 0
correlation: dict[str, Any] | None = None
def to_domain(self) -> "RunSettings":
return RunSettings(
run_id=self.run_id,
output_dir=self.output_dir,
seed=self.seed,
correlation=dict(self.correlation) if self.correlation else None,
)
class UsageRegistrationTomlSection(BaseModel):
model_config = ConfigDict(extra="ignore")
enabled: bool = True
def to_domain(self) -> "UsageRegistrationConfig":
return UsageRegistrationConfig(enabled=self.enabled)
class TasksetTomlSection(BaseModel):
model_config = ConfigDict(extra="ignore")
train_split: str = "train"
heldout_split: str = "test"
train_ids: list[str] = Field(default_factory=lambda: ["train:0"])
heldout_ids: list[str] = Field(default_factory=lambda: ["heldout:0"])
filters: dict[str, Any] = Field(default_factory=dict)
def to_domain(self) -> "TasksetSelection":
return TasksetSelection(
train_split=self.train_split,
heldout_split=self.heldout_split,
train_ids=list(self.train_ids),
heldout_ids=list(self.heldout_ids),
filters=dict(self.filters),
)
class ProposerPromptTomlSection(BaseModel):
model_config = ConfigDict(extra="ignore")
best_practices: str | None = None
best_practices_path: str | Path | None = None
def to_domain(self, base_dir: Path) -> "ProposerPromptConfig | None":
if self.best_practices is None and self.best_practices_path is None:
return None
best_practices_path = self.best_practices_path
if best_practices_path is not None:
path = Path(best_practices_path)
best_practices_path = path if path.is_absolute() else base_dir / path
return ProposerPromptConfig(
best_practices=self.best_practices,
best_practices_path=best_practices_path,
)
class ProposerDockerTomlSection(BaseModel):
model_config = ConfigDict(extra="ignore")
image: str | None = None
workspace_mount_path: str = "/workspace"
network: str = "bridge"
extra_env: dict[str, str] = Field(default_factory=dict)
def to_domain(self) -> "ProposerDockerConfig | None":
if self.image is None:
return None
return ProposerDockerConfig(
image=self.image,
workspace_mount_path=self.workspace_mount_path,
network=self.network,
extra_env=dict(self.extra_env),
)
class NanoCodexTomlSection(BaseModel):
model_config = ConfigDict(extra="forbid")
enabled: bool = False
mode: str = "live"
max_turns_per_session: int = 16
record_dir: str | Path | None = None
replay_dir: str | Path | None = None
allowed_tools: list[str] = Field(
default_factory=lambda: ["search", "read", "apply_patch", "exec"]
)
def to_domain(self, base_dir: Path) -> "NanoCodexConfig":
def resolve(path_value: str | Path | None) -> Path | None:
if path_value is None:
return None
path = Path(path_value)
return path if path.is_absolute() else base_dir / path
return NanoCodexConfig(
enabled=self.enabled,
mode=self.mode,
max_turns_per_session=self.max_turns_per_session,
record_dir=resolve(self.record_dir),
replay_dir=resolve(self.replay_dir),
allowed_tools=list(self.allowed_tools),
)
class ProposerTomlSection(BaseModel):
model_config = ConfigDict(extra="ignore")
backend: str = "codex_app_server"
runtime_substrate: str = "local"
execution_mode: str = "local_process"
provider: str = "openai"
api_family: str = "chat_completions"
base_url: str | None = None
model: str | None = "gpt-5.4-mini"
allow_unverified_model: bool = False
reasoning_effort: str | None = "medium"
service_tier: str | None = None
auth_mode: str = "api_key"
api_key_env: str | None = "OPENAI_API_KEY"
copy_host_auth: bool = False
codex_home: str | Path | None = None
timeout_seconds: int = 900
message_stall_timeout_seconds: int = 120
sandbox_mode: str | None = "workspace-write"
approval_policy: str | None = "never"
command: list[str] = Field(default_factory=list)
prompt: ProposerPromptTomlSection = Field(default_factory=ProposerPromptTomlSection)
docker: ProposerDockerTomlSection | None = None
nano_codex: NanoCodexTomlSection = Field(default_factory=NanoCodexTomlSection)
def to_domain(self, base_dir: Path) -> "ProposerConfig":
codex_home = None
if self.codex_home is not None:
path = Path(self.codex_home)
codex_home = path if path.is_absolute() else base_dir / path
# ChatGPT-subscription auth forbids api_key_env. Since this field defaults
# to "OPENAI_API_KEY" and TOML cannot express null to override it, null it
# out explicitly for chatgpt auth (mirrors the service.rs chatgpt path).
api_key_env = self.api_key_env
if str(self.auth_mode).strip().lower() == "chatgpt":
api_key_env = None
return ProposerConfig(
backend=self.backend,
runtime_substrate=self.runtime_substrate,
execution_mode=self.execution_mode,
provider=self.provider,
api_family=self.api_family,
base_url=self.base_url,
model=self.model,
allow_unverified_model=self.allow_unverified_model,
reasoning_effort=self.reasoning_effort,
service_tier=self.service_tier,
auth_mode=self.auth_mode,
api_key_env=api_key_env,
copy_host_auth=self.copy_host_auth,
codex_home=codex_home,
timeout_seconds=self.timeout_seconds,
message_stall_timeout_seconds=self.message_stall_timeout_seconds,
sandbox_mode=self.sandbox_mode,
approval_policy=self.approval_policy,
command=list(self.command),
prompt=self.prompt.to_domain(base_dir),
docker=self.docker.to_domain() if self.docker is not None else None,
nano_codex=self.nano_codex.to_domain(base_dir),
)
class PolicyTomlSection(BaseModel):
model_config = ConfigDict(extra="ignore")
enabled: bool = True
provider: str = "openai"
model: str = "gpt-4.1-nano"
api_key_env: str | None = "OPENAI_API_KEY"
policy_type: PolicyType | str = PolicyType.DAG
api_family: str = "chat_completions"
base_url: str | None = None
inference_url: str | None = None
max_tokens: int | None = None
disable_reasoning: str = "auto"
tool_call_style: str = "none"
proxy_mode: str = "proxy_only"
credential_mode: str = "byok"
config: dict[str, Any] = Field(default_factory=dict)
def to_domain(self) -> "PolicyConfig | None":
if not self.enabled:
return None
return PolicyConfig(
provider=self.provider,
model=self.model,
api_key_env=self.api_key_env,
policy_type=self.policy_type,
api_family=self.api_family,
base_url=self.base_url,
inference_url=self.inference_url,
max_tokens=self.max_tokens,
disable_reasoning=self.disable_reasoning,
tool_call_style=self.tool_call_style,
proxy_mode=self.proxy_mode,
credential_mode=self.credential_mode,
config=dict(self.config),
)
class GepaPipelineWorkersTomlSection(BaseModel):
model_config = ConfigDict(extra="ignore")
propose: int = 1
rollout: int = 8
evaluate: int = 1
class GepaSpeculativeCompletionTomlSection(BaseModel):
model_config = ConfigDict(extra="ignore")
enabled: bool = False
alpha: float = 0.25
class GepaAdaptiveStageWorkersTomlSection(BaseModel):
model_config = ConfigDict(extra="ignore")
enabled: bool = False
min: int = 1
max: int = 128
backlog_threshold: int = 2
stale_gap_threshold: int = 2
class GepaAdaptiveRolloutConcurrencyTomlSection(BaseModel):
model_config = ConfigDict(extra="forbid")
enabled: bool | None = None
initial: int | None = Field(default=None, ge=1)
min: int | None = Field(default=None, ge=1)
max: int | None = Field(default=None, ge=1)
increase_step: int | None = Field(default=None, ge=1)
decrease_step: int | None = Field(default=None, ge=1)
increase_after_successes: int | None = Field(default=None, ge=1)
overload_status_codes: list[int] | None = None
class GepaPipelineTomlSection(BaseModel):
model_config = ConfigDict(extra="ignore")
mode: GepaPipelineMode | str = GepaPipelineMode.SYNC_SERIAL
staleness_policy: GepaStalenessPolicy | str = GepaStalenessPolicy.FULL
delta_max: int = 2
max_in_flight_candidates: int = 1
adaptive_rollout_concurrency: GepaAdaptiveRolloutConcurrencyTomlSection | None = None
workers: GepaPipelineWorkersTomlSection = Field(default_factory=GepaPipelineWorkersTomlSection)
speculative_completion: GepaSpeculativeCompletionTomlSection = Field(
default_factory=GepaSpeculativeCompletionTomlSection
)
adaptive_stage_workers: GepaAdaptiveStageWorkersTomlSection = Field(
default_factory=GepaAdaptiveStageWorkersTomlSection
)
class ObjectiveAcceptanceTomlSection(BaseModel):
model_config = ConfigDict(extra="ignore")
protected_objectives: list[str] = Field(default_factory=list)
min_objective_delta: float | None = None
objective_regression_tolerance: float | None = None
class GepaTaskPoolsTomlSection(BaseModel):
model_config = ConfigDict(extra="forbid")
pareto: list[str] = Field(default_factory=list)
minibatch: list[str] = Field(default_factory=list)
reflection: list[str] = Field(default_factory=list)
heldout: list[str] = Field(default_factory=list)
def to_domain(self) -> "GepaTaskPools":
return GepaTaskPools(
pareto=list(self.pareto),
minibatch=list(self.minibatch),
reflection=list(self.reflection),
heldout=list(self.heldout),
)
class GepaTomlSection(BaseModel):
model_config = ConfigDict(extra="ignore")
max_cost_usd: float = 0.0
max_time_seconds: int | None = None
max_prompt_tokens: int | None = None
max_completion_tokens: int | None = None
max_total_tokens: int | None = None
proposer_estimated_cost_usd: float | None = None
proposer_estimated_prompt_tokens: int | None = None
proposer_estimated_completion_tokens: int | None = None
proposer_estimated_total_tokens: int | None = None
rollout_estimated_cost_usd: float | None = None
rollout_estimated_prompt_tokens: int | None = None
rollout_estimated_completion_tokens: int | None = None
rollout_estimated_total_tokens: int | None = None
rollout_estimated_wall_seconds: int | None = None
max_generations: int = 1
proposals_per_generation: int = 1
minibatch_size: int = 1
max_total_rollouts: int = 16
max_train_rollouts: int | None = None
max_heldout_rollouts: int | None = None
minibatch_accept_margin: float = 0.0
rollout_failure_rate_tolerance: float = 0.25
rollout_submission_mode: RolloutTransport | str = RolloutTransport.ASYNC
rollout_async_timeout_seconds: int = 600
rollout_chunk_size: int | None = None
pipeline: GepaPipelineTomlSection = Field(default_factory=GepaPipelineTomlSection)
objective_keys: list[str] = Field(default_factory=list)
objective_directions: dict[str, str] = Field(default_factory=dict)
selection_objective: str | None = None
frontier_type: str = "per_example"
minibatch_acceptance_criterion: str = "primary_improvement"
acceptance_criterion: str = "primary_improvement"
objective_acceptance: ObjectiveAcceptanceTomlSection = Field(
default_factory=ObjectiveAcceptanceTomlSection
)
task_pools: GepaTaskPoolsTomlSection = Field(default_factory=GepaTaskPoolsTomlSection)
def budget_config(self) -> "BudgetConfig":
return BudgetConfig(
max_cost_usd=self.max_cost_usd,
max_time_seconds=self.max_time_seconds,
max_prompt_tokens=self.max_prompt_tokens,
max_completion_tokens=self.max_completion_tokens,
max_total_tokens=self.max_total_tokens,
)
def gepa_budget_config(self) -> "GepaBudgetConfig":
return GepaBudgetConfig(
max_generations=self.max_generations,
proposals_per_generation=self.proposals_per_generation,
minibatch_size=self.minibatch_size,
max_total_rollouts=self.max_total_rollouts,
max_train_rollouts=self.max_train_rollouts,
max_heldout_rollouts=self.max_heldout_rollouts,
minibatch_accept_margin=self.minibatch_accept_margin,
rollout_failure_rate_tolerance=self.rollout_failure_rate_tolerance,
rollout_chunk_size=self.rollout_chunk_size,
proposer_estimated_cost_usd=self.proposer_estimated_cost_usd,
proposer_estimated_prompt_tokens=self.proposer_estimated_prompt_tokens,
proposer_estimated_completion_tokens=self.proposer_estimated_completion_tokens,
proposer_estimated_total_tokens=self.proposer_estimated_total_tokens,
rollout_estimated_cost_usd=self.rollout_estimated_cost_usd,
rollout_estimated_prompt_tokens=self.rollout_estimated_prompt_tokens,
rollout_estimated_completion_tokens=self.rollout_estimated_completion_tokens,
rollout_estimated_total_tokens=self.rollout_estimated_total_tokens,
rollout_estimated_wall_seconds=self.rollout_estimated_wall_seconds,
)
def pipeline_config(self) -> "GepaPipeline":
return GepaPipeline(
mode=self.pipeline.mode,
staleness_policy=self.pipeline.staleness_policy,
staleness_delta_max=self.pipeline.delta_max,
rollout_transport=self.rollout_submission_mode,
rollout_timeout_seconds=self.rollout_async_timeout_seconds,
candidate_concurrency=self.pipeline.max_in_flight_candidates,
proposer_concurrency=self.pipeline.workers.propose,
rollout_concurrency=self.pipeline.workers.rollout,
evaluator_concurrency=self.pipeline.workers.evaluate,
adaptive_rollout_concurrency=self.pipeline.adaptive_rollout_concurrency,
speculative_alpha=(
self.pipeline.speculative_completion.alpha
if self.pipeline.speculative_completion.enabled
else None
),
adaptive_stage_workers=self.pipeline.adaptive_stage_workers.enabled,
adaptive_stage_workers_max=self.pipeline.adaptive_stage_workers.max,
adaptive_stage_workers_backlog_threshold=(
self.pipeline.adaptive_stage_workers.backlog_threshold
),
adaptive_stage_workers_stale_gap_threshold=(
self.pipeline.adaptive_stage_workers.stale_gap_threshold
),
)
def objective_config(self) -> "ObjectiveConfig":
return ObjectiveConfig(
objective_keys=list(self.objective_keys),
objective_directions=dict(self.objective_directions),
selection_objective=self.selection_objective,
protected_objectives=list(self.objective_acceptance.protected_objectives),
frontier_type=self.frontier_type,
minibatch_acceptance_criterion=self.minibatch_acceptance_criterion,
acceptance_criterion=self.acceptance_criterion,
min_objective_delta=self.objective_acceptance.min_objective_delta,
objective_regression_tolerance=(
self.objective_acceptance.objective_regression_tolerance
),
)
class CacheTomlSection(BaseModel):
model_config = ConfigDict(extra="ignore")
mode: str = "readwrite"
path: str | Path | None = None
namespace: str | None = None
def to_domain(self) -> "CacheConfig":
return CacheConfig(
mode=self.mode,
path=self.path,
namespace=self.namespace,
)
class CandidateTomlSection(BaseModel):
model_config = ConfigDict(extra="ignore")
target_modules: list[str] = Field(default_factory=list)
class JesterkyWorkflowTomlSection(BaseModel):
model_config = ConfigDict(extra="ignore")
enabled: bool = False
spec: str = "examples/gepa_trace_annotate.json"
command: str = "jesterky"
actor: str = "codex"
model: str | None = None
concurrency: int = 4
timeout_seconds: int = 600
fail_closed: bool = True
def to_domain(self) -> "JesterkyWorkflowConfig":
return JesterkyWorkflowConfig(
enabled=bool(self.enabled),
spec=str(self.spec or "examples/gepa_trace_annotate.json"),
command=str(self.command or "jesterky"),
actor=str(self.actor or "codex"),
model=self.model,
concurrency=int(self.concurrency),
timeout_seconds=int(self.timeout_seconds),
fail_closed=bool(self.fail_closed),
)
class DiskBudgetTomlSection(BaseModel):
model_config = ConfigDict(extra="ignore")
enabled: bool = True
soft_limit_gb: float = 5.0
hard_limit_gb: float = 10.0
def to_domain(self) -> "DiskBudgetConfig":
return DiskBudgetConfig(
enabled=bool(self.enabled),
soft_limit_gb=float(self.soft_limit_gb),
hard_limit_gb=float(self.hard_limit_gb),
)
class GepaTomlDocument(BaseModel):
model_config = ConfigDict(extra="ignore")
container: ContainerTomlSection
run: RunSettingsTomlSection = Field(default_factory=RunSettingsTomlSection)
taskset: TasksetTomlSection = Field(default_factory=TasksetTomlSection)
proposer: ProposerTomlSection = Field(default_factory=ProposerTomlSection)
policy: PolicyTomlSection = Field(default_factory=PolicyTomlSection)
gepa: GepaTomlSection = Field(default_factory=GepaTomlSection)
jesterky_workflow: JesterkyWorkflowTomlSection = Field(
default_factory=JesterkyWorkflowTomlSection
)
cache: CacheTomlSection = Field(default_factory=CacheTomlSection)
disk_budget: DiskBudgetTomlSection = Field(default_factory=DiskBudgetTomlSection)
usage_registration: UsageRegistrationTomlSection = Field(
default_factory=UsageRegistrationTomlSection
)
candidate: CandidateTomlSection = Field(default_factory=CandidateTomlSection)
seed_candidate: dict[str, str] = Field(default_factory=dict)
def to_config(self, source_path: Path) -> "GepaConfig":
return GepaConfig(
container=self.container.to_connection(),
container_headers=dict(self.container.headers),
container_auth_bearer_env=self.container.resolved_auth_bearer_env(),
container_command=list(self.container.command),
container_cwd=self.container.cwd,
container_startup_timeout_seconds=self.container.startup_timeout_seconds,
taskset=self.taskset.to_domain(),
run=self.run.to_domain(),
objectives=self.gepa.objective_config(),
policy=self.policy.to_domain(),
proposer=self.proposer.to_domain(source_path.parent),
task_pools=self.gepa.task_pools.to_domain(),
budgets=self.gepa.gepa_budget_config(),
pipeline=self.gepa.pipeline_config(),
budget=self.gepa.budget_config(),
jesterky_workflow=self.jesterky_workflow.to_domain(),
cache=self.cache.to_domain(),
disk_budget=self.disk_budget.to_domain(),
usage_registration=self.usage_registration.to_domain(),
target_modules=list(self.candidate.target_modules),
seed_candidate=dict(self.seed_candidate),
_source_path=source_path,
)
class ContainerCapabilityMetadataPayload(BaseModel):
model_config = ConfigDict(extra="ignore")
policy_ready: bool = False
class ContainerCapabilitiesPayload(BaseModel):
model_config = ConfigDict(extra="ignore")
# Optional because this block is read on exactly one branch: a recipe that
# sets `policy = None` and needs the container to supply the policy. A
# recipe that configures its own policy never consults `policy_ready`, so
# requiring the block turned an unread field into a hard precondition and
# refused every container that does not advertise it -- which today is all
# of them. Defaulting to not-ready keeps the branch that *does* read it
# failing closed, with its own accurate message.
metadata: ContainerCapabilityMetadataPayload = Field(
default_factory=ContainerCapabilityMetadataPayload
)
class ContainerMetadataPayload(BaseModel):
model_config = ConfigDict(extra="ignore")
capabilities: ContainerCapabilitiesPayload
class ProgramTargetModulePayload(BaseModel):
model_config = ConfigDict(extra="ignore")
module_id: str = Field(min_length=1)
candidate_field: str = ""
objective: str = ""
class ProgramPayload(BaseModel):
model_config = ConfigDict(extra="ignore")
seed_candidate: dict[str, str] = Field(min_length=1)
target_modules: list[ProgramTargetModulePayload] = Field(min_length=1)
@dataclass(slots=True)
class RunSettings:
run_id: str = "gepa_sdk_run"
output_dir: str | Path = "runs"
seed: int = 0
#: `synth.correlation.v1`, set only when an experiment dispatched this run.
#: Carried verbatim so the manifest and run registry can be joined back to
#: the trial; nothing in this process reads it.
correlation: dict[str, Any] | None = None
def to_toml(self) -> dict[str, Any]:
payload: dict[str, Any] = {
"run_id": self.run_id,
"output_dir": str(self.output_dir),
"seed": int(self.seed),
}
if self.correlation is not None:
# Absent rather than empty: a run nobody dispatched must not grow a
# correlation key that later reads as a join to nothing.
payload["correlation"] = dict(self.correlation)
return payload
@dataclass(slots=True)
class UsageRegistrationConfig:
enabled: bool = True
def to_toml(self) -> dict[str, Any]:
return {"enabled": bool(self.enabled)}
@dataclass(slots=True)
class TasksetSelection:
train_split: str = "train"
heldout_split: str = "test"
train_ids: list[str] = field(default_factory=lambda: ["train:0"])
heldout_ids: list[str] = field(default_factory=lambda: ["heldout:0"])
filters: dict[str, Any] = field(default_factory=dict)
def to_toml(self) -> dict[str, Any]:
payload: dict[str, Any] = {
"train_split": self.train_split,
"heldout_split": self.heldout_split,
"train_ids": list(self.train_ids),
"heldout_ids": list(self.heldout_ids),
}
if self.filters:
payload["filters"] = dict(self.filters)
return payload
@dataclass(slots=True)
class GepaTaskPools:
pareto: list[str]
minibatch: list[str]
reflection: list[str]
heldout: list[str]
def validate(self) -> None:
for name, values in {
"pareto": self.pareto,
"minibatch": self.minibatch,
"reflection": self.reflection,
"heldout": self.heldout,
}.items():
if not values:
raise ValueError(f"GepaTaskPools.{name} must not be empty")
if any(not value.strip() for value in values):
raise ValueError(f"GepaTaskPools.{name} entries must not be empty")
minibatch = set(self.minibatch)
reflection = set(self.reflection)
missing = sorted(minibatch - reflection)
if missing:
raise ValueError(
"GepaTaskPools.minibatch must be a subset of GepaTaskPools.reflection; "
f"missing from reflection: {missing}"
)
heldout = set(self.heldout)
search_ids = set(self.pareto) | minibatch | reflection
overlaps = sorted(heldout & search_ids)
if overlaps:
raise ValueError(
"GepaTaskPools.heldout must be disjoint from pareto/minibatch/reflection; "
f"overlaps: {overlaps}"
)
def validate_against_taskset(self, train_ids: list[str], heldout_ids: list[str]) -> None:
"""Pools are split-local: search pools draw from train, heldout from heldout."""
unknown_search = sorted(
(set(self.pareto) | set(self.minibatch) | set(self.reflection)) - set(train_ids)
)
if unknown_search:
raise ValueError(
"GepaTaskPools pareto/minibatch/reflection ids must come from "
f"taskset.train_ids; unknown: {unknown_search}"
)
unknown_heldout = sorted(set(self.heldout) - set(heldout_ids))
if unknown_heldout:
raise ValueError(
"GepaTaskPools.heldout ids must come from taskset.heldout_ids; "
f"unknown: {unknown_heldout}"
)
def to_toml(self) -> dict[str, Any]:
self.validate()
return {
"pareto": list(self.pareto),
"minibatch": list(self.minibatch),
"reflection": list(self.reflection),
"heldout": list(self.heldout),
}
@dataclass(slots=True)
class ProposerPromptConfig:
best_practices: str | None = None
best_practices_path: str | Path | None = None
@classmethod
def from_defaults(cls) -> "ProposerPromptConfig":
return cls(best_practices=GepaDefaults.proposer_best_practices())
@classmethod
def from_path(cls, path: str | Path) -> "ProposerPromptConfig":
return cls(best_practices=Path(path).read_text())
def to_toml(self) -> dict[str, Any]:
if self.best_practices is not None and self.best_practices_path is not None:
raise ValueError(
"ProposerPromptConfig accepts at most one of best_practices or best_practices_path"
)
if self.best_practices is not None and not self.best_practices.strip():
raise ValueError("ProposerPromptConfig.best_practices must be non-empty when set")
return _drop_none(
{
"best_practices": self.best_practices,
"best_practices_path": (
str(self.best_practices_path) if self.best_practices_path is not None else None
),
}
)
@dataclass(frozen=True, slots=True)
class ProposerDefaults:
best_practices_md: str
@dataclass(frozen=True, slots=True)
class GepaDefaults:
proposer: ProposerDefaults
@staticmethod
def current() -> "GepaDefaults":
return GepaDefaults(
proposer=ProposerDefaults(best_practices_md=GepaDefaults.proposer_best_practices())
)
@staticmethod
def proposer_best_practices() -> str:
return _default_proposer_best_practices()
@staticmethod
def write_proposer_best_practices(path: str | Path) -> Path:
output_path = Path(path)
output_path.write_text(GepaDefaults.proposer_best_practices())
return output_path
@staticmethod
def proposer_config() -> "ProposerConfig":
return ProposerConfig()
@staticmethod
def config_template(*, container_url: str) -> "GepaConfig":
return GepaConfig(
container=ContainerConnection(url=container_url),
taskset=TasksetSelection(),
task_pools=GepaTaskPools(
pareto=["train:0"],
minibatch=["train:0"],
reflection=["train:0"],
heldout=["heldout:0"],
),
policy=None,
)
@dataclass(slots=True)
class ProposerDockerConfig:
image: str
workspace_mount_path: str = "/workspace"
network: str = "bridge"
extra_env: dict[str, str] = field(default_factory=dict)
def to_toml(self) -> dict[str, Any]:
return _drop_none(
{
"image": self.image,
"workspace_mount_path": self.workspace_mount_path,
"network": self.network,
"extra_env": dict(self.extra_env),
}
)
@dataclass(slots=True)
class NanoCodexConfig:
enabled: bool = False
mode: str = "live"
max_turns_per_session: int = 16
record_dir: str | Path | None = None
replay_dir: str | Path | None = None
allowed_tools: list[str] = field(
default_factory=lambda: ["search", "read", "apply_patch", "exec"]
)
def validate(self) -> None:
mode = self.mode.strip().lower().replace("-", "_")
if mode not in {"live", "replay"}:
raise ValueError("NanoCodexConfig.mode must be live or replay")
if self.max_turns_per_session <= 0:
raise ValueError("NanoCodexConfig.max_turns_per_session must be positive")
if mode == "replay" and self.replay_dir is None:
raise ValueError("NanoCodexConfig replay mode requires replay_dir")
if (
mode == "replay"
and self.record_dir is not None
and Path(self.record_dir).resolve() == Path(self.replay_dir).resolve()
):
raise ValueError(
"NanoCodexConfig replay record_dir must differ from replay_dir"
)
permitted = {"search", "read", "apply_patch", "exec"}
normalized = [tool.strip().lower().replace("-", "_") for tool in self.allowed_tools]
if not normalized or any(tool not in permitted for tool in normalized):
raise ValueError(
"NanoCodexConfig.allowed_tools must contain only search, read, apply_patch, exec"
)
if len(set(normalized)) != len(normalized):
raise ValueError("NanoCodexConfig.allowed_tools must not contain duplicates")
def to_toml(self) -> dict[str, Any]:
self.validate()
return _drop_none(
{
"enabled": bool(self.enabled),
"mode": self.mode,
"max_turns_per_session": int(self.max_turns_per_session),
"record_dir": str(self.record_dir) if self.record_dir is not None else None,
"replay_dir": str(self.replay_dir) if self.replay_dir is not None else None,
"allowed_tools": list(self.allowed_tools),
}
)
@dataclass(slots=True)
class ProposerConfig:
backend: str = "codex_app_server"
runtime_substrate: str = "local"
execution_mode: str = "local_process"
provider: str = "openai"
api_family: str = "chat_completions"
base_url: str | None = None
model: str | None = "gpt-5.4-mini"
allow_unverified_model: bool = False
reasoning_effort: str | None = "medium"
service_tier: str | None = None
auth_mode: str = "api_key"
api_key_env: str | None = "OPENAI_API_KEY"
copy_host_auth: bool = False
codex_home: str | Path | None = None
timeout_seconds: int = 900
message_stall_timeout_seconds: int = 120
sandbox_mode: str | None = "workspace-write"
approval_policy: str | None = "never"
command: list[str] = field(default_factory=list)
prompt: ProposerPromptConfig | None = None
docker: ProposerDockerConfig | None = None
nano_codex: NanoCodexConfig = field(default_factory=NanoCodexConfig)
@classmethod
def local(cls, **kwargs: Any) -> "ProposerConfig":
return cls(runtime_substrate="local", **kwargs)
@classmethod
def docker_substrate(cls, *, image: str, **kwargs: Any) -> "ProposerConfig":
return cls(
runtime_substrate="docker",
docker=ProposerDockerConfig(image=image),
**kwargs,
)
def to_toml(self) -> dict[str, Any]:
auth_mode = str(self.auth_mode).strip().lower().replace("-", "_")
if self.nano_codex.enabled:
if auth_mode not in {"chatgpt", "host"}:
raise ValueError(
"nano_codex requires proposer auth_mode='chatgpt' or 'host'"
)
if not self.copy_host_auth or self.api_key_env is not None:
raise ValueError(
"nano_codex requires copy_host_auth=True and api_key_env=None"
)
if str(self.runtime_substrate).strip().lower() != "local":
raise ValueError("nano_codex currently requires runtime_substrate='local'")
api_key_env = self.api_key_env
if auth_mode in {"chatgpt", "host"}:
api_key_env = None
payload = _drop_none(
{
"backend": self.backend,
"runtime_substrate": self.runtime_substrate,
"execution_mode": self.execution_mode,
"provider": self.provider,
"api_family": self.api_family,
"base_url": self.base_url,
"model": self.model,
"allow_unverified_model": bool(self.allow_unverified_model),
"reasoning_effort": self.reasoning_effort,
"service_tier": self.service_tier,
"auth_mode": self.auth_mode,
"api_key_env": api_key_env,
"copy_host_auth": bool(self.copy_host_auth),
"codex_home": str(self.codex_home) if self.codex_home is not None else None,
"timeout_seconds": int(self.timeout_seconds),
"message_stall_timeout_seconds": int(self.message_stall_timeout_seconds),
"sandbox_mode": self.sandbox_mode,
"approval_policy": self.approval_policy,
"command": list(self.command),
}
)
if self.prompt is not None:
prompt = self.prompt.to_toml()
if prompt:
payload["prompt"] = prompt
if self.docker is not None:
payload["docker"] = self.docker.to_toml()
payload["nano_codex"] = self.nano_codex.to_toml()
return payload