Engine
engine ¶
Async evolution engine for gepa-adk.
This module provides the AsyncGEPAEngine class that orchestrates the core evolution loop for optimizing agent instructions using the GEPA algorithm with async support.
| ATTRIBUTE | DESCRIPTION |
|---|---|
AsyncGEPAEngine | Main evolution engine class. TYPE: |
Examples:
Basic usage:
from gepa_adk.engine import AsyncGEPAEngine
from gepa_adk.domain.models import EvolutionConfig, Candidate
engine = AsyncGEPAEngine(
adapter=my_adapter,
config=EvolutionConfig(max_iterations=50),
initial_candidate=Candidate(components={"instruction": "Be helpful"}),
batch=training_data,
)
result = await engine.run()
See Also
gepa_adk.ports.adapter.AsyncGEPAAdapter: Protocol for adapters.gepa_adk.domain.models: Domain models used by the engine.
REFLECTION_INSTRUCTION module-attribute ¶
REFLECTION_INSTRUCTION = "## Component Text to Improve\n{component_text}\n\n## Trials\n{trials}\n\nPropose an improved version of the component text based on the trials above.\nReturn ONLY the improved component text, nothing else."
Default instruction template for reflection agents.
Uses ADK's native template substitution syntax ({key}) to inject session state values. ADK automatically replaces these placeholders with values from session.state[key] during instruction processing.
The template contains two placeholders:
{component_text}: The current text being evolved (str){trials}: JSON-serialized list of trial records (str)
The instruction is processed by ADK's inject_session_state() function before being sent to the LLM.
Examples:
Use the default instruction with a custom agent:
from google.adk.agents import LlmAgent
from gepa_adk.engine.adk_reflection import REFLECTION_INSTRUCTION
agent = LlmAgent(
name="reflector",
model="gemini-2.5-flash",
instruction=REFLECTION_INSTRUCTION,
)
Note
This replaces the previous workaround of embedding data in user messages via Python f-strings.
SESSION_STATE_KEYS module-attribute ¶
Expected keys and types in ADK session state for reflection.
The reflection agent accesses these keys via {key} template syntax in its instruction. ADK's inject_session_state() automatically substitutes placeholders with session state values.
Keys
component_text: The text content being evolved (str). trials: JSON-serialized list of trial records (str). Each trial contains {input, output, feedback, trajectory}.
ReflectionFn module-attribute ¶
Async callable for reflection.
Signature: (component_text: str, trials: list[dict]) -> str
Optionally supports: (component_text, trials, component_name: str | None) -> str
Takes current component text and trials, optionally with component name, returns proposed component text. The component_name parameter (when supported) enables component-aware auto-selection of reflection agents.
Note
For backward compatibility, reflection functions can accept either: - 2 parameters: (component_text, trials) - 3 parameters: (component_text, trials, component_name)
The proposer will inspect the function signature and call appropriately.
AsyncGEPAEngine ¶
Bases: Generic[DataInst, Trajectory, RolloutOutput]
flowchart TD
gepa_adk.engine.AsyncGEPAEngine[AsyncGEPAEngine]
click gepa_adk.engine.AsyncGEPAEngine href "" "gepa_adk.engine.AsyncGEPAEngine"
Async evolution engine orchestrating the GEPA loop.
This engine executes the core evolution algorithm: 1. Evaluate baseline candidate 2. For each iteration until max_iterations or convergence: a. Generate reflective dataset from traces b. Propose new candidate text c. Evaluate proposal d. Accept if improves above threshold e. Record iteration 3. Return frozen EvolutionResult
| ATTRIBUTE | DESCRIPTION |
|---|---|
adapter | Implementation of AsyncGEPAAdapter protocol. TYPE: |
config | Evolution parameters. TYPE: |
Examples:
Basic usage:
from gepa_adk.engine import AsyncGEPAEngine
from gepa_adk.domain.models import EvolutionConfig, Candidate
engine = AsyncGEPAEngine(
adapter=my_adapter,
config=EvolutionConfig(max_iterations=50),
initial_candidate=Candidate(components={"instruction": "Be helpful"}),
batch=training_data,
)
result = await engine.run()
print(f"Final score: {result.final_score}")
Note
Avoid reusing engine instances after run() completes.
Source code in src/gepa_adk/engine/async_engine.py
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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 | |
pareto_state property ¶
pareto_state: ParetoState | None
Return the current Pareto state, if initialized.
__init__ ¶
__init__(
adapter: AsyncGEPAAdapter[
DataInst, Trajectory, RolloutOutput
],
config: EvolutionConfig,
initial_candidate: Candidate,
batch: list[DataInst],
valset: list[DataInst] | None = None,
candidate_selector: CandidateSelectorProtocol
| None = None,
component_selector: ComponentSelectorProtocol
| None = None,
evaluation_policy: EvaluationPolicyProtocol
| None = None,
merge_proposer: ProposerProtocol | None = None,
) -> None
Initialize the evolution engine.
| PARAMETER | DESCRIPTION |
|---|---|
adapter | Implementation of AsyncGEPAAdapter protocol for evaluation and proposal generation. TYPE: |
config | Evolution parameters controlling iterations, thresholds, and early stopping. TYPE: |
initial_candidate | Starting candidate with 'instruction' component. TYPE: |
batch | Trainset data instances for reflection and mutation. TYPE: |
valset | Optional validation data for scoring candidates. Defaults to trainset when omitted. TYPE: |
candidate_selector | Optional selector strategy for Pareto-aware candidate sampling. TYPE: |
component_selector | Optional selector strategy for choosing which components to update. Defaults to RoundRobinComponentSelector. TYPE: |
evaluation_policy | Optional policy for selecting which validation examples to evaluate per iteration. Defaults to FullEvaluationPolicy. TYPE: |
merge_proposer | Optional proposer for merge operations. If provided and config.use_merge is True, merge proposals will be attempted after successful mutations. TYPE: |
| RAISES | DESCRIPTION |
|---|---|
ValueError | If batch is empty or initial_candidate lacks 'instruction'. |
ConfigurationError | If config validation fails (via EvolutionConfig). |
Examples:
Creating an engine:
engine = AsyncGEPAEngine(
adapter=my_adapter,
config=EvolutionConfig(max_iterations=50),
initial_candidate=Candidate(components={"instruction": "Be helpful"}),
batch=training_data,
candidate_selector=selector,
)
Note
Configures trainset and valset routing for reflection and scoring.
Source code in src/gepa_adk/engine/async_engine.py
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 | |
run async ¶
run() -> EvolutionResult
Execute the evolution loop.
Runs the core evolution loop: 1. Evaluate baseline candidate 2. For each iteration until max_iterations or convergence: a. Generate reflective dataset from traces b. Propose new candidate text c. Evaluate proposal d. Accept if improves above threshold e. Record iteration 3. Return frozen EvolutionResult
| RETURNS | DESCRIPTION |
|---|---|
EvolutionResult | EvolutionResult containing: - original_score: Baseline score before evolution - final_score: Best score achieved - evolved_component_text: Best component_text found - iteration_history: List of IterationRecord objects - total_iterations: Number of iterations performed |
| RAISES | DESCRIPTION |
|---|---|
Exception | Any exceptions from adapter methods propagate unchanged. |
Examples:
Running evolution:
result = await engine.run()
print(f"Improved: {result.improved}")
print(f"Best score: {result.final_score}")
Note
Outputs a frozen EvolutionResult after completing the evolution loop. Engine instance should not be reused after run() completes. Method is idempotent if called multiple times (restarts fresh). Fail-fast behavior: adapter exceptions are not caught.
Source code in src/gepa_adk/engine/async_engine.py
MergeProposer ¶
Proposer that combines two Pareto-optimal candidates via genetic crossover.
Selects two candidates from the frontier that share a common ancestor, identifies which components each improved, and creates a merged candidate that combines improvements from both branches.
| ATTRIBUTE | DESCRIPTION |
|---|---|
rng | Random number generator for candidate selection. TYPE: |
val_overlap_floor | Minimum overlapping validation coverage required. TYPE: |
max_attempts | Maximum merge attempts before giving up. TYPE: |
attempted_merges | Set of attempted merge triplets to prevent duplicates. TYPE: |
Examples:
Creating a merge proposer:
proposer = MergeProposer(rng=random.Random(42))
result = await proposer.propose(state)
if result:
print(f"Merged from parents {result.parent_indices}")
Note: A proposer that combines two Pareto-optimal candidates via genetic crossover. Selects candidates from the frontier that share a common ancestor and merges their complementary component improvements.
Source code in src/gepa_adk/engine/merge_proposer.py
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 | |
__init__ ¶
Initialize MergeProposer.
| PARAMETER | DESCRIPTION |
|---|---|
rng | Random number generator for candidate selection. TYPE: |
val_overlap_floor | Minimum overlapping validation examples required. TYPE: |
max_attempts | Maximum merge attempts before giving up. TYPE: |
Note
Creates a new MergeProposer instance with the specified random number generator and configuration parameters. The attempted_merges set is initialized empty to track merge attempts.
Source code in src/gepa_adk/engine/merge_proposer.py
propose async ¶
propose(
state: ParetoState, eval_batch: object | None = None
) -> ProposalResult | None
Attempt to merge two frontier candidates.
| PARAMETER | DESCRIPTION |
|---|---|
state | Current Pareto state with candidates, scores, and genealogy. Must contain at least 2 candidates on the Pareto frontier with a shared common ancestor for merge to succeed. TYPE: |
eval_batch | Ignored for merge proposals. Merge operations do not require evaluation batch data as they combine existing candidates. TYPE: |
| RETURNS | DESCRIPTION |
|---|---|
ProposalResult | None | ProposalResult | None: ProposalResult with merged candidate and both parent indices, |
ProposalResult | None | or None if merge not possible (e.g., no common ancestor, insufficient frontier, |
ProposalResult | None | or no complementary component changes). |
Examples:
Proposing a merge from evolution state:
proposer = MergeProposer(rng=random.Random(42))
result = await proposer.propose(state)
if result:
print(f"Merged from parents {result.parent_indices}")
print(f"Ancestor: {result.metadata['ancestor_idx']}")
Note
Operations select candidates from Pareto frontier only. Requires common ancestor and complementary component changes for successful merge. Validates minimum validation overlap before merging.
Source code in src/gepa_adk/engine/merge_proposer.py
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 | |
AsyncReflectiveMutationProposer ¶
Generates text mutations via LLM reflection.
This proposer takes a candidate's current component texts and feedback data, then uses an ADK reflection function to generate improved versions. It handles empty datasets gracefully by returning None without making LLM calls.
Terminology
- component: Evolvable unit with name + text (the "gear" being tuned)
- component_text: The text content of a component
- trial: One record {input, output, feedback, trajectory}
- trials: Collection of trial records for reflection
- proposed_component_text: The improved text for the same component
| ATTRIBUTE | DESCRIPTION |
|---|---|
adk_reflection_fn | ADK reflection function for proposing mutations. Created via TYPE: |
Examples:
Standard usage with ADK reflection agent:
from gepa_adk.engine import create_adk_reflection_fn
reflection_fn = create_adk_reflection_fn(reflection_agent, executor)
proposer = AsyncReflectiveMutationProposer(adk_reflection_fn=reflection_fn)
result = await proposer.propose(
candidate={"instruction": "Be helpful"},
reflective_dataset={"instruction": [trials]},
components_to_update=["instruction"],
)
Note
ADK-based reflection via adk_reflection_fn is the only supported approach. Use create_adk_reflection_fn() from gepa_adk.engine.adk_reflection to create the reflection function.
Source code in src/gepa_adk/engine/proposer.py
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 | |
__init__ ¶
__init__(adk_reflection_fn: ReflectionFn) -> None
Initialize the mutation proposer.
| PARAMETER | DESCRIPTION |
|---|---|
adk_reflection_fn | Async callable for ADK-based reflection. Takes (component_text, trials) and returns proposed text. Create with TYPE: |
| RAISES | DESCRIPTION |
|---|---|
ValueError | If adk_reflection_fn is None. |
Examples:
from gepa_adk.engine import create_adk_reflection_fn
reflection_fn = create_adk_reflection_fn(reflection_agent, executor)
proposer = AsyncReflectiveMutationProposer(adk_reflection_fn=reflection_fn)
Note
Configuration validation happens immediately to fail fast rather than waiting until the first propose() call.
Source code in src/gepa_adk/engine/proposer.py
propose async ¶
propose(
candidate: dict[str, str],
reflective_dataset: ReflectiveDataset,
components_to_update: list[str],
) -> ProposalResult
Propose mutated component text via LLM reflection.
| PARAMETER | DESCRIPTION |
|---|---|
candidate | Current candidate component texts. Keys are component names, values are component text. Example: {"instruction": "Be helpful and concise"} TYPE: |
reflective_dataset | Trials per component name. Each trial contains input, output, feedback, and optional trajectory. Example: {"instruction": [{ "input": "Hello", "output": "Hi there!", "feedback": {"score": 0.75, "feedback_text": "Could be more formal"}, "trajectory": {...} }]} TYPE: |
components_to_update | Component names to generate proposals for. Example: ["instruction"] TYPE: |
| RETURNS | DESCRIPTION |
|---|---|
ProposalResult | Dictionary mapping component names to proposed component text, or None if the reflective dataset is empty or has no entries for the requested components. TYPE: |
| RAISES | DESCRIPTION |
|---|---|
EvolutionError | If ADK reflection returns invalid response. |
Examples:
result = await proposer.propose(
candidate={"instruction": "Be helpful"},
reflective_dataset={
"instruction": [
{
"input": "I am the King",
"output": "Hey!",
"feedback": {"score": 0.3, "feedback_text": "Too casual"},
"trajectory": {...},
}
]
},
components_to_update=["instruction"],
)
# result: {"instruction": "Greet users formally..."}
Note
Output validation ensures that empty or None LLM responses raise EvolutionError rather than breaking the evolution loop silently.
Source code in src/gepa_adk/engine/proposer.py
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 | |
create_adk_reflection_fn ¶
create_adk_reflection_fn(
reflection_agent: Any | None,
executor: AgentExecutorProtocol,
session_service: Any | None = None,
output_key: str = "proposed_component_text",
output_field: str | None = None,
component_name: str | None = None,
model: str | None = None,
) -> ReflectionFn
Create a reflection function from an ADK LlmAgent.
This factory function creates an async callable that uses the Google ADK framework for reflection. The returned function can be passed to AsyncReflectiveMutationProposer as the adk_reflection_fn parameter.
Supports automatic agent selection based on component name when reflection_agent is None. Use this for component-aware reflection where different component types (e.g., output_schema vs instruction) require different validation tools and instructions.
| PARAMETER | DESCRIPTION |
|---|---|
reflection_agent | ADK LlmAgent configured with instruction containing TYPE: |
executor | AgentExecutorProtocol implementation for unified agent execution. Handles session management and execution, enabling feature parity across all agent types. TYPE: |
session_service | Optional session service for state management. Defaults to InMemorySessionService if None. Use custom services (e.g., DatabaseSessionService) for production deployments requiring session persistence. TYPE: |
output_key | Key in session state where ADK stores the agent's output. Defaults to "proposed_component_text". When set, the agent's output_key is configured to this value, and output is retrieved from session state after execution. Falls back to event-based extraction if the output_key is not found in session state. TYPE: |
output_field | Optional field name to extract from structured output. When the reflection agent has an output_schema (Pydantic model), the output is stored as a dict in session state. This parameter specifies which field to extract from that dict. If None (default), the entire output is returned as a string. TYPE: |
component_name | Optional component name for automatic agent selection. When reflection_agent is None, this is used to select the appropriate reflection agent from the component registry. Examples: "output_schema", "instruction". If None and reflection_agent is None, raises ValueError. TYPE: |
model | Model name/identifier for automatic agent selection. Required when reflection_agent is None. Examples: "gemini-2.5-flash", "gemini-2.5-flash". Ignored when reflection_agent is provided. TYPE: |
| RETURNS | DESCRIPTION |
|---|---|
ReflectionFn | Async callable matching ReflectionFn signature that generates proposed |
ReflectionFn | component text via the ADK agent. |
| RAISES | DESCRIPTION |
|---|---|
Exception | If ADK agent execution fails (propagated from ADK Runner). |
Examples:
Basic usage with executor:
from google.adk.agents import LlmAgent
from gepa_adk.adapters.agent_executor import AgentExecutor
from gepa_adk.engine.adk_reflection import create_adk_reflection_fn
agent = LlmAgent(
name="InstructionReflector",
model="gemini-2.5-flash",
instruction="""Improve this component text:
{component_text}
Based on these trials:
{trials}
Return proposed component text only."""
)
executor = AgentExecutor()
reflection_fn = create_adk_reflection_fn(agent, executor=executor)
trials = [{"input": "Hi", "output": "Hey", "feedback": {"score": 0.5}}]
proposed = await reflection_fn("Be helpful", trials)
With output_schema for structured output (e.g., schema evolution):
from pydantic import BaseModel, Field
class SchemaProposal(BaseModel):
class_definition: str = Field(description="The Pydantic class definition")
reasoning: str = Field(description="Why this change was made")
agent = LlmAgent(
name="schema_reflector",
model="gemini-2.5-flash",
instruction="Improve the schema based on feedback...",
output_schema=SchemaProposal,
)
# Extract only the class_definition field from structured output
executor = AgentExecutor()
reflection_fn = create_adk_reflection_fn(
agent,
executor=executor,
output_field="class_definition",
)
See Also
gepa_adk.engine.proposer: Module containing ReflectionFn type alias and AsyncReflectiveMutationProposer class.
Note
Opens a fresh ADK session for each invocation via AgentExecutor, ensuring complete isolation between reflection operations. State is initialized with component_text (str) and trials (JSON-serialized list of trial records).
Source code in src/gepa_adk/engine/adk_reflection.py
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 | |
detect_component_divergence ¶
detect_component_divergence(
ancestor_components: dict[str, str],
parent_components: dict[str, str],
) -> set[str]
Detect which components have diverged from ancestor to parent.
Identifies component keys where the parent's value differs from the ancestor's value, indicating where improvements or changes occurred.
| PARAMETER | DESCRIPTION |
|---|---|
ancestor_components | Component dictionary from ancestor candidate. TYPE: |
parent_components | Component dictionary from parent candidate. TYPE: |
| RETURNS | DESCRIPTION |
|---|---|
set[str] | Set of component keys that have diverged (changed values). |
Examples:
Detecting divergence:
ancestor = {"instruction": "A", "output_schema": "B"}
parent = {"instruction": "A", "output_schema": "C"}
divergence = detect_component_divergence(ancestor, parent)
# Returns: {"output_schema"}
Note
Only checks components present in the ancestor. Components added by the parent are ignored. Missing components are not considered diverged.
Source code in src/gepa_adk/engine/genealogy.py
filter_ancestors_by_score ¶
filter_ancestors_by_score(
ancestors: set[int],
candidate_scores: dict[int, dict[int, float]],
min_avg_score: float,
) -> set[int]
Filter ancestors by minimum average score constraint.
Removes ancestors that don't meet the minimum average score requirement, ensuring only viable ancestors are considered for merge operations.
| PARAMETER | DESCRIPTION |
|---|---|
ancestors | Set of ancestor candidate indices to filter. TYPE: |
candidate_scores | Mapping of candidate index to per-example scores. TYPE: |
min_avg_score | Minimum average score threshold. TYPE: |
| RETURNS | DESCRIPTION |
|---|---|
set[int] | Set of ancestor indices that meet the score constraint. |
Examples:
Filtering ancestors by score:
ancestors = {0, 1, 2}
candidate_scores = {
0: {0: 0.5, 1: 0.5}, # avg: 0.5
1: {0: 0.7, 1: 0.7}, # avg: 0.7
2: {0: 0.9, 1: 0.9}, # avg: 0.9
}
filtered = filter_ancestors_by_score(
ancestors, candidate_scores, min_avg_score=0.6
)
# Returns: {1, 2} (0 filtered out)
Note
Operations exclude ancestors without scores from the result.
Source code in src/gepa_adk/engine/genealogy.py
find_common_ancestor ¶
find_common_ancestor(
idx1: int,
idx2: int,
parent_indices: dict[int, list[int | None]],
) -> int | None
Find the most recent common ancestor of two candidates.
Identifies the common ancestor with the highest index (most recent) between two candidates. Returns None if no common ancestor exists (separate lineages).
| PARAMETER | DESCRIPTION |
|---|---|
idx1 | First candidate index. TYPE: |
idx2 | Second candidate index. TYPE: |
parent_indices | Mapping of candidate index to parent indices list. TYPE: |
| RETURNS | DESCRIPTION |
|---|---|
int | None | Index of the most recent common ancestor, or None if no common ancestor exists. |
Examples:
Candidates sharing a seed:
parent_indices = {0: [None], 1: [0], 2: [0]}
ancestor = find_common_ancestor(1, 2, parent_indices)
# Returns: 0
One candidate is ancestor of the other:
parent_indices = {0: [None], 1: [0], 2: [1]}
ancestor = find_common_ancestor(1, 2, parent_indices)
# Returns: 1 (1 is ancestor of 2)
No common ancestor:
parent_indices = {0: [None], 1: [0], 2: [None], 3: [2]}
ancestor = find_common_ancestor(1, 3, parent_indices)
# Returns: None (separate lineages)
Note
Operations return the highest-indexed common ancestor to ensure we find the most recent shared ancestor, which is most useful for merge operations.
Source code in src/gepa_adk/engine/genealogy.py
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 | |
get_ancestors ¶
Return all ancestor indices for a candidate.
Traverses the genealogy tree using breadth-first search to find all ancestors transitively. Seed candidates (with [None] parents) have no ancestors.
| PARAMETER | DESCRIPTION |
|---|---|
candidate_idx | Index of the candidate to trace. TYPE: |
parent_indices | Mapping of candidate index to parent indices list. TYPE: |
| RETURNS | DESCRIPTION |
|---|---|
set[int] | Set of all ancestor candidate indices (excluding the candidate itself). |
Examples:
Simple linear genealogy:
parent_indices = {0: [None], 1: [0], 2: [1]}
ancestors = get_ancestors(2, parent_indices)
# Returns: {0, 1}
Merge candidate with two parents:
parent_indices = {0: [None], 1: [0], 2: [0], 3: [1, 2]}
ancestors = get_ancestors(3, parent_indices)
# Returns: {0, 1, 2}
Note
Operations use BFS to avoid recursion depth issues with deep genealogies. Prevents cycles by tracking visited nodes.
Source code in src/gepa_adk/engine/genealogy.py
has_desirable_predictors ¶
has_desirable_predictors(
ancestor_components: dict[str, str],
parent1_components: dict[str, str],
parent2_components: dict[str, str],
) -> bool
Check if merge has desirable complementary component changes.
A merge is desirable when parents have changed different components from the ancestor, indicating complementary improvements that can be combined.
| PARAMETER | DESCRIPTION |
|---|---|
ancestor_components | Component dictionary from common ancestor. TYPE: |
parent1_components | Component dictionary from first parent. TYPE: |
parent2_components | Component dictionary from second parent. TYPE: |
| RETURNS | DESCRIPTION |
|---|---|
bool | True if parents have complementary component changes, False otherwise. |
Examples:
Complementary changes (desirable):
ancestor = {"instruction": "A", "output_schema": "B"}
parent1 = {"instruction": "A", "output_schema": "C"} # output_schema changed
parent2 = {"instruction": "D", "output_schema": "B"} # instruction changed
assert has_desirable_predictors(ancestor, parent1, parent2) is True
Overlapping changes (less desirable):
ancestor = {"instruction": "A", "output_schema": "B"}
parent1 = {"instruction": "C", "output_schema": "B"}
parent2 = {"instruction": "C", "output_schema": "B"} # Same change
assert has_desirable_predictors(ancestor, parent1, parent2) is False
Note
Operations return False if no components have changed, or if both parents changed the same components identically.
Source code in src/gepa_adk/engine/genealogy.py
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 | |