Adapters
adapters ¶
Adapters layer - External implementations of ports.
Adapters connect the domain logic to external systems (Google ADK, LiteLLM, etc.). Each adapter implements one or more protocol interfaces from the ports layer.
| ATTRIBUTE | DESCRIPTION |
|---|---|
ADKAdapter | AsyncGEPAAdapter implementation for Google ADK agents. TYPE: |
TrialBuilder | Shared utility for building trial records in reflection datasets. TYPE: |
Examples:
Basic usage with Google ADK agent:
from google.adk.agents import LlmAgent
from gepa_adk.adapters import ADKAdapter
agent = LlmAgent(name="helper", model="gemini-2.5-flash")
adapter = ADKAdapter(agent=agent, scorer=my_scorer)
result = await adapter.evaluate(batch, candidate)
See Also
gepa_adk.ports.adapter: AsyncGEPAAdapter protocol.gepa_adk.ports.scorer: Scorer protocol for metrics.gepa_adk.domain.trajectory: ADKTrajectory types.
Note
This layer ONLY contains adapters - they import from ports/ and domain/ but never the reverse. This maintains hexagonal architecture boundaries.
ADKAdapter ¶
ADK implementation of AsyncGEPAAdapter protocol.
Bridges GEPA evaluation patterns to Google ADK's agent/runner architecture, enabling evolutionary optimization of ADK agents through instruction mutation and reflective learning.
| ATTRIBUTE | DESCRIPTION |
|---|---|
agent | The ADK LlmAgent to evaluate with different candidate instructions. TYPE: |
scorer | Scoring implementation for evaluating agent outputs. TYPE: |
max_concurrent_evals | Maximum number of concurrent evaluations to run in parallel. TYPE: |
trajectory_config | Configuration for trajectory extraction behavior (redaction, truncation, feature selection). TYPE: |
_session_service | Session service for managing agent state isolation. TYPE: |
_app_name | Application name used for session management. TYPE: |
_proposer | Mutation proposer for generating improved instructions via LLM reflection. |
_logger | Bound logger with adapter context for structured logging. TYPE: |
Examples:
Basic adapter setup:
from google.adk.agents import LlmAgent
from gepa_adk.adapters import ADKAdapter
from gepa_adk.adapters.agent_executor import AgentExecutor
agent = LlmAgent(
name="helper",
model="gemini-2.5-flash",
instruction="Be helpful and concise",
)
scorer = MyScorer() # Implements Scorer protocol
executor = AgentExecutor()
adapter = ADKAdapter(agent, scorer, executor)
# Evaluate with candidate instruction
batch = [{"input": "What is 2+2?", "expected": "4"}]
candidate = {"instruction": "Be very precise with math"}
result = await adapter.evaluate(batch, candidate)
Note
Adheres to AsyncGEPAAdapter[dict[str, Any], ADKTrajectory, str] protocol. All methods are async and follow ADK's async-first patterns.
Source code in src/gepa_adk/adapters/adk_adapter.py
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 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 | |
__init__ ¶
__init__(
agent: LlmAgent,
scorer: Scorer,
executor: AgentExecutorProtocol,
max_concurrent_evals: int = 5,
session_service: BaseSessionService | None = None,
app_name: str = "gepa_adk_eval",
trajectory_config: TrajectoryConfig | None = None,
proposer: AsyncReflectiveMutationProposer | None = None,
reflection_agent: LlmAgent | None = None,
reflection_output_field: str | None = None,
schema_constraints: SchemaConstraints | None = None,
video_service: VideoBlobServiceProtocol | None = None,
) -> None
Initialize the ADK adapter with agent and scorer.
| PARAMETER | DESCRIPTION |
|---|---|
agent | The ADK LlmAgent to evaluate with different instructions. TYPE: |
scorer | Scorer implementation for evaluating agent outputs. TYPE: |
executor | AgentExecutorProtocol implementation for unified agent execution. The executor handles session management and execution, enabling feature parity across all agent types. TYPE: |
max_concurrent_evals | Maximum number of concurrent evaluations to run in parallel. Must be at least 1. Defaults to 5. TYPE: |
session_service | Optional session service for state management. If None, creates an InMemorySessionService. TYPE: |
app_name | Application name for session identification. TYPE: |
trajectory_config | Configuration for trajectory extraction behavior. If None, uses TrajectoryConfig defaults (secure, all features enabled). TYPE: |
proposer | Optional mutation proposer for generating improved instructions via LLM reflection. If provided, takes precedence over reflection_agent. TYPE: |
reflection_agent | ADK LlmAgent to use for reflection operations. Either this or proposer must be provided. When provided, creates an ADK-based reflection function and passes it to a new proposer. TYPE: |
reflection_output_field | Field name to extract from structured output when reflection_agent has an output_schema. When the reflection agent returns structured output (dict), this specifies which field contains the proposed text. For schema evolution, use "class_definition" with a SchemaProposal output_schema. Only used when reflection_agent is provided. TYPE: |
schema_constraints | Optional SchemaConstraints for output_schema evolution. When provided, proposed schema mutations are validated against these constraints. Mutations that violate constraints (e.g., remove required fields) are rejected and the original schema is preserved. TYPE: |
video_service | Optional VideoBlobServiceProtocol for multimodal input support. When provided, enables processing of trainset examples with 'videos' field. If None, defaults to a new VideoBlobService instance. TYPE: |
| RAISES | DESCRIPTION |
|---|---|
TypeError | If agent is not an LlmAgent instance. |
TypeError | If scorer does not satisfy Scorer protocol. |
TypeError | If reflection_agent is provided but not an LlmAgent instance. |
ValueError | If app_name is empty string or max_concurrent_evals < 1. |
ValueError | If neither proposer nor reflection_agent is provided. |
Examples:
Basic setup with reflection agent:
from gepa_adk.adapters.agent_executor import AgentExecutor
reflection_agent = LlmAgent(name="reflector", model="gemini-2.5-flash")
executor = AgentExecutor()
adapter = ADKAdapter(
agent, scorer, executor, reflection_agent=reflection_agent
)
With custom trajectory configuration:
config = TrajectoryConfig(
redact_sensitive=True,
max_string_length=5000,
)
executor = AgentExecutor()
adapter = ADKAdapter(
agent,
scorer,
executor,
reflection_agent=reflection_agent,
trajectory_config=config,
)
With shared session service:
from google.adk.sessions import InMemorySessionService
from gepa_adk.adapters.agent_executor import AgentExecutor
session_service = InMemorySessionService()
executor = AgentExecutor(session_service=session_service)
adapter = ADKAdapter(
agent,
scorer,
executor,
reflection_agent=reflection_agent,
session_service=session_service,
)
Note
Caches the agent's original instruction and restores it after each evaluation to ensure no side effects between evaluations.
Source code in src/gepa_adk/adapters/adk_adapter.py
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 | |
cleanup ¶
Clean up adapter resources and clear handler constraints.
Clears any schema constraints set on the OutputSchemaHandler to prevent constraint leakage between evolution runs. Should be called when the adapter is no longer needed.
Note
OutputSchemaHandler is a singleton, so constraints set during one evolution run could affect subsequent runs if not cleared.
Source code in src/gepa_adk/adapters/adk_adapter.py
evaluate async ¶
evaluate(
batch: list[dict[str, Any]],
candidate: dict[str, str],
capture_traces: bool = False,
) -> EvaluationBatch[ADKTrajectory, str]
Evaluate agent with candidate instruction over a batch of inputs.
| PARAMETER | DESCRIPTION |
|---|---|
batch | List of input examples, each with "input" key and optional "expected" key for scoring. TYPE: |
candidate | Component name to text mapping. If "instruction" key is present, it overrides the agent's instruction. TYPE: |
capture_traces | Whether to capture execution traces (tool calls, state deltas, token usage). TYPE: |
| RETURNS | DESCRIPTION |
|---|---|
EvaluationBatch[ADKTrajectory, str] | EvaluationBatch containing outputs, scores, and optional trajectories. |
Examples:
Basic evaluation without traces:
batch = [
{"input": "What is 2+2?", "expected": "4"},
{"input": "Capital of France?", "expected": "Paris"},
]
candidate = {"instruction": "Be concise"}
result = await adapter.evaluate(batch, candidate)
assert len(result.outputs) == 2
assert len(result.scores) == 2
With trace capture:
result = await adapter.evaluate(batch, candidate, capture_traces=True)
assert result.trajectories is not None
assert len(result.trajectories) == len(batch)
Note
Original instruction is restored after evaluation completes, even if an exception occurs during evaluation. Evaluations run in parallel with concurrency controlled by max_concurrent_evals parameter. Results maintain input order despite parallel execution.
Source code in src/gepa_adk/adapters/adk_adapter.py
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 | |
make_reflective_dataset async ¶
make_reflective_dataset(
candidate: dict[str, str],
eval_batch: EvaluationBatch[ADKTrajectory, str],
components_to_update: list[str],
) -> Mapping[str, Sequence[Mapping[str, Any]]]
Build trials from evaluation results for reflection.
Terminology
- trial: One performance record {input, output, feedback, trajectory}
- trials: Collection of trial records for a component
| PARAMETER | DESCRIPTION |
|---|---|
candidate | Current candidate component values. TYPE: |
eval_batch | Evaluation results including trajectories and optional scorer metadata (e.g., from CriticScorer). TYPE: |
components_to_update | List of component names to generate trials for. TYPE: |
| RETURNS | DESCRIPTION |
|---|---|
Mapping[str, Sequence[Mapping[str, Any]]] | Mapping from component name to sequence of trials. |
Mapping[str, Sequence[Mapping[str, Any]]] | Each trial contains input, output, feedback (with score and |
Mapping[str, Sequence[Mapping[str, Any]]] | feedback_text), and optional trajectory. |
Examples:
Generate trials for reflection:
result = await adapter.evaluate(batch, candidate, capture_traces=True)
trials_dataset = await adapter.make_reflective_dataset(
candidate, result, ["instruction"]
)
assert "instruction" in trials_dataset
# Each trial has structured feedback
trial = trials_dataset["instruction"][0]
assert "input" in trial
assert "output" in trial
assert "feedback" in trial
assert trial["feedback"]["score"] == 0.75
Note
Operates on eval_batch trajectories (capture_traces=True required). Dataset format is compatible with proposer's trial-based interface. Scorer metadata (feedback_text, feedback_dimensions) from eval_batch.metadata is included in each trial's feedback dict.
Source code in src/gepa_adk/adapters/adk_adapter.py
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 | |
propose_new_texts async ¶
propose_new_texts(
candidate: dict[str, str],
reflective_dataset: Mapping[
str, Sequence[Mapping[str, Any]]
],
components_to_update: list[str],
) -> dict[str, str]
Propose new component texts based on trials.
Delegates to AsyncReflectiveMutationProposer to generate improved component text via LLM reflection on trials. When the proposer returns None (no trials), falls back to unchanged candidate values.
| PARAMETER | DESCRIPTION |
|---|---|
candidate | Current candidate component texts (name → text). TYPE: |
reflective_dataset | Trials from make_reflective_dataset(). Maps component name to list of trial records. TYPE: |
components_to_update | Components to generate proposals for. TYPE: |
| RETURNS | DESCRIPTION |
|---|---|
dict[str, str] | Dictionary mapping component names to proposed component text. |
dict[str, str] | When proposer returns None, returns unchanged candidate values. |
Examples:
Using the proposer to generate improved component text:
# After evaluation with traces
result = await adapter.evaluate(batch, candidate, capture_traces=True)
trials = await adapter.make_reflective_dataset(
candidate, result, ["instruction"]
)
# Propose new component text via LLM reflection on trials
new_texts = await adapter.propose_new_texts(
candidate, trials, ["instruction"]
)
# new_texts["instruction"] contains proposed component text
Note
Delegates to AsyncReflectiveMutationProposer for actual mutation generation. Falls back gracefully when no trials available.
Source code in src/gepa_adk/adapters/adk_adapter.py
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 | |
AgentExecutor ¶
Unified agent execution adapter.
Provides a single execution path for all ADK agent types (generator, critic, reflection) with consistent session management, event capture, and result handling.
| ATTRIBUTE | DESCRIPTION |
|---|---|
_session_service | ADK session service for state management. TYPE: |
_app_name | Application name for ADK runner. TYPE: |
Examples:
Basic usage:
executor = AgentExecutor()
result = await executor.execute_agent(
agent=my_agent,
input_text="Hello, world!",
)
if result.status == ExecutionStatus.SUCCESS:
print(f"Output: {result.extracted_value}")
With custom session service:
from google.adk.sessions import InMemorySessionService
session_service = InMemorySessionService()
executor = AgentExecutor(session_service=session_service)
Note
Adapter implements AgentExecutorProtocol for dependency injection and testing. All ADK-specific logic is encapsulated here.
Source code in src/gepa_adk/adapters/agent_executor.py
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 | |
__init__ ¶
__init__(
session_service: BaseSessionService | None = None,
app_name: str = "gepa_executor",
) -> None
Initialize AgentExecutor.
| PARAMETER | DESCRIPTION |
|---|---|
session_service | ADK session service for state management. If None, creates an InMemorySessionService. TYPE: |
app_name | Application name for ADK runner. Defaults to "gepa_executor". TYPE: |
Examples:
Default initialization:
With custom app name:
Note
Creates a shared executor that uses the session service for all agent executions, allowing session state to be shared between executions when desired.
Source code in src/gepa_adk/adapters/agent_executor.py
execute_agent async ¶
execute_agent(
agent: Any,
input_text: str,
*,
input_content: Content | None = None,
instruction_override: str | None = None,
output_schema_override: Any | None = None,
session_state: dict[str, Any] | None = None,
existing_session_id: str | None = None,
timeout_seconds: int = 300,
) -> ExecutionResult
Execute an agent and return structured result.
Runs the specified agent with the given input, optionally applying instruction or schema overrides for evolution scenarios. Manages session lifecycle and captures execution events.
| PARAMETER | DESCRIPTION |
|---|---|
agent | ADK LlmAgent to execute. The agent's tools, output_key, and other ADK features are preserved during execution. TYPE: |
input_text | User message to send to the agent. Used when input_content is None for backward compatibility. TYPE: |
input_content | Pre-assembled multimodal Content for the agent. When provided, takes precedence over input_text. Use this for multimodal inputs containing video or other media. TYPE: |
instruction_override | If provided, replaces the agent's instruction for this execution only. Original agent is not modified. TYPE: |
output_schema_override | If provided, replaces the agent's output schema for this execution only (type[BaseModel]). Used for schema evolution. TYPE: |
session_state | Initial state to inject into the session. Used for template variable substitution (e.g., {component_text}). TYPE: |
existing_session_id | If provided, uses get-or-create semantics to retrieve or create a session with this ID. Enables session sharing between agents (e.g., critic accessing generator state). TYPE: |
timeout_seconds | Maximum execution time in seconds. Defaults to 300. Execution terminates with TIMEOUT status if exceeded. TYPE: |
| RETURNS | DESCRIPTION |
|---|---|
ExecutionResult | ExecutionResult with status, output, and debugging information. |
Examples:
Basic execution:
result = await executor.execute_agent(
agent=greeter,
input_text="Hello!",
)
print(result.extracted_value)
With session state for reflection:
result = await executor.execute_agent(
agent=reflector,
input_text="Improve the instruction",
session_state={
"component_text": "Be helpful.",
"trials": '[{"score": 0.5}]',
},
)
With multimodal content:
from google.genai.types import Content, Part
content = Content(
role="user",
parts=[Part(text="Describe this video"), video_part],
)
result = await executor.execute_agent(
agent=analyzer,
input_text="", # Can be empty when content provided
input_content=content,
)
Note
Optional typing (Any) is used for agent parameter to avoid coupling to ADK types in the ports layer. Implementations should validate that the agent is a valid LlmAgent.
Source code in src/gepa_adk/adapters/agent_executor.py
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 | |
SessionNotFoundError ¶
Bases: EvolutionError
flowchart TD
gepa_adk.adapters.SessionNotFoundError[SessionNotFoundError]
gepa_adk.domain.exceptions.EvolutionError[EvolutionError]
gepa_adk.domain.exceptions.EvolutionError --> gepa_adk.adapters.SessionNotFoundError
click gepa_adk.adapters.SessionNotFoundError href "" "gepa_adk.adapters.SessionNotFoundError"
click gepa_adk.domain.exceptions.EvolutionError href "" "gepa_adk.domain.exceptions.EvolutionError"
Raised when a requested session does not exist.
| ATTRIBUTE | DESCRIPTION |
|---|---|
session_id | The session ID that was not found. TYPE: |
Examples:
Handling session not found with strict existence checking:
from gepa_adk.adapters.agent_executor import SessionNotFoundError
try:
session = await executor._get_session(
session_id="invalid_session",
user_id="user_123",
)
except SessionNotFoundError as e:
print(f"Session not found: {e.session_id}")
Note
Arises only from strict existence-checking paths like _get_session(). The execute_agent() method uses get-or-create semantics and will not raise this exception.
Source code in src/gepa_adk/adapters/agent_executor.py
__init__ ¶
Initialize SessionNotFoundError.
| PARAMETER | DESCRIPTION |
|---|---|
session_id | The session ID that was not found. TYPE: |
CurrentBestCandidateSelector ¶
Always select the candidate with the highest average score.
Note
A greedy selector always exploits the best-average candidate.
Examples:
Source code in src/gepa_adk/adapters/candidate_selector.py
select_candidate async ¶
select_candidate(state: ParetoState) -> int
Return the best-average candidate index.
| PARAMETER | DESCRIPTION |
|---|---|
state | Current evolution state with Pareto tracking. TYPE: |
| RETURNS | DESCRIPTION |
|---|---|
int | Selected candidate index. |
| RAISES | DESCRIPTION |
|---|---|
NoCandidateAvailableError | If no candidates are available. |
Examples:
Source code in src/gepa_adk/adapters/candidate_selector.py
EpsilonGreedyCandidateSelector ¶
Epsilon-greedy selection balancing exploration and exploitation.
| ATTRIBUTE | DESCRIPTION |
|---|---|
_epsilon | Exploration probability. TYPE: |
_rng | RNG for exploration decisions. TYPE: |
Note
A mixed strategy sometimes explores and otherwise exploits the best.
Examples:
selector = EpsilonGreedyCandidateSelector(epsilon=0.1, rng=random.Random(7))
candidate_idx = await selector.select_candidate(state)
Source code in src/gepa_adk/adapters/candidate_selector.py
__init__ ¶
Initialize the selector.
| PARAMETER | DESCRIPTION |
|---|---|
epsilon | Probability of random exploration. TYPE: |
rng | Optional random number generator for reproducibility. TYPE: |
| RAISES | DESCRIPTION |
|---|---|
ConfigurationError | If epsilon is outside [0.0, 1.0]. |
Source code in src/gepa_adk/adapters/candidate_selector.py
select_candidate async ¶
select_candidate(state: ParetoState) -> int
Select a candidate using epsilon-greedy strategy.
| PARAMETER | DESCRIPTION |
|---|---|
state | Current evolution state with Pareto tracking. TYPE: |
| RETURNS | DESCRIPTION |
|---|---|
int | Selected candidate index. |
| RAISES | DESCRIPTION |
|---|---|
NoCandidateAvailableError | If no candidates are available. |
Examples:
Source code in src/gepa_adk/adapters/candidate_selector.py
ParetoCandidateSelector ¶
Sample from the Pareto front proportional to leadership frequency.
| ATTRIBUTE | DESCRIPTION |
|---|---|
_rng | RNG for sampling candidates. TYPE: |
Note
A Pareto selector emphasizes candidates that lead more examples.
Examples:
selector = ParetoCandidateSelector(rng=random.Random(42))
candidate_idx = await selector.select_candidate(state)
Source code in src/gepa_adk/adapters/candidate_selector.py
__init__ ¶
Initialize the selector.
| PARAMETER | DESCRIPTION |
|---|---|
rng | Optional random number generator for reproducibility. TYPE: |
select_candidate async ¶
select_candidate(state: ParetoState) -> int
Select a candidate index from the Pareto frontier.
| PARAMETER | DESCRIPTION |
|---|---|
state | Current evolution state with Pareto tracking. TYPE: |
| RETURNS | DESCRIPTION |
|---|---|
int | Selected candidate index. |
| RAISES | DESCRIPTION |
|---|---|
NoCandidateAvailableError | If no candidates or leaders exist. |
Examples:
Source code in src/gepa_adk/adapters/candidate_selector.py
ComponentHandlerRegistry ¶
Registry for component handlers with O(1) lookup.
Stores component handlers keyed by component name, providing registration, lookup, and existence checking operations.
| ATTRIBUTE | DESCRIPTION |
|---|---|
_handlers | Internal dict mapping component names to handlers. TYPE: |
Examples:
Create and use a registry:
registry = ComponentHandlerRegistry()
registry.register("instruction", InstructionHandler())
handler = registry.get("instruction")
See Also
get_handler(): Convenience function for default registry.
Note
A default registry instance is available as component_handlers module variable, with convenience functions get_handler() and register_handler().
Source code in src/gepa_adk/adapters/component_handlers.py
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 | |
__init__ ¶
Initialize empty registry.
Examples:
Note
Creates an empty internal dict for handler storage.
Source code in src/gepa_adk/adapters/component_handlers.py
register ¶
register(name: str, handler: ComponentHandler) -> None
Register a handler for a component name.
| PARAMETER | DESCRIPTION |
|---|---|
name | Component name (e.g., "instruction", "output_schema"). Must be a non-empty string. TYPE: |
handler | Handler implementing ComponentHandler protocol. TYPE: |
| RAISES | DESCRIPTION |
|---|---|
ValueError | If name is empty or None. |
TypeError | If handler doesn't implement ComponentHandler protocol. |
Examples:
registry.register("instruction", InstructionHandler())
registry.register("output_schema", OutputSchemaHandler())
Note
Overwrites existing handler if name already registered. Logs a debug message on replacement.
Source code in src/gepa_adk/adapters/component_handlers.py
get ¶
get(name: str) -> ComponentHandler
Retrieve handler for component name.
| PARAMETER | DESCRIPTION |
|---|---|
name | Component name to look up. TYPE: |
| RETURNS | DESCRIPTION |
|---|---|
ComponentHandler | The registered ComponentHandler. |
| RAISES | DESCRIPTION |
|---|---|
ValueError | If name is empty or None. |
KeyError | If no handler registered for name. |
Examples:
Source code in src/gepa_adk/adapters/component_handlers.py
has ¶
Check if handler exists for component name.
| PARAMETER | DESCRIPTION |
|---|---|
name | Component name to check. TYPE: |
| RETURNS | DESCRIPTION |
|---|---|
bool | True if handler registered, False otherwise. |
Examples:
Note
Outputs False for empty/None names (no ValueError). This allows safe checking without exception handling.
Source code in src/gepa_adk/adapters/component_handlers.py
names ¶
Return sorted list of registered handler names.
| RETURNS | DESCRIPTION |
|---|---|
list[str] | Sorted list of component names with registered handlers. |
Examples:
Note
Output is sorted alphabetically for consistent error messages and validation feedback.
Source code in src/gepa_adk/adapters/component_handlers.py
GenerateContentConfigHandler ¶
Handler for agent.generate_content_config component.
Manages serialization, application, and restoration of the agent's LLM generation configuration during evolution.
Examples:
handler = GenerateContentConfigHandler()
original = handler.serialize(agent) # YAML string
handler.apply(agent, "temperature: 0.5")
# ... evaluate ...
handler.restore(agent, original_config)
Note
All state is stored in the agent object - handler is stateless. On invalid config, logs warning and keeps original.
Source code in src/gepa_adk/adapters/component_handlers.py
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 | |
serialize ¶
Extract generate_content_config from agent as YAML.
| PARAMETER | DESCRIPTION |
|---|---|
agent | The LlmAgent instance. TYPE: |
| RETURNS | DESCRIPTION |
|---|---|
str | YAML string with parameter descriptions as comments. |
str | Returns empty string if generate_content_config is None. |
Examples:
Source code in src/gepa_adk/adapters/component_handlers.py
apply ¶
Apply new generate_content_config to agent, return original.
| PARAMETER | DESCRIPTION |
|---|---|
agent | The LlmAgent instance to modify. TYPE: |
value | YAML string defining the new config parameters. TYPE: |
| RETURNS | DESCRIPTION |
|---|---|
Any | The original GenerateContentConfig (or None). |
Examples:
original = handler.apply(agent, "temperature: 0.5")
# agent.generate_content_config.temperature is now 0.5
Note
On deserialization or validation failure, logs warning and keeps original config. Never raises exceptions.
Source code in src/gepa_adk/adapters/component_handlers.py
restore ¶
Restore original generate_content_config to agent.
| PARAMETER | DESCRIPTION |
|---|---|
agent | The LlmAgent instance to restore. TYPE: |
original | The original GenerateContentConfig (or None). TYPE: |
Examples:
Source code in src/gepa_adk/adapters/component_handlers.py
InstructionHandler ¶
Handler for agent.instruction component.
Manages serialization, application, and restoration of the agent's instruction (system prompt) during evolution.
Examples:
handler = InstructionHandler()
original = handler.serialize(agent) # "Be helpful"
handler.apply(agent, "Be concise")
# ... evaluate ...
handler.restore(agent, original) # Back to "Be helpful"
Note
All state is stored in the agent object - handler is stateless. No instance attributes are maintained.
Source code in src/gepa_adk/adapters/component_handlers.py
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 | |
serialize ¶
Extract instruction from agent as string.
| PARAMETER | DESCRIPTION |
|---|---|
agent | The LlmAgent instance. TYPE: |
| RETURNS | DESCRIPTION |
|---|---|
str | The agent's instruction as string. |
str | Returns empty string if instruction is None. |
Examples:
Source code in src/gepa_adk/adapters/component_handlers.py
apply ¶
Apply new instruction to agent, return original.
| PARAMETER | DESCRIPTION |
|---|---|
agent | The LlmAgent instance to modify. TYPE: |
value | The new instruction string. TYPE: |
| RETURNS | DESCRIPTION |
|---|---|
str | The original instruction value. |
Examples:
Source code in src/gepa_adk/adapters/component_handlers.py
restore ¶
Restore original instruction to agent.
| PARAMETER | DESCRIPTION |
|---|---|
agent | The LlmAgent instance to restore. TYPE: |
original | The original instruction value. TYPE: |
Examples:
Source code in src/gepa_adk/adapters/component_handlers.py
OutputSchemaHandler ¶
Handler for agent.output_schema component.
Manages serialization, application, and restoration of the agent's output schema (Pydantic model) during evolution.
| ATTRIBUTE | DESCRIPTION |
|---|---|
_constraints | Optional SchemaConstraints for field preservation. TYPE: |
Examples:
handler = OutputSchemaHandler()
handler.set_constraints(SchemaConstraints(required_fields=("score",)))
original_schema = handler.apply(agent, new_schema_text)
# ... evaluate ...
handler.restore(agent, original_schema)
Note
Applies serialize_pydantic_schema and deserialize_schema utilities. On invalid schema text, keeps original and logs warning. When constraints are set, validates proposed schemas before applying.
Source code in src/gepa_adk/adapters/component_handlers.py
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 | |
__init__ ¶
Initialize handler with no constraints.
Examples:
Source code in src/gepa_adk/adapters/component_handlers.py
set_constraints ¶
set_constraints(
constraints: SchemaConstraints | None,
) -> None
Set schema constraints for field preservation.
| PARAMETER | DESCRIPTION |
|---|---|
constraints | SchemaConstraints specifying required fields and type preservation rules. Pass None to clear constraints. TYPE: |
Examples:
handler.set_constraints(SchemaConstraints(required_fields=("score",)))
handler.set_constraints(None) # Clear constraints
Note
Once set, constraints are checked during apply() - proposed schemas that violate constraints will be rejected and the original kept.
Source code in src/gepa_adk/adapters/component_handlers.py
serialize ¶
Extract output schema from agent as Python source.
| PARAMETER | DESCRIPTION |
|---|---|
agent | The LlmAgent instance. TYPE: |
| RETURNS | DESCRIPTION |
|---|---|
str | Python source code defining the schema class. |
str | Returns empty string if output_schema is None. |
Examples:
Source code in src/gepa_adk/adapters/component_handlers.py
apply ¶
Apply new output schema to agent, return original.
| PARAMETER | DESCRIPTION |
|---|---|
agent | The LlmAgent instance to modify. TYPE: |
value | Python source code defining the new schema. TYPE: |
| RETURNS | DESCRIPTION |
|---|---|
Any | The original output_schema (class or None). |
Examples:
Note
On deserialization failure, logs warning and keeps original. On constraint violation, keeps original. Never raises exceptions - graceful degradation.
Source code in src/gepa_adk/adapters/component_handlers.py
restore ¶
Restore original output schema to agent.
| PARAMETER | DESCRIPTION |
|---|---|
agent | The LlmAgent instance to restore. TYPE: |
original | The original output_schema (class or None). TYPE: |
Examples:
Source code in src/gepa_adk/adapters/component_handlers.py
AllComponentSelector ¶
Selects all available components for simultaneous update.
This selector returns the full list of components every time, enabling simultaneous evolution of all parts of the candidate.
Examples:
selector = AllComponentSelector()
all_comps = await selector.select_components(["a", "b"], 1, 0)
# Returns ["a", "b"]
Note
Always returns all components, enabling comprehensive mutations across the entire candidate in a single iteration.
Source code in src/gepa_adk/adapters/component_selector.py
select_components async ¶
Select all components to update.
| PARAMETER | DESCRIPTION |
|---|---|
components | List of available component keys. TYPE: |
iteration | Current global iteration number (unused). TYPE: |
candidate_idx | Index of the candidate being evolved (unused). TYPE: |
| RETURNS | DESCRIPTION |
|---|---|
list[str] | List containing all component keys. |
| RAISES | DESCRIPTION |
|---|---|
ValueError | If components list is empty. |
Examples:
Note
Outputs the complete component list unchanged, enabling simultaneous evolution of all candidate parts.
Source code in src/gepa_adk/adapters/component_selector.py
RoundRobinComponentSelector ¶
Selects components in a round-robin fashion.
This selector cycles through the list of components one by one, maintaining state per candidate index to ensure consistent rotation.
| ATTRIBUTE | DESCRIPTION |
|---|---|
_next_index | Mapping of candidate_idx to next component index. TYPE: |
Examples:
selector = RoundRobinComponentSelector()
# First call selects first component
c1 = await selector.select_components(["a", "b"], 1, 0) # ["a"]
# Second call selects second component
c2 = await selector.select_components(["a", "b"], 2, 0) # ["b"]
Note
Alternates through components sequentially, ensuring balanced evolution across all candidate parts.
Source code in src/gepa_adk/adapters/component_selector.py
__init__ ¶
Initialize the round-robin selector.
Note
Creates empty index tracking dictionary for per-candidate rotation state.
select_components async ¶
Select a single component to update using round-robin logic.
| PARAMETER | DESCRIPTION |
|---|---|
components | List of available component keys. TYPE: |
iteration | Current global iteration number (unused by this strategy). TYPE: |
candidate_idx | Index of the candidate being evolved. TYPE: |
| RETURNS | DESCRIPTION |
|---|---|
list[str] | List containing the single selected component key. |
| RAISES | DESCRIPTION |
|---|---|
ValueError | If components list is empty. |
Examples:
Note
Outputs one component per call, advancing the rotation index for the specified candidate.
Source code in src/gepa_adk/adapters/component_selector.py
CriticOutput ¶
Bases: BaseModel
flowchart TD
gepa_adk.adapters.CriticOutput[CriticOutput]
click gepa_adk.adapters.CriticOutput href "" "gepa_adk.adapters.CriticOutput"
Advanced schema for structured critic feedback with dimensions.
This schema defines the expected JSON structure that critic agents should return when configured with output_schema. The score field is required, while other fields are optional and will be preserved in metadata.
| ATTRIBUTE | DESCRIPTION |
|---|---|
score | Score value between 0.0 and 1.0 (required). TYPE: |
feedback | Human-readable feedback text (optional). TYPE: |
dimension_scores | Per-dimension evaluation scores (optional). TYPE: |
actionable_guidance | Specific improvement suggestions (optional). TYPE: |
Examples:
Advanced critic output:
{
"score": 0.75,
"feedback": "Good response but could be more concise",
"dimension_scores": {
"accuracy": 0.9,
"clarity": 0.6,
"completeness": 0.8
},
"actionable_guidance": "Reduce response length by 30%"
}
Note
All critic agents using this schema must return structured JSON. When this schema is used as output_schema on an LlmAgent, the agent can ONLY reply and CANNOT use any tools. This is acceptable for critic agents focused on scoring.
See Also
SimpleCriticOutput: KISS schema with just score + feedback.
Source code in src/gepa_adk/adapters/critic_scorer.py
CriticScorer ¶
Adapter that wraps ADK critic agents to provide structured scoring.
CriticScorer implements the Scorer protocol, enabling integration with gepa-adk's evaluation and evolution workflows. It executes ADK critic agents (LlmAgent, SequentialAgent, etc.) and extracts structured scores with metadata from their outputs.
| ATTRIBUTE | DESCRIPTION |
|---|---|
critic_agent | ADK agent configured for evaluation. TYPE: |
_session_service | Session service for state management. TYPE: |
_app_name | Application name for session identification. TYPE: |
_logger | Bound logger with scorer context. TYPE: |
Examples:
Basic usage:
from google.adk.agents import LlmAgent
from gepa_adk.adapters.critic_scorer import CriticScorer, CriticOutput
from gepa_adk.adapters.agent_executor import AgentExecutor
critic = LlmAgent(
name="quality_critic",
model="gemini-2.5-flash",
instruction="Evaluate response quality...",
output_schema=CriticOutput,
)
executor = AgentExecutor()
scorer = CriticScorer(critic_agent=critic, executor=executor)
score, metadata = await scorer.async_score(
input_text="What is Python?",
output="Python is a programming language.",
)
Note
Adapter wraps ADK critic agents to provide structured scoring. Implements Scorer protocol for compatibility with evolution engine. Creates isolated sessions per scoring call unless session_id provided.
Source code in src/gepa_adk/adapters/critic_scorer.py
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 | |
__init__ ¶
__init__(
critic_agent: BaseAgent,
executor: AgentExecutorProtocol,
session_service: BaseSessionService | None = None,
app_name: str = "critic_scorer",
) -> None
Initialize CriticScorer with critic agent.
| PARAMETER | DESCRIPTION |
|---|---|
critic_agent | ADK agent (LlmAgent or workflow agent) configured for evaluation. 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. If None, creates an InMemorySessionService. TYPE: |
app_name | Application name for session identification. TYPE: |
| RAISES | DESCRIPTION |
|---|---|
TypeError | If critic_agent is not a BaseAgent instance. |
ValueError | If app_name is empty string. |
Examples:
Basic setup with executor:
from gepa_adk.adapters.agent_executor import AgentExecutor
executor = AgentExecutor()
scorer = CriticScorer(critic_agent=critic, executor=executor)
With shared session service:
from google.adk.sessions import InMemorySessionService
from gepa_adk.adapters.agent_executor import AgentExecutor
session_service = InMemorySessionService()
executor = AgentExecutor(session_service=session_service)
scorer = CriticScorer(
critic_agent=critic,
executor=executor,
session_service=session_service,
)
Note
Creates logger with scorer context and validates agent type.
Source code in src/gepa_adk/adapters/critic_scorer.py
async_score async ¶
async_score(
input_text: str,
output: str,
expected: str | None = None,
session_id: str | None = None,
) -> tuple[float, dict[str, Any]]
Score an agent output asynchronously using the critic agent.
Executes the critic agent with formatted input and extracts structured score and metadata from the response.
| PARAMETER | DESCRIPTION |
|---|---|
input_text | The original input provided to the agent being evaluated. TYPE: |
output | The agent's generated output to score. TYPE: |
expected | Optional expected/reference output for comparison. TYPE: |
session_id | Optional session ID to share state with main agent workflow. If None, creates an isolated session. TYPE: |
| RETURNS | DESCRIPTION |
|---|---|
float | Tuple of (score, metadata) where: |
dict[str, Any] |
|
tuple[float, dict[str, Any]] |
|
| RAISES | DESCRIPTION |
|---|---|
CriticOutputParseError | If critic output is not valid JSON. |
MissingScoreFieldError | If score field missing from output. |
Examples:
Basic async scoring:
score, metadata = await scorer.async_score(
input_text="What is Python?",
output="Python is a programming language.",
)
With session sharing:
score, metadata = await scorer.async_score(
input_text="...",
output="...",
session_id="existing_session_123",
)
Note
Orchestrates critic agent execution via AgentExecutor and extracts structured output. Creates isolated session unless session_id provided for state sharing.
Source code in src/gepa_adk/adapters/critic_scorer.py
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 | |
score ¶
Score an agent output synchronously using the critic agent.
Synchronous wrapper around async_score() using asyncio.run().
| PARAMETER | DESCRIPTION |
|---|---|
input_text | The original input provided to the agent being evaluated. TYPE: |
output | The agent's generated output to score. TYPE: |
expected | Optional expected/reference output for comparison. TYPE: |
| RETURNS | DESCRIPTION |
|---|---|
float | Tuple of (score, metadata) where: |
dict[str, Any] |
|
tuple[float, dict[str, Any]] |
|
| RAISES | DESCRIPTION |
|---|---|
CriticOutputParseError | If critic output is not valid JSON. |
MissingScoreFieldError | If score field missing from output. |
Examples:
Basic sync scoring:
Note
Operates synchronously by wrapping async_score() with asyncio.run(). Uses asyncio.run() to execute async_score(). Prefer async_score() for better performance in async contexts.
Source code in src/gepa_adk/adapters/critic_scorer.py
SimpleCriticOutput ¶
Bases: BaseModel
flowchart TD
gepa_adk.adapters.SimpleCriticOutput[SimpleCriticOutput]
click gepa_adk.adapters.SimpleCriticOutput href "" "gepa_adk.adapters.SimpleCriticOutput"
KISS schema for basic critic feedback.
This is the minimal schema for critic agents that only need to provide a score and text feedback. Use this for straightforward evaluation tasks where dimension breakdowns are not needed.
| ATTRIBUTE | DESCRIPTION |
|---|---|
score | Score value between 0.0 and 1.0 (required). TYPE: |
feedback | Human-readable feedback text (required). TYPE: |
Examples:
Simple critic output:
Using with LlmAgent:
from google.adk.agents import LlmAgent
from gepa_adk.adapters.critic_scorer import SimpleCriticOutput
critic = LlmAgent(
name="simple_critic",
model="gemini-2.5-flash",
instruction=SIMPLE_CRITIC_INSTRUCTION,
output_schema=SimpleCriticOutput,
)
Note
Applies to basic evaluation tasks where only a score and feedback are needed. For more detailed evaluations with dimension scores, use CriticOutput instead.
See Also
CriticOutput: Advanced schema with dimension scores and guidance.
Source code in src/gepa_adk/adapters/critic_scorer.py
FullEvaluationPolicy ¶
Evaluation policy that scores all validation examples every iteration.
This is the default evaluation policy, providing complete visibility into solution performance across all validation examples.
Note
Always returns all valset IDs, ensuring complete evaluation coverage each iteration.
Examples:
policy = FullEvaluationPolicy()
batch = policy.get_eval_batch([0, 1, 2, 3, 4], state)
# Returns: [0, 1, 2, 3, 4]
Source code in src/gepa_adk/adapters/evaluation_policy.py
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 | |
get_eval_batch ¶
get_eval_batch(
valset_ids: Sequence[int],
state: ParetoState,
target_candidate_idx: int | None = None,
) -> list[int]
Return all validation example indices.
| PARAMETER | DESCRIPTION |
|---|---|
valset_ids | All available validation example indices. TYPE: |
state | Current evolution state (unused for full evaluation). TYPE: |
target_candidate_idx | Optional candidate being evaluated (unused). TYPE: |
| RETURNS | DESCRIPTION |
|---|---|
list[int] | list[int]: List of all valset_ids. |
Note
Outputs the complete valset for comprehensive evaluation coverage.
Examples:
policy = FullEvaluationPolicy()
batch = policy.get_eval_batch([0, 1, 2], state)
assert batch == [0, 1, 2]
Source code in src/gepa_adk/adapters/evaluation_policy.py
get_best_candidate ¶
get_best_candidate(state: ParetoState) -> int
Return index of candidate with highest average score.
| PARAMETER | DESCRIPTION |
|---|---|
state | Current evolution state with candidate scores. TYPE: |
| RETURNS | DESCRIPTION |
|---|---|
int | Index of best performing candidate. |
| RAISES | DESCRIPTION |
|---|---|
NoCandidateAvailableError | If state has no candidates. |
Note
Outputs the candidate index with the highest mean score across all evaluated examples.
Examples:
Source code in src/gepa_adk/adapters/evaluation_policy.py
get_valset_score ¶
get_valset_score(
candidate_idx: int, state: ParetoState
) -> float
Return mean score across all evaluated examples for a candidate.
| PARAMETER | DESCRIPTION |
|---|---|
candidate_idx | Index of candidate to score. TYPE: |
state | Current evolution state. TYPE: |
| RETURNS | DESCRIPTION |
|---|---|
float | Mean score across all examples, or float('-inf') if no scores. TYPE: |
Note
Outputs the arithmetic mean of all scores for the candidate, or negative infinity if no scores exist.
Examples:
Source code in src/gepa_adk/adapters/evaluation_policy.py
SubsetEvaluationPolicy ¶
Evaluation policy that scores a configurable subset with round-robin coverage.
This policy reduces evaluation cost for large validation sets by evaluating only a subset of examples per iteration, using round-robin selection to ensure all examples are eventually covered.
| ATTRIBUTE | DESCRIPTION |
|---|---|
subset_size | If int, absolute count of examples to evaluate per iteration. If float (0.0-1.0), fraction of total valset size. TYPE: |
_offset | Internal state tracking current position for round-robin selection. TYPE: |
Note
Advances offset each iteration to provide round-robin coverage across the full valset over multiple iterations.
Examples:
# Evaluate 20% of valset per iteration
policy = SubsetEvaluationPolicy(subset_size=0.2)
# Evaluate exactly 5 examples per iteration
policy = SubsetEvaluationPolicy(subset_size=5)
Source code in src/gepa_adk/adapters/evaluation_policy.py
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 | |
__init__ ¶
Initialize subset evaluation policy.
| PARAMETER | DESCRIPTION |
|---|---|
subset_size | If int, evaluate this many examples per iteration. If float, evaluate this fraction of total valset. Default: 0.2 (20% of valset per iteration). TYPE: |
Note
Creates policy with initial offset of 0 for round-robin selection.
Source code in src/gepa_adk/adapters/evaluation_policy.py
get_eval_batch ¶
get_eval_batch(
valset_ids: Sequence[int],
state: ParetoState,
target_candidate_idx: int | None = None,
) -> list[int]
Return subset of validation example indices with round-robin selection.
| PARAMETER | DESCRIPTION |
|---|---|
valset_ids | All available validation example indices. TYPE: |
state | Current evolution state (unused for subset selection). TYPE: |
target_candidate_idx | Optional candidate being evaluated (unused). TYPE: |
| RETURNS | DESCRIPTION |
|---|---|
list[int] | List of example indices to evaluate this iteration. |
list[int] | Uses round-robin to ensure all examples are eventually covered. |
| RAISES | DESCRIPTION |
|---|---|
ValueError | If subset_size is outside the allowed range. |
Note
Outputs a subset of valset IDs starting at the current offset, wrapping around if needed to provide round-robin coverage.
Examples:
policy = SubsetEvaluationPolicy(subset_size=0.25)
batch = policy.get_eval_batch(list(range(8)), state)
assert len(batch) == 2
Source code in src/gepa_adk/adapters/evaluation_policy.py
get_best_candidate ¶
get_best_candidate(state: ParetoState) -> int
Return index of candidate with highest average score.
| PARAMETER | DESCRIPTION |
|---|---|
state | Current evolution state with candidate scores. TYPE: |
| RETURNS | DESCRIPTION |
|---|---|
int | Index of best performing candidate. TYPE: |
| RAISES | DESCRIPTION |
|---|---|
NoCandidateAvailableError | If state has no candidates. |
Note
Outputs the candidate index with the highest mean score across evaluated examples, consistent with FullEvaluationPolicy behavior.
Examples:
Source code in src/gepa_adk/adapters/evaluation_policy.py
get_valset_score ¶
get_valset_score(
candidate_idx: int, state: ParetoState
) -> float
Return mean score across evaluated examples for a candidate.
| PARAMETER | DESCRIPTION |
|---|---|
candidate_idx | Index of candidate to score. TYPE: |
state | Current evolution state. TYPE: |
| RETURNS | DESCRIPTION |
|---|---|
float | Mean score across evaluated examples, or float('-inf') if no scores. TYPE: |
Note
Outputs the arithmetic mean of scores for the candidate across only the examples that were actually evaluated (subset).
Examples:
Source code in src/gepa_adk/adapters/evaluation_policy.py
MultiAgentAdapter ¶
Adapter for multi-agent pipeline evaluation with per-agent component routing.
Wraps multiple ADK agents into a SequentialAgent for evaluation, enabling session state sharing between agents. Implements AsyncGEPAAdapter protocol for use with AsyncGEPAEngine.
Supports per-agent component configuration via the components parameter, allowing different components to be evolved for each agent (e.g., evolve generator's instruction while evolving critic's generate_content_config).
| ATTRIBUTE | DESCRIPTION |
|---|---|
agents | Named ADK agents to evaluate together. TYPE: |
components | Per-agent component configuration. TYPE: |
primary | Name of agent whose output is used for scoring. TYPE: |
scorer | Scoring implementation (CriticScorer or similar). TYPE: |
share_session | Whether agents share session state. TYPE: |
session_service | Session service for state management. TYPE: |
trajectory_config | Configuration for trajectory extraction. TYPE: |
_executor | Optional unified executor for consistent agent execution. When None, uses legacy execution path. TYPE: |
_proposer | Mutation proposer for generating improved instructions via LLM reflection. |
_logger | Bound structlog logger with context. TYPE: |
Examples:
Basic adapter setup with per-agent components (API v0.3.x):
from google.adk.agents import LlmAgent
from gepa_adk.adapters import MultiAgentAdapter
from gepa_adk.ports.scorer import Scorer
generator = LlmAgent(
name="generator",
model="gemini-2.5-flash",
output_key="generated_code",
)
critic = LlmAgent(
name="critic",
model="gemini-2.5-flash",
instruction="Review the code in {generated_code}.",
)
scorer = MyScorer()
adapter = MultiAgentAdapter(
agents={"generator": generator, "critic": critic},
primary="generator",
scorer=scorer,
components={
"generator": ["instruction", "output_schema"],
"critic": ["generate_content_config"],
},
)
# Candidates use qualified names (agent.component format per ADR-012)
candidate = {
"generator.instruction": "Generate high-quality code",
"generator.output_schema": "class Output(BaseModel): ...",
"critic.generate_content_config": "temperature: 0.3",
}
result = await adapter.evaluate(batch, candidate)
Exclude an agent from evolution:
adapter = MultiAgentAdapter(
agents={"generator": gen, "validator": val},
primary="generator",
scorer=scorer,
components={
"generator": ["instruction"],
"validator": [], # Empty list = no evolution
},
)
Note
Adheres to AsyncGEPAAdapter[dict[str, Any], MultiAgentTrajectory, str] protocol. All methods are async and follow ADK's async-first patterns.
Breaking Change (0.3.x): - agents parameter changed from list[LlmAgent] to dict[str, LlmAgent] - components parameter is now required - Candidate keys use qualified names (agent.component) instead of {agent_name}_instruction format
Session Sharing Behavior: - When share_session=True (default): Uses SequentialAgent to execute agents sequentially with shared InvocationContext. Earlier agents can write to session state (via output_key), later agents can read that state via template strings like {output_key} in their instructions. - When share_session=False: Each agent executes with an isolated session. Agents cannot access each other's outputs. This is useful when agents should not interfere with each other's state (EdgeCase-5: incompatible outputs behavior).
output_key State Propagation: - When an agent has output_key set, its final response is automatically saved to session.state[output_key]. - With share_session=True, subsequent agents can reference this via template strings: instruction="Process {output_key}". - With share_session=False, state is not shared and template references will not resolve (agents see empty or undefined state).
Source code in src/gepa_adk/adapters/multi_agent.py
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 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 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 | |
__init__ ¶
__init__(
agents: dict[str, LlmAgent],
primary: str,
components: ComponentsMapping,
scorer: Scorer | None = None,
share_session: bool = True,
session_service: BaseSessionService | None = None,
app_name: str = "multi_agent_eval",
trajectory_config: TrajectoryConfig | None = None,
proposer: AsyncReflectiveMutationProposer | None = None,
executor: AgentExecutorProtocol | None = None,
workflow: AnyAgentType | None = None,
) -> None
Initialize the MultiAgent adapter with named agents and component config.
| PARAMETER | DESCRIPTION |
|---|---|
agents | Named ADK agents to evolve together. Must have at least one agent. Keys are agent names, values are LlmAgent instances. TYPE: |
primary | Name of the agent whose output is used for scoring. Must match one of the agent names in the dict. TYPE: |
components | Per-agent component configuration mapping agent names to lists of component names to evolve. All agents must have an entry (use empty list to exclude from evolution). Component names must have registered handlers. TYPE: |
scorer | Optional scorer implementation. If None, the primary agent must have an output_schema for schema-based scoring. TYPE: |
share_session | Whether agents share session state during execution. When True (default), uses SequentialAgent. When False, agents execute with isolated sessions. TYPE: |
session_service | Optional session service for state management. If None, creates an InMemorySessionService. TYPE: |
app_name | Application name for session identification. TYPE: |
trajectory_config | Configuration for trajectory extraction behavior. If None, uses TrajectoryConfig defaults. TYPE: |
proposer | Mutation proposer for generating improved instructions via LLM reflection. Required. Create using TYPE: |
executor | Optional unified executor for consistent agent execution. If None, uses legacy execution path with direct Runner calls. When provided, all agent executions use the executor's execute_agent method for consistent session management and feature parity (FR-001). TYPE: |
workflow | Optional original workflow structure to preserve during cloning. When provided, _build_pipeline() uses clone_workflow_with_overrides() to preserve workflow type (LoopAgent iterations, ParallelAgent concurrency). When None, creates a flat SequentialAgent (legacy behavior). TYPE: |
| RAISES | DESCRIPTION |
|---|---|
MultiAgentValidationError | If agents dict is empty, primary agent not found, or no scorer and primary lacks output_schema. |
ValueError | If proposer is not provided, or if components mapping contains unknown agents, unknown component handlers, or is missing entries for agents in the agents dict. |
Examples:
With per-agent components (API v0.3.x):
from gepa_adk.engine import (
create_adk_reflection_fn,
AsyncReflectiveMutationProposer,
)
reflection_fn = create_adk_reflection_fn(reflection_agent, executor)
proposer = AsyncReflectiveMutationProposer(adk_reflection_fn=reflection_fn)
adapter = MultiAgentAdapter(
agents={"generator": gen, "critic": critic},
primary="generator",
components={
"generator": ["instruction", "output_schema"],
"critic": ["instruction"],
},
scorer=scorer,
proposer=proposer,
)
Excluding an agent from evolution:
adapter = MultiAgentAdapter(
agents={"generator": gen, "validator": val},
primary="generator",
components={
"generator": ["instruction"],
"validator": [], # Excluded from evolution
},
scorer=scorer,
proposer=proposer,
)
Note
Clones agents during evaluation to apply candidate instructions. Original agents are never mutated.
Source code in src/gepa_adk/adapters/multi_agent.py
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 | |
evaluate async ¶
evaluate(
batch: list[dict[str, Any]],
candidate: dict[str, str],
capture_traces: bool = False,
) -> EvaluationBatch[MultiAgentTrajectory, str]
Evaluate multi-agent pipeline with candidate component values over a batch.
| PARAMETER | DESCRIPTION |
|---|---|
batch | List of input examples, each with "input" key and optional "expected" key for scoring. TYPE: |
candidate | Qualified component name to text mapping. Keys should follow the pattern TYPE: |
capture_traces | Whether to capture execution traces (tool calls, state deltas, token usage). TYPE: |
| RETURNS | DESCRIPTION |
|---|---|
EvaluationBatch[MultiAgentTrajectory, str] | EvaluationBatch containing outputs, scores, and optional trajectories. |
Examples:
Basic evaluation without traces:
batch = [
{"input": "Generate code...", "expected": "def foo(): ..."},
]
candidate = {
"generator.instruction": "Generate high-quality code",
"critic.instruction": "Review thoroughly",
}
result = await adapter.evaluate(batch, candidate)
assert len(result.outputs) == 1
assert len(result.scores) == 1
With trace capture:
result = await adapter.evaluate(batch, candidate, capture_traces=True)
assert result.trajectories is not None
assert len(result.trajectories) == len(batch)
Note
Orchestrates evaluation by applying candidate components to agents, building a SequentialAgent pipeline with cloned agents, then restoring original agent state. Primary agent's output is scored.
Uses try/finally to ensure agents are restored even on evaluation errors, preventing state corruption between candidate evaluations.
Source code in src/gepa_adk/adapters/multi_agent.py
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 | |
make_reflective_dataset async ¶
make_reflective_dataset(
candidate: dict[str, str],
eval_batch: EvaluationBatch[MultiAgentTrajectory, str],
components_to_update: list[str],
) -> Mapping[str, Sequence[Mapping[str, Any]]]
Build reflective datasets from evaluation results with traces.
| PARAMETER | DESCRIPTION |
|---|---|
candidate | Current candidate component values. TYPE: |
eval_batch | Evaluation results including trajectories. TYPE: |
components_to_update | List of component names to generate datasets for. TYPE: |
| RETURNS | DESCRIPTION |
|---|---|
Mapping[str, Sequence[Mapping[str, Any]]] | Mapping from component name to sequence of reflection examples. |
Mapping[str, Sequence[Mapping[str, Any]]] | Each example contains input, output, score, and trace context. |
Examples:
Generate reflection dataset:
result = await adapter.evaluate(batch, candidate, capture_traces=True)
dataset = await adapter.make_reflective_dataset(
candidate, result, ["generator_instruction", "critic_instruction"]
)
assert "generator_instruction" in dataset
Note
Operates on eval_batch trajectories (capture_traces=True required). Dataset format is compatible with MutationProposer interface.
Source code in src/gepa_adk/adapters/multi_agent.py
1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 | |
propose_new_texts async ¶
propose_new_texts(
candidate: dict[str, str],
reflective_dataset: Mapping[
str, Sequence[Mapping[str, Any]]
],
components_to_update: list[str],
) -> dict[str, str]
Propose new component texts based on reflective dataset.
Delegates to AsyncReflectiveMutationProposer to generate improved instruction text via LLM reflection. When the proposer returns None (empty dataset), falls back to unchanged candidate values.
| PARAMETER | DESCRIPTION |
|---|---|
candidate | Current candidate component values. TYPE: |
reflective_dataset | Dataset from make_reflective_dataset(), keyed by component name with sequences of reflection examples in the format produced by build_reflection_example(). TYPE: |
components_to_update | Components to generate proposals for. TYPE: |
| RETURNS | DESCRIPTION |
|---|---|
dict[str, str] | Dictionary mapping component names to proposed new text values. |
dict[str, str] | When proposer returns None, returns unchanged candidate values. |
Examples:
Propose new component texts via LLM reflection:
# After evaluation with traces
result = await adapter.evaluate(batch, candidate, capture_traces=True)
dataset = await adapter.make_reflective_dataset(
candidate, result, ["generator_instruction", "critic_instruction"]
)
# Propose new texts via LLM reflection
proposals = await adapter.propose_new_texts(
candidate,
dataset,
["generator_instruction", "critic_instruction"],
)
# proposals contains improved instructions based on feedback
Note
Delegates to AsyncReflectiveMutationProposer for actual mutation generation. Falls back gracefully when dataset is empty.
Source code in src/gepa_adk/adapters/multi_agent.py
1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 | |
TimeoutStopper ¶
Stop evolution after a specified timeout.
Terminates evolution when wall-clock time exceeds the configured timeout duration. Useful for resource management and CI/CD pipelines.
| ATTRIBUTE | DESCRIPTION |
|---|---|
timeout_seconds | Maximum wall-clock time for evolution. TYPE: |
Examples:
Creating a 5-minute timeout:
from gepa_adk.adapters.stoppers import TimeoutStopper
from gepa_adk.domain.stopper import StopperState
stopper = TimeoutStopper(300.0) # 5 minutes
state = StopperState(
iteration=10,
best_score=0.8,
stagnation_counter=2,
total_evaluations=50,
candidates_count=3,
elapsed_seconds=400.0, # Exceeds timeout
)
stopper(state) # Returns True (should stop)
Note
All timeout values must be positive. Zero and negative values raise ValueError to prevent invalid configurations.
Source code in src/gepa_adk/adapters/stoppers/timeout.py
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 | |
__init__ ¶
Initialize timeout stopper with maximum duration.
| PARAMETER | DESCRIPTION |
|---|---|
timeout_seconds | Maximum wall-clock time for evolution in seconds. Must be a positive value. TYPE: |
| RAISES | DESCRIPTION |
|---|---|
ValueError | If timeout_seconds is zero or negative. |
Examples:
Note
Consider using reasonable timeouts for your use case. Very short timeouts may not allow sufficient evolution progress.
Source code in src/gepa_adk/adapters/stoppers/timeout.py
__call__ ¶
__call__(state: StopperState) -> bool
Check if evolution should stop due to timeout.
| PARAMETER | DESCRIPTION |
|---|---|
state | Current evolution state snapshot containing elapsed_seconds. TYPE: |
| RETURNS | DESCRIPTION |
|---|---|
bool | True if elapsed time meets or exceeds timeout, False otherwise. |
Examples:
stopper = TimeoutStopper(60.0)
# Not yet timed out
state1 = StopperState(
iteration=5,
best_score=0.5,
stagnation_counter=0,
total_evaluations=25,
candidates_count=1,
elapsed_seconds=30.0,
)
stopper(state1) # False
# Timed out
state2 = StopperState(
iteration=10,
best_score=0.7,
stagnation_counter=1,
total_evaluations=50,
candidates_count=2,
elapsed_seconds=65.0,
)
stopper(state2) # True
Note
Often called after each iteration. Returns True as soon as the time limit is reached.
Source code in src/gepa_adk/adapters/stoppers/timeout.py
TrialBuilder ¶
Build trial records for reflection datasets.
Constructs consistent trial structures following the GEPA whitepaper format. Extracts feedback fields from scorer metadata and builds trajectory dicts.
| ATTRIBUTE | DESCRIPTION |
|---|---|
_logger | Logger for metadata passthrough debugging. TYPE: |
Examples:
Basic trial building:
builder = TrialBuilder()
# With minimal data
trial = builder.build_trial(
input_text="Hello",
output="Hi there!",
score=0.8,
)
# With full metadata
trial = builder.build_trial(
input_text="Explain AI",
output="AI is...",
score=0.9,
metadata={
"feedback": "Clear explanation",
"dimension_scores": {"clarity": 0.95},
"actionable_guidance": "Add examples",
},
extra_trajectory={"component": "instruction"},
)
See Also
build_feedback: Build just the feedback dict.
Note
All optional metadata fields are validated before inclusion to prevent malformed data from propagating to reflection prompts.
Source code in src/gepa_adk/adapters/trial_builder.py
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 | |
__init__ ¶
Initialize the TrialBuilder.
Examples:
Note
Creates a module-scoped logger for metadata passthrough debugging.
Source code in src/gepa_adk/adapters/trial_builder.py
build_feedback ¶
build_feedback(
score: float,
metadata: dict[str, Any] | None = None,
*,
error: str | None = None,
log_passthrough: bool = False,
) -> dict[str, Any]
Build the feedback dict from score and metadata.
Extracts and validates feedback fields from scorer metadata, including feedback_text, feedback_guidance, and feedback_dimensions.
| PARAMETER | DESCRIPTION |
|---|---|
score | Evaluation score (mandatory). TYPE: |
metadata | Optional scorer metadata dict containing: - feedback: Text feedback from critic. - actionable_guidance: Improvement suggestions. - dimension_scores: Per-dimension score breakdown. TYPE: |
error | Optional error message to include in feedback. TYPE: |
log_passthrough | If True, log debug info about metadata extraction. TYPE: |
| RETURNS | DESCRIPTION |
|---|---|
dict[str, Any] | Feedback dict with keys: - score (mandatory): The evaluation score. - feedback_text (if available): Text feedback from critic. - feedback_guidance (if available): Improvement suggestions. - feedback_dimensions (if available): Dimension score breakdown. - error (if provided): Error message from execution. |
Examples:
builder = TrialBuilder()
# Minimal feedback
feedback = builder.build_feedback(0.75)
assert feedback == {"score": 0.75}
# With metadata
feedback = builder.build_feedback(
0.85,
metadata={
"feedback": "Good work",
"dimension_scores": {"accuracy": 0.9},
},
)
assert "feedback_text" in feedback
Note
Only non-empty strings and dicts are included to keep feedback clean.
Source code in src/gepa_adk/adapters/trial_builder.py
build_trial ¶
build_trial(
input_text: str | None,
output: str,
score: float,
metadata: dict[str, Any] | None = None,
*,
error: str | None = None,
trace: dict[str, Any] | None = None,
extra_trajectory: dict[str, Any] | None = None,
log_passthrough: bool = False,
) -> dict[str, Any]
Build a complete trial record for reflection.
Constructs a trial with feedback and trajectory dicts following the GEPA whitepaper structure.
| PARAMETER | DESCRIPTION |
|---|---|
input_text | The input that was given to the system. Can be None for pipelines where input context is implicit. TYPE: |
output | What the system produced. TYPE: |
score | Evaluation score for this output. TYPE: |
metadata | Optional scorer metadata dict (from CriticScorer). TYPE: |
error | Optional error message from execution. TYPE: |
trace | Optional execution trace dict (tool calls, state, tokens). TYPE: |
extra_trajectory | Optional extra fields to include in trajectory (e.g., component name, component value, tokens). TYPE: |
log_passthrough | If True, log debug info about metadata extraction. TYPE: |
| RETURNS | DESCRIPTION |
|---|---|
dict[str, Any] | Trial dict with keys: - feedback: Evaluation feedback (score, feedback_text, etc.) - trajectory: Execution journey (input, output, trace, etc.) |
Examples:
builder = TrialBuilder()
# Simple trial
trial = builder.build_trial(
input_text="What is Python?",
output="A programming language",
score=0.9,
)
assert trial["feedback"]["score"] == 0.9
assert trial["trajectory"]["output"] == "A programming language"
# With trace and extra trajectory data
trial = builder.build_trial(
input_text="Count to 3",
output="1, 2, 3",
score=1.0,
trace={"tool_calls": [{"name": "count"}]},
extra_trajectory={"component": "counter"},
)
assert "trace" in trial["trajectory"]
assert trial["trajectory"]["component"] == "counter"
Note
Optional input is only included in trajectory when not None, supporting pipelines where input context is implicit.
Source code in src/gepa_adk/adapters/trial_builder.py
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 | |
VideoBlobService ¶
Video blob loading service for multimodal content.
Implements VideoBlobServiceProtocol to convert video files to ADK Part objects. Validates video files for existence, size limits, and MIME types before loading.
| ATTRIBUTE | DESCRIPTION |
|---|---|
_logger | Structured logger for video operations. TYPE: |
Examples:
Load a single video:
service = VideoBlobService()
parts = await service.prepare_video_parts(["/data/lecture.mp4"])
assert len(parts) == 1
Load multiple videos:
paths = ["/data/intro.mp4", "/data/main.mp4"]
parts = await service.prepare_video_parts(paths)
assert len(parts) == 2
Handle validation errors:
from gepa_adk.domain.exceptions import VideoValidationError
try:
parts = await service.prepare_video_parts(["/missing.mp4"])
except VideoValidationError as e:
print(f"Invalid: {e.video_path}")
Note
Adapter implements VideoBlobServiceProtocol for dependency injection and testing. All ADK-specific Part creation is encapsulated here.
Source code in src/gepa_adk/adapters/video_blob_service.py
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 | |
__init__ ¶
Initialize VideoBlobService.
Examples:
Default initialization:
Note
Creates a service instance with a bound logger for video operations. No external dependencies are required.
Source code in src/gepa_adk/adapters/video_blob_service.py
validate_video_file ¶
validate_video_file(video_path: str) -> VideoFileInfo
Validate a video file and return its metadata.
Checks that the file exists, is within size limits, and has a valid video MIME type.
| PARAMETER | DESCRIPTION |
|---|---|
video_path | Absolute path to the video file to validate. TYPE: |
| RETURNS | DESCRIPTION |
|---|---|
VideoFileInfo | VideoFileInfo containing validated metadata. |
| RAISES | DESCRIPTION |
|---|---|
VideoValidationError | If validation fails. |
Examples:
Validate a video file:
Note
Operates synchronously for fast pre-validation. File content is not read, only metadata is checked.
Source code in src/gepa_adk/adapters/video_blob_service.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 224 225 226 227 228 229 230 231 232 | |
prepare_video_parts async ¶
Load video files and create Part objects for multimodal content.
Validates and loads all video files, converting them to ADK Part objects with inline video data.
| PARAMETER | DESCRIPTION |
|---|---|
video_paths | List of absolute paths to video files. TYPE: |
| RETURNS | DESCRIPTION |
|---|---|
list[Part] | List of Part objects, one per input path. Order is preserved. |
| RAISES | DESCRIPTION |
|---|---|
ValueError | If video_paths is empty. |
VideoValidationError | If any file fails validation. |
Examples:
Load videos:
parts = await service.prepare_video_parts(
[
"/data/intro.mp4",
"/data/main.mp4",
]
)
assert len(parts) == 2
Note
Operations include async file I/O. Videos are validated before loading to provide early failure with clear error messages.
Source code in src/gepa_adk/adapters/video_blob_service.py
create_candidate_selector ¶
create_candidate_selector(
selector_type: str,
*,
epsilon: float = 0.1,
rng: Random | None = None,
) -> CandidateSelectorProtocol
Create a candidate selector by name.
| PARAMETER | DESCRIPTION |
|---|---|
selector_type | Selector identifier (pareto, greedy, epsilon_greedy). TYPE: |
epsilon | Exploration rate for epsilon-greedy selector. TYPE: |
rng | Optional RNG for selectors using randomness. TYPE: |
| RETURNS | DESCRIPTION |
|---|---|
CandidateSelectorProtocol | CandidateSelectorProtocol implementation. |
| RAISES | DESCRIPTION |
|---|---|
ConfigurationError | If selector_type is unsupported. |
Examples:
selector = create_candidate_selector("pareto")
candidate_idx = await selector.select_candidate(state)
Source code in src/gepa_adk/adapters/candidate_selector.py
get_handler ¶
get_handler(name: str) -> ComponentHandler
Get handler from default registry.
| PARAMETER | DESCRIPTION |
|---|---|
name | Component name to look up. TYPE: |
| RETURNS | DESCRIPTION |
|---|---|
ComponentHandler | The registered ComponentHandler. |
| RAISES | DESCRIPTION |
|---|---|
ValueError | If name is empty or None. |
KeyError | If no handler registered for name. |
Examples:
See Also
- [
ComponentHandlerRegistry.get()]: Underlying registry method.
Note
Shortcut for component_handlers.get(name).
Source code in src/gepa_adk/adapters/component_handlers.py
register_handler ¶
register_handler(
name: str, handler: ComponentHandler
) -> None
Register handler in default registry.
| PARAMETER | DESCRIPTION |
|---|---|
name | Component name to register. TYPE: |
handler | Handler implementing ComponentHandler protocol. TYPE: |
| RAISES | DESCRIPTION |
|---|---|
ValueError | If name is empty or None. |
TypeError | If handler doesn't implement ComponentHandler protocol. |
Examples:
See Also
- [
ComponentHandlerRegistry.register()]: Underlying registry method.
Note
Shortcut for component_handlers.register(name, handler).
Source code in src/gepa_adk/adapters/component_handlers.py
create_component_selector ¶
create_component_selector(
selector_type: str,
) -> ComponentSelectorProtocol
Create a component selector strategy from a string alias.
| PARAMETER | DESCRIPTION |
|---|---|
selector_type | Name of the selector strategy. Supported values: - 'round_robin', 'roundrobin': Round-robin cycling. - 'all', 'all_components': All components simultaneously. TYPE: |
| RETURNS | DESCRIPTION |
|---|---|
ComponentSelectorProtocol | Instance of requested component selector. |
| RAISES | DESCRIPTION |
|---|---|
ValueError | If selector_type is unknown. |
Examples:
# Create round-robin selector
selector = create_component_selector("round_robin")
# Create all-components selector
selector = create_component_selector("all")
Note
Supports flexible string aliases with normalization for common variations (underscores, hyphens, case-insensitive).
Source code in src/gepa_adk/adapters/component_selector.py
normalize_feedback ¶
Normalize critic feedback to consistent trial format.
Converts both simple and advanced critic outputs to a standardized format for use in trial records. This enables the reflection agent to receive consistent feedback regardless of which critic schema was used.
| PARAMETER | DESCRIPTION |
|---|---|
score | The numeric score from the critic (0.0-1.0). TYPE: |
metadata | Optional metadata dict from critic output. May contain: - feedback (str): Simple feedback text - dimension_scores (dict): Per-dimension scores - actionable_guidance (str): Improvement suggestions - Any additional fields from critic output TYPE: |
| RETURNS | DESCRIPTION |
|---|---|
dict[str, Any] | Normalized feedback dict with structure: |
dict[str, Any] | ```python |
dict[str, Any] | { "score": 0.75, "feedback_text": "Main feedback message", "dimension_scores": {...}, # Optional "actionable_guidance": "...", # Optional |
dict[str, Any] | } |
dict[str, Any] | ``` |
Examples:
Normalize simple feedback:
normalized = normalize_feedback(0.8, {"feedback": "Good job"})
# {"score": 0.8, "feedback_text": "Good job"}
Normalize advanced feedback:
normalized = normalize_feedback(
0.6,
{
"feedback": "Needs work",
"dimension_scores": {"clarity": 0.5},
"actionable_guidance": "Add examples",
},
)
# {
# "score": 0.6,
# "feedback_text": "Needs work",
# "dimension_scores": {"clarity": 0.5},
# "actionable_guidance": "Add examples",
# }
Handle missing feedback:
Note
Supports both SimpleCriticOutput and CriticOutput schemas for flexible critic integration. Extracts the "feedback" field and renames it to "feedback_text" for consistent trial structure. Additional fields like dimension_scores are preserved when present.
Source code in src/gepa_adk/adapters/critic_scorer.py
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 | |
find_llm_agents ¶
Find all LlmAgents in a workflow (recursive traversal with depth limiting).
Traverses a workflow agent structure recursively to discover all LlmAgent instances at any nesting level, up to the specified maximum depth.
| PARAMETER | DESCRIPTION |
|---|---|
agent | Agent or workflow to search. Can be LlmAgent, workflow agent, or any object. TYPE: |
max_depth | Maximum recursion depth (default: 5). When current_depth reaches max_depth, traversal stops. Must be >= 1 for meaningful results. TYPE: |
current_depth | Current recursion level (internal use, default: 0). TYPE: |
| RETURNS | DESCRIPTION |
|---|---|
list['LlmAgent'] | List of LlmAgent instances found. Only includes agents with string |
list['LlmAgent'] | instructions (skips InstructionProvider callables). |
Examples:
Finding LlmAgents in a SequentialAgent:
from google.adk.agents import LlmAgent, SequentialAgent
from gepa_adk.adapters.workflow import find_llm_agents
agent1 = LlmAgent(name="agent1", instruction="First")
agent2 = LlmAgent(name="agent2", instruction="Second")
workflow = SequentialAgent(name="pipeline", sub_agents=[agent1, agent2])
agents = find_llm_agents(workflow)
assert len(agents) == 2
Finding LlmAgents in nested workflows:
# Sequential -> Parallel -> LlmAgents
nested_parallel = ParallelAgent(name="parallel", sub_agents=[agent2, agent3])
workflow = SequentialAgent(
name="pipeline", sub_agents=[agent1, nested_parallel]
)
agents = find_llm_agents(workflow, max_depth=5)
assert len(agents) == 3 # Finds all agents across levels
Note
Operates recursively with depth limiting to discover nested LlmAgents. Skips LlmAgents with InstructionProvider callables (non-string instructions). Respects max_depth to prevent infinite recursion.
Source code in src/gepa_adk/adapters/workflow.py
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 | |
is_workflow_agent ¶
Check if an agent is a workflow type.
Detects whether an agent is a workflow agent (SequentialAgent, LoopAgent, or ParallelAgent) versus a regular LlmAgent or other agent type.
| PARAMETER | DESCRIPTION |
|---|---|
agent | Agent instance to check. Can be any object type. TYPE: |
| RETURNS | DESCRIPTION |
|---|---|
bool | True if agent is SequentialAgent, LoopAgent, or ParallelAgent. |
bool | False otherwise (including LlmAgent, None, or non-agent objects). |
Examples:
Detecting workflow agents:
from google.adk.agents import SequentialAgent, LlmAgent
from gepa_adk.adapters.workflow import is_workflow_agent
sequential = SequentialAgent(name="Pipeline", sub_agents=[])
assert is_workflow_agent(sequential) is True
llm = LlmAgent(name="Agent", instruction="Be helpful")
assert is_workflow_agent(llm) is False
Note
Only workflow agent types (SequentialAgent, LoopAgent, ParallelAgent) are detected. All workflow agents inherit from BaseAgent and have sub_agents, but type detection uses specific class checks for accuracy.