Domain
domain ¶
Domain layer for gepa-adk evolution engine.
This module exports the core domain models for the GEPA-ADK evolution engine.
| ATTRIBUTE | DESCRIPTION |
|---|---|
EvolutionConfig | Configuration parameters for evolution runs. TYPE: |
EvolutionResult | Outcome of a completed evolution run. TYPE: |
Candidate | Instruction candidate being evolved. TYPE: |
IterationRecord | Metrics for a single evolution iteration. TYPE: |
TokenRollup | Token usage summed over evaluated rows. TYPE: |
Score | Type alias for normalized scores. TYPE: |
ComponentName | Type alias for component identifiers. TYPE: |
ModelName | Type alias for model identifiers. TYPE: |
TrajectoryConfig | Configuration for trajectory extraction. TYPE: |
StopReason | Why an evolution run terminated. TYPE: |
OnIterationCallback | Callback invoked after each iteration. TYPE: |
ProposalValidator | Check run on each proposed component text. TYPE: |
DEFAULT_SENSITIVE_KEYS | Default keys for trajectory redaction. TYPE: |
CURRENT_SCHEMA_VERSION | Current result schema version. TYPE: |
EvolutionError | Base exception for all gepa-adk errors. TYPE: |
ConfigurationError | Raised when configuration validation fails. TYPE: |
EvaluationError | Raised when batch evaluation fails. TYPE: |
AdapterError | Raised when adapter operations fail. TYPE: |
EmptyProposalError | Raised when reflection stays empty after one retry. TYPE: |
ReflectionTimeoutError | Raised when the reflection agent exceeds its timeout. TYPE: |
IncompleteProposalError | Raised when the reflection output was cut off or opens a reasoning tag it never closes. TYPE: |
ReflectionError | Raised when the reflection function raises; retryable errors are skipped, others abort the run. TYPE: |
MultiAgentEvolutionResult | Outcome of a completed multi-agent evolution run. TYPE: |
ParetoState | Tracks evolution state for Pareto-aware selection. TYPE: |
ParetoFrontier | Tracks non-dominated candidates across multiple frontier dimensions. TYPE: |
StopperState | Immutable snapshot of evolution state for stopper decisions. TYPE: |
ADKTrajectory | Execution trace from ADK agent evaluation. TYPE: |
MultiAgentTrajectory | Execution trace from multi-agent pipeline evaluation. TYPE: |
ToolCallRecord | Record of a single tool call during agent execution. TYPE: |
TokenUsage | Token usage statistics from LLM calls. TYPE: |
COMPONENT_INSTRUCTION | Name of the instruction component. TYPE: |
COMPONENT_OUTPUT_SCHEMA | Name of the output schema component. TYPE: |
COMPONENT_GENERATE_CONFIG | Name of the generate_content_config component. TYPE: |
DEFAULT_COMPONENT_NAME | Component evolved when none is named ( TYPE: |
FrontierType | Supported frontier tracking strategies for Pareto selection. TYPE: |
MultiAgentCandidate | Mapping of qualified component names to their text. TYPE: |
MergeAttempt | Merged candidate with its parent and ancestor indices, or None. TYPE: |
AncestorLog | Parent and ancestor indices of an attempted merge. TYPE: |
SchemaConstraints | Constraints for output schema evolution. TYPE: |
ScoringError | Base exception for all scoring-related errors. TYPE: |
CriticOutputParseError | Raised when critic agent output cannot be parsed as valid JSON. TYPE: |
MissingScoreFieldError | Raised when score field is missing or null in parsed output. TYPE: |
MultiAgentValidationError | Raised when multi-agent configuration validation fails. TYPE: |
NoCandidateAvailableError | Raised when no candidates are available for selection. TYPE: |
VideoValidationError | Raised when video file validation fails. TYPE: |
Examples:
Basic usage with configuration and records:
from gepa_adk.domain import EvolutionConfig, IterationRecord
config = EvolutionConfig(max_iterations=20)
record = IterationRecord(
iteration_number=1,
score=0.85,
component_text="Test",
evolved_component="instruction",
accepted=True,
)
See Also
gepa_adk.domain.models: Core dataclass implementations.gepa_adk.domain.types: Type aliases for domain concepts.gepa_adk.domain.exceptions: Exception hierarchy.
Notes
This package contains pure domain logic with no external dependencies. All models follow hexagonal architecture principles (ADR-000).
CURRENT_SCHEMA_VERSION module-attribute ¶
Schema version for evolution result serialization.
Incremented when the result schema changes in a way that requires migration logic in from_dict().
COMPONENT_GENERATE_CONFIG module-attribute ¶
COMPONENT_GENERATE_CONFIG: ComponentName = (
"generate_content_config"
)
Component name for LLM generation configuration (temperature, top_p, etc.).
COMPONENT_INSTRUCTION module-attribute ¶
COMPONENT_INSTRUCTION: ComponentName = 'instruction'
Component name for agent instructions (same as DEFAULT_COMPONENT_NAME).
COMPONENT_OUTPUT_SCHEMA module-attribute ¶
COMPONENT_OUTPUT_SCHEMA: ComponentName = 'output_schema'
Component name for Pydantic output schema definitions.
DEFAULT_COMPONENT_NAME module-attribute ¶
DEFAULT_COMPONENT_NAME: ComponentName = 'instruction'
Default component name for single-component evolution.
This constant provides a single source of truth for the default component name used when evolving a single component (typically an agent's instruction). Use this constant instead of hardcoding 'instruction' throughout the codebase.
DEFAULT_SENSITIVE_KEYS module-attribute ¶
DEFAULT_SENSITIVE_KEYS: tuple[str, ...] = (
"api_key",
"token",
"secret",
"password",
"credential",
"authorization",
"bearer",
)
Default keys treated as sensitive during trajectory redaction.
Used by TrajectoryConfig.sensitive_keys as the default value. Pass sensitive_keys=() to disable key-based redaction.
AncestorLog module-attribute ¶
Type alias for tracking attempted merges.
Represents a merge attempt triplet that has been tried, preventing duplicate merges.
Type
tuple[int, int, int]: (parent1_idx, parent2_idx, ancestor_idx)
Examples:
from gepa_adk.domain.types import AncestorLog
# Log of attempted merge
log: AncestorLog = (5, 8, 2) # (parent1_idx, parent2_idx, ancestor_idx)
Notes
Type alias used by MergeProposer to track which merge combinations have already been attempted, preventing redundant merge operations.
ComponentName module-attribute ¶
Name of a candidate component (e.g., 'instruction', 'output_schema').
MergeAttempt module-attribute ¶
Type alias for merge attempt results.
Represents a successful merge attempt with the merged candidate and parent/ancestor indices, or None if merge was not possible.
Type:
tuple[Candidate, int, int, int] | None: (merged_candidate, parent1_idx,
parent2_idx, ancestor_idx) or None
Examples:
from gepa_adk.domain.types import MergeAttempt
from gepa_adk.domain.models import Candidate
# Successful merge
attempt: MergeAttempt = (
Candidate(components={"instruction": "..."}),
5, # parent1_idx
8, # parent2_idx
2, # ancestor_idx
)
# Failed merge
failed: MergeAttempt = None
Notes
Type alias reserved for future merge reporting; currently unused but kept for parity with the merge-proposer design docs.
ModelName module-attribute ¶
Model identifier (e.g., 'ollama_chat/gpt-oss:20b', 'gemini-3.8-flash', 'gpt-4o').
MultiAgentCandidate module-attribute ¶
Type alias for multi-agent candidate structure.
Maps qualified component names to their values using dot-separated format: {agent_name}.{component_name} as the key.
See ADR-012 for the addressing scheme rationale.
Examples:
Basic multi-agent candidate:
from gepa_adk.domain.types import MultiAgentCandidate, ComponentSpec
# Using ComponentSpec for type-safe construction
gen_inst = ComponentSpec(agent="generator", component="instruction")
critic_schema = ComponentSpec(agent="critic", component="output_schema")
candidate: MultiAgentCandidate = {
gen_inst.qualified: "Generate Python code...",
critic_schema.qualified: "Review code output schema...",
}
# Equivalent direct construction
candidate: MultiAgentCandidate = {
"generator.instruction": "Generate Python code...",
"critic.output_schema": "Review code output schema...",
}
Notes
This type alias is compatible with GEPA's Candidate type (dict[str, str]), enabling seamless integration with existing mutation proposers and evolution engine components.
OnIterationCallback module-attribute ¶
OnIterationCallback: TypeAlias = Callable[
["IterationRecord", str | None], Awaitable[None] | None
]
Callback the engine invokes after each iteration record is appended.
Type
Callable[[IterationRecord, str | None], Awaitable[None] | None]: Receives the iteration's record and the id of the candidate it concerns (None for an empty_proposal skip). May be sync or async.
Examples:
from gepa_adk.domain.types import OnIterationCallback
def log_iteration(record, candidate_id):
print(record.iteration_number, record.score, candidate_id)
callback: OnIterationCallback = log_iteration
Notes
Set it as EvolutionConfig.on_iteration. An awaitable return value is awaited before the loop continues; exceptions propagate out of run().
ProposalValidator module-attribute ¶
Check the engine runs on each proposed component text before evaluation.
Type
Callable[[str, str], str | None]: Receives the component name and the proposed text. Returns None to accept the proposal, or a short reason string to reject it.
Examples:
from gepa_adk.domain.types import ProposalValidator
def require_placeholder(component, text):
if "{question}" not in text:
return "dropped the {question} placeholder"
return None
validator: ProposalValidator = require_placeholder
Notes
Set it as EvolutionConfig.proposal_validator. A rejected proposal is recorded with skip_reason="proposal_rejected" and the reason, costs no evaluation and counts toward patience. Exceptions propagate out of run().
AdapterError ¶
Bases: EvaluationError
flowchart TD
gepa_adk.domain.AdapterError[AdapterError]
gepa_adk.domain.exceptions.EvaluationError[EvaluationError]
gepa_adk.domain.exceptions.EvolutionError[EvolutionError]
gepa_adk.domain.exceptions.EvaluationError --> gepa_adk.domain.AdapterError
gepa_adk.domain.exceptions.EvolutionError --> gepa_adk.domain.exceptions.EvaluationError
click gepa_adk.domain.AdapterError href "" "gepa_adk.domain.AdapterError"
click gepa_adk.domain.exceptions.EvaluationError href "" "gepa_adk.domain.exceptions.EvaluationError"
click gepa_adk.domain.exceptions.EvolutionError href "" "gepa_adk.domain.exceptions.EvolutionError"
Raised when an adapter operation fails.
This exception is used by adapter implementations (e.g., ADKAdapter) for adapter-specific failures such as session errors or configuration issues.
Examples:
Raising an adapter error:
from gepa_adk.domain.exceptions import AdapterError
if not self._session_service:
raise AdapterError(
"Session service unavailable",
adapter="ADKAdapter",
operation="evaluate",
)
Notes
AdapterError is a subclass of EvaluationError, so callers can catch either for different granularity of error handling.
Source code in src/gepa_adk/domain/exceptions.py
ConfigurationError ¶
Bases: EvolutionError
flowchart TD
gepa_adk.domain.ConfigurationError[ConfigurationError]
gepa_adk.domain.exceptions.EvolutionError[EvolutionError]
gepa_adk.domain.exceptions.EvolutionError --> gepa_adk.domain.ConfigurationError
click gepa_adk.domain.ConfigurationError href "" "gepa_adk.domain.ConfigurationError"
click gepa_adk.domain.exceptions.EvolutionError href "" "gepa_adk.domain.exceptions.EvolutionError"
Raised when configuration validation fails.
This exception is raised during EvolutionConfig initialization when a parameter violates its validation constraints.
| ATTRIBUTE | DESCRIPTION |
|---|---|
field | The name of the configuration field that failed validation. TYPE: |
value | The invalid value that was provided. TYPE: |
constraint | Description of the validation constraint that was violated. TYPE: |
Examples:
Creating a configuration error with context:
from gepa_adk.domain.exceptions import ConfigurationError
error = ConfigurationError(
"max_iterations must be non-negative",
field="max_iterations",
value=-5,
constraint=">= 0",
)
print(error.field, error.value, error.constraint)
# Output: max_iterations -5 >= 0
Notes
Arises from user-provided invalid settings, not programming errors. Should be caught and reported with clear guidance on valid values.
Source code in src/gepa_adk/domain/exceptions.py
__init__ ¶
__init__(
message: str,
*,
field: str | None = None,
value: object = None,
constraint: str | None = None,
) -> None
Initialize ConfigurationError with context.
| PARAMETER | DESCRIPTION |
|---|---|
message | Human-readable error description. TYPE: |
field | Name of the invalid configuration field. TYPE: |
value | The invalid value provided. TYPE: |
constraint | Description of the validation constraint. TYPE: |
Source code in src/gepa_adk/domain/exceptions.py
__str__ ¶
Return string representation with context.
| RETURNS | DESCRIPTION |
|---|---|
str | Formatted error message including field and value context. |
Notes
Outputs formatted error message with field and value context when available, preserving base message structure.
Source code in src/gepa_adk/domain/exceptions.py
CriticOutputParseError ¶
Bases: ScoringError
flowchart TD
gepa_adk.domain.CriticOutputParseError[CriticOutputParseError]
gepa_adk.domain.exceptions.ScoringError[ScoringError]
gepa_adk.domain.exceptions.EvolutionError[EvolutionError]
gepa_adk.domain.exceptions.ScoringError --> gepa_adk.domain.CriticOutputParseError
gepa_adk.domain.exceptions.EvolutionError --> gepa_adk.domain.exceptions.ScoringError
click gepa_adk.domain.CriticOutputParseError href "" "gepa_adk.domain.CriticOutputParseError"
click gepa_adk.domain.exceptions.ScoringError href "" "gepa_adk.domain.exceptions.ScoringError"
click gepa_adk.domain.exceptions.EvolutionError href "" "gepa_adk.domain.exceptions.EvolutionError"
Raised when critic agent output cannot be parsed as valid JSON.
This exception indicates that the critic agent returned output that could not be parsed as JSON or did not conform to the expected schema.
| ATTRIBUTE | DESCRIPTION |
|---|---|
raw_output | The unparseable output from critic. TYPE: |
parse_error | Description of parsing failure. TYPE: |
Examples:
Handling parse errors:
from gepa_adk.domain.exceptions import CriticOutputParseError
try:
score, metadata = await scorer.async_score(...)
except CriticOutputParseError as e:
print(f"Invalid JSON: {e.raw_output}")
print(f"Error: {e.parse_error}")
Notes
Arises when critic agent output cannot be parsed as valid JSON. Typically occurs when LLM output doesn't follow structured format despite output_schema being set.
Source code in src/gepa_adk/domain/exceptions.py
__init__ ¶
__init__(
message: str,
*,
raw_output: str,
parse_error: str,
cause: Exception | None = None,
) -> None
Initialize CriticOutputParseError with context.
| PARAMETER | DESCRIPTION |
|---|---|
message | Human-readable error description. TYPE: |
raw_output | The unparseable output string from critic. TYPE: |
parse_error | Description of the parsing failure. TYPE: |
cause | Original exception that caused this error. TYPE: |
Source code in src/gepa_adk/domain/exceptions.py
__str__ ¶
Return string with parse error details.
| RETURNS | DESCRIPTION |
|---|---|
str | Formatted message including parse error and raw output preview. |
Notes
Outputs formatted error message with parse error and raw output preview (the first 100 chars followed by ... when longer), preserving base message structure.
Source code in src/gepa_adk/domain/exceptions.py
EmptyProposalError ¶
Bases: EvolutionError
flowchart TD
gepa_adk.domain.EmptyProposalError[EmptyProposalError]
gepa_adk.domain.exceptions.EvolutionError[EvolutionError]
gepa_adk.domain.exceptions.EvolutionError --> gepa_adk.domain.EmptyProposalError
click gepa_adk.domain.EmptyProposalError href "" "gepa_adk.domain.EmptyProposalError"
click gepa_adk.domain.exceptions.EvolutionError href "" "gepa_adk.domain.exceptions.EvolutionError"
Raised when reflection returns an empty proposal after one retry.
The engine treats this error as a failed iteration rather than a fatal one: it records the iteration as skipped and continues the loop.
| ATTRIBUTE | DESCRIPTION |
|---|---|
component | Name of the component the reflection was proposing text for. TYPE: |
Examples:
Notes
Raised by the mutation proposer after the reflection function has returned an empty or whitespace-only string twice in a row.
Source code in src/gepa_adk/domain/exceptions.py
__init__ ¶
Initialize EmptyProposalError with the component name.
| PARAMETER | DESCRIPTION |
|---|---|
component | Name of the component whose reflection was empty. TYPE: |
Source code in src/gepa_adk/domain/exceptions.py
EvaluationError ¶
Bases: EvolutionError
flowchart TD
gepa_adk.domain.EvaluationError[EvaluationError]
gepa_adk.domain.exceptions.EvolutionError[EvolutionError]
gepa_adk.domain.exceptions.EvolutionError --> gepa_adk.domain.EvaluationError
click gepa_adk.domain.EvaluationError href "" "gepa_adk.domain.EvaluationError"
click gepa_adk.domain.exceptions.EvolutionError href "" "gepa_adk.domain.exceptions.EvolutionError"
Raised when batch evaluation fails.
This exception indicates failures during agent evaluation, such as agent execution errors, timeout, or malformed output.
| ATTRIBUTE | DESCRIPTION |
|---|---|
cause | Original exception that caused this error. TYPE: |
context | Additional context for debugging. TYPE: |
Examples:
Wrapping an ADK error:
from gepa_adk.domain.exceptions import EvaluationError
try:
result = await runner.run_async(...)
except ADKError as e:
raise EvaluationError(
"Agent execution failed",
cause=e,
agent_name="my_agent",
) from e
Notes
Always preserves the original cause for debugging while providing a consistent interface for error handling.
Source code in src/gepa_adk/domain/exceptions.py
__init__ ¶
Initialize EvaluationError with cause and context.
| PARAMETER | DESCRIPTION |
|---|---|
message | Human-readable error description. TYPE: |
cause | Original exception that caused this error. TYPE: |
**context | Arbitrary key-value pairs stored as exception attributes for debugging context. TYPE: |
Notes
Context is passed via keyword arguments. Positional arguments after message are not allowed.
Source code in src/gepa_adk/domain/exceptions.py
__str__ ¶
Return string with cause chain if present.
| RETURNS | DESCRIPTION |
|---|---|
str | Formatted message with context and cause information. |
Notes
Outputs formatted error message with context dict and cause chain when available, preserving base message structure.
Source code in src/gepa_adk/domain/exceptions.py
EvolutionError ¶
Bases: Exception
flowchart TD
gepa_adk.domain.EvolutionError[EvolutionError]
click gepa_adk.domain.EvolutionError href "" "gepa_adk.domain.EvolutionError"
Base exception for all gepa-adk errors.
All custom exceptions in gepa-adk should inherit from this class to allow for unified exception handling.
| ATTRIBUTE | DESCRIPTION |
|---|---|
partial_result | Partial result the engine attaches when it aborts a run after the baseline was scored, built with TYPE: |
Examples:
Catching evolution errors:
from gepa_adk.domain.exceptions import EvolutionError
try:
raise EvolutionError("Evolution failed unexpectedly")
except EvolutionError as e:
print(f"Caught: {e}")
# Output: Caught: Evolution failed unexpectedly
Notes
Always use this base class or its subclasses for domain errors. Standard Python exceptions should still be raised for programming errors (e.g., TypeError, ValueError for developer mistakes).
Source code in src/gepa_adk/domain/exceptions.py
IncompleteProposalError ¶
Bases: EvolutionError
flowchart TD
gepa_adk.domain.IncompleteProposalError[IncompleteProposalError]
gepa_adk.domain.exceptions.EvolutionError[EvolutionError]
gepa_adk.domain.exceptions.EvolutionError --> gepa_adk.domain.IncompleteProposalError
click gepa_adk.domain.IncompleteProposalError href "" "gepa_adk.domain.IncompleteProposalError"
click gepa_adk.domain.exceptions.EvolutionError href "" "gepa_adk.domain.exceptions.EvolutionError"
Raised when the reflection output is incomplete.
A proposal is incomplete when the last model response behind it reports a length stop (the output-token limit), or when its text opens a reasoning tag such as <think> that it never closes. The engine treats this error as a skipped iteration: it records the iteration with skip_reason="incomplete_proposal", keeps the raw text as the record's component_text, counts it toward patience and continues the loop without evaluating. The proposer does not retry it.
| ATTRIBUTE | DESCRIPTION |
|---|---|
component | Name of the component the reflection was proposing text for. TYPE: |
finish_reason | Why the proposal is incomplete: the finish reason name (for example TYPE: |
raw_text | The incomplete text the reflection produced. TYPE: |
output_length | Length of TYPE: |
Examples:
raise IncompleteProposalError(
"instruction", finish_reason="MAX_TOKENS", raw_text="Be concise and"
)
Notes
Raised by the ADK reflection function after a successful execution, before the empty-response handling, so a length stop with no text is still reported as incomplete.
Source code in src/gepa_adk/domain/exceptions.py
__init__ ¶
Initialize IncompleteProposalError with the incomplete output.
| PARAMETER | DESCRIPTION |
|---|---|
component | Name of the component whose proposal is incomplete. TYPE: |
finish_reason | Finish reason name or TYPE: |
raw_text | The incomplete text the reflection produced. TYPE: |
Source code in src/gepa_adk/domain/exceptions.py
MissingScoreFieldError ¶
Bases: ScoringError
flowchart TD
gepa_adk.domain.MissingScoreFieldError[MissingScoreFieldError]
gepa_adk.domain.exceptions.ScoringError[ScoringError]
gepa_adk.domain.exceptions.EvolutionError[EvolutionError]
gepa_adk.domain.exceptions.ScoringError --> gepa_adk.domain.MissingScoreFieldError
gepa_adk.domain.exceptions.EvolutionError --> gepa_adk.domain.exceptions.ScoringError
click gepa_adk.domain.MissingScoreFieldError href "" "gepa_adk.domain.MissingScoreFieldError"
click gepa_adk.domain.exceptions.ScoringError href "" "gepa_adk.domain.exceptions.ScoringError"
click gepa_adk.domain.exceptions.EvolutionError href "" "gepa_adk.domain.exceptions.EvolutionError"
Raised when score field is missing or null in parsed output.
This exception indicates that the output was successfully parsed and validated, but the required score field is missing or null.
| ATTRIBUTE | DESCRIPTION |
|---|---|
parsed_output | The parsed output without valid score. TYPE: |
available_fields | Fields that were present. TYPE: |
Examples:
Handling missing score field:
from gepa_adk.domain.exceptions import MissingScoreFieldError
try:
score, metadata = await scorer.async_score(...)
except MissingScoreFieldError as e:
print(f"Missing score. Available fields: {e.available_fields}")
Notes
Applies when parsed output lacks a valid score value. The parsed_output may contain other valid fields that will be preserved in metadata if score is found.
Source code in src/gepa_adk/domain/exceptions.py
__init__ ¶
Initialize MissingScoreFieldError with parsed output.
| PARAMETER | DESCRIPTION |
|---|---|
message | Human-readable error description. TYPE: |
parsed_output | The parsed dict without valid score field. TYPE: |
cause | Original exception that caused this error. TYPE: |
Source code in src/gepa_adk/domain/exceptions.py
__str__ ¶
Return string with available fields.
| RETURNS | DESCRIPTION |
|---|---|
str | Formatted message including list of available fields. |
Notes
Outputs formatted error message with list of available fields from parsed output, preserving base message structure.
Source code in src/gepa_adk/domain/exceptions.py
MultiAgentValidationError ¶
Bases: EvolutionError
flowchart TD
gepa_adk.domain.MultiAgentValidationError[MultiAgentValidationError]
gepa_adk.domain.exceptions.EvolutionError[EvolutionError]
gepa_adk.domain.exceptions.EvolutionError --> gepa_adk.domain.MultiAgentValidationError
click gepa_adk.domain.MultiAgentValidationError href "" "gepa_adk.domain.MultiAgentValidationError"
click gepa_adk.domain.exceptions.EvolutionError href "" "gepa_adk.domain.exceptions.EvolutionError"
Raised when multi-agent configuration validation fails.
This exception is raised during MultiAgentAdapter initialization when a parameter violates its validation constraints.
| ATTRIBUTE | DESCRIPTION |
|---|---|
field | The name of the configuration field that failed validation. TYPE: |
value | The invalid value that was provided. TYPE: |
constraint | Description of the validation constraint that was violated. TYPE: |
Examples:
Creating a multi-agent validation error:
from gepa_adk.domain.exceptions import MultiAgentValidationError
error = MultiAgentValidationError(
"agents list cannot be empty",
field="agents",
value=[],
constraint="len >= 1",
)
print(error.field, error.value) # agents []
Notes
Arises from user-provided invalid multi-agent settings, not programming errors. Should be caught and reported with clear guidance on valid values.
Source code in src/gepa_adk/domain/exceptions.py
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 | |
__init__ ¶
Initialize MultiAgentValidationError with context.
| PARAMETER | DESCRIPTION |
|---|---|
message | Human-readable error description. TYPE: |
field | Name of the invalid configuration field. TYPE: |
value | The invalid value provided. TYPE: |
constraint | Description of the validation constraint. TYPE: |
Source code in src/gepa_adk/domain/exceptions.py
__str__ ¶
Return string representation with context.
| RETURNS | DESCRIPTION |
|---|---|
str | Formatted error message including field and value context. |
Notes
Outputs formatted error message with field, value, and constraint context when available, preserving base message structure.
Source code in src/gepa_adk/domain/exceptions.py
NoCandidateAvailableError ¶
Bases: EvolutionError
flowchart TD
gepa_adk.domain.NoCandidateAvailableError[NoCandidateAvailableError]
gepa_adk.domain.exceptions.EvolutionError[EvolutionError]
gepa_adk.domain.exceptions.EvolutionError --> gepa_adk.domain.NoCandidateAvailableError
click gepa_adk.domain.NoCandidateAvailableError href "" "gepa_adk.domain.NoCandidateAvailableError"
click gepa_adk.domain.exceptions.EvolutionError href "" "gepa_adk.domain.exceptions.EvolutionError"
Raised when no candidates are available for selection.
| ATTRIBUTE | DESCRIPTION |
|---|---|
cause | Original exception that caused this error. TYPE: |
context | Extra context (candidate_idx, frontier_type). TYPE: |
Examples:
Notes
Arises when candidate selector cannot find any valid candidates from the Pareto frontier, typically due to empty frontier or filtering constraints.
Source code in src/gepa_adk/domain/exceptions.py
__init__ ¶
Initialize NoCandidateAvailableError with context.
| PARAMETER | DESCRIPTION |
|---|---|
message | Human-readable error description. TYPE: |
cause | Original exception that caused this error. TYPE: |
**context | Arbitrary key-value pairs stored as exception attributes for debugging context. TYPE: |
Source code in src/gepa_adk/domain/exceptions.py
__str__ ¶
Return string with context and cause details.
| RETURNS | DESCRIPTION |
|---|---|
str | Formatted error message including context and cause information. |
Notes
Outputs formatted error message with context dict and cause chain when available, preserving base message structure.
Source code in src/gepa_adk/domain/exceptions.py
ReflectionError ¶
Bases: EvolutionError
flowchart TD
gepa_adk.domain.ReflectionError[ReflectionError]
gepa_adk.domain.exceptions.EvolutionError[EvolutionError]
gepa_adk.domain.exceptions.EvolutionError --> gepa_adk.domain.ReflectionError
click gepa_adk.domain.ReflectionError href "" "gepa_adk.domain.ReflectionError"
click gepa_adk.domain.exceptions.EvolutionError href "" "gepa_adk.domain.exceptions.EvolutionError"
Raised when the reflection function raises an unexpected exception.
The proposer wraps any non-EvolutionError exception from the reflection function in this error and classifies it. A retryable error (quota, availability or connection failure) is retried once; when the retry fails too, the engine records the iteration with skip_reason="reflection_error", counts it toward patience and continues the loop. A non-retryable error aborts the run.
| ATTRIBUTE | DESCRIPTION |
|---|---|
component | Name of the component the reflection was proposing text for. TYPE: |
cause | The exception the reflection function raised on the last attempt. TYPE: |
retryable | Whether the cause is a transient provider failure. TYPE: |
attempts | Number of reflection calls made before giving up. TYPE: |
Examples:
raise ReflectionError(
"instruction",
cause=RuntimeError("503 UNAVAILABLE"),
retryable=True,
attempts=2,
)
Notes
Raised by the mutation proposer. ReflectionTimeoutError and other EvolutionError subclasses from the reflection function pass through unwrapped.
Source code in src/gepa_adk/domain/exceptions.py
__init__ ¶
Initialize ReflectionError with the component and its cause.
| PARAMETER | DESCRIPTION |
|---|---|
component | Name of the component whose reflection failed. TYPE: |
cause | The exception the reflection function raised. TYPE: |
retryable | Whether the cause is a transient provider failure. TYPE: |
attempts | Number of reflection calls made before giving up. TYPE: |
Source code in src/gepa_adk/domain/exceptions.py
ReflectionTimeoutError ¶
Bases: EvolutionError
flowchart TD
gepa_adk.domain.ReflectionTimeoutError[ReflectionTimeoutError]
gepa_adk.domain.exceptions.EvolutionError[EvolutionError]
gepa_adk.domain.exceptions.EvolutionError --> gepa_adk.domain.ReflectionTimeoutError
click gepa_adk.domain.ReflectionTimeoutError href "" "gepa_adk.domain.ReflectionTimeoutError"
click gepa_adk.domain.exceptions.EvolutionError href "" "gepa_adk.domain.exceptions.EvolutionError"
Raised when the reflection agent exceeds its timeout.
The engine treats this error as a skipped iteration rather than a fatal one: it records the iteration with skip_reason="reflection_timeout", counts it toward patience and continues the loop. The proposer does not retry a timed-out reflection.
| ATTRIBUTE | DESCRIPTION |
|---|---|
component | Name of the component the reflection was proposing text for. TYPE: |
timeout_seconds | Timeout the reflection ran under, or TYPE: |
Examples:
Notes
Raised by the ADK reflection function when the executor returns ExecutionStatus.TIMEOUT, as distinct from a failed run or an empty response.
Source code in src/gepa_adk/domain/exceptions.py
__init__ ¶
Initialize ReflectionTimeoutError with the component and timeout.
| PARAMETER | DESCRIPTION |
|---|---|
component | Name of the component whose reflection timed out. TYPE: |
timeout_seconds | Timeout the reflection ran under, or TYPE: |
Source code in src/gepa_adk/domain/exceptions.py
ScoringError ¶
Bases: EvolutionError
flowchart TD
gepa_adk.domain.ScoringError[ScoringError]
gepa_adk.domain.exceptions.EvolutionError[EvolutionError]
gepa_adk.domain.exceptions.EvolutionError --> gepa_adk.domain.ScoringError
click gepa_adk.domain.ScoringError href "" "gepa_adk.domain.ScoringError"
click gepa_adk.domain.exceptions.EvolutionError href "" "gepa_adk.domain.exceptions.EvolutionError"
Base exception for all scoring-related errors.
All scoring exceptions inherit from this class to allow for unified exception handling in scoring operations.
| ATTRIBUTE | DESCRIPTION |
|---|---|
cause | Original exception that caused this error. TYPE: |
Examples:
Catching scoring errors:
from gepa_adk.domain.exceptions import ScoringError
try:
score, metadata = await scorer.async_score(...)
except ScoringError as e:
print(f"Scoring failed: {e}")
Notes
All scoring exceptions inherit from this base class. ScoringError extends EvolutionError, following ADR-009 exception hierarchy guidelines.
Source code in src/gepa_adk/domain/exceptions.py
__init__ ¶
Initialize ScoringError with message and optional cause.
| PARAMETER | DESCRIPTION |
|---|---|
message | Human-readable error description. TYPE: |
cause | Original exception that caused this error. TYPE: |
Source code in src/gepa_adk/domain/exceptions.py
__str__ ¶
Return string with cause chain if present.
| RETURNS | DESCRIPTION |
|---|---|
str | Formatted message with cause information. |
Notes
Outputs formatted error message with cause chain when available, preserving base message structure.
Source code in src/gepa_adk/domain/exceptions.py
VideoValidationError ¶
Bases: ConfigurationError
flowchart TD
gepa_adk.domain.VideoValidationError[VideoValidationError]
gepa_adk.domain.exceptions.ConfigurationError[ConfigurationError]
gepa_adk.domain.exceptions.EvolutionError[EvolutionError]
gepa_adk.domain.exceptions.ConfigurationError --> gepa_adk.domain.VideoValidationError
gepa_adk.domain.exceptions.EvolutionError --> gepa_adk.domain.exceptions.ConfigurationError
click gepa_adk.domain.VideoValidationError href "" "gepa_adk.domain.VideoValidationError"
click gepa_adk.domain.exceptions.ConfigurationError href "" "gepa_adk.domain.exceptions.ConfigurationError"
click gepa_adk.domain.exceptions.EvolutionError href "" "gepa_adk.domain.exceptions.EvolutionError"
Raised when video file validation fails.
This exception is raised during video file processing when a video file does not exist, exceeds size limits, or has an invalid MIME type.
| ATTRIBUTE | DESCRIPTION |
|---|---|
video_path | The path to the video file that failed validation. TYPE: |
field | The configuration field name (default "video"). TYPE: |
constraint | Description of the validation constraint that was violated. TYPE: |
Examples:
Raising a video validation error:
from gepa_adk.domain.exceptions import VideoValidationError
raise VideoValidationError(
"Video file not found",
video_path="/path/to/missing.mp4",
constraint="file must exist",
)
Handling video validation errors:
from gepa_adk.domain.exceptions import VideoValidationError
try:
await video_service.prepare_video_parts(["/bad/path.mp4"])
except VideoValidationError as e:
print(f"Invalid video: {e.video_path}")
print(f"Constraint violated: {e.constraint}")
Notes
Arises from video file validation failures during multimodal input processing. File existence, size limits (2GB), and MIME type (video/*) are validated before loading video content.
Source code in src/gepa_adk/domain/exceptions.py
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 | |
__init__ ¶
Initialize VideoValidationError with video file context.
| PARAMETER | DESCRIPTION |
|---|---|
message | Human-readable error description. TYPE: |
video_path | The path to the video file that failed validation. TYPE: |
field | Name of the configuration field (default "video"). TYPE: |
constraint | Description of the validation constraint violated. TYPE: |
Source code in src/gepa_adk/domain/exceptions.py
__str__ ¶
Return string representation with video path context.
| RETURNS | DESCRIPTION |
|---|---|
str | Formatted error message including video_path and constraint. |
Notes
Outputs formatted error message with video_path for easy identification of the problematic file in error logs.
Source code in src/gepa_adk/domain/exceptions.py
Candidate dataclass ¶
Represents an instruction candidate being evolved.
Unlike GEPA's simple dict[str, str] type alias, this class provides richer state tracking for async scenarios including lineage and metadata.
| ATTRIBUTE | DESCRIPTION |
|---|---|
components | Component name to text value mapping. Common keys include 'instruction' (main agent prompt) and 'output_schema'. TYPE: |
generation | Generation number in the evolution lineage (0 = initial). A mutation proposal gets its parent's generation plus one when the engine creates it. TYPE: |
parent_id |
TYPE: |
parent_ids | Pareto indices of both parents of a merge candidate, set by the merge proposer. None for seed candidates and for mutation proposals, whose lineage is TYPE: |
metadata | Extensible metadata dict for async tracking and debugging. TYPE: |
id | Read-only short content hash of TYPE: |
Examples:
Creating a candidate:
from gepa_adk.domain.models import Candidate
candidate = Candidate(
components={"instruction": "Be helpful"},
generation=0,
)
print(candidate.components["instruction"]) # Be helpful
print(candidate.generation) # 0
Notes
to_dict() and from_dict() round-trip every field; the engine uses them to checkpoint the best candidate. A mutable candidate representation with richer state tracking than GEPA's simple dict. Components and metadata can be modified during the evolution process. Use generation and parent_id to track lineage.
Source code in src/gepa_adk/domain/models.py
1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 | |
id property ¶
Return a short, stable hash of this candidate's components.
| RETURNS | DESCRIPTION |
|---|---|
str | The first 12 hex characters of the SHA-256 digest of the |
str | components serialised as JSON with sorted keys. |
Examples:
to_dict ¶
Serialise this candidate to a stdlib-only dict.
| RETURNS | DESCRIPTION |
|---|---|
dict[str, Any] | Dict with |
dict[str, Any] |
|
dict[str, Any] |
|
dict[str, Any] |
|
Examples:
data = Candidate(components={"instruction": "seed"}).to_dict()
assert Candidate.from_dict(data).components == {"instruction": "seed"}
Source code in src/gepa_adk/domain/models.py
from_dict classmethod ¶
from_dict(data: dict[str, Any]) -> Candidate
Rebuild a candidate from to_dict() output.
| PARAMETER | DESCRIPTION |
|---|---|
data | Dict produced by TYPE: |
| RETURNS | DESCRIPTION |
|---|---|
Candidate | The reconstructed candidate. |
| RAISES | DESCRIPTION |
|---|---|
KeyError | If |
Source code in src/gepa_adk/domain/models.py
EvolutionConfig dataclass ¶
Configuration parameters for an evolution run.
Defines the parameters that control how evolution proceeds, including iteration limits, concurrency settings, and stopping criteria.
| ATTRIBUTE | DESCRIPTION |
|---|---|
max_iterations | Maximum number of evolution iterations. 0 means just evaluate baseline without evolving. TYPE: |
max_concurrent_evals | Maximum concurrent evaluation rows per batch in evolve(). Does not apply to evolve_group() or evolve_workflow(). Must be at least 1. TYPE: |
min_improvement_threshold | Minimum score improvement to accept a new candidate. Set to 0.0 to accept any improvement. TYPE: |
patience | Number of iterations without improvement before stopping early. Set to 0 to disable early stopping. TYPE: |
reflection_model | Model for reflection/mutation operations: a non-empty model identifier string or a TYPE: |
frontier_type | Frontier tracking strategy for Pareto selection (default: INSTANCE). OBJECTIVE, HYBRID and CARTESIAN require per-example objective scores. The single-agent adapter forwards non-empty TYPE: |
acceptance_metric | Aggregation method for acceptance decisions on iteration evaluation batches. "sum" uses sum of scores (default, aligns with upstream GEPA). "mean" uses mean of scores (legacy behavior). TYPE: |
use_merge | Enable merge proposals for genetic crossover. Defaults to False. TYPE: |
max_merge_invocations | Maximum number of merge attempts per run. Defaults to 10. Must be non-negative. TYPE: |
reflection_prompt | Custom reflection/mutation prompt template. If provided, this template is used instead of the default when the reflection model proposes improved text. Required placeholders: - {component_text}: The current component text being evolved - {trials}: Trial data with feedback and trajectory for each test case If None or empty string, the default prompt template is used. TYPE: |
stop_callbacks | List of stopper callbacks for custom stop conditions. Each callback receives a StopperState and returns True to signal stop. Defaults to an empty list. TYPE: |
seed | Random seed for deterministic engine decisions. When set, a seeded TYPE: |
reflection_max_trials | Maximum number of trials per component sent to the reflection prompt. When a component has more, failing trials (score below 1.0) fill up to half the slots (rounded up) and passing trials fill the rest, each in batch order. TYPE: |
reflection_max_trial_chars | Maximum length of any string value inside a trial sent to the reflection prompt, at any depth. Longer strings are cut and end with a TYPE: |
reflection_timeout_seconds | Seconds the reflection agent may run for one proposal before the executor stops it. TYPE: |
max_consecutive_reflection_errors | Number of consecutive TYPE: |
reflection_minibatch_size | Number of trainset rows a proposal runs on before it earns its full evaluation. Each iteration the engine draws a fresh seeded sample of this many rows, evaluates the proposal on them and compares its mean score with the parent's cached scores on the same rows. Only a strictly higher mean earns the full trainset pass and the scoring pass; a proposal that loses or ties is recorded with TYPE: |
on_iteration | Called once per iteration, after its IterationRecord is appended to the history and before stop conditions are checked, with the record and the id of the candidate it concerns. Skipped iterations are reported too: an TYPE: |
proposal_validator | Called with each evolved component's name and proposed text after reflection and before schema validation or evaluation. The first non-None return rejects the proposal: the iteration is recorded with TYPE: |
checkpoint_path | JSON file the engine writes its state to after the baseline and after every recorded iteration, atomically (a temporary file beside it, then TYPE: |
resume | When True, TYPE: |
Examples:
Creating a configuration with defaults:
from gepa_adk.domain.models import EvolutionConfig
config = EvolutionConfig(max_iterations=100, patience=10)
print(config.max_iterations) # 100
print(config.reflection_model) # ollama_chat/gpt-oss:20b
print(config.max_consecutive_reflection_errors) # 3
Aborting after the first repeat of an identical reflection error:
Notes
All numeric parameters are validated in post_init to ensure they meet their constraints. Cross-field consistency is also checked (e.g., use_merge requires max_merge_invocations > 0, stop_callbacks, on_iteration and proposal_validator must be callable). Invalid values raise ConfigurationError.
Determinism applies to engine decisions only (candidate selection, component selection, merge proposals). LLM inference is inherently stochastic and not covered by the seed guarantee.
Source code in src/gepa_adk/domain/models.py
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 | |
__post_init__ ¶
Validate configuration parameters after initialization.
| RAISES | DESCRIPTION |
|---|---|
ConfigurationError | If any parameter violates its constraints, including non-finite floats (NaN, Inf), cross-field consistency rules (e.g., use_merge requires max_merge_invocations > 0, stop_callbacks, on_iteration and proposal_validator must be callable), a reflection cap (reflection_max_trials, reflection_max_trial_chars) below 1, a |
Notes
Operates automatically after dataclass init completes. Validates all fields including finite-float checks, cross-field consistency, and raises ConfigurationError with context on failure. A non-string reflection_model passes this check; the resolver in gepa_adk.api rejects values that are not a BaseLlm. A str checkpoint_path is converted to Path.
Source code in src/gepa_adk/domain/models.py
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 | |
EvolutionResult dataclass ¶
Outcome of a completed evolution run.
Contains the final results after evolution completes, including all evolved component values, performance metrics, and full history.
| ATTRIBUTE | DESCRIPTION |
|---|---|
schema_version | Schema version for forward-compatible serialization. Always TYPE: |
stop_reason | Why the evolution run terminated. Defaults to TYPE: |
original_score | Starting performance score (baseline). TYPE: |
final_score | Ending performance score (best achieved). TYPE: |
evolved_components | Dictionary mapping component names to their final evolved text values. Keys include "instruction" and optionally "output_schema" or other components. Access individual components via TYPE: |
iteration_history | Chronological list of iteration records. A skipped iteration's record names why in TYPE: |
total_iterations | Number of iterations performed. TYPE: |
valset_score | Score on validation set used for acceptance decisions. None if no validation set was used. TYPE: |
trainset_score | Score on trainset used for reflection diagnostics. None if not computed. TYPE: |
objective_scores | Optional per-example multi-objective scores from the best candidate's final evaluation. None when no objective scores were tracked. Each dict maps objective name to score value. Index-aligned with evaluation batch examples. TYPE: |
original_components | Optional snapshot of pre-evolution component values. When present, enables zero-arg TYPE: |
baseline_failed_evaluations | Number of rows whose agent run or scorer raised, or whose run returned a failed execution, during the baseline evaluation of the initial candidate. Defaults to 0. TYPE: |
total_failed_evaluations |
TYPE: |
token_usage | Token usage observed on the rows evaluated over the run, baseline included, and on its reflection calls. None when not recorded (results saved before schema version 3). The rollup carries an TYPE: |
reflection_reasoning | Read-only property returning the reflection reasoning from the last iteration. Convenience accessor; None if no iterations or last iteration has no reasoning. TYPE: |
Examples:
Creating and analyzing a result:
from gepa_adk.domain.models import EvolutionResult, IterationRecord
result = EvolutionResult(
original_score=0.60,
final_score=0.85,
evolved_components={"instruction": "Be helpful and concise"},
original_components={"instruction": "Be helpful"},
iteration_history=[],
total_iterations=10,
)
print(result.improvement) # 0.25
print(result.show_diff()) # unified diff of instruction changes
Serialization round-trip:
import json
d = result.to_dict()
json_str = json.dumps(d)
restored = EvolutionResult.from_dict(json.loads(json_str))
Notes
As a frozen dataclass, EvolutionResult instances cannot be modified.
Source code in src/gepa_adk/domain/models.py
1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 | |
reflection_reasoning property ¶
Return the reflection reasoning from the last iteration.
Convenience accessor for the most recent iteration's reasoning explaining why the reflection agent proposed its mutation.
| RETURNS | DESCRIPTION |
|---|---|
str | None | The reasoning string from the last iteration record, or None |
str | None | if no iterations exist or the last iteration has no reasoning. |
improvement property ¶
Calculate the score improvement from original to final.
| RETURNS | DESCRIPTION |
|---|---|
float | The difference between final_score and original_score. |
float | Positive values indicate improvement, negative indicates degradation. |
Notes
Override is not needed since frozen dataclasses support properties.
improved property ¶
Check if the final score is better than the original.
| RETURNS | DESCRIPTION |
|---|---|
bool | True if final_score > original_score, False otherwise. |
Notes
Only returns True for strict improvement, not equal scores.
to_dict ¶
Serialize this result to a stdlib-only dict.
| RETURNS | DESCRIPTION |
|---|---|
dict[str, Any] | Dict containing all fields. |
dict[str, Any] | as its string value. |
dict[str, Any] | list of dicts. Includes |
dict[str, Any] |
|
dict[str, Any] | unset). Output is directly |
Source code in src/gepa_adk/domain/models.py
from_dict classmethod ¶
from_dict(data: dict[str, Any]) -> EvolutionResult
Reconstruct an EvolutionResult from a dict.
Validates schema version, applies migration if needed, and reconstructs all nested objects including optional original_components. Version 1 dicts migrate through _migrate_v1_to_v2(), so their failure counts read as 0, and version 1 and 2 dicts through _migrate_v2_to_v3(), so their token_usage reads as None, and version 1 to 3 dicts through _migrate_v3_to_v4(), so each record's candidate_id and parent_ids read as None, and version 1 to 4 dicts through _migrate_v4_to_v5(), so each record's rejection_reason reads as None, and version 1 to 5 dicts through _migrate_v5_to_v6(), so each token_usage loads as its evaluation split with reflection None, and version 1 to 6 dicts through _migrate_v6_to_v7(), so each record's rows_evaluated reads as None.
| PARAMETER | DESCRIPTION |
|---|---|
data | Dict containing evolution result fields. TYPE: |
| RETURNS | DESCRIPTION |
|---|---|
EvolutionResult | Reconstructed EvolutionResult instance. |
| RAISES | DESCRIPTION |
|---|---|
ConfigurationError | If |
KeyError | If a required field is missing from the dict. |
Source code in src/gepa_adk/domain/models.py
1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 | |
__repr__ ¶
Narrative summary of the evolution result.
| RETURNS | DESCRIPTION |
|---|---|
str | Human-readable multi-line summary with improvement percentage, |
str | iterations, stop reason, component names, and acceptance rate. |
str | Uses 2-space indent, no box-drawing characters, every line |
str | greppable. When the original score is zero the improvement is |
str | reported as an absolute value instead of a percentage. |
Source code in src/gepa_adk/domain/models.py
show_diff ¶
Show unified diff between original and evolved components.
Uses stored original_components if no explicit argument is provided. Produces git-diff-style output (---/+++/@@) for each component that changed.
| PARAMETER | DESCRIPTION |
|---|---|
original_components | Pre-evolution component values. If None, falls back to TYPE: |
| RETURNS | DESCRIPTION |
|---|---|
str | Unified diff string, or |
str | components are identical. |
| RAISES | DESCRIPTION |
|---|---|
ValueError | If both the argument and |
Source code in src/gepa_adk/domain/models.py
IterationRecord dataclass ¶
Captures metrics for a single evolution iteration.
This is an immutable record of what happened during one iteration of the evolution process. Records are created by the engine and stored in EvolutionResult.iteration_history.
| ATTRIBUTE | DESCRIPTION |
|---|---|
iteration_number | 1-indexed iteration number for human readability. TYPE: |
score | Score achieved in this iteration (typically in [0.0, 1.0]). TYPE: |
component_text | The component_text that was evaluated in this iteration (e.g., the instruction text for the "instruction" component). TYPE: |
evolved_component | The name of the component that was evolved in this iteration (e.g., "instruction", "output_schema"). Used for tracking which component changed in round-robin evolution strategies. TYPE: |
accepted | Whether this proposal was accepted as the new best. TYPE: |
objective_scores | Optional per-example multi-objective scores from the valset evaluation. None when adapter does not provide objective scores. Each dict maps objective name to score value. Index-aligned with evaluation batch examples. TYPE: |
reflection_reasoning | Optional natural language reasoning from the reflection agent explaining why the mutation was proposed. None when reasoning is not available (e.g., model without thinking support or older data without this field). TYPE: |
skip_reason | Why the iteration produced no evaluated proposal, or None for an ordinary iteration. TYPE: |
failed_evaluations | Number of evaluated rows in this iteration whose agent run or scorer raised, or whose run returned a failed execution, summed over every evaluation the iteration made (trainset, valset and merge). Such a row still scores 0.0, so this count separates a crash from a wrong answer. Defaults to 0; an TYPE: |
token_usage | Token usage observed on the rows this iteration evaluated and its reflection calls, or None when not recorded (results saved before schema version 3). The rollup carries an TYPE: |
candidate_id |
TYPE: |
parent_ids |
TYPE: |
rejection_reason | The reason TYPE: |
rows_evaluated | Number of rows TYPE: |
Examples:
Creating an iteration record:
from gepa_adk.domain.models import IterationRecord
record = IterationRecord(
iteration_number=1,
score=0.85,
component_text="Be helpful",
evolved_component="instruction",
accepted=True,
)
print(record.score) # 0.85
print(record.evolved_component) # "instruction"
print(record.accepted) # True
Serialization round-trip:
Notes
An immutable record that captures iteration metrics. Once created, IterationRecord instances cannot be modified, ensuring historical accuracy of the evolution trace.
Source code in src/gepa_adk/domain/models.py
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 | |
to_dict ¶
Serialize this record to a stdlib-only dict.
| RETURNS | DESCRIPTION |
|---|---|
dict[str, Any] | Dict containing all 14 fields; |
dict[str, Any] |
|
dict[str, Any] | always present and None when unset. |
dict[str, Any] |
|
dict[str, Any] |
|
Source code in src/gepa_adk/domain/models.py
from_dict classmethod ¶
from_dict(data: dict[str, Any]) -> IterationRecord
Reconstruct an IterationRecord from a dict.
Unknown keys are silently ignored for forward compatibility, allowing older code to load records produced by newer versions. Optional fields (objective_scores, reflection_reasoning, skip_reason, token_usage, candidate_id, parent_ids, rejection_reason, rows_evaluated) default to None and failed_evaluations to 0 when missing from the input dict. parent_ids is copied to a new list so the frozen record does not alias the input.
| PARAMETER | DESCRIPTION |
|---|---|
data | Dict containing iteration record fields. TYPE: |
| RETURNS | DESCRIPTION |
|---|---|
IterationRecord | Reconstructed IterationRecord instance. |
| RAISES | DESCRIPTION |
|---|---|
KeyError | If a required field is missing from the dict. |
Source code in src/gepa_adk/domain/models.py
MultiAgentEvolutionResult dataclass ¶
Outcome of a completed multi-agent evolution run.
Contains evolved component_text for all agents in the group, along with performance metrics and evolution history.
| ATTRIBUTE | DESCRIPTION |
|---|---|
schema_version | Schema version for forward-compatible serialization. TYPE: |
stop_reason | Why the evolution run terminated. TYPE: |
evolved_components | Mapping of agent name to evolved component_text. TYPE: |
original_score | Starting performance score (baseline). TYPE: |
final_score | Ending performance score (best achieved). TYPE: |
primary_agent | Name of the agent whose output was used for scoring. TYPE: |
iteration_history | Chronological list of iteration records. TYPE: |
total_iterations | Number of iterations performed. TYPE: |
original_components | Optional snapshot of pre-evolution component values. When present, enables zero-arg TYPE: |
baseline_failed_evaluations | Number of rows whose pipeline run or scorer raised, or whose run returned a failed execution, during the baseline evaluation. Defaults to 0. TYPE: |
total_failed_evaluations |
TYPE: |
token_usage | Token usage observed on the rows evaluated over the run, baseline included, and on its reflection calls. None when not recorded (results saved before schema version 3). The rollup carries an TYPE: |
Examples:
Creating and analyzing a multi-agent result:
from gepa_adk.domain.models import MultiAgentEvolutionResult, IterationRecord
result = MultiAgentEvolutionResult(
evolved_components={
"generator": "Generate high-quality code",
"critic": "Review code thoroughly",
},
original_components={
"generator": "Generate code",
"critic": "Review code",
},
original_score=0.60,
final_score=0.85,
primary_agent="generator",
iteration_history=[],
total_iterations=10,
)
print(result.improvement) # 0.25
print(result.show_diff()) # unified diff of component changes
print(result.agent_names) # ["critic", "generator"]
assert result.schema_version == 7
Serialization round-trip:
import json
d = result.to_dict()
restored = MultiAgentEvolutionResult.from_dict(json.loads(json.dumps(d)))
Notes
An immutable result container for multi-agent evolution. Once created, MultiAgentEvolutionResult instances cannot be modified. Use computed properties like improvement, improved, and agent_names to analyze results without modifying the underlying data.
Source code in src/gepa_adk/domain/models.py
2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 | |
improvement property ¶
Calculate the score improvement from original to final.
| RETURNS | DESCRIPTION |
|---|---|
float | The difference between final_score and original_score. |
float | Positive values indicate improvement, negative indicates degradation. |
Notes
Override is not needed since frozen dataclasses support properties.
improved property ¶
Check if the final score is better than the original.
| RETURNS | DESCRIPTION |
|---|---|
bool | True if final_score > original_score, False otherwise. |
Notes
Only returns True for strict improvement, not equal scores.
agent_names property ¶
Get sorted list of evolved agent names.
| RETURNS | DESCRIPTION |
|---|---|
list[str] | Sorted list of agent names from evolved_components keys. |
Notes
Outputs a new list each time, sorted alphabetically for consistent ordering regardless of insertion order.
to_dict ¶
Serialize this result to a stdlib-only dict.
| RETURNS | DESCRIPTION |
|---|---|
dict[str, Any] | Dict containing all 12 fields. |
dict[str, Any] | as its string value. |
dict[str, Any] | list of dicts. Output is directly |
Source code in src/gepa_adk/domain/models.py
from_dict classmethod ¶
from_dict(
data: dict[str, Any],
) -> MultiAgentEvolutionResult
Reconstruct a MultiAgentEvolutionResult from a dict.
Validates schema version, applies migration if needed, and reconstructs all nested objects including optional original_components. Version 1 dicts migrate through _migrate_v1_to_v2(), so their failure counts read as 0, and version 1 and 2 dicts through _migrate_v2_to_v3(), so their token_usage reads as None, and version 1 to 3 dicts through _migrate_v3_to_v4(), so each record's candidate_id and parent_ids read as None, and version 1 to 4 dicts through _migrate_v4_to_v5(), so each record's rejection_reason reads as None, and version 1 to 5 dicts through _migrate_v5_to_v6(), so each token_usage loads as its evaluation split with reflection None, and version 1 to 6 dicts through _migrate_v6_to_v7(), so each record's rows_evaluated reads as None.
| PARAMETER | DESCRIPTION |
|---|---|
data | Dict containing multi-agent evolution result fields. TYPE: |
| RETURNS | DESCRIPTION |
|---|---|
MultiAgentEvolutionResult | Reconstructed MultiAgentEvolutionResult instance. |
| RAISES | DESCRIPTION |
|---|---|
ConfigurationError | If |
KeyError | If a required field is missing from the dict. |
Source code in src/gepa_adk/domain/models.py
2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 | |
__repr__ ¶
Narrative summary of the multi-agent evolution result.
| RETURNS | DESCRIPTION |
|---|---|
str | Human-readable multi-line summary with improvement percentage, |
str | iterations, stop reason, primary agent, agent names, and |
str | acceptance rate. Uses 2-space indent, no box-drawing characters, |
str | every line greppable. When the original score is zero the |
str | improvement is reported as an absolute value instead of a |
str | percentage. |
Source code in src/gepa_adk/domain/models.py
show_diff ¶
Show unified diff between original and evolved components.
Uses stored original_components if no explicit argument is provided. Produces git-diff-style output (---/+++/@@) for each component that changed.
| PARAMETER | DESCRIPTION |
|---|---|
original_components | Pre-evolution component values. If None, falls back to TYPE: |
| RETURNS | DESCRIPTION |
|---|---|
str | Unified diff string, or |
str | components are identical. |
| RAISES | DESCRIPTION |
|---|---|
ValueError | If both the argument and |
Source code in src/gepa_adk/domain/models.py
TokenRollup dataclass ¶
Token usage summed over evaluated rows and reflection calls.
Each counter is the sum over the rows that reported usage. A row that reported none is counted in rows_unknown, never as zero tokens. The counters are None only when no row reported usage and at least one row was unknown; nothing evaluated gives zeros. A rollup built with split() also carries its evaluation and reflection parts, and its counters cover both; a rollup built by from_batch() is a plain rollup without splits.
| ATTRIBUTE | DESCRIPTION |
|---|---|
input_tokens | Prompt tokens over the counted rows, or None when unknown. TYPE: |
output_tokens | Generated tokens over the counted rows, or None when unknown. TYPE: |
total_tokens | Total tokens over the counted rows, or None when unknown. TYPE: |
rows_counted | Rows that reported usage. TYPE: |
rows_unknown | Rows that reported no usage. TYPE: |
evaluation | The evaluated rows' part of a split rollup, or None for a rollup without splits. TYPE: |
reflection | The reflection calls' part of a split rollup, one row per call, or None when no reflection call was observed. TYPE: |
Examples:
Summing an evaluation batch and serializing the result:
from gepa_adk.domain.models import TokenRollup
rollup = TokenRollup.from_batch(batch)
print(rollup.total_tokens, rollup.rows_unknown)
data = rollup.to_dict() # None counters become "unknown"
assert TokenRollup.from_dict(data) == rollup
Notes
The evaluation part covers the rows the adapters evaluated with traces; rows evaluated without traces, such as a separate valset pass, are not observed. The reflection part counts each reflection call that returned; a call whose executor captured no events is unknown. The parts are rollups without splits of their own.
Source code in src/gepa_adk/domain/models.py
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 | |
from_batch classmethod ¶
from_batch(batch: Any) -> TokenRollup
Sum the token usage reported by each row of an evaluation batch.
Reads batch.trajectories[i] for each row of batch.scores. A trajectory whose token_usage or total_token_usage is a TokenUsage counts its three numbers; any other row (no trajectories, a trajectory without usage, a dict) is unknown.
| PARAMETER | DESCRIPTION |
|---|---|
batch | An TYPE: |
| RETURNS | DESCRIPTION |
|---|---|
TokenRollup | The rollup of the batch. An empty batch gives zeros. |
Source code in src/gepa_adk/domain/models.py
split classmethod ¶
split(
*,
evaluation: TokenRollup | None,
reflection: TokenRollup | None,
) -> TokenRollup
Build a rollup from its evaluation and reflection parts.
| PARAMETER | DESCRIPTION |
|---|---|
evaluation | The evaluated rows' rollup, or None when absent. TYPE: |
reflection | The reflection calls' rollup, or None when no reflection call was observed. TYPE: |
| RETURNS | DESCRIPTION |
|---|---|
TokenRollup | A rollup whose counters combine both parts (a None part adds |
TokenRollup | nothing; counters are None only when nothing was counted and |
TokenRollup | something was unknown) and whose |
TokenRollup |
|
| RAISES | DESCRIPTION |
|---|---|
ValueError | If a part has splits of its own; parts are rollups without splits, and a nested split would be flattened on save and load. |
Source code in src/gepa_adk/domain/models.py
combine ¶
combine(other: TokenRollup) -> TokenRollup
Add another rollup to this one.
Counted rows and both row counts add up. A None counter on either side is treated as absent. When either side has splits, the result combines split-wise: a side without splits counts as evaluation, and a split absent on both sides stays None.
| PARAMETER | DESCRIPTION |
|---|---|
other | The rollup to add. TYPE: |
| RETURNS | DESCRIPTION |
|---|---|
TokenRollup | A new rollup; its counters are None only when no row was counted |
TokenRollup | and at least one row was unknown. |
Source code in src/gepa_adk/domain/models.py
to_dict ¶
Serialize this rollup to a stdlib-only dict.
| RETURNS | DESCRIPTION |
|---|---|
dict[str, Any] | Dict with the five counters, where a None counter is written as |
dict[str, Any] |
|
dict[str, Any] | the part's dict or None when absent. Output is directly |
dict[str, Any] |
|
Source code in src/gepa_adk/domain/models.py
from_dict classmethod ¶
from_dict(data: dict[str, Any]) -> TokenRollup
Reconstruct a TokenRollup from a dict.
| PARAMETER | DESCRIPTION |
|---|---|
data | Dict produced by TYPE: |
| RETURNS | DESCRIPTION |
|---|---|
TokenRollup | Reconstructed TokenRollup; |
| RAISES | DESCRIPTION |
|---|---|
KeyError | If a row count is missing from the dict or a part. |
Source code in src/gepa_adk/domain/models.py
ParetoFrontier dataclass ¶
Tracks non-dominated candidates across multiple frontier dimensions.
| ATTRIBUTE | DESCRIPTION |
|---|---|
example_leaders | Instance-level mapping of example_idx to leader candidate indices. TYPE: |
best_scores | Instance-level mapping of example_idx to best score. TYPE: |
objective_leaders | Objective-level mapping of objective_name to leader candidate indices. TYPE: |
objective_best_scores | Objective-level mapping of objective_name to best score. TYPE: |
cartesian_leaders | Cartesian mapping of (example_idx, objective) to leader candidate indices. TYPE: |
cartesian_best_scores | Cartesian mapping of (example_idx, objective) to best score. TYPE: |
Examples:
Notes
A frontier stores the best candidate indices per dimension for sampling. The active dimension depends on frontier_type.
Source code in src/gepa_adk/domain/state.py
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 | |
update ¶
update(
candidate_idx: int,
scores: dict[int, float],
*,
logger: FrontierLogger | None = None,
) -> None
Update frontier leadership with a candidate's scores.
| PARAMETER | DESCRIPTION |
|---|---|
candidate_idx | Index of the candidate being added. TYPE: |
scores | Mapping of example index to score. TYPE: |
logger | Optional structured logger for leader updates. TYPE: |
Notes
Mutates example_leaders and best_scores for instance-level frontier tracking.
Examples:
Source code in src/gepa_adk/domain/state.py
get_non_dominated ¶
Return candidate indices that lead any example.
| RETURNS | DESCRIPTION |
|---|---|
set[int] | Set of candidate indices that are non-dominated (lead at |
set[int] | least one example). |
Notes
Outputs the union of all leader sets across example indices.
Source code in src/gepa_adk/domain/state.py
get_selection_weights ¶
Return selection weights based on leadership frequency.
| RETURNS | DESCRIPTION |
|---|---|
dict[int, int] | Mapping of candidate index to leadership count, usable as |
dict[int, int] | weights for weighted sampling. |
Notes
Outputs weights proportional to how many examples each candidate leads, enabling weighted sampling.
Source code in src/gepa_adk/domain/state.py
update_objective ¶
update_objective(
candidate_idx: int,
objective_scores: dict[str, float],
*,
logger: FrontierLogger | None = None,
) -> None
Update objective-level frontier with a candidate's objective scores.
| PARAMETER | DESCRIPTION |
|---|---|
candidate_idx | Index of the candidate being added. TYPE: |
objective_scores | Mapping of objective name to score. TYPE: |
logger | Optional structured logger for leader updates. TYPE: |
Notes
Mutates objective_leaders and objective_best_scores for objective-level frontier tracking.
Examples:
Source code in src/gepa_adk/domain/state.py
update_cartesian ¶
update_cartesian(
candidate_idx: int,
scores: dict[int, float],
objective_scores: dict[int, dict[str, float]],
*,
logger: FrontierLogger | None = None,
) -> None
Update cartesian frontier per (example, objective) pair.
| PARAMETER | DESCRIPTION |
|---|---|
candidate_idx | Index of the candidate being added. TYPE: |
scores | Mapping of example index to score. TYPE: |
objective_scores | Mapping of example index to objective scores dict. TYPE: |
logger | Optional structured logger for leader updates. TYPE: |
Notes
Mutates cartesian_leaders and cartesian_best_scores for per (example, objective) pair frontier tracking.
Examples:
Source code in src/gepa_adk/domain/state.py
get_pareto_front_mapping ¶
get_pareto_front_mapping(
frontier_type: FrontierType,
) -> dict[FrontierKey, set[int]]
Return frontier mapping for specified frontier type.
| PARAMETER | DESCRIPTION |
|---|---|
frontier_type | Type of frontier to return mapping for. TYPE: |
| RETURNS | DESCRIPTION |
|---|---|
dict[FrontierKey, set[int]] | dict[FrontierKey, set[int]]: Mapping from frontier key to set of candidate indices. |
| RAISES | DESCRIPTION |
|---|---|
ValueError | If frontier_type is not a supported value. |
Notes
Outputs a mapping with keys appropriate for the frontier type (int for INSTANCE, str for OBJECTIVE, tuples for HYBRID/CARTESIAN).
Examples:
mapping = frontier.get_pareto_front_mapping(FrontierType.INSTANCE)
# Returns: {0: {1, 2}, 1: {2, 3}}
Source code in src/gepa_adk/domain/state.py
ParetoState dataclass ¶
Tracks evolution state for Pareto-aware selection.
| ATTRIBUTE | DESCRIPTION |
|---|---|
candidates | Candidates discovered during evolution. TYPE: |
candidate_scores | Per-example scores mapping candidate index to example-score mappings. TYPE: |
frontier | Current frontier leader sets. TYPE: |
frontier_type | Frontier tracking strategy. TYPE: |
iteration | Current iteration number. TYPE: |
best_average_idx | Index of best-average candidate. TYPE: |
parent_indices | Genealogy map tracking parent relationships, mapping candidate_idx to parent index list or TYPE: |
Examples:
Notes
A single state object keeps frontier and candidate metrics aligned.
Source code in src/gepa_adk/domain/state.py
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 | |
__post_init__ ¶
Validate state configuration and initialize averages.
| RAISES | DESCRIPTION |
|---|---|
ConfigurationError | If any candidate_scores index exceeds the candidates list length. |
Notes
Checks candidate_scores indices are valid and marks frontier_type as initialized for immutability enforcement.
Source code in src/gepa_adk/domain/state.py
__setattr__ ¶
Enforce frontier_type immutability after initialization (T069).
| PARAMETER | DESCRIPTION |
|---|---|
name | Attribute being set. TYPE: |
value | New value. Re-assigning the current frontier_type is allowed. TYPE: |
| RAISES | DESCRIPTION |
|---|---|
ConfigurationError | If frontier_type is changed after ParetoState initialization. |
Notes
Only frontier_type is protected because it determines the frontier update routing logic in add_candidate(). Other fields (candidates, frontier, candidate_scores) are intentionally mutable to support evolution state updates. Using frozen=True would prevent all mutations, which is too restrictive for evolution state management.
Source code in src/gepa_adk/domain/state.py
add_candidate ¶
add_candidate(
candidate: Candidate,
scores: Sequence[Score],
*,
score_indices: Sequence[int] | None = None,
objective_scores: dict[str, float] | None = None,
per_example_objective_scores: dict[
int, dict[str, float]
]
| None = None,
parent_indices: list[int] | None = None,
logger: FrontierLogger | None = None,
) -> int
Add a candidate and update frontier tracking.
| PARAMETER | DESCRIPTION |
|---|---|
candidate | Candidate to add. TYPE: |
scores | Per-example scores for the candidate. TYPE: |
score_indices | Optional sequence mapping scores to example indices. If None, scores are assumed to be indexed 0, 1, 2, ... (full valset). If provided, scores[i] corresponds to example index score_indices[i]. TYPE: |
objective_scores | Optional aggregated objective scores (required for OBJECTIVE, HYBRID, CARTESIAN). TYPE: |
per_example_objective_scores | Optional per-example objective scores (required for CARTESIAN). TYPE: |
parent_indices | Optional parent candidate indices for genealogy tracking. The engine passes the index of the candidate the proposal was mutated from, as returned with the proposal. If None, uses candidate.parent_ids if available, otherwise [None] for seed. TYPE: |
logger | Optional structured logger for frontier updates. TYPE: |
| RETURNS | DESCRIPTION |
|---|---|
int | Index of the newly added candidate. |
| RAISES | DESCRIPTION |
|---|---|
ConfigurationError | If objective_scores are required but not provided. |
ValueError | If score_indices and scores differ in length. |
TypeError | If a parent index is neither an int nor None. |
Notes
Outputs the new candidate index after routing to the appropriate frontier update method based on frontier_type.
Examples:
candidate_idx = state.add_candidate(candidate, [0.7, 0.8])
candidate_idx = state.add_candidate(
candidate, [0.7, 0.8], objective_scores={"accuracy": 0.9}
)
Source code in src/gepa_adk/domain/state.py
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 | |
get_average_score ¶
Return average score for a candidate.
| PARAMETER | DESCRIPTION |
|---|---|
candidate_idx | Index of the candidate. TYPE: |
| RETURNS | DESCRIPTION |
|---|---|
float | Mean score across examples. |
| RAISES | DESCRIPTION |
|---|---|
NoCandidateAvailableError | If candidate scores are missing. |
Notes
Outputs the arithmetic mean of all scores for the candidate across evaluated examples.
Examples:
Source code in src/gepa_adk/domain/state.py
update_best_average ¶
Update best_average_idx based on current scores.
Notes
Outputs the candidate index with the highest mean score, or None if no candidates have scores.
Source code in src/gepa_adk/domain/state.py
StopperState dataclass ¶
Immutable snapshot of evolution state for stopper decisions.
Provides stoppers with read-only access to evolution metrics without exposing internal engine state.
| ATTRIBUTE | DESCRIPTION |
|---|---|
iteration | Current iteration number (0-indexed). TYPE: |
best_score | Best score achieved so far. TYPE: |
stagnation_counter | Number of iterations without improvement. TYPE: |
total_evaluations | Total examples evaluated (sum of batch sizes). TYPE: |
candidates_count | Number of candidates in the frontier. TYPE: |
elapsed_seconds | Wall-clock time since evolution started. TYPE: |
latest_score | Score recorded for the most recent iteration, accepted or not. TYPE: |
Examples:
Creating a state snapshot:
from gepa_adk.domain.stopper import StopperState
state = StopperState(
iteration=10,
best_score=0.92,
stagnation_counter=3,
total_evaluations=100,
candidates_count=5,
elapsed_seconds=300.0,
latest_score=0.88,
)
print(state.best_score) # 0.92
print(state.latest_score) # 0.88
print(state.stagnation_counter) # 3
Attempting to modify raises an error:
Notes
A frozen dataclass, all fields are immutable after creation. Using slots=True for memory efficiency. latest_score is the only field with a default, so it stays last.
Source code in src/gepa_adk/domain/stopper.py
ADKTrajectory dataclass ¶
Execution trace from ADK agent evaluation.
Captures complete execution details from a single agent evaluation run, including all tool calls, state changes, token usage, and final output. This data enables debugging, optimization, and reflection-based learning. to_dict() and from_dict() convert it to and from a JSON-safe dict, turning tuples into lists and back.
| ATTRIBUTE | DESCRIPTION |
|---|---|
tool_calls | Immutable sequence of tool invocations during execution. TYPE: |
state_deltas | Sequence of state changes (session state updates). TYPE: |
token_usage | Optional token consumption metrics from LLM calls. TYPE: |
final_output | Final text response from the agent. TYPE: |
error | Error message if execution failed, None otherwise. TYPE: |
Examples:
trajectory = ADKTrajectory(
tool_calls=(ToolCallRecord("search", {"query": "AI"}, ["result1"], 0.1),),
state_deltas=({"search_count": 1},),
token_usage=TokenUsage(100, 50, 150),
final_output="Based on the search...",
error=None,
)
Notes
All fields use immutable types (tuples, not lists) to prevent accidental modification of captured trace data.
Source code in src/gepa_adk/domain/trajectory.py
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 | |
to_dict ¶
Serialise this trace to a JSON-safe dict.
| RETURNS | DESCRIPTION |
|---|---|
dict[str, Any] | Dict with |
dict[str, Any] |
|
dict[str, Any] |
|
dict[str, Any] | as its |
Source code in src/gepa_adk/domain/trajectory.py
from_dict classmethod ¶
from_dict(data: dict[str, Any]) -> ADKTrajectory
Rebuild a trace from to_dict() output.
| PARAMETER | DESCRIPTION |
|---|---|
data | Dict produced by TYPE: |
| RETURNS | DESCRIPTION |
|---|---|
ADKTrajectory | The reconstructed trace, with lists turned back into tuples. |
| RAISES | DESCRIPTION |
|---|---|
KeyError | If a field is missing from |
Source code in src/gepa_adk/domain/trajectory.py
MultiAgentTrajectory dataclass ¶
Execution trace from multi-agent pipeline evaluation.
Captures individual agent trajectories and overall pipeline metrics. to_dict() and from_dict() convert it to and from a JSON-safe dict, nesting each agent's ADKTrajectory dict.
| ATTRIBUTE | DESCRIPTION |
|---|---|
agent_trajectories | Mapping of agent name to trajectory. TYPE: |
pipeline_output | Final output from the primary agent. TYPE: |
total_token_usage | Aggregated token usage across all agents. TYPE: |
error | Error message if pipeline execution failed. TYPE: |
Examples:
Creating a multi-agent trajectory:
from gepa_adk.domain.trajectory import (
MultiAgentTrajectory,
ADKTrajectory,
TokenUsage,
)
trajectory = MultiAgentTrajectory(
agent_trajectories={
"generator": ADKTrajectory(...),
"critic": ADKTrajectory(...),
},
pipeline_output="Generated code output",
total_token_usage=TokenUsage(200, 100, 300),
error=None,
)
Notes
All fields use immutable types to prevent accidental modification of captured trace data. agent_trajectories maps agent names to their individual ADKTrajectory records.
Source code in src/gepa_adk/domain/trajectory.py
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 | |
to_dict ¶
Serialise this pipeline trace to a JSON-safe dict.
| RETURNS | DESCRIPTION |
|---|---|
dict[str, Any] | Dict with |
dict[str, Any] |
|
dict[str, Any] |
|
Source code in src/gepa_adk/domain/trajectory.py
from_dict classmethod ¶
from_dict(data: dict[str, Any]) -> MultiAgentTrajectory
Rebuild a pipeline trace from to_dict() output.
| PARAMETER | DESCRIPTION |
|---|---|
data | Dict produced by TYPE: |
| RETURNS | DESCRIPTION |
|---|---|
MultiAgentTrajectory | The reconstructed pipeline trace. |
| RAISES | DESCRIPTION |
|---|---|
KeyError | If a required field is missing from |
Source code in src/gepa_adk/domain/trajectory.py
TokenUsage dataclass ¶
Token usage statistics from LLM calls.
Tracks token consumption for monitoring costs and performance of language model interactions during agent execution. to_dict() and from_dict() convert it to and from a JSON-safe dict.
| ATTRIBUTE | DESCRIPTION |
|---|---|
input_tokens | Number of tokens in the prompt/context. TYPE: |
output_tokens | Number of tokens generated in the response. TYPE: |
total_tokens | Sum of input_tokens and output_tokens. TYPE: |
Examples:
Source code in src/gepa_adk/domain/trajectory.py
to_dict ¶
Serialise these counts to a JSON-safe dict.
| RETURNS | DESCRIPTION |
|---|---|
dict[str, Any] | Dict with |
dict[str, Any] |
|
Source code in src/gepa_adk/domain/trajectory.py
from_dict classmethod ¶
from_dict(data: dict[str, Any]) -> TokenUsage
Rebuild token counts from to_dict() output.
| PARAMETER | DESCRIPTION |
|---|---|
data | Dict produced by TYPE: |
| RETURNS | DESCRIPTION |
|---|---|
TokenUsage | The reconstructed counts. |
| RAISES | DESCRIPTION |
|---|---|
KeyError | If a field is missing from |
Source code in src/gepa_adk/domain/trajectory.py
ToolCallRecord dataclass ¶
Record of a single tool call during agent execution.
Captures the invocation details of a tool/function call made by an agent during evaluation, including arguments, results, and timing information. to_dict() and from_dict() convert it to and from a JSON-safe dict.
| ATTRIBUTE | DESCRIPTION |
|---|---|
name | Tool or function name that was called. TYPE: |
arguments | Dictionary of arguments passed to the tool. TYPE: |
result | Return value from the tool execution. TYPE: |
timestamp | Relative time in seconds from evaluation start. TYPE: |
Examples:
record = ToolCallRecord(
name="get_weather",
arguments={"city": "Paris"},
result={"temp": 22, "condition": "sunny"},
timestamp=0.123,
)
Source code in src/gepa_adk/domain/trajectory.py
to_dict ¶
Serialise this record to a JSON-safe dict.
| RETURNS | DESCRIPTION |
|---|---|
dict[str, Any] | Dict with |
dict[str, Any] | An argument value or result that JSON cannot encode is stored as |
dict[str, Any] | its |
Source code in src/gepa_adk/domain/trajectory.py
from_dict classmethod ¶
from_dict(data: dict[str, Any]) -> ToolCallRecord
Rebuild a record from to_dict() output.
| PARAMETER | DESCRIPTION |
|---|---|
data | Dict produced by TYPE: |
| RETURNS | DESCRIPTION |
|---|---|
ToolCallRecord | The reconstructed record. |
| RAISES | DESCRIPTION |
|---|---|
KeyError | If a field is missing from |
Source code in src/gepa_adk/domain/trajectory.py
FrontierType ¶
Bases: str, Enum
flowchart TD
gepa_adk.domain.FrontierType[FrontierType]
click gepa_adk.domain.FrontierType href "" "gepa_adk.domain.FrontierType"
Supported frontier tracking strategies for Pareto selection.
Notes
INSTANCE tracks per-example scores, OBJECTIVE aggregated objective scores, HYBRID both, and CARTESIAN per-example objective scores. Members are str values, so they compare equal to and serialize as their plain strings ("instance" and so on).
Examples:
Source code in src/gepa_adk/domain/types.py
SchemaConstraints dataclass ¶
Constraints for output schema evolution.
Controls which fields must be preserved during schema evolution, including field existence and type constraints. Used by the OutputSchemaHandler to validate proposed schema mutations.
| ATTRIBUTE | DESCRIPTION |
|---|---|
required_fields | Field names that must exist in evolved schemas. Mutations removing these fields are rejected. TYPE: |
preserve_types | Mapping of field names to allowed type(s). Mutations changing a field's type to an incompatible type are rejected. TYPE: |
Examples:
Preserve required fields only:
from gepa_adk.domain.types import SchemaConstraints
constraints = SchemaConstraints(
required_fields=("score", "feedback"),
)
Preserve required fields with type constraints:
constraints = SchemaConstraints(
required_fields=("score",),
preserve_types={
"score": (float, int), # Allow numeric types
"order_id": str, # Must stay string
},
)
Notes
A frozen dataclass ensures immutability during evolution runs. Configuration is validated at evolution start.
Source code in src/gepa_adk/domain/types.py
StopReason ¶
Bases: str, Enum
flowchart TD
gepa_adk.domain.StopReason[StopReason]
click gepa_adk.domain.StopReason href "" "gepa_adk.domain.StopReason"
Why an evolution run terminated.
Each value represents a distinct termination condition. The engine sets the appropriate value when building the final EvolutionResult. Members are str values, so a serialized result stores them as plain strings.
The engine sets KEYBOARD_INTERRUPT or CANCELLED when a run is interrupted or cancelled after the baseline is scored. TIMEOUT is reserved and not set by the engine yet.
MAX_ITERATIONS means the iteration cap was reached. PATIENCE means early stopping fired because stagnation_counter reached patience.
ERROR marks the partial result the engine attaches to an EvolutionError in partial_result when it aborts a run after the baseline was scored.
Examples:
Source code in src/gepa_adk/domain/types.py
TrajectoryConfig dataclass ¶
Configuration for trajectory extraction behavior.
Controls which components are extracted from ADK event streams, whether sensitive data should be redacted, and whether large values should be truncated.
Notes
All configuration fields are immutable after instantiation, ensuring consistent extraction behavior throughout evolution.
| ATTRIBUTE | DESCRIPTION |
|---|---|
include_tool_calls | Extract tool/function call records. Defaults to True. TYPE: |
include_state_deltas | Extract session state changes. Defaults to True. TYPE: |
include_token_usage | Extract LLM token consumption metrics. Defaults to True. TYPE: |
redact_sensitive | Apply sensitive data redaction. When True, fields matching sensitive_keys will be replaced with "[REDACTED]". Defaults to True for secure-by-default behavior. TYPE: |
sensitive_keys | Field names to redact via exact match. Case-sensitive. Defaults to TYPE: |
max_string_length | Truncate strings longer than this with a marker indicating truncation. None disables truncation. Defaults to 10000 characters. TYPE: |
Examples:
Default configuration (secure, with truncation):
Minimal configuration (tool calls only):
config = TrajectoryConfig(
include_tool_calls=True,
include_state_deltas=False,
include_token_usage=False,
redact_sensitive=False,
)
Custom sensitive keys (extends defaults):
config = TrajectoryConfig(
sensitive_keys=DEFAULT_SENSITIVE_KEYS + ("ssn",),
max_string_length=5000, # Truncate DOM/screenshots earlier
)
Disable truncation (keep full values):
Notes
Redaction takes precedence over truncation. Sensitive values are replaced with "[REDACTED]" first, then truncation applies to the remaining (non-sensitive) strings.